将pytest灯具保存在一个位置并在子模块中使用它们

问题描述 投票:1回答:1

我正在构建一个python包,使用pytest进行所有单元测试。我的包由几个模块组成,每个模块下都有各种子模块。单元测试在每个模块的test文件夹中(例如,./tumble/tumble/math/test/test_multiply.py./tumble/tumble/science/test/test_divide.py

我有一些想要在所有模块和子模块中共享的灯具。因此,我想把它们放在一个中心位置,在这个例子中是./tumble/tumble/test,并且每个子模块中没有重复的固定装置(math/testscience/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   
python unit-testing pytest fixtures
1个回答
3
投票

来自pytest docabout plugins in pytest

本地conftest.py插件包含特定于目录的钩子实现。 Hook Session和测试运行活动将调用conftest.py文件中定义的更靠近文件系统根目录的所有挂钩

所以,为了让你的测试知道夹具,它应该在层次结构中更高。即将您的共享灯具放在根文件夹/tumble/conftest.py

© www.soinside.com 2019 - 2024. All rights reserved.