Pytest - 使用介绍
1. 概述
pytest是一个非常成熟的全功能的Python测试框架,主要特点有以下几点:
- 1、简单灵活,容易上手,文档丰富;
- 2、支持参数化,可以细粒度地控制要测试的测试用例;
- 3、能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests);
- 4、pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等;
- 5、测试用例的skip和xfail处理;
- 6、可以很好的和CI工具结合,例如jenkins
2. 使用介绍
2.1. 安装
pip install pytest
2.2. 示例代码
编写规则
编写pytest测试样例非常简单,只需要按照下面的规则:
- 测试文件以test_开头(以_test结尾也可以)
- 测试类以Test开头,并且不能带有 init 方法
- 测试函数以test_开头
- 断言使用基本的assert即可
pytest1.py
# -*- coding:utf-8 -*-
import pytest
@pytest.fixture(scope='function')
def setup_function(request):
def teardown_function():
print("teardown_function called.")
request.addfinalizer(teardown_function) # 此内嵌函数做teardown工作
print('setup_function called.')
@pytest.fixture(scope='module')
def setup_module(request):
def teardown_module():
print("teardown_module called.")
request.addfinalizer(teardown_module)
print('setup_module called.')
@pytest.mark.website
def test_1(setup_function):
print('Test_1 called.')
def test_2(setup_module):
print('Test_2 called.')
def test_3(setup_module):
print('Test_3 called.')
assert 2==1+1 # 通过assert断言确认测试结果是否符合预期
fixture的scope参数
scope参数有四种,分别是'function','module','class','session',默认为function。
- function:每个test都运行,默认是function的scope
- class:每个class的所有test只运行一次
- module:每个module的所有test只运行一次
- session:每个session只运行一次
setup和teardown操作
- setup,在测试函数或类之前执行,完成准备工作,例如数据库链接、测试数据、打开文件等
- teardown,在测试函数或类之后执行,完成收尾工作,例如断开数据库链接、回收内存资源等
- 备注:也可以通过在fixture函数中通过yield实现setup和teardown功能
2.3. 测试结果
如何执行
- pytest # run all tests below current dir
- pytest test_mod.py # run tests in module file test_mod.py
- pytest somepath # run all tests below somepath like ./tests/
- pytest -k stringexpr # only run tests with names that match the
# the "string expression", e.g. "MyClass and not method"
# will select TestMyClass.test_something
# but not TestMyClass.test_method_simple - pytest test_mod.py::test_func # only run tests that match the "node ID",
# e.g "test_mod.py::test_func" will be selected
# only run test_func in test_mod.py
通过pytest.mark对test方法分类执行
通过@pytest.mark控制需要执行哪些feature的test,例如在执行test前增加修饰@pytest.mark.website
- 通过 -m "website" 执行有website标记的test方法
$ pytest -v -m "website" pytest1.py
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /home/kevin/soft/anaconda2/bin/python
cachedir: .cache
Using --randomly-seed=1522925202
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
collected 3 items
pytest1.py::test_1 PASSED
============================================================================= pytest-warning summary =============================================================================
WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0. Please remove the prefix and use the @pytest.fixture decorator instead.
=============================================================================== 2 tests deselected ===============================================================================
=========================================================== 1 passed, 2 deselected, 1 pytest-warnings in 0.00 seconds ============================================================
- 通过 -m "not website" 执行没有website标记的test方法
$ pytest -v -m "not website" pytest1.py
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /home/kevin/soft/anaconda2/bin/python
cachedir: .cache
Using --randomly-seed=1522925192
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
collected 3 items
pytest1.py::test_3 PASSED
pytest1.py::test_2 PASSED
============================================================================= pytest-warning summary =============================================================================
WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0. Please remove the prefix and use the @pytest.fixture decorator instead.
=============================================================================== 1 tests deselected ===============================================================================
=========================================================== 2 passed, 1 deselected, 1 pytest-warnings in 0.00 seconds ============================================================
Console参数介绍
- -v 用于显示每个测试函数的执行结果
- -q 只显示整体测试结果
- -s 用于显示测试函数中print()函数输出
- -x, --exitfirst, exit instantly on first error or failed test
- -h 帮助
Case 1
$ pytest -v pytest1.py
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /home/kevin/soft/anaconda2/bin/python
cachedir: .cache
Using --randomly-seed=1522920341
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
collected 3 items
pytest1.py::test_1 PASSED
pytest1.py::test_3 PASSED
pytest1.py::test_2 PASSED
============================================================================= pytest-warning summary =============================================================================
WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0. Please remove the prefix and use the @pytest.fixture decorator instead.
================================================================== 3 passed, 1 pytest-warnings in 0.01 seconds ===================================================================
Case 2
$ pytest -s pytest1.py
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1
Using --randomly-seed=1522920508
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
collected 3 items
pytest1.py setup_function called.
Test_1 called.
.teardown_function called.
setup_module called.
Test_2 called.
.Test_3 called.
.teardown_module called.
============================================================================= pytest-warning summary =============================================================================
WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0. Please remove the prefix and use the @pytest.fixture decorator instead.
================================================================== 3 passed, 1 pytest-warnings in 0.01 seconds ===================================================================
3. 扩展插件
3.1. 测试报告
安装与样例
pip install pytest-cov # 计算pytest覆盖率,支持输出多种格式的测试报告
pytest --cov-report=html --cov=./ test_code_target_dir
Console参数介绍
- --cov=[path], measure coverage for filesystem path (multi-allowed), 指定被测试对象,用于计算测试覆盖率
- --cov-report=type, type of report to generate: term, term-missing, annotate, html, xml (multi-allowed), 测试报告的类型
- --cov-config=path, config file for coverage, default: .coveragerc, coverage配置文件
- --no-cov-on-fail, do not report coverage if test run fails, default: False,如果测试失败,不生成测试报告
- --cov-fail-under=MIN, Fail if the total coverage is less than MIN. 如果测试覆盖率低于MIN,则认为失败
Console Result
---------------------------------------------------------------- coverage: platform linux2, python 2.7.14-final-0 ----------------------------------------------------------------
Name Stmts Miss Cover
--------------------------------
pytest1.py 18 0 100%
Html Result

