开发者

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.


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