首页 > 其他 > 详细

4.pytest之skip跳过

时间:2020-09-29 13:10:20      阅读:28      评论:0      收藏:0      [点我收藏+]

pytest.mark.skip可以用于标记某些不想执行的测试用例。

创建test_04.py文件,内容如下

# filename:test_04.py
import pytest

class TestDemo01():

    @pytest.mark.skip(reason=我要跳过)
    def test_01(self):
        print(\ntest_01方法执行)
        assert 1 == 1

    def test_02(self):
        print(\ntest_02方法执行)
        assert 1 == 1

    def test_03(self):
        print(\ntest_03方法执行)
        assert 1 == 1

 

这样,被标记的方法test_01将不会被执行,也可以在代码执行过程中直接调用pytest.skip(reason)来强制跳过,我们修改test_02方法如下

    def test_02(self):
        if 2 > 1:
            pytest.skip("2>1才跳过")
        print(‘\ntest_02方法执行‘)
        assert 1 == 1

执行 pytest -s test_04.py命令,你会得到如下结果

============================= test session starts =============================
platform win32 -- Python 3.7.1, pytest-6.0.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\study\auto-pytest
collected 3 items

test_04.py ss
test_03方法执行
.

======================== 1 passed, 2 skipped in 0.06s =========================

还可以使用pytest.skip(reason, allow_module_level=True)来跳过整个module,只需要在顶部加入:

if 2>1:
    pytest.skip(跳过整个模块,allow_module_level=True)

 

这样,只要条件为True,那么整个模块下的测试用例将不会执行。

skipif

你可以使用skipif来在某些条件下跳过测试。 下面是一个在检查python的版本是否高于3.6的示例:

class TestDemo01():

    @pytest.mark.skipif(sys.version_info > (3, 6), reason=python版本大于3.6就跳过)
    def test_01(self):
        print(\ntest_01方法执行)
        assert 1 == 1

    def test_02(self):
        print(\ntest_02方法执行)
        assert 1 == 1

 

如果python安装版本大于3.6,则test_01方法不会执行。

你可以在各个模块中共享skipif标记,比如有下面的模块定义:

import pytest
import sys

maxversion = pytest.mark.skipif(sys.version_info > (3, 6), reason=python版本大于3.6就跳过)

class TestDemo01():

    @maxversion
    def test_01(self):
        print(\ntest_01方法执行)
        assert 1 == 1

    def test_02(self):
        print(\ntest_02方法执行)
        assert 1 == 1

 

使用定义好的maxversion作为方法装饰器,则对应的用例将不会执行。

如果其他模块也会用到相同条件的跳过,可以从别的模块导入,你可以这样写

# filename: test_skip.py
from test_04 import maxversion

@maxversion
def test_function():
    .....

 

跳过模块或者class中的所有测试

你可以在class上使用skipif标记:

@pytest.mark.skipif(sys.version_info > (3, 6), reason=python版本大于3.6就跳过)
class TestDemo01():

    def test_01(self):
        print(test_01被执行)

 

如果要跳过模块的所有测试功能,可以在全局级别使用pytestmark名称

pytestmark = pytest.mark.skipif(sys.version_info > (3, 6), reason=python版本大于3.6就跳过)

 

4.pytest之skip跳过

原文:https://www.cnblogs.com/easy-test/p/13749081.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!