Pytest - 测试用例管理及运行管理

跳过测试用例

常用的标记有以下几种:

  • skip:只有当某些条件满足时,才执行测试用例,否则跳过整个测试用例的执行
  • xfail:因为一个确切的原因,我们知道这个用例会失败。例如阻塞于某个已知的BUG

pytest默认不显示skip和xfail用例的详细信息,我们可以通过-r选项来自定义这种行为

具体的规则如下:

  • f:failed
  • E:Error
  • s: Skipped
  • x: xfailed
  • X: Xpassed
  • p: passed
  • P: Passed with output
  • a: all except passed(p/P)
  • A: All

@pytest.mark.skip 和 @pytest.mark.skipif 装饰器

@pytest.mark.skip(reason="原因") :无条件跳过

@pytest.mark.skipif(条件, reason="原因"): 条件满足时跳过


"""演示 pytest 跳过方法的使用"""
import pytest

version = 25

class TestDemo:

    def test_demo1(self):
        print("this is demo1")

    @pytest.mark.skip(reason="无条件跳过")
    def test_demo2(self):
        print("this is a demo2")

    @pytest.mark.skipif(version >= 25, reason="xxxxxxxxx")
    def test_demo2(self):
        print("this is a demo2")

执行后结果如下:

============================= test session starts =============================
collecting ... collected 3 items

06_pyest_skip.py::TestDemo::test_demo1 PASSED                            [ 33%]this is demo1

06_pyest_skip.py::TestDemo::test_demo2 SKIPPED (无条件跳过)              [ 66%]
Skipped: 无条件跳过

06_pyest_skip.py::TestDemo::test_demo3 SKIPPED (xxxxxxxxx)               [100%]
Skipped: xxxxxxxxx
======================== 1 passed, 2 skipped in 0.01s =========================

叠加@pytest.mark.skipif


import pytest

version = 25
a = 10


class TestDemo:

    def test_demo1(self):
        print("this is demo1")

    @pytest.mark.skipif(version == 25, reason="xxxxxxxxx")  # 真
    @pytest.mark.skipif(a < 20, reason='a < 20')  # 真
    def test_demo2(self):
        print("this is a demo2")

运行结果:

PS E:\PyProject\pytestDemo> pytest -sv
======================================================================= test session starts =======================================================================
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0 -- e:\pyproject\pytestdemo\venv\scripts\python.exe
cachedir: .pytest_cache                                                                                       
rootdir: E:\PyProject\pytestDemo                                                                              
collected 2 items                                                                                                                                                   

test_scripts/test_parm.py::TestDemo::test_demo1 this is demo1
PASSED
test_scripts/test_parm.py::TestDemo::test_demo2 SKIPPED (a < 20)

================================================================== 1 passed, 1 skipped in 0.01s =================================================================== 

总结:

  • 当一个用例指定了多个skipif,只要满足其中一个就可以跳过
  • 当多个skipif都满足时,以最后一个最终的结果

pytest.skip() 方法

import pytest

version = 25

class TestDemo:

    def test_demo1(self):
        print("this is demo1")

    def test_demo2(self):
        pytest.skip(msg='无条件跳过')

    def test_demo3(self):
        if version >= 25:
            pytest.skip(msg='version >= 25')

运行结果:

PS E:\PyProject\pytestDemo> pytest -v                   
======================================================================= test session starts =======================================================================
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0 -- e:\pyproject\pytestdemo\venv\scripts\python.exe
cachedir: .pytest_cache
rootdir: E:\PyProject\pytestDemo
collected 3 items                                                                                                                                                   

test_scripts/test_parm.py::TestDemo::test_demo1 PASSED                                                                                                       [ 33%] 
test_scripts/test_parm.py::TestDemo::test_demo2 SKIPPED (无条件跳过)                                                                                         [ 66%] 
test_scripts/test_parm.py::TestDemo::test_demo3 SKIPPED (version >= 25)                                                                                      [100%] 

======================================================================== warnings summary ========================================================================= 
test_scripts/test_parm.py::TestDemo::test_demo2
  E:\PyProject\pytestDemo\test_scripts\test_parm.py:11: PytestRemovedIn8Warning: pytest.skip(msg=...) is now deprecated, use pytest.skip(reason=...) instead        
    pytest.skip(msg='无条件跳过')

test_scripts/test_parm.py::TestDemo::test_demo3
  E:\PyProject\pytestDemo\test_scripts\test_parm.py:15: PytestRemovedIn8Warning: pytest.skip(msg=...) is now deprecated, use pytest.skip(reason=...) instead        
    pytest.skip(msg='version >= 25')

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html

忽略警告需要加入 --disable-warnings参数:
pytest -s -v --disable-warnings

pytest.skip还有一个参数:allow_module_level=True,代表模块级别的跳过

tips:不存在pytest.skipif()方法,而是pytest.mark.skipif()

"""演示 pytest 跳过方法的使用"""
# test_parm.py

import pytest

version = 25

if version >= 25:
    pytest.skip(msg='version >= 25', allow_module_level=True)

