pytest学习

test.py::test_passing PASSED [100%]

test2.py::test_failing FAILED [100%]

test2.py::test_func1 PASSED [ 50%]

test2.py::test_func2 FAILED [100%]

测试时使用 -m 选择标记的测试函数:

$ pytest -m finished tests/test-function/test_with_mark.py ============================= test session starts ============================= platform win32 -- Python 3.6.4, pytest-3.6.1, py-1.5.2, pluggy-0.6.0 rootdir: F:\self-repo\learning-pytest, inifile: collected 2 items / 1 deselected tests\test-function\test_with_mark.py . [100%] =================== 1 passed, 1 deselected in 0.10 seconds ====================

使用 mark,我们可以给每个函数打上不同的标记,测试时指定就可以允许所有被标记的函数。

Pytest 使用特定的标记 pytest.mark.skip 完美的解决了这个问题。

# test_skip.py @pytest.mark.skip(reason='out-of-date api') def test_connect(): pass

Pytest 还支持使用 pytest.mark.skipif 为测试函数指定被忽略的条件。

@pytest.mark.skipif(conn.__version__ < '0.2.0', reason='not supported until v0.2.0') def test_api(): pass

预见的错误

如果我们事先知道测试函数会执行失败,但又不想直接跳过,而是希望显示的提示。

Pytest 使用 pytest.mark.xfail 实现预见错误功能:

# test_xfail.py @pytest.mark.xfail(gen.__version__ < '0.2.0', reason='not supported until v0.2.0') def test_api(): id_1 = gen.unique_id() id_2 = gen.unique_id() assert id_1 != id_2

执行结果:

$ pytest tests/test-function/test_xfail.py ============================= test session starts ============================= platform win32 -- Python 3.6.4, pytest-3.6.1, py-1.5.2, pluggy-0.6.0 rootdir: F:\self-repo\learning-pytest, inifile: collected 1 item tests\test-function\test_xfail.py x [100%] ========================== 1 xfailed in 0.12 seconds ==========================

注解

pytest 使用 x 表示预见的失败(XFAIL)。

如果预见的是失败,但实际运行测试却成功通过,pytest 使用 X 进行标记(XPASS)。

什么是固件

固件(Fixture)是一些函数,pytest 会在执行测试函数之前(或之后)加载运行它们。

我们可以利用固件做任何事情,其中最常见的可能就是数据库的初始连接和最后关闭操作。

Pytest 使用 pytest.fixture() 定义固件,

定制报告

Feature: 标注主要功能模块

Story: 标注Features功能模块下的分支功能

Severity: 标注测试用例的重要级别

Step: 标注测试用例的重要步骤

Issue和TestCase: 标注Issue、Case,可加入URL

attach: 标注增加附件

Environment: 标注环境Environment字段

发布了52 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/m0_37636884/article/details/105735231