Mocking Functions in C

Unit-testing is important. You want to know if your code works the way it is designed do, and the only way to be sure is to test it. However, that code may be quite complex. It might call many other routines, and deal with other interfaces. If so, it can be difficult to test.

Mocking interfaces can make the job of testing much easier. Instead of your module calling others, it can call a "mock" interface that is much simpler. Your testing code can then interpose itself on all sides of the module you wish to test. By examining all outputs, and handling all inputs, the scope of effects is greatly diminished. The problem is finding the best way to do this.

To be more concrete, what we want to do is convert our set of functions in a module to call our testing mock-functions instead of some others that they might otherwise use. i.e:

Pretend we want to test the function bar(), above. To do so, we want to make it call a mock version of foo(). Our "testing" version of foo() can be much simpler than the original. The original foo() might inspect a database, do a cpu-intensive calculation, or something else unwieldy to test. Thus we need some way to replace the call.

One way to do that is to use a macro. With simple text-replacing we can make bar() do different things depending on whether or not we are unit-testing:

So now bar() will call mock_foo when the TEST is #defined. This works... but isn't as good as it could be. The problem is that different tests on the function bar() might like different ways of mocking the functions that bar() calls. The above only handles a single method of interposing. We would like something more flexible. One way to add flexibility is to use a function pointer for extra indirection:

The above is much better. We can test now in more complex ways, and thus be more convinced that our implementation is correct. However, the technique is not without its flaws. The first is that the tested version of the module isn't the same as the non-tested version. We are calling via a function pointer instead of using a function. The difference is small, but could cause the compiler to use different register and stack-slot allocations. It is conceivable that some (rare) bugs might be visible in the normal code, but not trigger in the unit tests.

Another problem is that it requires the function bar() to be compiled twice. Once with testing, once without. If the code-base is large, the doubling of compile time can be an issue. We would like to minimize the amount of extra compilation if at all possible

The third problem is more political. In some corporate settings, macros are greatly discouraged in code-bases. So the above might be disallowed do to that. Another possibility is that macros are forced to be in all-upper-case (just like shown in the example). This isn't too much of a problem if only a few interface functions are mocked. However, as more and more unit testing is added, more and more code can be "uglified" by the requirement. We would ideally like the tested code to be unaffected by the external requirements of the test harness.

There is another way to mock the interface. We can add a mock function that wraps calls to foo(). The wrapper function can test a function pointer to see if it should call the original function or not. Since it is a function and not a macro, the coding style issues disappear:

The above has different pros and cons compared to the previous method. One massive advantage is that bar() is completely unaffected by unit testing. We only need to compile it once. The problem is that the code for foo() is now "contaminated" by the need to mock it. We use as simple a wrapper as possible... but the function header is split up in a confusing way. There are other ways of using the C pre-processor to do the above, but all are just as ugly.

There is also another subtle issue with the above technique. It works in the case shown, but sometimes will not be as easy. The big problem occurs when the function specification for foo describes a variable-argument function (i.e. printf()). If a 'v' version of that function exists (vprintf()), then we are okay. Our wrapper can construct a va_list pointer, and then use that to call the 'v' version of the function. However, if it doesn't we are stuck. We are forced to perhaps create one.

Ideally, what we would like is to create some kind of automated wrapping technique that handles all function types, including ones with variable arguments. We would also like it to be not quite as ugly as the method shown. Minimal changes to the mocked functions is the goal.

Obviously, such a wrapper cannot be done in pure C. Pure C will fail to handle the variable arguments. Fortunately, assembly language is powerful and expressive enough to do what we want. Basically, we want to tail-call foo__() or *test_foo depending on whether or not test_foo is NULL. The tail-call means that arguments passed on the stack are not corrupted. An asm wrapper that does this looks like:

movq test_foo(%rip), %r11
testq %r11, %r11
je foo__
jmp *%r11

So we load the pointer into %r11, test to see if it is zero, and if not, call it. Otherwise we jump to foo__directly. We choose the %r11 register because it is a "scratch" register as defined by the ABI. Other registers are owned by the caller or callee, and we can't use them here. Note that %rax appears at first glance to be free. However, it is used by the ABI to record the number of floating point values passed in registers to variable-argument routines, so it isn't always free.

The 32-bit version of the above is a bit more tricky. We don't have any spare registers we can use. (The caller might be using a "regparm" method, passing values in registers.) The trick here is to work out how to branch to our mock version. We can't use a simple indirect jump, as the register used for it will be corrupted. However, there is one other way to dynamically jump somewhere: the return instruction. It pops a value off of the stack, and jumps there. Thus by manipulating the stack, we can get control flow altered the way we need. Some code that does this looks like:

The above saves a slot for the dynamic return, and then saves %edx and %eax by pushing to the stack. We then decide where to jump, and store it in the first stack slot. Finally, we restore %eax and %edx and make our tail-call via a return statement.

So how do we introduce the above into our .c file? It is assembly language, not C. Normally, you can only use inline assemble from within a function. However, we would like to do so from file scope. This is basically impossible... but there is one trick. The section __attribute__ pastes its string input directly into the asm output gcc is generating. So by inserting asm directives into that string, we can do all sorts of crazy things. The following shows how we can dynamically wrap functions for mocking:

We've added extra directives so debugging and exceptions work correctly. You use the above very simply, just place it into a "mocking" header used by the unit-testing code. The unit testing code then uses them:

Notice how little the code needs to be changed now. We just add one line into a header file, and edit the definition of the mocked functions a tiny bit. The magic macros will declare test_foo and foo__ for us. Since foo isn't a macros, functions calling it do not need to be altered. We can test the same object files as is used by the release version, and our source-code remains clean.