3.2. 测试顺序随机
pip install pytest-randomly
3.3. 分布式测试
pip install pytest-xdist
3.4. 出错立即返回
pip install pytest-instafail
4. 参考
python的测试工具大全
https://wiki.python.org/moin/PythonTestingToolsTaxonomypython主流的测试工具横向比较
http://docs.python-guide.org/en/latest/writing/tests/
http://pythontesting.net/test-podcast/python单元测试框架pytest简介
https://blog.csdn.net/liuchunming033/article/details/46501653
作者:红薯爱帅
链接:https://www.jianshu.com/p/a754e3d47671
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
Pytest - 使用介绍的更多相关文章
- Pytest框架介绍
Pytest框架介绍.安装 pytest是python测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,功能更强大 pytest特征 1:断言提示信 ...
- pytest一:pytest 框架介绍
pytest 是 python 的一种单元测试框架,与python 自带的 unittest测试框架类似,但是比 unittest 框架使用起来更简洁,效率更高.根据pytest 的官方网站介绍,它具 ...
- pytest框架-介绍、Mark(打标签)、命令运行用例、用例执行顺序、
1.pytest介绍:基于unittest 之上的单元测试框架 1.1.自动发现测试模块和测试用例: unitest 需要添加用例,(泰斯特楼贷)加载器加载测试用例 pytest 只需要一条代码就可以 ...
- try easy pytest 1tep介绍
『 tep is a testing tool to help you write pytest more easily. Try Easy Pytest! 』 tep前身 tep的前身是接口自动化测 ...
- 一、pytest的介绍和安装
需要针对一个项目系统开发一套UI自动化测试脚本,自己结合着学习,采用了pytest去实现,这里留下记录. 什么是pytest pytest 是一个非常成熟的全功能的Python测试框架 可以胜任uni ...
- Pytest安装介绍--使用(html报告)
Pytes是 一个单元测试框架,可以生成html报告. #卸载# pip uninstall pytest#安装# pip install -U pytest# 查看# pytest --versio ...
- pytest单侧模块_入门汇总
Pytest简单介绍 (pytest是python的一个测试框架,主要是用来进行一些小的测试) 安装:pip install -U pytest 查看是否安装成功:pytest --version 运 ...
- [Python]使用pytest进行单元测试
安装pytest pipenv install pytest 验证安装的版本: pytest --version This , imported /site-packages/pytest.py 接下 ...
- 『德不孤』Pytest框架 — 3、Pytest的基础说明
目录 1.Pytest参数介绍 2.Pytest框架用例命名规则 3.Pytest Exit Code说明 4.pytest.ini全局配置文件 5.Pytest执行测试用例的顺序 1.Pytest参 ...
随机推荐
- MySQL 开启远程访问权限 | 宝塔系统
1.进入 MySQL 管理菜单 2.选择权限为所有人
- tp5.1 本地正常, 线上route.php不起作用的问题
由于本项目 的.htaccess文件是放在根目录的, 上传没有覆盖,重新编辑 <IfModule mod_rewrite.c> Options +FollowSymlinks -Multi ...
- 大咖手把手教您,DLA一键建仓!
DLA很早之前就支持了对关系型数据库的查询,但是一直以来用户会有一个担心: 直接分析RDS里面的数据会不会影响线上业务. 这个担心很合理,除非你要查询的RDS是专门用来做后台数据分析使用的,否则直接大 ...
- Vue--使用watch、computed、filter方法来监控
watch与computed.filter: watch:监控已有属性,一旦属性发生了改变就去自动调用对应的方法 computed:监控已有的属性,一旦属性的依赖发生了改变,就去自动调用对应的方法 f ...
- gb2312的6763个汉字
0a啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥薄雹保堡 ...
- 阿里云ecs环境配置
在阿里云 CentOS 服务器(ECS)上搭建 nginx + mysql + php-fpm 环境 https://ninghao.net/blog/1368 阿里云ecs从购买到环境搭建和建站!! ...
- WordPress使用自定义文章类型实现任意模板的方法和怎么做邮件回复
主要就是使用了register_post_type 函数. 1.创建插件目录 新建一个文件夹用来存放插件文件,这里我就命名这个文件夹为myMood 2.创php代码文件 在刚才创建的文件夹里面新建一个 ...
- input 手机数字键盘
要一点击提起数字键盘,安卓只要设置input的类型是number或tel, ios 需要 pattern="number"可以直接打开搜狗输入法的数字键盘,可以输入.和数字如果只能 ...
- Kubernetes Ingress 日志分析与监控的最佳实践
摘要: Ingress主要提供HTTP层(7层)路由功能,是目前K8s中HTTP/HTTPS服务的主流暴露方式.为简化广大用户对于Ingress日志分析与监控的门槛,阿里云容器服务和日志服务将Ingr ...
- BigDecimal创建初始化值类型对比
当初始化String类型和double类型,入参值相同,对比输出值 BigDecimal bigDecimalStr = new BigDecimal("0.1"); BigDec ...