如果您需要在测试之前和之后执行代码,可以在fixture https://docs.pytest.org/en/latest/fixture.html。例子:
import pytest
@pytest.fixture
def wrapper(request):
print('\nhere I am before the test')
print('test function name is', request.node.name)
print('test file is located under', request.node.fspath)
yield
print('\nand here I am after the test')
@pytest.mark.usefixtures('wrapper')
def test_spam_good():
assert True
@pytest.mark.usefixtures('wrapper')
def test_spam_bad():
assert False
正如您所看到的,这比编写自定义装饰器要强大得多。作为pytest
非常擅长围绕测试进行元编程,您可能需要的很多东西已经存在,您只需要知道如何访问它即可。pytest docs https://docs.pytest.org/en/latest/reference.html包含许多适合初学者的示例和食谱。
如果您需要夹具中的测试结果,文档中有一个方法:在夹具中提供测试结果信息 https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures。创建文件conftest.py
在项目根目录中包含以下内容:
import pytest
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
# execute all other hooks to obtain the report object
outcome = yield
rep = outcome.get_result()
# set a report attribute for each phase of a call, which can
# be "setup", "call", "teardown"
setattr(item, "rep_" + rep.when, rep)
现在您可以通过以下方式访问测试结果request
自定义装置中的装置:
@pytest.fixture
def something(request):
yield
# request.node is an "item" because we use the default
# "function" scope
if request.node.rep_setup.failed:
print("setting up a test failed!", request.node.nodeid)
elif request.node.rep_setup.passed:
if request.node.rep_call.failed:
print("executing test failed", request.node.nodeid)