Pytest Fixture(二)

2023-03-15,

作用域

固件的作用是为了抽离出重复的工作和方便复用,为了更精细化控制固件(比如只想对数据库访问测试脚本使用自动连接关闭的固件),pytest 使用作用域来进行指定固件的使用范围。

在定义固件时,通过 scope 参数声明作用域,可选项有:

1.function: 函数级,每个测试函数都会执行一次固件;
2.class: 类级别,每个测试类执行一次,所有方法都可以使用;
3.module: 模块级,每个模块执行一次,模块内函数和方法都可使用;
4.session: 会话级,一次测试只执行一次,所有被找到的函数和方法都可用;
5.package: 包级别,每个python包只执行一次;

  

默认的作用域为 function。 

import pytest

@pytest.fixture(scope='function')
def func_scope():
print('方法级别') @pytest.fixture(scope='module')
def mod_scope():
print('模块级别') @pytest.fixture(scope='session')
def sess_scope():
print('会话级别') @pytest.fixture(scope='class')
def class_scope():
print('类级别') def test_multi_scope(sess_scope, mod_scope, func_scope):
pass

执行结果如下,可以清楚看到各固件的作用域和执行顺序:

对于类使用作用域,需要使用 pytest.mark.usefixtures (对函数和方法也适用)

import pytest

@pytest.fixture(scope='class')
def class_scope():
print('类级别前置')
yield
print('类级别后置') @pytest.mark.usefixtures('class_scope')
class TestClassScope:
def test_1(self):
print("test_1方法") def test_2(self):
print("test_2方法")

叠加usefixtures

如果一个方法或者一个class用例想要同时调用多个fixture,可以使用@pytest.mark.usefixture()进行叠加。注意叠加顺序,先执行的放底层,后执行的放上层。

import pytest

@pytest.fixture(scope='function')
def class_open():
print('方法级别前置')
yield
print('方法级别后置') @pytest.fixture(scope='class')
def class_close():
print('类级别前置')
yield
print('类级别后置') class TestClassScope:
@pytest.mark.usefixtures('class_open')
def test_1(self):
print("test_1方法") @pytest.mark.usefixtures('class_open')
@pytest.mark.usefixtures('class_close')
def test_2(self):
print("test_2方法") if __name__ == '__main__':
pytest.main(['-vs'])

  

自动执行

目前为止,所有固件的使用都是手动指定,或者作为参数,或者使用 usefixtures。

如果我们想让固件自动执行,可以在定义时指定 autouse 参数。

下面是两个自动计时固件,一个用于统计每个函数运行时间(function 作用域),一个用于计算测试总耗时(session 作用域)

注意下面的测试函数并都没有使用固件:

import pytest

@pytest.fixture(scope='session', autouse=True)
def timer_session_scope():
print("用例执行前")
yield
print("用例执行后") def test_one():
print('test_one方法')

结果如下

我们可以看到,我们选择自动执行,即使我们没有选择使用,pytest也会给自动执行的。执行到对应的function级别。

夹具 yield和return的区别

夹具中可以使用return,yield关键字为测试函数提供值,推荐使用yield关键字,他们的区别如下:

yield返回值后,后面的代码还会继续运行
return返回值后,后面的代码不会继续运行

Pytest Fixture(二)的相关教程结束。

《Pytest Fixture(二).doc》

下载本文的Word格式文档,以方便收藏与打印。