The basic premise is that I want to test functions written in C using the Python unittest framework.
My C code is compiled into shared library files during compilation. I want to be able to mock the int do_thing(void)
function that is called by int set_thing(int)
.
// helper.c
static int thing = 0;
int get_thing (void) {
return thing;
}
int do_thing (void) { // do_thing is called by set_thing. This is what I want to mock out
return thing;
}
int set_thing (int x) {
thing = x;
return do_thing()
}
In Python, I use ctypes to load the shared object file.
# test_helper.py
from ctypes import *
import unittest
from unittest.mock import *
class TestThing(unittest.TestCase):
def setUp(self):
self.lib = CDLL("helper.so") # load library
def test_three(self):
arg = c_int(1)
with patch.object(self.lib, 'do_thing', Mock(return_value=-2)): # mock self.lib.do_thing() return value as -2
self.lib.set_thing.argtypes = [c_int]
ret = self.lib.set_thing(arg) # pass 1 as a c_int to set_thing()
ret2 = self.lib.do_thing()
print("ret = {}".format(ret))
print("ret2 = {}".format(ret2))
assert ret == ret2
The problem with this solution is that my patch.object
line only mocks self.lib.do_thing()
and doesn't mock the actual C int do_thing(void)
function that is loaded through memory of the shared library file.
Is what I'm asking for possible with an already compiled shared library file? How do you mock a function that is already written on disk and loaded in memory?