I need to create python wrapper for the library using SWIG and write unit tests for it. I don't know how to do this. My first take on this problem is to mock dynamic library with the same interface as those library that I'm writing wrapper for. This mock library can log every call or return some generated data. This logs and generated data can be checked by the unit tests.
2 Answers
I have many situations, where I am using the SWIG generated wrapper for unit testing a library, but I guess what you are asking for is unit testing for the wrapper itself.
The way that I have pursued testing the wrapper, say mylib
itself is the following:
Properties: For each class say MyClass
with properties exposed, I use MyClass._swig_getmethods__
for listing all properties, which can be modified. I verify that the right number of properties is available and they work as expected
# Filter out builtin_function_type
getmethods = {k: v for k,v in mylib.MyClass.__swig_getmethods__.iteritems() if type(v) != types.BuiltinFunctionType}
# Filter out lambda functions (constructors)
getmethods = {k: v for k,v in getmethods.iteritems() if v.func_name != '<lambda>'}.keys()
nGetSuccess = 0
testMe = set()
m = mylib.MyClass()
for method in getmethods:
try:
value = eval('m.'+method)
nGetSuccess = nGetSuccess + 1
except Exception as e:
print(e.message)
self.assertEqual(nGetSuccess,len(getmethods))
Static Methods
For static methods, I have established a list of the expected functions by name and search for their existence in mylib.__dict__
and call them. For some methods I have used a trick I found in here for converting a C struct argument into a dictionary in Python and exposing the possibility for creating a default structure, which can be used for testing.

- 4,627
- 1
- 25
- 40
I'd absolutely recommend doing some basic testing of the wrapped code. Even some basic "can I instantiate my objects" test is super helpful; you can always write more tests as you find problem areas.
Basically what you're testing is the accuracy of the SWIG interface file - which is code that you wrote in your project!
If your objects are at all interesting it is very possible to confuse SWIG. It's also easy to accidentally skip wrapping something, or for a wrapper to use a diferent typemap than you hoped.

- 13,144
- 3
- 60
- 86