Pytest中跳过测试的5种方法及模块级跳过技巧
本文详细介绍在Pytest中跳过测试的多种实现方式,包括使用@pytest.mark.skip()和@pytest.mark.skipif()装饰器、自定义标记变量以及通过pytest.skip()函数在代码内部跳过。此外,还讲解了如何利用pytestmark实现模块级跳过,以及在PyCharm中运行多个测试文件的具体操作,帮助开发者灵活控制测试执行流程。
使用skip和skipif装饰器跳过测试
第一种方法是使用@pytest.mark.skip()装饰器来跳过特定的测试函数。
该装饰器接受一个可选参数reason,用于指定跳过测试的具体原因。
import pytest
@pytest.mark.skip(reason="no reason")
def test_01():
print("---用例a执行---")
class TestCase():
@pytest.mark.skip(reason="no reason")
def test_02(self):
print("---用例b执行---")
def test_03(self):
print("---用例c执行---")
执行上述代码后的输出结果如下:
test_fixture2.py ss---用例c执行---
第二种方法是利用@pytest.mark.skipif()装饰器,当满足指定的condition条件时,跳过测试函数的执行。
此方法需要传入condition参数作为判断条件,同样支持可选的reason参数。如果在一个测试函数上应用了多个skipif标签,只要满足其中任意一个跳过条件,该测试函数就会被跳过。
import pytest
def test_01():
print("---用例a执行---")
class TestCase():
#当多个@pytest.mark.skipif()标签时,若满足一个,则跳过测试函数
@pytest.mark.skipif(condition='a' >= 'b', reason="no reason")
@pytest.mark.skipif(condition='a' <= 'b', reason="no reason")
def test_02(self):
print("---用例b执行---")
def test_03(self):
print("---用例c执行---")
相关代码执行后的输出结果为:
test_fixture2.py ---用例a执行--- .s---用例c执行---
自定义标记与内部跳过方法
第三种方法是自定义@pytest.mark.skip()标记。
可以通过赋值语句创建自定义标记,例如:myskip = pytest.mark.skip() 或 myskip = pytest.mark.skipif(condition=...)。
在装饰测试函数时,直接使用这个变量代替原有的标签即可,例如:@myskip。
import pytest
# myskip = pytest.mark.skip()
myskip = pytest.mark.skipif(condition=2>1, reason="no reason")
@myskip
def test_01():
print("---用例a执行---")
class TestCase():
@myskip
def test_02(self):
print("---用例b执行---")
def test_03(self):
print("---用例c执行---")
运行上述自定义标记代码后的输出结果如下:
test_fixture2.py ss---用例c执行---
第四种方法是通过调用pytest.skip()函数来跳过测试函数。
import pytest
def test_01():
pytest.skip(msg="no reason")
print("---用例a执行---")
class TestCase():
def test_02(self):
pytest.skip()
print("---用例b执行---")
def test_03(self):
print("---用例c执行---")
该方法通常在测试函数内部调用,其输出结果如下:
test_fixture2.py ss---用例c执行--
跳过测试类与模块
第五种方法是跳过整个测试类。
跳过测试类的操作与跳过单个测试方法类似,只需使用@pytest.mark.skip()或@pytest.mark.skipif()这两个装饰器来装饰整个测试类即可。
import pytest
myskip = pytest.mark.skip(reason="no reason")
def test_01():
print("---用例a执行---")
@myskip
class TestCase():
def test_02(self):
print("---用例b执行---")
def test_03(self):
print("---用例c执行---")
跳过测试类后的输出结果如下:
test_fixture2.py ---用例a执行---
第六种方法是跳过整个模块。
这可以通过使用名为pytestmark的变量来实现,将其赋值为相应的标记即可。注意,该变量名不可更改。
import pytest
pytestmark = pytest.mark.skip(condition=2>1, reason='no reason')
def test_01():
print("---用例a执行---")
class TestCase():
def test_02(self):
print("---用例b执行---")
def test_03(self):
print("---用例c执行---")
应用模块级跳过后的输出结果为:
test_fixture2.py sss
在IDE中运行多个测试文件
第七种方法是在PyCharm中运行多个测试文件。
只需在命令行参数中依次列出需要运行的文件名,并用逗号分隔即可,无需使用列表或元组等复杂数据结构。
if __name__ == "__main__":
pytest.main(['-s', 'test_fixture1.py', 'test_fixture2.py'])
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













