Skip and xfail
skip 意为着你的测试只有在满足某些条件时才能通过,否则pytest应该跳过运行test
pytest计数并分别列出skip和xfail的测试,默认情况下,不会显示skipped或xfailed测试的详细信息,你可以使用-r选项去查看
Skipping the function
跳过test最简单的方式就是使用skip装饰器,并传递一个reason参数
@pytest.mark.skip(reason='skip function')
def test_1():
print("1")
也可以在test运行期间调用pytest.skip(reason):
def test_function():
a = 0
if a == 0:
pytest.skip("skip function")
skipif
如果你想根据一些条件来判断是否跳过, 可以使用sipif
import sys, pytest
@pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python3.9 or higher")
def test_function():
print("skip")
当里面的条件为true时,这个test会被跳过,同时可以使用-xs查看在test summary中查看reason
如果skip在class之上,那么条件为true的话,会跳过整个class:
@pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python3.7 or higher")
class TestCase:
def test_2(self):
print("2")
def test_3(self):
print('3')
条件为true,那么会为class里面每个test都产生一个skip结果
xFail
你可以使用xfail标记一个期望失败的test
@pytest.mark.xfail(reason='xfail')
def test_function():
print("xfail")
可以使用-rX查看test summar中的结果, reason也会在其中输出
也可以在test里面标记一条失败的test
def test_function():
a = 0
if a == 0:
pytest.xfail(reason="xfail")
print("ok")
调用pytest.xfail()之后,不会在执行其他的代码
如果想根据条件来进行xfail,可以判断条件放在参数的第一位, 条件为true时, 执行xfail:
@pytest.mark.xfail(1 == 1,reason='skip function')
def test_1():
print("1")
XFAIL和XPASS默认是不会让test出现fail,你可以使用strict参数修改这个:
@pytest.mark.xfail(strict=False)
def test_1():
print("1")
test_1将会以XPASS结果出现, 如果strict=True, test_1将会以fail结果出现