class TestDemo:

    def test_demo1(self):
        print("this is demo1")

    def test_demo2(self):
        print('test_demo2 run')

    def test_demo3(self):
        print('test_demo3 run')

运行结果:

PS E:\PyProject\pytestDemo> pytest -v --disable-warnings
======================================================================= test session starts =======================================================================
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0 -- e:\pyproject\pytestdemo\venv\scripts\python.exe
cachedir: .pytest_cache
rootdir: E:\PyProject\pytestDemo
collected 1 item / 1 skipped                                                                                                                                        

test_scripts/test_a.py::test_one PASSED                                                                                                                      [100%] 

============================================================= 1 passed, 1 skipped, 1 warning in 0.01s ============================================================= 

通过结果发现该模块得用例一个都没有执行,用例收集阶段不会统计该模块的用例,collected 1 item, 是收集了test_a.py的用例信息

pytest.importorskip() 方法

引入失败时跳过

当引入某个模块失败或者引入的版本不符合时,我们可以跳过后续部分的执行

import pytest

return_module = pytest.importorskip('requests')

if return_module:
    print(f'var type:{type(return_module)}',return_module)

else:
    print(f'return_module is None')

def test_two():
    print('test_two run')

未安装requests模块前:

PS E:\PyProject\pytestDemo> pytest -rA -s
======================================================================= test session starts =======================================================================
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0
rootdir: E:\PyProject\pytestDemo
collected 0 items / 1 skipped                                                                                                                                       

===================================================================== short test summary info ===================================================================== 
SKIPPED [1] test_scripts\test_importtoskip.py:7: could not import 'requests': No module named 'requests'
======================================================================= 1 skipped in 0.01s ======================================================================== 

安装requests模块后:

PS E:\PyProject\pytestDemo> pytest -rA -s
======================================================================= test session starts =======================================================================
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0
rootdir: E:\PyProject\pytestDemo
collecting ... var type:<class 'module'> <module 'requests' from 'e:\\pyproject\\pytestdemo\\venv\\lib\\site-packages\\requests\\__init__.py'>
collected 1 item

test_scripts\test_importtoskip.py test_two run
.

============================================================================= PASSES ============================================================================== 
===================================================================== short test summary info ===================================================================== 
PASSED test_scripts/test_importtoskip.py::test_two
======================================================================== 1 passed in 0.07s ======================================================================== 

模块版本不符合时跳过

requests 安装版本2.28.2

import pytest

result = pytest.importorskip("requests", minversion='2.28.3')
print(result)

def test_one():
    print('test_one run')

运行结果:

PS E:\PyProject\pytestDemo> pytest -rA -s
======================================================================= test session starts ======================================================================= 
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0
rootdir: E:\PyProject\pytestDemo
collected 0 items / 1 skipped

===================================================================== short test summary info ===================================================================== 
SKIPPED [1] test_scripts\test_importtoskip.py:10: module 'requests' has __version__ '2.28.2', required is: '2.28.3'
======================================================================= 1 skipped in 0.07s ======================================================================== 

minversion='2.28.3 修改为:minversion='2.28.2

import pytest

result = pytest.importorskip("requests", minversion='2.28.2')
print(result)

def test_one():
    print('test_one run')

运行结果:

PS E:\PyProject\pytestDemo> pytest -rA -s
======================================================================= test session starts =======================================================================
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0
rootdir: E:\PyProject\pytestDemo                           
collecting ... <module 'requests' from 'e:\\pyproject\\pytestdemo\\venv\\lib\\site-packages\\requests\\__init__.py'>
collected 1 item

test_scripts\test_importtoskip.py test_one run
.

============================================================================= PASSES ============================================================================== 
===================================================================== short test summary info ===================================================================== 
PASSED test_scripts/test_importtoskip.py::test_one
======================================================================== 1 passed in 0.07s ======================================================================== 

两个不同模块共享pytest.mark.skipif() 方法标记

test_module_1/test_module_1.py

import datetime
import pytest


date = datetime.datetime.now().strftime('%Y-%m-%d')
print(date)

mark = pytest.mark.skipif(date=='2023-01-19' ,reason='date == 2023-01-19')
# mark = pytest.mark.skipif(date=='2023-01-18' ,reason='date == 2023-01-18')

@mark
def test_module_1():
    print('test_module_1 run')

test_module_2/test_module_2.py

from test_module_1.test_module_1 import  mark

@mark
def test_one():
    print('test_module_2 - test_one run')

运行结果:

PS E:\PyProject\pytestDemo> pytest -rA -s
======================================================================= test session starts =======================================================================
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0
rootdir: E:\PyProject\pytestDemo
collecting ... 2023-01-19
PASSED test_scripts/test_importtoskip.py::test_two
SKIPPED [1] test_module_1\test_module_1.py:15: date == 2023-01-19
SKIPPED [1] test_module_2\test_module_2.py:8: date == 2023-01-19
================================================================== 1 passed, 2 skipped in 0.08s =================================================================== 
posted @ 2023-01-19 10:54  chuangzhou  阅读(228)  评论(0编辑  收藏  举报