Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Python based Unit Test frameworks and runners, to test C Code

Python based Unit test Frameworks like "nose" have a lot of rich features, i wonder if we can leverage them to test C Code.

like image 567
kamal Avatar asked Oct 04 '11 18:10

kamal


1 Answers

Of course you can.... but you'll have to write a binding to call your C code in python (with ctypes for example), and write the tests in python (this is really possible and an easy way to do smart tests)

Example :

  • Write a dummy C library.

foolib.c

int my_sum(int , int);

int my_sum(int a , int b);
{
    return a + b;
}
  • Compile it as a shared library:

gcc -shared -Wl,-soname,foolib -o foolib.so -fPIC foolib.c

  • Write the wrapper with ctypes:

foolib_test.py

import ctypes
import unittest

class FooLibTestCase(unittest.TestCase):
    def setUp(self):
        self.foolib = ctypes.CDLL('/full/path/to/foolib.so')

    def test_01a(self):
        """ Test in an easy way"""
        self.failUnlessEqual(4, foolib.my_sum(2, 2))

And then, when running this test with nose you should have a nice test of your C code :)

like image 149
Cédric Julien Avatar answered Nov 19 '22 21:11

Cédric Julien