pytest文档1-环境准备与入门
安装pytest
1.安装方法
pip install -U pytest
2.pip show pytest查看安装版本
pip show pytest
3.也可以pytest --version查看安装的版本
pytest --version
This is pytest version 3.6.3, imported from d:\soft\python3.6\lib\site-packages\
pytest.py
快速开始
1.新建一个test_sample.py文件,写以下代码
# content of test_sample.py
def func(x):
return x +1
def test_answer():
assert func(3)==5
2.打开test_sample.py所在的文件夹,cmd窗口输入:pytest(或者输入py.test也可以)
D:\YOYO>pytest
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO, inifile:
collected 1 item
test_sample.py F [100%]
================================== FAILURES ===================================
_________________________________ test_answer _________________________________
def test_answer():
> assert func(3)==5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:6: AssertionError
========================== 1 failed in 0.19 seconds ===========================
3.pytest运行规则:**查找当前目录及其子目录下以test_*.py或*_test.py文件,找到文件后,在文件中找到以test开头函数并执行。**
写个测试类
1.前面是写的一个test开头的测试函数,当用例用多个的时候,写函数就不太合适了。这时可以把多个测试用例,写到一个测试类里。
# test_class.py
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
2.pytest会找到符合规则(test_.py和_test.py)所有测试,因此它发现两个test_前缀功能。 如果只想运行其中一个,可以指定传递文件名test_class.py来运行模块:
备注: -q, --quiet decrease verbosity( 显示简单结果)
py.test -q test_class.py
D:\YOYO>py.test -q test_class.py
.F [100%]
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________
self = <test_class.TestClass object at 0x00000000039F1828>
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:11: AssertionError
1 failed, 1 passed in 0.04 seconds
第一次测试通过,第二次测试失败。 您可以在断言中轻松查看失败的原因。
pytest用例规则
- 测试文件以test_开头(以_test结尾也可以)
- 测试类以Test开头,并且不能带有 init 方法
- 测试函数以test_开头
- 断言使用assert
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架