Pytest前后置处理

Pytest框架实现一些前后置的处理,常用三种。

1.setup/teardown,setup_class/teardown_class

使用场景:用例执行之前,需要做初始化操作;用例执行结束之后,需要做资源清理
总配置文件pytest.ini

[pytest]
addopts = -vs
testpaths = testcase/test_setup_teardown.py
python_files = test_*.py
python_classes = Test*
python_functions = test

1.1、setup/teardown

测试用例:

# -*- coding: UTF-8 -*-
class TestSetupTeardown:def setup(self):print('\n在执行测试用例之前初始化的代码')def test_01_login(self):print('\n登录')def test_02_browse(self):print('\n浏览网页')def test_03_exit(self):print('\n退出')def teardown(self):print('\n清理资源')

命令行操作:

% pytest
============================================================================= test session starts =============================================================================
platform darwin -- Python 3.7.9, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- /Users/xxx/opt/anaconda3/envs/py37/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.9', 'Platform': 'Darwin-20.2.0-x86_64-i386-64bit', 'Packages': {'pytest': '6.2.4', 'py': '1.10.0', 'pluggy': '0.13.1'}, 'Plugins': {'xdist': '2.3.0', 'html': '3.1.1', 'ordering': '0.6', 'rerunfailures': '10.1', 'metadata': '1.11.0', 'forked': '1.3.0'}}
rootdir: /Users/xxx/PycharmProjects/pytestDemo, configfile: pytest.ini, testpaths: testcase/test_setup_teardown.py
plugins: xdist-2.3.0, html-3.1.1, ordering-0.6, rerunfailures-10.1, metadata-1.11.0, forked-1.3.0
collected 3 items                                                                                                                                                             testcase/test_setup_teardown.py::TestSetupTeardown::test_01_login
在执行测试用例之前初始化的代码登录
PASSED
清理资源testcase/test_setup_teardown.py::TestSetupTeardown::test_02_browse
在执行测试用例之前初始化的代码浏览网页
PASSED
清理资源testcase/test_setup_teardown.py::TestSetupTeardown::test_03_exit
在执行测试用例之前初始化的代码退出
PASSED
清理资源============================================================================== 3 passed in 0.01s ==============================================================================

1.2、setup_class/teardown_class

测试用例:

# -*- coding: UTF-8 -*-
class TestSetupTeardown:def setup_class(self):"""在所有的用力之前只执行一次:return:"""print('\n在每个类执行前的初始化操作。比如:创建日志对象,创建数据库的连接,创建接口的请求对象')def test_01_login(self):print('登录')def test_02_browse(self):print('\n浏览网页')def test_03_exit(self):print('\n退出')def teardown_class(self):print('\n在每个类执行后的扫尾工作。比如:销毁日志对象,销毁数据库的连接,销毁接口的请求对象。')

命令行操作:

% pytest
============================================================================= test session starts =============================================================================
platform darwin -- Python 3.7.9, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- /Users/xxx/opt/anaconda3/envs/py37/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.9', 'Platform': 'Darwin-20.2.0-x86_64-i386-64bit', 'Packages': {'pytest': '6.2.4', 'py': '1.10.0', 'pluggy': '0.13.1'}, 'Plugins': {'xdist': '2.3.0', 'html': '3.1.1', 'ordering': '0.6', 'rerunfailures': '10.1', 'metadata': '1.11.0', 'forked': '1.3.0'}}
rootdir: /Users/xxx/PycharmProjects/pytestDemo, configfile: pytest.ini, testpaths: testcase/test_setup_teardown.py
plugins: xdist-2.3.0, html-3.1.1, ordering-0.6, rerunfailures-10.1, metadata-1.11.0, forked-1.3.0
collected 3 items                                                                                                                                                             testcase/test_setup_teardown.py::TestSetupTeardown::test_01_login
在每个类执行前的初始化操作。比如:创建日志对象,创建数据库的连接,创建接口的请求对象
登录
PASSED
testcase/test_setup_teardown.py::TestSetupTeardown::test_02_browse
浏览网页
PASSED
testcase/test_setup_teardown.py::TestSetupTeardown::test_03_exit
退出
PASSED
在每个类执行后的扫尾工作。比如:销毁日志对象,销毁数据库的连接,销毁接口的请求对象。============================================================================== 3 passed in 0.01s ==============================================================================

2、使用@pytest.fixture()装饰器来实现部分用例的前后置

@pytest.fixture(scope=‘function’, params=’’, autouse=’’, ids=’’, name=’’)

  • scope表示的是被@pytest.fixture标记的方法的作用域。function(默认)、class、module、package/session
  • params:参数化(支持:列表[],元祖(),字典列表[{},{},{}],字典元组({},{},{}))
  • autouse=True:自动执行,默认False
  • ids:当使用params参数化时,给每一个值设置一个变量名。意义不大
  • name:给被@pytest.fixture标记的方法取一个别名

