pytest文档57-计算单元测试代码覆盖率(pytest-cov)
前言
我们在做测试的时候,经常遇到领导的灵魂拷问:你的测试用例覆盖率是多少,达到100%了么?你如何保证你的测试质量?
测试用例的覆盖率如何统计呢,如何知道开发的代码,我们都测到了,不会存在漏测的情况。
pytest-cov
先命令行安装 pytest-cov 2.10.1版本
pip install pytest-cov==2.10.1
环境要求:
1.python3.6.6 版本
备注:其它版本没试过
python3.6.0会遇到以下问题
INTERNALERROR>raise CoverageException("Couldn't use data file {!r}:{}".format(self.filename, msg))
INTERNALERROR> coverage.misc.CoverageException: Couldn't use data file'C:\\Users\\Desktop\\Pytest\\.coverage':
Safety level may not be changed inside a transaction
解决办法:安装3.6.1以上版本
实现功能
在做单元测试时,代码覆盖率常常被拿来作为衡量测试好坏的指标,甚至,用代码覆盖率来考核测试任务完成情况,
比如,代码覆盖率必须达到80%或 90%。于是乎,测试人员费尽心思设计案例覆盖代码。
单元测试的方法有:语句覆盖/判定覆盖/条件覆盖/路径覆盖
先看一个简单的案例,前端实现一个功能,根据接口返回的不同code值,判断支付的结果,给用户返回提示友好的信息
前端实现功能:根据接口返回的不同code值,判断支付的结果,给用户返回提示友好的信息
接口返回格式:
{
"code": 0,
"msg": "success!",
"data": []
}
错误码参照
0 - 成功
30000 - 参数错误
30001 - 余额不足
30002 - 达到当天最大额度
201102 - 银行卡被冻结
实现代码
'''
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
接口返回格式
{
"code": 0,
"msg": "success!",
"data": []
}
错误码参照
0 - 成功
30000 - 参数错误
30001 - 余额不足
30002 - 达到当天最大额度
201102 - 银行卡被冻结
'''
# pay.py
def pay_status(result):
'''根据接口返回code状态,给用户提示对应的结果'''
if result.get("code") == 0:
return "支付成功"
elif result.get("code") == 30000:
return "支付失败: %s" % result.get("msg")
elif result.get("code") == 30001:
return "支付失败: %s" % result.get("msg")
elif result.get("code") == 30002:
return "支付失败: %s" % result.get("msg")
elif result.get("code") == 201102:
return "支付失败: %s" % result.get("msg")
else:
return "支付失败: 系统异常,未知错误"
整个项目目录结构如下
- src 是项目的源码
- tests 是我们写的单元测试用例
- src和tests放同一个项目的根目录下

用例设计
在tests/test_pay.py下写测试用例,先只写一个支付成功的案例
from src.pay import pay_status
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
def test_pay_success():
result = {
"code": 0,
"msg": "success!",
"data": []
}
assert pay_status(result) == "支付成功"
运行用例
运行用例的时候加上 --cov 参数
pytest --cov
运行结果
>pytest --cov
================================================= test session starts =================================================
platform win32 -- Python 3.6.6, pytest-6.0.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\soft\pytest-demo-cov
plugins: change-report-1.0, cov-2.10.1, html-1.19.0, metadata-1.8.0
collected 1 item
tests\test_pay.py . [100%]
----------- coverage: platform win32, python 3.6.6-final-0 -----------
Name Stmts Miss Cover
---------------------------------------
src\__init__.py 0 0 100%
src\pay.py 13 9 31%
tests\__init__.py 0 0 100%
tests\test_pay.py 4 0 100%
---------------------------------------
TOTAL 17 9 47%
================================================== 1 passed in 0.10s ==================================================
从报告可以看出src\pay.py 的代码测试覆盖率是31%,其它文件都是100%覆盖,这就说明我们单元测试代码测试覆盖率是31%
还有一个指标是测试用例的执行率,测试用例在test_pay.py文件,执行率是100%,说明用例全部执行了。
coverage生成html报告
coverage 相关参数查看,使用pytest -h
> pytest -h
coverage reporting with distributed testing support:
--cov=[SOURCE] Path or package name to measure during execution (multi-allowed). Use --cov= to not do any
source filtering and record everything.
--cov-report=TYPE Type of report to generate: term, term-missing, annotate, html, xml (multi-allowed). term, term-
missing may be followed by ":skip-covered". annotate, html and xml may be followed by ":DEST"
where DEST specifies the output location. Use --cov-report= to not generate any output.
--cov-config=PATH Config file for coverage. Default: .coveragerc
--no-cov-on-fail Do not report coverage if test run fails. Default: False
--no-cov Disable coverage report completely (useful for debuggers). Default: False
--cov-fail-under=MIN Fail if the total coverage is less than MIN.
--cov-append Do not delete coverage but append to current. Default: False
--cov-branch Enable branch coverage.
--cov-context=CONTEXT
Dynamic contexts to use. "test" for now.
生成html的报告
pytest --cov --cov-report=html
执行完成,在项目根目录会生成 htmlcov 目录

运行 index.html 文件查看代码覆盖率

点开src\pay.py

