基于此堆栈溢出: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,所以我甚至不确定这是否可能?
发布于 2019-04-01 20:00:31
是的,这是可能的。
如果测试和所有的fixture都在一个文件中: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 =====================================但是如果您将这些fixture放在一个不同的文件中: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 fixture就足够了,因为在导入时它已经执行了foo fixture,然后就会得到错误。
======================================= 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 ======================================要解决这个问题,还需要在test_foo_bar.py模块中导入foo装置。
https://stackoverflow.com/questions/47402435
复制相似问题