2.1、scope是function

手动调用前后置方法,好处是想让哪些方法执行前后置就让哪些方法执行前后置
用例:

# -*- coding: UTF-8 -*-
import pytest@pytest.fixture(scope='function')
def my_fixture():print('这是前置的方法,可以实现部分以及全部用例的前置')yield # 通过yield将前后置方法分隔print('\n这是后置的方法,可以实现部分以及全部用例的后置')class TestSetupTeardown:def test_01(self):print('没有前置方法')def test_02(self, my_fixture):   # 调用处print('有前置方法')

命令行操作:

 % pytest
============================================================================= test session starts =============================================================================
platform darwin -- Python 3.7.9, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- /Users/xxx/opt/anaconda3/envs/py37/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.9', 'Platform': 'Darwin-20.2.0-x86_64-i386-64bit', 'Packages': {'pytest': '6.2.4', 'py': '1.10.0', 'pluggy': '0.13.1'}, 'Plugins': {'xdist': '2.3.0', 'html': '3.1.1', 'ordering': '0.6', 'rerunfailures': '10.1', 'metadata': '1.11.0', 'forked': '1.3.0'}}
rootdir: /Users/liyabin01/PycharmProjects/pytestDemo, configfile: pytest.ini, testpaths: testcase/test_fixture.py
plugins: xdist-2.3.0, html-3.1.1, ordering-0.6, rerunfailures-10.1, metadata-1.11.0, forked-1.3.0
collected 2 items                                                                                                                                                             testcase/test_fixture.py::TestSetupTeardown::test_01 没有前置方法
PASSED
testcase/test_fixture.py::TestSetupTeardown::test_02 这是前置的方法,可以实现部分以及全部用例的前置
有前置方法
PASSED
这是后置的方法,可以实现部分以及全部用例的后置============================================================================== 2 passed in 0.01s ==============================================================================

自动调用前后置方法,好处是方法可以自动执行,但是不能控制哪些执行哪些不执行,全部作用域命中的方法都要执行
用例:

# -*- coding: UTF-8 -*-
import pytest
@pytest.fixture(scope='function', autouse=True)    # 调用处
def my_fixture():print('这是前置的方法,可以实现部分以及全部用例的前置')yieldprint('\n这是后置的方法,可以实现部分以及全部用例的后置')
class TestSetupTeardown:def test_01(self):print('没有前置方法')def test_02(self):print('有前置方法')

命令行操作,会发现test_01方法也加了前后置处理

% pytest
============================================================================= test session starts =============================================================================
platform darwin -- Python 3.7.9, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- /Users/xxx/opt/anaconda3/envs/py37/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.9', 'Platform': 'Darwin-20.2.0-x86_64-i386-64bit', 'Packages': {'pytest': '6.2.4', 'py': '1.10.0', 'pluggy': '0.13.1'}, 'Plugins': {'xdist': '2.3.0', 'html': '3.1.1', 'ordering': '0.6', 'rerunfailures': '10.1', 'metadata': '1.11.0', 'forked': '1.3.0'}}
rootdir: /Users/liyabin01/PycharmProjects/pytestDemo, configfile: pytest.ini, testpaths: testcase/test_fixture.py
plugins: xdist-2.3.0, html-3.1.1, ordering-0.6, rerunfailures-10.1, metadata-1.11.0, forked-1.3.0
collected 2 items                                                                                                                                                             testcase/test_fixture.py::TestSetupTeardown::test_01 这是前置的方法,可以实现部分以及全部用例的前置
没有前置方法
PASSED
这是后置的方法,可以实现部分以及全部用例的后置testcase/test_fixture.py::TestSetupTeardown::test_02 这是前置的方法,可以实现部分以及全部用例的前置
有前置方法
PASSED
这是后置的方法,可以实现部分以及全部用例的后置============================================================================== 2 passed in 0.01s ==============================================================================

2.2、scope是class

fixture为class级别的时候,如果一个class里面有多个用例,都调用了此fixture,那么此fixture只在该class里所有用例开始前执行一次
(1)验证执行次数
用例:

# -*- coding: UTF-8 -*-
import pytest@pytest.fixture(scope="class")
def first():print("\n获取用户名,scope为class级别只运行一次")a = "yoyo"return aclass TestCase():def test_1(self, first):'''用例传fixture'''print("测试账号:%s" % first)assert first == "yoyo"def test_2(self, first):'''用例传fixture'''print("测试账号:%s" % first)assert first == "yoyo"

命令行操作:

