Pytest 简明教程

pytest-learn

通过文章 Python 单元测试框架之 Pytest 剖解入门(第一篇) 学习 Pytest。

有很多的第三方插件可以自定义扩展,并且支持 Allure,生成可视化的测试报告和测试结果,并能输出 log 信息

说明

本文实验环境为:

  • windows 7
  • python 3.7.0
  • pytest version 4.0.1

安装

pip install -U pytest
pytest --version # This is pytest version 4.0.1
# 安装插件
pip install pytest-html # 自动生成 HTML 格式测试报告
pip install pytest-autochecklog # 不只是自动生成测试日志
pip install pytest-describe # 给测试用例一个美丽的名字

Pycahrm 配置 Pytest

File -> Settings -> Tools -> Python Integrated Tools,在 Default test runner 中选择 Pytest 。我们可以回到写有测试函数的文件中直接右键,会出现一个Run 'py.test' for project_name,直接点击即可运行自动化测试。

Pytest 测试样例规范

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

创建第一个测试用例

# content of test_sample.py
def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

直接在该文件夹下打开命令行,输入pytest即可运行。

断言某个异常会引发

# content of test_sysexit.py
import pytest
def f():
    raise SystemExit(1)

def test_mytest():
    with pytest.raises(SystemExit):
        f()

运行如下命令:

pytest -q test_sysexit.py # 用例通过 -q 表示 quite

在一个 class 中组合多个测试

一旦开发了多个测试,您可能希望将它们分组到一个类中。 pytest 可以轻松创建包含多个测试的类:

# content of test_class.py
class TestClass(object):
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

运行如下命令:

pytest -q test_class.py

为功能测试请求一个唯一的临时目录

pytest 提供 Built fixtures/function arguments 来请求任意资源,比如一个独一无二的临时目录:

# content of test_tmpdir.py
def test_needsfiles(tmpdir):
    print(tmpdir)
    assert 0
pytest -q test_tmpdir.py

pytest 会在测试函数调用之前,查找并调用一个fixture factory来创建这个资源。 在这个测试用例运行之前,pytest 为每个测试调用创建独一无二的目录。

关于提供的tmpdir更多的信息,可以查询Temporary diretories and files

可以通过如下命令查看自带的 pytest fixtures

pytest --fixtures   # shows builtin and custom fixtures

Note: 命令行除非加上 -v ,否则如上命令将会自动省略_开头的fixtures

生成测试报告

pytest-html

# 安装插件
pip install -U pytest-html

运行:

pytest --html=report.html

参考

posted @ 2019-03-03 18:34  Michael翔  阅读(2875)  评论(0编辑  收藏  举报