[英]How to replace test functions in py.test while collecting tests?
我有一個帶有測試功能的模塊,我想編寫conftest.py
文件,以在收集階段之后和測試運行之前修飾模塊中的所有功能。 而且我不想使用測試功能來編輯模塊。 我這樣嘗試過:
def test_foo ():
assert 1 == 42
def pytest_generate_tests (metafunc):
def test_bar ():
assert 1 == 2
metafunc.function = test_bar
運行測試時,我得到以下信息:
==================================== FAILURES =====================================
____________________________________ test_foo _____________________________________
def test_foo ():
> assert 1 == 42
E assert 1 == 42
但是我期望斷言錯誤大約為1 == 2
。
如果要在測試前運行某個功能,請定義一個夾具並將夾具名稱用作測試參數。
import pytest
@pytest.fixture
def fixture1():
assert 1 == 2
def test_foo(fixture1):
assert 1 == 42
輸出:
@pytest.fixture
def fixture1():
> assert 1 == 2
E assert 1 == 2
如果要在每次測試之前運行某個功能,請使用autouse=True
定義一個夾具 。 我想這就是你想要的。
import pytest
@pytest.fixture(autouse=True)
def fixture1():
assert 1 == 2
def test_foo():
assert 1 == 42
輸出:
@pytest.fixture(autouse=True)
def fixture1():
> assert 1 == 2
E assert 1 == 2
如果要使用自定義測試裝飾器 ,請使用標准裝飾器語法。
def my_test_decorator(test):
def wrapper():
assert 1 == 2
return wrapper
@my_test_decorator
def test_foo():
assert 1 == 42
輸出:
def wrapper():
> assert 1 == 2
E assert 1 == 2
我只需要替換pytest項目的runtest
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.