自动使用在单独模块中定义的 pytest 装置

lin*_*ndy 3 python fixtures pytest

我的项目中有以下文件树:

...
tests/
    __init__.py
    test_abc.py
...
Run Code Online (Sandbox Code Playgroud)

我有一个定义在__init__.py

@pytest.fixture(autouse=True)
def client():
    return TestClient()
Run Code Online (Sandbox Code Playgroud)

我想在以下位置使用这个装置test_abc.py

from . import client

def test_def():
    client.get(...) # Throws an error
Run Code Online (Sandbox Code Playgroud)

如何autouse在其他模块的测试方法中使用我的装置,而不传递对装置的显式引用或使用 pytest 装饰器?

Bru*_*ira 5

自动使用适用于执行所有测试所需的一些设置的固定装置,并且可能会也可能不会返回仍然有用的东西作为测试使用的固定装置。

想要访问固定装置返回的内容的测试必须将固定装置声明为参数,以便它们可以访问它。因此,如果您的测试想要访问固定装置,则必须将其声明为参数,这就是 pytest 的工作原理。希望这可以帮助。