Python第三方测试框架pytest学习笔记

编程 · 05-08 · 301 人浏览

之前有用到Python自带的测试框架unittest,听说,Python中最火的第三方开源测试框架是pytest,我们也稍微来学习一下吧!

介绍

pytest是一个非常成熟的全功能Python测试框架,简单灵活,容易上手。

文档:http://docs.pytest.org/en/latest/contents.html

Github地址:https://github.com/pytest-dev/pytest/

安装

安装pytest:pip install pytest,pip下载速度慢的话,可通过修改pip镜像源加快模块下载速度

查看pytest版本:pytest --version

使用

文件hello.py:

def hello(to="world"):
    return f"hello, {to}"

print(hello())
print(hello("python"))

文件test_hello.py:

from hello import hello

def test_hello():
    assert hello() == "hello, world"
    assert hello("python") == "hello, python"

执行测试:pytest test_hello.py,指定测试文件路径,也可指定文件夹,假设是test文件夹:pytest test

pytest发现用例规则:

  • 文件名以test_开头或以_test.py结尾
  • 函数名以test_开头
  • 类名以Test开头
  • 使用pytest自动发现测试用例,或通过配置文件自定义规则
Python
Theme Jasmine by Kent Liao