想覆盖率达到100%,那得再继续写用例,让每个if分支情况都覆盖到
指定被测代码
如果我们想指定执行项目里面的某个模块,可以通过--cov=模块 来运行
pytest --cov=src
>pytest --cov=src
================================================= test session starts =================================================
platform win32 -- Python 3.6.6, pytest-6.0.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\soft\pytest-demo-cov
plugins: change-report-1.0, cov-2.10.1, html-1.19.0, metadata-1.8.0
collected 1 item
tests\test_pay.py . [100%]
----------- coverage: platform win32, python 3.6.6-final-0 -----------
Name Stmts Miss Cover
-------------------------------------
src\__init__.py 0 0 100%
src\pay.py 13 9 31%
-------------------------------------
TOTAL 13 9 31%
================================================== 1 passed in 0.07s ==================================================
也可以指定具体的py模块名称
pytest --cov=src.pay
但不能写成pytest --cov=src/pay.py
pytest文档57-计算单元测试代码覆盖率(pytest-cov)的更多相关文章
- pytest文档7-计算单元测试代码覆盖率(pytest-cov)
pytest-cov 先命令行安装 pytest-cov 2.10.1版本 pip install pytest-cov==2.10.1 环境要求:1.python3.6.6 版本备注:其它版本没试过 ...
- pytest文档7-pytest-html生成html报告
前言 pytest-HTML是一个插件,pytest用于生成测试结果的HTML报告.兼容Python 2.7,3.6 pytest-html 1.github上源码地址[https://github. ...
- pytest文档3-pycharm运行pytest
前言 上一篇pytest文档2-用例运行规则已经介绍了如何在cmd执行pytest用例,平常我们写代码在pycharm比较多 写完用例之后,需要调试看看,是不是能正常运行,如果每次跑去cmd执行,太麻 ...
- pytest文档46-关于https请求警告问题(InsecureRequestWarning: Unverified HTTPS request is being made)
前言 使用 pytest 执行 https 请求用例的时候,控制台会出现警告:InsecureRequestWarning: Unverified HTTPS request is being mad ...
- pytest文档19-doctest测试框架
前言 doctest从字面意思上看,那就是文档测试.doctest是python里面自带的一个模块,它实际上是单元测试的一种. 官方解释:doctest 模块会搜索那些看起来像交互式会话的 Pytho ...
- pytest文档1-环境准备与入门
前言 首先说下为什么要学pytest,在此之前相信大家已经掌握了python里面的unittest单元测试框架,那再学一个框架肯定是需要学习时间成本的. 刚开始我的内心是拒绝的,我想我用unittes ...
- pytest文档56-插件打包上传到 pypi 库
前言 pytest 的插件完成之后,可以上传到 github,方便其他小伙伴通过 pip 源码安装.如果我们想通过 pip install packages 这种方式安装的话,需上传到 pypi 仓库 ...
- pytest文档55-plugins插件开发
前言 前面一篇已经学会了使用hook函数改变pytest运行的结果,代码写在conftest.py文件,实际上就是本地的插件了. 当有一天你公司的小伙伴觉得你写的还不错,或者更多的小伙伴想要你这个功能 ...
- pytest文档51-内置fixture之cache使用
前言 pytest 运行完用例之后会生成一个 .pytest_cache 的缓存文件夹,用于记录用例的ids和上一次失败的用例. 方便我们在运行用例的时候加上--lf 和 --ff 参数,快速运行上一 ...
随机推荐
- Java字符串的常用方法
[转换] //int 10进制----> 转16进制Integer.toHexString(10) // int 10进制----> 转8进制Integer.toOctalString(1 ...
- pytest(2):使用pycharm运行pytest
pycharm运行 1.在pycharm里创建测试文件test_demo.py # Author xuejie zeng # encoding utf-8 # content of test_demo ...
- linux 多进程
Linux下的多进程编程初步 Linux下的多进程编程初步 多进程编程 1 Linux下进程的结构 2 Linux下的进程控制 21 僵尸进程 22 fork 23 exec 函数族 3 Linux下 ...
- [LeetCode]21. 合并两个有序链表(递归)
题目 将两个有序链表合并为一个新的有序链表并返回.新链表是通过拼接给定的两个链表的所有节点组成的. 示例: 输入:1->2->4, 1->3->4 输出:1->1-> ...
- 跨平台框架与React Native基础
跨平台框架 什么是跨平台框架? 这里的多个平台一般是指 iOS 和 Android . 为什么需要跨平台框架? 目前,移动开发技术主要分为原生开发和跨平台开发两种.其中,原生应用是指在某个特定的移动平 ...
- Spring boot +Thymeleaf 搭建springweb
对接天猫精灵的时候需要有网关服务器方提供几个页面,服务器已经有了,spring boot的 纯后台的,就加了Thymeleaf jar包添加几个页面跳转 maven配置 <!-- 引入thy ...
- hystrix文档翻译之开始使用
获取包 使用maven获取包. <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId ...
- java ThreadLocal理解和使用
一.ThreadLoal的理解 ThreadLoal 变量,它的基本原理是,同一个 ThreadLocal 所包含的对象(对ThreadLocal< String >而言即为 String ...
- JVM学习(四)JVM调优
一.调优命令 Sun JDK监控和故障处理命令有jps.jstat.jmap.jhat.jstack.jinfo jps,JVM Process Status Tool,显示指定系统内所有的HotSp ...
- Android如何使用注解进行代码检查
原文首发于微信公众号:躬行之(jzman-blog),欢迎关注交流! Android Studio 内置了代码检查工具 Lint,可在菜单栏选择 Analyze > Inspect Code 执 ...