% pytest
testcase/test_fixture.py::TestCase::test_1
获取用户名,scope为class级别只运行一次
测试账号:yoyo
PASSED
testcase/test_fixture.py::TestCase::test_2 测试账号:yoyo
PASSED

(2)验证作用域
用例:

# -*- coding: UTF-8 -*-
import pytest
@pytest.fixture(scope='class', autouse=True)
def my_fixture():print('\n这是前置的类方法,可以实现部分以及全部用例的前置')yieldprint('\n这是后置的类方法,可以实现部分以及全部用例的后置')
class TestSetupTeardown1:def test_01(self):print('我是测试方法1')
class TestSetupTeardown2:def test_02(self):print('我是测试方法2')

命令行操作:

% pytest
============================================================================= test session starts =============================================================================
platform darwin -- Python 3.7.9, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- /Users/xxx/opt/anaconda3/envs/py37/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.9', 'Platform': 'Darwin-20.2.0-x86_64-i386-64bit', 'Packages': {'pytest': '6.2.4', 'py': '1.10.0', 'pluggy': '0.13.1'}, 'Plugins': {'xdist': '2.3.0', 'html': '3.1.1', 'ordering': '0.6', 'rerunfailures': '10.1', 'metadata': '1.11.0', 'forked': '1.3.0'}}
rootdir: /Users/liyabin01/PycharmProjects/pytestDemo, configfile: pytest.ini, testpaths: testcase/test_fixture.py
plugins: xdist-2.3.0, html-3.1.1, ordering-0.6, rerunfailures-10.1, metadata-1.11.0, forked-1.3.0
collected 2 items                                                                                                                                                             testcase/test_fixture.py::TestSetupTeardown1::test_01
这是前置的类方法,可以实现部分以及全部用例的前置
我是测试方法1
PASSED
这是后置的类方法,可以实现部分以及全部用例的后置testcase/test_fixture.py::TestSetupTeardown2::test_02
这是前置的类方法,可以实现部分以及全部用例的前置
我是测试方法2
PASSED
这是后置的类方法,可以实现部分以及全部用例的后置============================================================================== 2 passed in 0.01s ==============================================================================

2.3、params

简单用例:

# -*- coding: UTF-8 -*-
import pytest@pytest.fixture(scope='function', params=['成龙', '甄子丹', '李小龙'])
def get_data(request):return request.paramclass TestFixture:def test_01(self):print('我是吴奇隆')def test_02(self, get_data):print('我是{}'.format(get_data))

命令行操作:

% pytest
testcase/test_fixture.py::TestFixture::test_01 我是吴奇隆
PASSED
testcase/test_fixture.py::TestFixture::test_02[\u6210\u9f99] 我是成龙
PASSED
testcase/test_fixture.py::TestFixture::test_02[\u7504\u5b50\u4e39] 我是甄子丹
PASSED
testcase/test_fixture.py::TestFixture::test_02[\u674e\u5c0f\u9f99] 我是李小龙
PASSED

可以观察到test_02方法调用了三次,固定写法。

3、通过conftest.py和@pytest.fixture()结合实现全局的前置应用(比如:项目的全局登录,模块的全局处理)

1.conftest.py文件是单独存放的一个夹具(@pytest.fixture())配置文件,名称不能更改。
2.用处可以在不同的py文件中使用同一个fixture函数
3.原则上conftest.py需要和运行的用例放在同一层。并且不需要做任何的import导入操作。
总结:

  • setup/teardown,setup_class/teardown_class:它是作用域所有用例或者所有类
  • @pytest.fixture():它的作用是既可以部分也可以全部前后置
  • conftest.py和@pytest.fixture()结合使用,作用域全局的前后置。
    用例:
    pytest.ini
[pytest]
addopts = -vs
testpaths = testcase/
python_files = test_*.py
python_classes = Test*
python_functions = test

项目目录结构:

conftest.py

import pytest@pytest.fixture(scope='function')   # conftest.py
def all_fixture():print('\n全局的前置')yieldprint('\n全局的后置')@pytest.fixture(scope='function')    # product/conftest.py
def product_fixture():print('\nproduct的前置')yieldprint('\nproduct的后置')@pytest.fixture(scope='function')  # user/conftest.py
def user_fixture():print('\nuser的前置')yieldprint('\nuser的后置')

test_product.py/test_user.py

import pytestclass TestProduct:def test_product(self, all_fixture, product_fixture):print('我是一个product~')class TestUser:def test_user(self, user_fixture):print('我是一个user~')

命令行操作:

% pytest
============================================================================= test session starts =============================================================================collected 2 items                                                                                                                                                             testcase/product/test_product.py::TestProduct::test_product
全局的前置product的前置
我是一个product~
PASSED
product的后置全局的后置testcase/user/test_user.py::TestUser::test_user
user的前置
我是一个user~
PASSED
user的后置============================================================================== 2 passed in 0.02s ==============================================================================

