pytest笔记(四)-skip和xfail

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结果出现

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值