pytest 使用

pytest 上手比较简单.

环境

Python

最好在工作目录建个虚拟环境:

1
2
python -m venv venv
source venv/bin/activate

pytest

安装

1
pip install pytest

资源

文档

在线文档
PDF
想要运行示例,看在线文档第一页就行.
想要系统学习,个人感觉看PDF文档比较好.

帮助

1
pytest --help

可以看到所有的命令行参数及输入输出控制.
其中有一个比较重要的参数可以详细看看:

1
2
3
4
5
6
7
8
9
10
11
12
13
general:
-k EXPRESSION only run tests which match the given substring expression. An
expression is a python evaluatable expression where all names
are substring-matched against test names and their parent
classes. Example: -k 'test_method or test_other' matches all
test functions and classes whose name contains 'test_method'
or 'test_other', while -k 'not test_method' matches those
that don't contain 'test_method' in their names. -k 'not
test_method and not test_other' will eliminate the matches.
Additionally keywords are matched to classes and functions
containing extra names in their 'extra_keyword_matches' set,
as well as functions which have names assigned directly to
them. The matching is case-insensitive.

pytest 默认会collect test_.py 或者 _test.py module 中 以test为前缀的function 或者以Test为前缀的class中以test为前缀的function(no init),
通过这个参数可以自定义控制

示例

入门例子

在工作目录新建:test_sample.py

1
2
3
4
5
6
# test_sample.py
def inc(x):
return x + 1

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

当前目录运行:
1
pytest

便可以看到report.

Report 示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
(venv) ➜  ln_pytest pytest
=========================== test session starts ============================
platform darwin -- Python 3.6.5, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: ../ln_pytest
collected 5 items

test_cases1.py FF. [ 60%]
test_cases2.py F. [100%]

================================= FAILURES =================================
_______________________________ test_answer ________________________________

def test_answer():
> assert inc(3) == 5
E assert 4 == 5
E + where 4 = inc(3)

test_cases1.py:10: AssertionError
_______________________________ test_answer2 _______________________________

def test_answer2():
> assert inc(3) == 5
E assert 4 == 5
E + where 4 = inc(3)

test_cases1.py:14: AssertionError
_______________________________ test_answer ________________________________

def test_answer():
> assert inc(3) == 5
E assert 4 == 5
E + where 4 = inc(3)

test_cases2.py:10: AssertionError
========================= short test summary info ==========================
FAILED test_cases1.py::test_answer - assert 4 == 5
FAILED test_cases1.py::test_answer2 - assert 4 == 5
FAILED test_cases2.py::test_answer - assert 4 == 5
======================= 3 failed, 2 passed in 0.39s ========================

Feature

用例(进入) 默认情况下自动发现关键词:“test”,
断言(判断) 灵活易懂

报告

依赖

1
2
pip install allure-pytest
brew install allure

生成测试结果数据

1
pytest --alluredir ./result/

将结果渲染到页面

1
allure serve result -h 127.0.0.1 -p 8080

Markdown