基于此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)
要解决此问题,还要foo
在test_foo_bar.py
模块中导入夹具。
归档时间: |
|
查看次数: |
2146 次 |
最近记录: |