项目之间的pytest重用夹具
pytest reuse fixture between projects
我想将装置创建为库组件。
标准测试数据库配置对不同存储库中的多个项目很有用。目前 copy/pasted 进入每个独立项目,因为它们无法共享 config.py。
我将代码重构为 pip 可安装库,但无法找到一种优雅的方式在每个项目中使用它。这不起作用:
import my_db_fixture
@pytest.fixture
def adapted_db_fixture(my_db_fixture):
# adapt the test setup
对于实际代码,我想重新使用的夹具是从其他夹具构建的。到目前为止,我能找到的最佳解决方法是创建一个本地 conftest.py 作为 copy/paste 代码,但仅限于导入函数并在本地夹具函数中调用它们。我不喜欢 copy/paste 并且不必要地暴露了固定装置的内部工作原理。
可以从已安装的库中重新使用固定装置。
像往常一样在可安装包中定义固定装置。然后将它们导入到项目的本地 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
这篇文章对我有帮助:
peterhurford/pytest-fixture-modularization.md
我认为 pytest 应该将返回生成器的东西识别为生成器,因此将其记录为错误。我想对此做出回应的评论可能会有用:
call_fixture_func should test the return value not the function
我想将装置创建为库组件。
标准测试数据库配置对不同存储库中的多个项目很有用。目前 copy/pasted 进入每个独立项目,因为它们无法共享 config.py。
我将代码重构为 pip 可安装库,但无法找到一种优雅的方式在每个项目中使用它。这不起作用:
import my_db_fixture
@pytest.fixture
def adapted_db_fixture(my_db_fixture):
# adapt the test setup
对于实际代码,我想重新使用的夹具是从其他夹具构建的。到目前为止,我能找到的最佳解决方法是创建一个本地 conftest.py 作为 copy/paste 代码,但仅限于导入函数并在本地夹具函数中调用它们。我不喜欢 copy/paste 并且不必要地暴露了固定装置的内部工作原理。
可以从已安装的库中重新使用固定装置。
像往常一样在可安装包中定义固定装置。然后将它们导入到项目的本地 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
这篇文章对我有帮助:
peterhurford/pytest-fixture-modularization.md
我认为 pytest 应该将返回生成器的东西识别为生成器,因此将其记录为错误。我想对此做出回应的评论可能会有用:
call_fixture_func should test the return value not the function