使用Pytest进行单元测试 pytest教程
zhezhongyun 2024-12-16 17:34 104 浏览
PyTest简介
`pytest` 是一个非常流行的 Python 测试框架,提供了简单易用的测试功能。以下是 `pytest` 的基本使用方法:
- 安装 `pytest`
pip install pytest
- 创建测试文件
`pytest` 会自动发现以 `test_` 开头或 `_test` 结尾的文件。你可以创建一个名为 `test_example.py` 的文件。
# test_example.py
def add(a, b):
return a + b
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
- 运行测试
在命令行中,导航到包含测试文件的目录,然后运行以下命令:
pytest
`pytest` 会自动查找以 `test_` 开头的测试文件,并执行其中的测试函数。
- 查看测试结果
运行 `pytest` 后,你会看到测试的结果,包括通过的测试和失败的测试。如果测试失败,`pytest` 会提供详细的错误信息,帮助你调试。
- 测试夹具(Fixtures)
`pytest` 还支持测试夹具,用于设置测试环境。可以使用 `@pytest.fixture` 装饰器定义夹具。例如:
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_sum(sample_data):
assert sum(sample_data) == 6
- 参数化测试
你可以使用 `@pytest.mark.parametrize` 来参数化测试函数。例如:
import pytest
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(-1, 1, 0),
(0, 0, 0)
])
def test_add(a, b, expected):
assert add(a, b) == expected
- 运行特定测试
如果你只想运行特定的测试,可以使用以下命令:
pytest -k "test_add"
- 生成测试报告
你还可以生成测试报告,比如 HTML 格式的报告。首先安装 `pytest-html`:
pip install pytest-html
然后运行测试并生成报告:
pytest --html=report.html
`pytest` 是一个功能强大且灵活的测试框架,适合用于单元测试和集成测试。通过上述方法,你可以快速上手并编写测试用例。
实践
这里有一个基于Alchemy 访问MySQL的类,要对其中的方法进行测试,使用pytest输出测试报告。写了三个单元测试文件,应用了夹具和参数进行测试,最终的结果如下:
测试代码如下:
# hanzi_test.py
import os
import sys
# 添加当前文件所在目录到Python路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
# 添加包的父目录到Python路径中
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
from interface.mysql.db_dictation.service.HanziService import HanziService
from interface.mysql.db_dictation.entity.Hanzi import Hanzi
def test_hanzi():
obj = HanziService()
res = obj.getByHanzi('好')
for itm in res:
assert itm.f_hanzi == '好'
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
def test_hanzi_pinyin():
obj = HanziService()
res = obj.getByHanziAndPinyin('好', 'hào')
assert res.f_hanzi == '好'
assert res.f_pinyin == 'hào'
itm = res
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
def test_pinyin():
obj = HanziService()
res = obj.getByPinyin('hào')
for itm in res:
assert itm.f_pinyin == 'hào'
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
# fixture_test.py
import os
import sys
# 添加当前文件所在目录到Python路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
# 添加包的父目录到Python路径中
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
import pytest
@pytest.fixture
def getObj():
from interface.mysql.db_dictation.service.HanziService import HanziService
from interface.mysql.db_dictation.entity.Hanzi import Hanzi
return HanziService()
def test_fixture_hanzi(getObj):
res = getObj.getByHanzi('好')
for itm in res:
assert itm.f_hanzi == '好'
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
def test_fixture_hanzi_pinyin(getObj):
res = getObj.getByHanziAndPinyin('好', 'hào')
assert res.f_hanzi == '好'
assert res.f_pinyin == 'hào'
itm = res
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
def test_fixture_pinyin(getObj):
res = getObj.getByPinyin('hào')
for itm in res:
assert itm.f_pinyin == 'hào'
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
# parametrize_test.py
import os
import sys
# 添加当前文件所在目录到Python路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
# 添加包的父目录到Python路径中
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
from interface.mysql.db_dictation.service.HanziService import HanziService
from interface.mysql.db_dictation.entity.Hanzi import Hanzi
import pytest
@pytest.mark.parametrize("hanzi, pinyin, expected", [
('好', 'hào','好'),
('耗', 'hào','耗'),
('浩', 'hào','浩'),
('颢', 'hào','颢'),
])
def test_parametrize_hanzi(hanzi,pinyin,expected):
obj = HanziService()
res = obj.getByHanzi(hanzi)
for itm in res:
assert itm.f_hanzi == expected
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
@pytest.mark.parametrize("hanzi, pinyin, expected", [
('好', 'hào','好'),
('耗', 'hào','耗'),
('浩', 'hào','浩'),
('颢', 'hào','颢'),
])
def test_parametrize_hanzi_pinyin(hanzi,pinyin,expected):
obj = HanziService()
res = obj.getByHanziAndPinyin(hanzi, pinyin)
assert res.f_hanzi == hanzi
assert res.f_pinyin == pinyin
itm = res
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
@pytest.mark.parametrize("hanzi, pinyin, expected", [
('好', 'hào','好'),
('耗', 'hào','耗'),
('浩', 'hào','浩'),
('颢', 'hào','颢'),
])
def test_parametrize_pinyin(hanzi,pinyin,expected):
obj = HanziService()
res = obj.getByPinyin(pinyin)
for itm in res:
assert itm.f_pinyin == pinyin
print(f"{itm.f_hanzi} {itm.f_pinyin} {itm.f_meaning} {itm.f_sound_url} {itm.f_writing_url}")
参考文章:
- Python技术架构 https://www.toutiao.com/article/7422119050685334054/
- PyTest : https://docs.pytest.org/en/stable/index.html
相关推荐
- perl基础——循环控制_principle循环
-
在编程中,我们往往需要进行不同情况的判断,选择,重复操作。这些时候我们需要对简单语句来添加循环控制变量或者命令。if/unless我们需要在满足特定条件下再执行的语句,可以通过if/unle...
- CHAPTER 2 The Antechamber of M de Treville 第二章 特雷维尔先生的前厅
-
CHAPTER1TheThreePresentsofD'ArtagnantheElderCHAPTER2TheAntechamber...
- CHAPTER 5 The King'S Musketeers and the Cardinal'S Guards 第五章 国王的火枪手和红衣主教的卫士
-
CHAPTER3TheAudienceCHAPTER5TheKing'SMusketeersandtheCardinal'SGuard...
- CHAPTER 3 The Audience 第三章 接见
-
CHAPTER3TheAudienceCHAPTER3TheAudience第三章接见M.DeTrévillewasatt...
- 别搞印象流!数据说明谁才是外线防守第一人!
-
来源:Reddit译者:@assholeeric编辑:伯伦WhoarethebestperimeterdefendersintheNBA?Here'sagraphofStea...
- V-Day commemorations prove anti-China claims hollow
-
People'sLiberationArmyhonorguardstakepartinthemilitaryparademarkingthe80thanniversary...
- EasyPoi使用_easypoi api
-
EasyPoi的主要特点:1.设计精巧,使用简单2.接口丰富,扩展简单3.默认值多,writelessdomore4.springmvc支持,web导出可以简单明了使用1.easypoi...
- 关于Oracle数据库12c 新特性总结_oracle数据库12514
-
概述今天主要简单介绍一下Oracle12c的一些新特性,仅供参考。参考:http://docs.oracle.com/database/121/NEWFT/chapter12102.htm#NEWFT...
- 【开发者成长】JAVA 线上故障排查完整套路!
-
线上故障主要会包括CPU、磁盘、内存以及网络问题,而大多数故障可能会包含不止一个层面的问题,所以进行排查时候尽量四个方面依次排查一遍。同时例如jstack、jmap等工具也是不囿于一个方面的问题...
- 使用 Python 向多个地址发送电子邮件
-
在本文中,我们将演示如何使用Python编程语言向使用不同电子邮件地址的不同收件人发送电子邮件。具体来说,我们将向许多不同的人发送电子邮件。使用Python向多个地址发送电子邮件Python...
- 提高工作效率的--Linux常用命令,能够决解95%以上的问题
-
点击上方关注,第一时间接受干货转发,点赞,收藏,不如一次关注评论区第一条注意查看回复:Linux命令获取linux常用命令大全pdf+Linux命令行大全pdf为什么要学习Linux命令?1、因为Li...
- linux常用系统命令_linux操作系统常用命令
-
系统信息arch显示机器的处理器架构dmidecode-q显示硬件系统部件-(SMBIOS/DMI)hdparm-i/dev/hda罗列一个磁盘的架构特性hdparm-tT/dev/s...
- 小白入门必知必会-PostgreSQL-15.2源码编译安装
-
一PostgreSQL编译安装1.1下载源码包在PostgreSQL官方主页https://www.postgresql.org/ftp/source/下载区选择所需格式的源码包下载。cd/we...
- Linux操作系统之常用命令_linux系统常用命令详解
-
Linux操作系统一、常用命令1.系统(1)系统信息arch显示机器的处理器架构uname-m显示机器的处理器架构uname-r显示正在使用的内核版本dmidecode-q显示硬件系...
- linux网络命名空间简介_linux 网络相关命令
-
此篇会以例子的方式介绍下linux网络命名空间。此例中会创建两个networknamespace:nsa、nsb,一个网桥bridge0,nsa、nsb中添加网络设备veth,网络设备间...
- 一周热门
- 最近发表
-
- perl基础——循环控制_principle循环
- CHAPTER 2 The Antechamber of M de Treville 第二章 特雷维尔先生的前厅
- CHAPTER 5 The King'S Musketeers and the Cardinal'S Guards 第五章 国王的火枪手和红衣主教的卫士
- CHAPTER 3 The Audience 第三章 接见
- 别搞印象流!数据说明谁才是外线防守第一人!
- V-Day commemorations prove anti-China claims hollow
- EasyPoi使用_easypoi api
- 关于Oracle数据库12c 新特性总结_oracle数据库12514
- 【开发者成长】JAVA 线上故障排查完整套路!
- 使用 Python 向多个地址发送电子邮件
- 标签列表
-
- HTML 教程 (33)
- HTML 简介 (35)
- HTML 实例/测验 (32)
- HTML 测验 (32)
- JavaScript 和 HTML DOM 参考手册 (32)
- HTML 拓展阅读 (30)
- HTML文本框样式 (31)
- HTML滚动条样式 (34)
- HTML5 浏览器支持 (33)
- HTML5 新元素 (33)
- HTML5 WebSocket (30)
- HTML5 代码规范 (32)
- HTML5 标签 (717)
- HTML5 标签 (已废弃) (75)
- HTML5电子书 (32)
- HTML5开发工具 (34)
- HTML5小游戏源码 (34)
- HTML5模板下载 (30)
- HTTP 状态消息 (33)
- HTTP 方法:GET 对比 POST (33)
- 键盘快捷键 (35)
- 标签 (226)
- HTML button formtarget 属性 (30)
- opacity 属性 (32)
- transition 属性 (33)