跳过
# 直接跳过
@pytest.mark.skip(reason="The test case)
def test_one():
print(“test_one”)
# 条件跳过 condition 为跳过条件,例:1==1 跳过 1!=1时执行
@pytest.mark.skipif(condition="1==1", reason='The test case')
def test_7():
print("test_7")
if __name__ == "__main__":
pytest.main(["-s", "test.py"])
参数化
1、传一个参数时
@pytest.mark.parametrize("a", [1])
def test_2(a):
if a < 2:
print(a)
# 值多时,会循环执行所有
@pytest.mark.parametrize("a", [1, 2, 3])
def test_2(a):
if a < 2:
print(a)
2、多个参数时
@pytest.mark.parametrize("a, b, c", [[1, 2, 3], [4, 5,6], [7, 8, 9]])
def test_2(a, b, c):
if a < b:
print('\n-----------------')
print(a, b)
elif a < c:
print(a + c)
elif a+b < c:
print(c)
if __name__ == "__main__":
pytest.main(["-s", "test_new.py"])
或
value = [[1, 2, 3], [4, 5,6], [7, 8, 9]]
@pytest.mark.parametrize("a, b, c", value)
def test_2(a, b, c):
if a < b:
print('\n-----------------')
print(a, b)
elif a < c:
print(a + c)
elif a+b < c:
print(c)
if __name__ == "__main__":
pytest.main(["-s", "test_new.py"])
条件判断 “预期失败”
# condition 条件相等判断失败
@pytest.mark.xfail(condition='1==1', reason="The test case")
def test_1():
print("\n-------")
# condition 条件不等判断成功
@pytest.mark.xfail(condition='1==2', reason="The test case")
def test_2():
print("\n-------")
数据继承
@pytest.fixture()
def test1():
a = '测试数据的继承1'
return a
def test2(test1, test3):
print(test1, test3)
@pytest.fixture()
def test3():
return "测试数据的继承2"
if __name__ == "__main__":
pytest.main(["-s", "test_new.py"])
执行顺序设定
安装插件: pytest-ordering
# 全是正数的话,越小越先执行,比如order=3, 2, 1的话,order为1的先执行
# 都是负数的话,值越小越先执行
# 0和负数的话,0先执行,剩下的数值越小越先执行;0和正数的话,0先执行,剩下的数越小越先执行
# 0 正数 负数,0先执行,正数再执行,负数最后
# 顺序:0 ---> 较小的正数 ---> 较大的正数 ---> 较小的负数 ---> 较大的负数
@pytest.mark.run(order=3)
def test1():
print('\n测试数据3')
@pytest.mark.run(order=2)
def test2():
print('\n测试数据2')
@pytest.mark.run(order=4)
def test3():
print('\n测试数据4')
if __name__ == "__main__":
pytest.main(["-s", "test_new.py"])
失败后二次执行
安装插件:pytest-rerunfailures
# reruns 设置失败后反复执行的次数
# reruns_delay 设置每次执行间隔的时间
# 执行成功,反复停止
@pytest.mark.flaky(reruns=5, reruns_delay=1)
def test3():
print("\n执行")
assert 1 == 2
if __name__ == "__main__":
pytest.main(["-s", "test_new.py"])