Search code examples
ctestingheader-files

Testing an opaque type's internals


First: What is an opaque pointer in C?

Now when it comes to testing such a type, I know of 3 ways:

  1. Include the source file (the one containing the definition of the type and the functions that work with it) directory into the test source file. (This is the easiest, but often discouraged without presenting any rationale).

  2. Make public accessors that are conditionally available (i.e. only if if LIB_TEST is defined before including its header).

  3. Make a separate "lib-test.h" header file that contains the public accessors.

The last two avoid making the accessors part of the public API (we're speaking of the case where the clients have no business knowing anything about the opaque type's internals, and shouldn't be provided with any accessors).

What is the usual approach (or the good approach) in C? Does one way have more upsides/downsides than the other?

As an example, say I have this struct:

typedef struct arena {
    size_t count;
    size_t capacity;
    size_t current;
    size_t last_alloc_size;
    M_Pool *pools[];
} Arena;

and a function associated with it:

void arena_reset(Arena *arena)
{
    for (size_t i = 0; i < arena->count; ++i) {
        arena->pools[i]->offset = 0;
    }
    arena->current = 1;
}

Now I wish to assert that arena_reset() actually has set the offset field of all the arena's pools to 0, and the arena's current field to 1. Including the API (header file) that this library provides is of no good, because only a forward declaration of the struct type has been provided, and its members can not be accessed.


Solution

  • If you want to test internal details of a source module (i.e. as functions or objects declared as static, or struct definitions defined only in the source module), this is one of the rare cases where it makes sense to #include a .c file.

    So for example if the struct and function above reside in arena.c, your test module could do something like this:

    #include <stdlib.h>
    #include "arena.c"
    
    void test_arena_reset()
    {
        int pool_cnt = 3;
        Arena *p = malloc(sizeof *p + (pool_cnt * sizeof(M_Pool));
        p->count = pool_cnt;
        for (int i = 0; i < pool_cnt; i++) {
            p->pools[i]->offset = 1;
        }
        p->current = 0;
    
        arena_reset(p);
    
        assert(p->current == 1);
        for (int i = 0; i < pool_cnt; i++) {
            assert(p->pools[i]->offset == 0);
        }
    }