2)pytest用例运行及skip、xfail的使用

用例运行级别

模块级(setup_module/teardown_module):全局的,整个.py模块开始前和结束后调用一次
函数级(setup_function/teardown_function):只对函数用例生效(不在类内),每个函数级用例开始和结束时调用一次
类级(setup_class/teardown_class):只在类中前后运行一次(在类中)
方法级(setup_method/teardown_method):开始于方法始末(在类中)
类里面的(setup/teardown):运行在调用方法的前后

类中运行顺序:setup_class>setup_method>setup>用例>teardown>teardown_method>teardown_class

skip跳过用例(无条件跳过)

使用场景

1)调试时不想运行这个用例

2)标记无法在某些平台上运行的测试功能

3)当前的外部资源不可用时跳过(如果测试数据是从数据库中取到的,连接数据库的功能如果返回结果未成功就不执行,跳过,因为执行也都报错)

4)在某些版本中执行,其他版本中跳过

使用方法

1)使用跳过装饰器,并传递一个可选的原因

@pytest.mark.skip(reason="no way of currently testing this")
def test_the_unknown():
    ...

2)pytest.skip(reason):在测试执行或设置期间强制跳过

def test_function():
    if not valid_config():
        pytest.skip("unsupported configuration")

3)pytest.skip(reason,allow_module_level=True):跳过整个模块级别

import pytest
if not pytest.config.getoption("--custom-flag"):
    pytest.skip("--custom-flag is missing, skipping tests", allow_module_level=True)

skipIf跳过用例(有条件跳过)

1)装饰器(标记测试的实例在python3.6之前的解释器上运行时要跳过的函数)

import sys
@pytest.mark.skipif(sys.version_info < (3,6),
reason="requires python3.6 or higher")
def test_function():
    ...

2)模块之间共享skipif标记

# content of test_mymodule.py
import mymodule
minversion = pytest.mark.skipif(mymodule.__versioninfo__ < (1,1),
reason="at least mymodule-1.1 required")
@minversion
def test_function():
    ...

在另一个模块中重复使用它

# test_myothermodule.py
from test_mymodule import minversion
@minversion
def test_anotherfunction():
    ...

Skip类或模块

在类中使用skipIf标记,条件为True时,将为该类的每个测试方法生成跳过结果

@pytest.mark.skipif(sys.platform == 'win32',
reason="does not run on windows")
class TestPosixCalls(object):
    def test_function(self):
        "will not be setup or run under 'win32' platform"

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

# test_module.py
pytestmark = pytest.mark.skipif(...)

猜你喜欢

转载自www.cnblogs.com/crystal1126/p/12221168.html