夹具的pytest夹具,未找到

时间:2017-11-20 22:48:22

标签: pytest

基于此stackoverflow:pytest fixture of fixtures

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

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

@pytest.fixture
def example_event(form_data):
    return {... 'data': form_data, ... }

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

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

1 个答案:

答案 0 :(得分:1)

是的,有可能。

如果您将测试和所有灯具放在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

先运行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 =====================================

但是,如果您将灯具放在另一个文件中:test_foo_bar.py

from test import bar

def test_foo_bar(bar):
    expected = ("foo", "bar")
    assert bar == expected

并运行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 ======================================

要解决此问题,请同时将foo固定装置导入test_foo_bar.py模块中。

相关问题