我正在尝试使用 Python 和 CFFI 模块在 C 中进行单元测试。它几乎可以工作,但我不能将它用于子目录。
在测试时,我的项目看起来像:
$ tree tests
tests/
├── sum.c
├── sum.h
├── tests_units.py
...
$ python3 tests_unit.py
...
OK
但是当我为我的项目转换它时:
$ tree
.
├── Makefile
├── src
│ ├── sum.c
│ └── sum.h
│ └── ...
└── tests
└── tests_units.py
我的make check
运行如下:
check:
python3 tests/tests_units.py
我必须调整我的测试文件:
import unittest
import cffi
import importlib
def load(filename):
# load source code
source = open(filename + '.c').read()
includes = open(filename + '.h').read()
# pass source code to CFFI
ffibuilder = cffi.FFI()
ffibuilder.cdef(includes)
ffibuilder.set_source(filename + '_', source)
ffibuilder.compile()
# import and return resulting module
module = importlib.import_module(filename + '_')
return module.lib
class SumTest(unittest.TestCase):
def setUp(self):
self.module = load('src/sum')
def test_zero(self):
self.assertEqual(self.module.sum(0), 0)
if __name__ == '__main__':
unittest.main()
注意这一行:
self.module = load('src/sum')
所以我的日志是
...
Traceback (most recent call last):
File "tests/tests_units.py", line 28, in setUp
self.module = load('src/sum')
File "tests/tests_units.py", line 17, in load
ffibuilder.set_source(filename + '_', source)
File "/usr/local/lib/python3.6/site-packages/cffi/api.py", line 625, in set_source
raise ValueError("'module_name' must not contain '/': use a dotted "
ValueError: 'module_name' must not contain '/': use a dotted name to make a 'package.module' location
...
但它不是一个模块,它是一个简单的目录。
你有解决办法吗?
问候。