我正在尝试使用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
...


但这不是一个模块,而是一个简单的目录。

你有解决办法吗?

问候。

最佳答案

子目录在Python中仍被视为软件包,因此,您仍然需要使用点。如src.sum中所示。

10-07 19:26
查看更多