微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

pytest测试框架入门

安装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

一个简单的demo

import pytest

def func(x):
    return x + 1

 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-1,pluggy-0.13.1
rootdir: C:\Users\haiy\Desktop\code\iot_yjb_api
plugins: html-Metadata-0
collected  item

test_api.py F                                                           [100%]

================================== FAILURES ================================== ________________________________ test_answer _________________________________

    def test_answer():
>       assert func(3) == 5
E    assert 4 == 
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即可

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