【问题标题】:Autousing pytest fixtures defined in a separate module自动使用在单独模块中定义的 pytest 固定装置
【发布时间】:2015-07-04 17:51:53
【问题描述】:

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

...
tests/
    __init__.py
    test_abc.py
...

我在__init__.py 中定义了一个夹具:

@pytest.fixture(autouse=True)
def client():
    return TestClient()

我想在test_abc.py使用这个夹具:

from . import client

def test_def():
    client.get(...) # Throws an error

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

【问题讨论】:

  • 您应该将夹具放入conftest 文件:pytest.org/latest/…
  • 我不想把它放在那里...这是解决夹具的唯一方法吗?
  • 另一种方式是写一个插件:pytest.org/latest/…
  • 我已经尝试将灯具移动到conftest.py,但仍然是NameError: global name 'client' is not defined
  • 在你的测试方法中声明一个带有夹具名称的参数:def test_def(client):

标签: python fixtures pytest


【解决方案1】:

Autouse 适用于进行所有测试所需的设置的夹具,并且可能会或可能不会返回仍然有用的东西作为测试使用的夹具。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多