如果不申报my_fixture
为一个夹具,那么测试将无法将其用作夹具:
import pytest
def my_fixture():
data = {'x': 1, 'y': 2, 'z': 3}
return data
def test_my_fixture(my_fixture):
assert my_fixture['x'] == 1
这个脚本会导致错误:
def test_my_fixture(my_fixture):
E fixture 'my_fixture' not found
> available fixtures: cache, capfd, capsys, doctest_namespace, monkeypatch, pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory
> use 'pytest --fixtures [testpath]' for help on them.
灯具的目的是测试(S)之前准备的东西。然后杀死它。而不是测试的一部分(例如在日志记录,报告,异常处理方式等方面)。这是一种先决条件,由别的东西创造,并且只是给了测试。
如果您只是将其声明为函数,并将其用作函数,则它是函数,而不是夹具。它的失败成为测试的失败,而不是一般的框架运行。
考虑这个例子:
import pytest
@pytest.fixture()
def my_fixture():
data = {'x': 1, 'y': 2, 'z': 3}
print('prepare')
yield data
print('destroy')
def test_my_fixture(my_fixture):
print('test it')
assert my_fixture['x'] == 1
此外,在此例尝试取消对提高线,看看其中的差别。这将是错误与失败。如何解释和处理测试结果(例如由开发人员,QA工程师或分析测试结果的人员)是至关重要的。
import pytest
@pytest.fixture()
def my_fixture():
print('prepare')
# raise Exception('Oops')
yield None
print('destroy')
def test_my_fixture(my_fixture):
# raise Exception('Booms!')
print('test it')
在夹具:
======================================= test session starts ========================================
collected 1 item
t.py E
============================================== ERRORS ==============================================
________________________________ ERROR at setup of test_my_fixture _________________________________
@pytest.fixture()
def my_fixture():
data = {'x': 1, 'y': 2, 'z': 3}
print('prepare')
> raise Exception('Oops')
E Exception: Oops
t.py:7: Exception
===================================== 1 error in 0.03 seconds ======================================
在测试或从测试调用的任何功能:
======================================= test session starts ========================================
collected 1 item
t.py F
============================================= FAILURES =============================================
_________________________________________ test_my_fixture __________________________________________
my_fixture = {'x': 1, 'y': 2, 'z': 3}
def test_my_fixture(my_fixture):
> raise Exception('Booms!')
E Exception: Booms!
t.py:12: Exception
===================================== 1 failed in 0.03 seconds =====================================
还要注意的是,灯具有范围:会话,模块功能。在一个简短的例子中很难演示,但在这种情况下,夹具将在该范围内的多次测试中准备和销毁一次(通常只有一次)。这对于重量级装置很重要,例如数据库预填充。这样的灯具通常驻留在目录结构中的conftest.py
伪插件中(注意:这不是要导入的常规模块!至少按设计进行)。
坚实的回应。谢谢 – imagineerThat