Pytest学习(七) - skip、skipif的使用html
做为一个java党,我仍是以为pytest和testng很像,有时候真的会感受到代码语言在某种程度上是相通的,那么今天来讲说这两个知识点。java
skip和skipif,见名知意,就是跳过测试呗,直白的说就是用于不想执行的代码,标记后,标记的代码不执行。windows
skip的用法
使用示例:@pytest.mark.skip(reason="不想执行的缘由,执行时会输出reason内容")ide
一、标记在函数方法上
示例代码以下:函数
# 标记在函数上 @pytest.mark.skip(reason="标记在函数上,被标记函数不会被执行!!") def test_case2(): print("我是测试用例2,但我不会执行")
运行结果以下:学习
二、标记在类中的函数方法上
示例代码以下:测试
class TestClass1(object): def test_case3(self): print("我是用例3") # 标记在类中的函数上 @pytest.mark.skip(reason="标记在类中的函数上,一样也不会执行哦!") def test_case4(self): print("我是测试用例4,但我不会执行")
运行结果以下:3d
三、标记在类上
示例代码以下:code
@pytest.mark.skip(reason="标记在类上,整个类及类中的方法都不会执行!") class TestClass2(object): def test_case5(self): print("我是用例5")
运行结果以下:orm
小结:
@pytest.mark.skip 能够加在函数上,类上,类方法上
若是加在类上面,类里面的全部测试用例都不会执行
四、在测试用例执行期间强制跳过
以简单的for循环为例,执行到第三个的时候,跳出,示例代码以下:
def test_case6(): for i in range(50): print(f"输出第 【{i}】个数") if i == 3: pytest.skip("我跑不动了,不输出了")
运行结果以下:
总结:
能够理解为这时的跳过测试就和循环的break同样,这时再也不用注解的形式了。
五、在模块级别跳过测试
语法:pytest.skip(msg="",allow_module_level=False),当 allow_module_level=True 时,能够设置在模块级别跳过整个模块,示例代码以下:
# -*- coding: utf-8 -*- # @Time : 2020/11/12 20:30 # @Author : longrong.lang # @FileName: test_skip.py # @Software: PyCharm # @Cnblogs :https://www.cnblogs.com/longronglang import sys import pytest if sys.platform.startswith("win"): pytest.skip("当 allow_module_level=True 时,能够设置在模块级别跳过整个模块",allow_module_level=True) @pytest.fixture(autouse=True) def dataTable(): print("数据初始化成功") def test_case1(): print("我是用例1")
运行结果以下:
六、但愿有条件地跳过某些测试用例
语法:@pytest.mark.skipif(条件表达式, reason="")
示例代码以下:
@pytest.mark.skip(sys.platform.startswith("win"),reason="windows系统不执行哦") def test_case7(): print("我是用例6")
运行结果以下:
七、跳过标记的使用
好处
方便用例的统一管理维护
可在不一样模块标记
须要将 pytest.mark.skip 和 pytest.mark.skipif 赋值给一个标记变量,用变量(注解变量)进行标记,示例代码以下:
skip = pytest.mark.skip("skip的标记变量,标记的函数或类不执行") skipif = pytest.mark.skipif("skipif的标记变量,标记的函数或类不执行") @skip def test_case8(): print("测试用例8") class TestClass(object): @skipif def test_case9(self): print("测试用例9")
运行结果以下:
八、缺乏某些导入跳过的测试
语法:pytest.importorskip( modname: str, minversion: Optional[str] = None, reason: Optional[str] = None )
参数列表
importskip = pytest.importorskip("importskip", minversion="0.3",reason="此处是导入失败,跳过的测试") @importskip def test_10(): print('测试用例10')
运行结果以下:
系列参考文章:
https://www.cnblogs.com/poloyy/category/1690628.html
EOF
本文做者:久曲建的测试窝
本文连接:http://www.javashuo.com/article/p-scuxpmtv-nv.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客全部文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:若是您以为文章对您有帮助,能够点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
优秀不够,你是否无可替代