pytest总结

1、xunit-style setup

相比unittest只有setUp()和tearDown(),pytest则拥有module级别、class级别、method和function级别的setup()和teardown(),能够更好地控制用例的执行。

1.1 setup_module()和teardown_module

如果在一个.py文件中有多个测试函数和测试类,并且只想执行执行一次setup和teardown,则可选择在该文件中使用setup_module和teardown_module。
ps:pytest3.0中,“_module”可省略

def setup_module(module):
    """ setup any state specific to the execution of the given module."""


def teardown_module(module):
    """ teardown any state that was previously setup with a setup_module
    method.
    """
1.2 setup_class和teardown_class

同样地,如果一个测试类中有多个测试方法,并且只想执行一次setup和teardown,则可选择在该类中使用setup_class和teardown_class。

@classmethod
def setup_class(cls):
    """ setup any state specific to the execution of the given class (which
    usually contains tests).
    """


@classmethod
def teardown_class(cls):
    """ teardown any state that was previously setup with a call to
    setu
1.3 setup_method和teardown_method

同理,如果希望类中每个方法执行前后都执行setup和teardown,则在类中使用setup_method和teardown_method。
ps:pytest3.0后,“_method”可省略

def setup_method(self, method):
    """ setup any state tied to the execution of the given method in a
    class.  setup_method is invoked for every test method of a class.
    """


def teardown_method(self, method):
    """ teardown any state that was previously setup with a setup_method
    call.
    """
1.4 setup_funciton和teardown_function

如果你直接在.py文件中定义测试函数,那么使用setup_funciton和teardown_function会在每个函数执行前后都执行一次setup和teardown。
ps:pytest3.0后,“_function”可省略

def setup_function(function):
    """ setup any state tied to the execution of the given function.
    Invoked for every test function in the module.
    """


def teardown_function(function):
    """ teardown any state that was previously setup with a setup_function
    call.
    """

2、marker与参数化

通过使用pytest.mark.xxx,我们可以给测试方法添加各种标志,并且在执行的时候可以有选择的只执行某个/某几个标志的测试。下面是pytest内置的一些marker:

# 每次都跳过不执行
@pytest.mark.skip  
# 满足条件则跳过不执行  
@pytest.mark.skipif    
# 将该函数执行结果置为失败,但是不会被统计到失败的用例数里,而是统计到expected failures中
@pytest.mark.xfail    
# 用例失败重试,需要先安装pytest-rerunfailures插件
@pytest.mark.flaky(reruns=2)

import pytest
values_list = [(1,2,3),(2,3,4),(3,4,5)]
@pytest.mark.parametrize('n1,n2,n3',values_list)
def test_params(n1,n2,n3):
'''将逐个判断values_list中的元素与(1,2,3)是否相等'''
    assert (n1,n2,n3) == (1,2,3)

3、pytest.fixture

3.1 pytest.fixture参数

3.1.1 scope参数
scope值可指定为session、module、class、function,对应着相应的作用域。
3.1.2 autouse参数
autouse=True表示所有测试方法执行前会默认执行该fixture

3.2 pytest.fixture实现setup和teardown

在以下的测试代码中,在执行test_func1前,会先执行fix_func1中yield前面的代码,相当于setup。执行完test_func1后,再执行yield后的代码,相当于teardown。

@pytest.fixture
def fix_func1():
    print('setup')
    result = 1
    yield result
    print('teardown')

def test_func1(fix_func1):
    assert 1 == fix_func1
3.3 使用fixture提供测试数据

fixture可以返回任意类型的数据,因此适合用来提供测试数据

未完待续……

你可能感兴趣的:(pytest总结)