上述执行结果可以看出,@pytest.fixture的生效顺序是函数中调用的顺序
def test_product(self, all_fixture, product_fixture)

Pytest前后置处理相关推荐

  1. pytest文档80 - 内置 fixtures 之 cache 写入中文显示\u4e2d\u6587问题(用打补丁方式解决)

    前言 pytest 内置 fixtures 之 cache 写入中文的时候会在文件中写入\u4e2d\u6587 这种unicode编码格式. 如果想在文件中显示正常的中文,需重新Cache类的set ...

  2. python自动测试p-python 自动化测试 pytest 的使用

    pytest 是一款以python为开发语言的第三方测试,主要特点如下: 比自带的 unittest 更简洁高效,兼容 unittest框架 支持参数化 可以更精确的控制要测试的测试用例 丰富的插件, ...

  3. [翻译]pytest测试框架(一)

    此文已由作者吴琪惠授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 纯官网译文而已... pytest是一个成熟的.全功能的python测试工具. pytest框架编写测试用例 ...

  4. [转]Pytest 基础教程

    文章目录 第一部分:快速入门 一.快速入门 1. 安装 Pytest 2. 第一个测试函数 3. 运行测试函数 4. 测试失败 第二部分:测试函数 一.断言 二.捕获异常 三.标记函数 1.Pytes ...

  5. pytest使用入门

    pytest是第三方开发的一个python测试模块,可以轻松地编写小型测试,而且可以扩展以支持应用程序和库的复杂功能测试,帮助我们编写更好的程序. 安装pytest 先在命令行中运行pytest的安装 ...

  6. pytest【marker标记】

    测试函数标记 pytest提供了标记机制,允许你使用marker对测试函数(测试用例)做标记,一个测试函数(测试用例)可以有多个marker,一个marker也可以用例标记多个测试函数(测试用例).针 ...

  7. 如何使用Pytest进行自动化测试

    为什么需要自动化测试 自动化测试有很多优点,但这里有3个主要的点 可重用性:不需要总是编写新的脚本,除非必要,即使是新的操作系统版本也不需要编写脚本. 可靠性:人容易出错,机器不太可能.当运行不能跳过 ...

  8. 全网最全pytest大型攻略,单元测试学这就够了

    pytest 是一款以python为开发语言的第三方测试,主要特点如下: 比自带的 unittest 更简洁高效,兼容 unittest框架 支持参数化 可以更精确的控制要测试的测试用例 丰富的插件, ...

  9. Pytest 基础教程

    文章目录 第一部分:快速入门 一.快速入门 1. 安装 Pytest 2. 第一个测试函数 3. 运行测试函数 4. 测试失败 第二部分:测试函数 一.断言 二.捕获异常 三.标记函数 1.Pytes ...

最新文章

  1. PHP- 深入PHP、Redis连接
  2. 公司要上监控,选型调研下 Zabbix 和 Prometheus
  3. Tautology--POJ 3295
  4. java创建描述文件,IT技术交流:Java 轻量级整合开发
  5. opencv 入门 demo
  6. codevs 1230【pb_ds】
  7. JAVA错误日志(part1)--编码GBK的不可映射字符
  8. 豆瓣评分9.4!这部大片你不应该错过,每一秒都是不敢看的残忍!
  9. 如何在Java Reflection中的类下获取所有方法信息?
  10. redis实例python_生产消费者模式与python+redis实例运用(基础篇)
  11. Vue Bootstrap OSS 实现文件上传
  12. 用python写一个自动注册脚本_python实现自动化上线脚本的示例
  13. python测试嵌入式_用Python测试嵌入式系统的测试框架
  14. 如何快速实现自定义sql分页?若不会,我便手把手教你【详细】
  15. 关于 idea 快捷键 alt + f7 无法使用的一些尝试
  16. springboot志愿者管理系统
  17. vue将数据导出到excel
  18. 2022年股权转让怎么计算个人所得税
  19. 公司股权分配协议范文
  20. 离散数学 学习笔记-Day4

热门文章

  1. MySQL(八)MySQL性能优化
  2. 淘宝技术架构从1.0到4.0的演变
  3. 干货 | 工行分布式数据库选型与大规模容器化实践
  4. 理解HTTP协议中的multipart/form-data
  5. 读者吐槽:Go 面试总被问到 RPC
  6. 一些实用的编程模式 | Options模式
  7. WebSocket使用案例
  8. LF AI Day中国站火热报名中
  9. 荣登2019中国“十佳大数据案例”,腾讯大数据再获国家认可
  10. 央视-腾讯发布报告:九成受访者认为AI 距离自己并不遥远