我想创建夹具作为库组件。
一个标准的测试数据库配置对于不同仓库中的几个项目来说是有用的,目前它被复制到每个独立的项目中,因为它们不能共享config.py。目前它被复制到每个独立的项目中,因为它们不能共享一个config.py。
我将代码重构为一个可安装的pip库,但无法找到一个优雅的方式在每个项目中使用它。这样做是行不通的。
import my_db_fixture
@pytest.fixture
def adapted_db_fixture(my_db_fixture):
# adapt the test setup
对于真正的代码,我想重用的夹具是由其他夹具构建的。到目前为止,我能找到的最好的解决方法是创建一个本地的conftest.py作为复制粘贴代码,但仅限于导入函数并在本地夹具函数中调用它们。我不喜欢复制粘贴,而且不必要地暴露了夹具的内部运作。
可以从已安装的库中重复使用夹具。
像往常一样在可安装包中定义固定装置。然后将它们导入到项目本地的conftest.py中。您不仅需要导入您想要的夹具,还需要导入它所依赖的所有夹具和(如果使用)pytest_addoption。
from my.package import (
the_fixture_i_want,
all_fixtures_it_uses,
pytest_addopt
)
我还发现,你不能用拆解的方式解除对一个库函数的装饰,并在本地conftest.py中调用它。
# This doesn't work
# pip installed my_fixture.py
def my_fixture(dependencies)
# setup code
yield fixture_object
# teardown code
# local conftest.py
import pytest
import my_fixture # NB: the module
@pytest.fixture
def my_fixture(dependencies):
my_fixture.my_fixture()
# teardown code isn't called: pytest knows the function has no yield
# but doesn't realise it's returning a generator none the less
这篇文章帮助了我。
peterhurfordpytest-fixture-modularization.md。
我估计pytest应该把返回生成器的东西识别为生成器,所以把它记录为一个bug。我想对它的评论可能是有用的。