1

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?

Sundeep
  • 33
  • 5
  • Does this answer your question? [How to mock library calls?](https://stackoverflow.com/questions/11686897/how-to-mock-library-calls) (Note that Python can’t do this directly, and that this method *does* work within a library if it’s compiled in the normal PIC fashion.) – Davis Herring Jan 21 '20 at 15:06
  • @DavisHerring Thanks for the reply. While that did work, I need to be able to do this within Python for my problem. The LD_PRELOAD trick is an interesting thing [Link](http://www.goldsborough.me/c/low-level/kernel/2016/08/29/16-48-53-the_-ld_preload-_trick/) – Sundeep Jan 21 '20 at 22:44
  • So… would you like an answer that says “This is impossible, but `LD_PRELOAD` is cool.”? Is that better than marking it as a duplicate? – Davis Herring Jan 22 '20 at 01:06

0 Answers0