找不到夹具的pytest夹具

Jam*_*Lin 5 pytest

基于此stackoverflow:夹具的pytest夹具

我在同一文件中有以下代码:

@pytest.fixture
def form_data():
    return { ... }

@pytest.fixture
def example_event(form_data):
    return {... 'data': form_data, ... }
Run Code Online (Sandbox Code Playgroud)

但是当我运行pytest时,它抱怨 fixture 'form_data' not found

我是pytest的新手,所以我什至不确定这是否可行?

小智 23

对的,这是可能的。

如果您在 1 个文件中包含测试和所有装置: test.py

import pytest

@pytest.fixture
def foo():
    return "foo"

@pytest.fixture
def bar(foo):
    return foo, "bar"

def test_foo_bar(bar):
    expected = ("foo", "bar")
    assert bar == expected
Run Code Online (Sandbox Code Playgroud)

然后运行pytest test.py成功!!!

======================================= test session starts ========================================
platform darwin -- Python 3.6.8, pytest-4.3.0
collected 1 item                                                                                   

test.py .                                                                                    [100%]

===================================== 1 passed in 0.02 seconds =====================================

Run Code Online (Sandbox Code Playgroud)

但是,如果您将灯具放在不同的文件中: test_foo_bar.py

from test import bar

def test_foo_bar(bar):
    expected = ("foo", "bar")
    assert bar == expected
Run Code Online (Sandbox Code Playgroud)

并运行pytest test_foo_bar.py期望(就像我所做的那样)只导入bar夹具就足够了,因为在导入时它已经执行了foo夹具然后你会得到你得到的错误。

======================================= test session starts ========================================
platform darwin -- Python 3.6.8, pytest-4.3.0
collected 1 item                                                                                   

test2.py E                                                                                   [100%]

============================================== ERRORS ==============================================
__________________________________ ERROR at setup of test_foo_bar __________________________________
file .../test_foo_bar.py, line 3
  def test_foo_bar(bar):
.../test.py, line 7
  @pytest.fixture
  def bar(foo):
E       fixture 'foo' not found
>       available fixtures: TIMEOUT, bar, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, once_without_docker, pytestconfig, record_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

.../test.py:7
===================================== 1 error in 0.03 seconds ======================================

Run Code Online (Sandbox Code Playgroud)

要解决此问题,还要footest_foo_bar.py模块中导入夹具。

  • 值得一提的是:pytest支持`conftest.py`文件来跨文件共享fixture,请参阅https://docs.pytest.org/en/6.2.x/fixture.html#conftest-py-sharing-fixtures-across-multiple - 文件 (2认同)