How can cmocka be used to mock functions using --wrap within shared libraries?

1.1k views Asked by At

I'm using cmocka to unit test a large code base written in C. I'd like unit tests to run at a library level, but I'm having issues mocking functions when compiled in a shared library. I believe the shared library is the issue because I can successfully mock the same code using --wrap linker flag when not part of a shared library. For the same SOURCE_FILE, here are my two different methods of compiling. For reference, I'm trying to mock the C Standard Library function strcmp.

Compilation steps resulting in a successfully mocked strcmp:

gcc -std=c99 -c SOURCE_FILE.c -o OBJECT_FILE.o
gcc -Wl,-rpath=cmocka/build/src,--wrap=strcmp -Icmocka/include TEST_FILE.c -Lcmocka/build/src -lcmocka OBJECT_FILE.o -o my_test
./my_test

Compilation steps for creating a shared library and then testing. An error is thrown executing my_test demonstrating unsuccessful mocking of strcmp:

gcc -std=c99 -fpic -c SOURCE_FILE.c -o OBJECT_FILE.o
gcc -shared OBJECT_FILE.o -o lMY_LIBRARY.so 
gcc -Wl,-rpath=cmocka/build/src,-rpath={path to current dir},--wrap=strcmp -Icmocka/include TEST_FILE.c -L/home/{path to current dir} -Lcmocka/build/src  -lMY_LIBRARY -lcmocka -o my_test 
./my_test

for reference this is the error I'm seeing:

[  ERROR   ] --- __wrap_strcmp() has remaining non-returned values.
TEST_FILE.c:28: note: remaining item was declared here
__wrap_strcmp.x parameter still has values that haven't been checked.

This cmocka error is thrown whenever you're trying to use cmocka will_return, but the function wrapping did not occur. I'm trying to figure out why the small step of creating a shared object prevents the gcc linker from wrapping a function call.

I can't find any information on stack overflow or elsewhere regarding use of cmocka on shared objects. Would appreciate any ideas, suggestions, or explainations of why this does not work. I know that --wrap does not work when the caller and callee are defined in the same file. Is that what's causing a problem here?

0

There are 0 answers