我正在构建一个python包,使用pytest
进行所有单元测试。我的包由几个模块组成,每个模块下都有各种子模块。单元测试在每个模块的test
文件夹中(例如,./tumble/tumble/math/test/test_multiply.py
或./tumble/tumble/science/test/test_divide.py
)
我有一些想要在所有模块和子模块中共享的灯具。因此,我想把它们放在一个中心位置,在这个例子中是./tumble/tumble/test
,并且每个子模块中没有重复的固定装置(math/test
和science/test
)。
如果我将conftest.py
放在每个子模块的test
文件夹中,一切都按预期工作。但是,我在两个地方有相同的灯具,这并不理想。
当我将灯具放置在中心位置时,我能够在使用命令pytest --fixtures
时看到它们,但是,当我运行pytest
时,它告诉我fixture not found
并且夹具未列在available fixtures
中。
我是否需要在test
文件夹下移动所有单元测试,或者我可以做些什么来保持子模块内的单元测试,但是在中心位置的灯具?
tumble
+-- setup.py
+-- README.md
+-- tumble
| +-- math
| | +-- __init__.py
| | +-- multiply.py
| | +-- test
| | +-- __init__.py
| | | +-- test
| | | | +-- __init__.py
| | | | +-- test_multiply.py
| +-- science
| | +-- __init__.py
| | +-- divide.py
| | +-- test
| | +-- __init__.py
| | | +-- test
| | | | +-- __init__.py
| | | | +-- test_divide.py
| +-- test
| | +-- __init__.py
| | +-- conftest.py
multiply.朋友
def multipy(x, y):
return x * y
conf test.朋友
import pytest
@pytest.fixture()
def numbers():
return (1, 5, 10)
test_multiply.朋友
import tumble
import pytest
assert tumble.multiply(numbers[0], numbers[1]) == 5
来自pytest doc和about plugins in pytest:
本地conftest.py插件包含特定于目录的钩子实现。 Hook Session和测试运行活动将调用conftest.py文件中定义的更靠近文件系统根目录的所有挂钩
所以,为了让你的测试知道夹具,它应该在层次结构中更高。即将您的共享灯具放在根文件夹/tumble/conftest.py
下