pytest测试框架入门

1|0安装pytest

命令行输入:

pip install -U pytest

检查是否安装了正确的版本:

λ pytest --version This is pytest version 5.3.5, imported from e:\python37\lib\site-packages\pytest\__init__.py setuptools registered plugins: pytest-html-2.0.1 at e:\python37\lib\site-packages\pytest_html\plugin.py pytest-metadata-1.8.0 at e:\python37\lib\site-packages\pytest_metadata\plugin.py

2|0一个简单的demo

import pytest def func(x): return x + 1 def test_answer(): assert func(3) == 5

运行demo

首先进入到此demo文件的路径下,然后执行 pytest ,会运行名称为test*.py的文件(*匹配任意符合字母和数字)

pytest运行规则查找当前目录及其子目录下以test_.py或_test.py文件,找到文件后,在文件中找到以test开头函数并执行。

C:\Users\haiy\Desktop\code\iot_yjb_api λ pytest ============================ test session starts ============================= platform win32 -- Python 3.7.1rc1, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 rootdir: C:\Users\haiy\Desktop\code\iot_yjb_api plugins: html-2.0.1, metadata-1.8.0 collected 1 item test_api.py F [100%] ================================== FAILURES ================================== ________________________________ test_answer _________________________________ def test_answer(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) test_api.py:9: AssertionError ============================= 1 failed in 0.23s =============================

此测试返回失败报告,因为 func(3) 不返 5 .

 如何编写pytest测试样例

通过上面的实例,我们发现编写pytest测试样例非常简单,只需要按照下面的规则:

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试类以Test开头,并且不能带有 init 方法
  • 测试函数以test_开头
  • 断言使用基本的assert即可

__EOF__

本文作者Harry
本文链接https://www.cnblogs.com/harry66/p/13363360.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   Harry_666  阅读(432)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示