0%

pytest学习笔记

安装

安装pytest时,直接使用pip安装就可以了:

1
pip install pytest

pytest辨认测试文件和测试函数

如果运行pytest没有指定文件的话,pytest会将所有形式为”test_*.py”或者”*_test.py”的文件运行。

另外,pytest要求测试函数必须以”test”开头,并且不能通过其他方式在代码中显示指定哪些函数是需要被pytest测试的测试函数。

第一个测试程序

在项目目录下新建一个叫做”test_first.py”的文件,文件的内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
import math

def test_sqrt():
num = 25
assert math.sqrt(num) == 5

def testsqure():
num = 7
assert num * num == 40

def tesequlity():
assert 10 == 11

之后,在命令行中执行命令:

1
pytest

之后pytest就会开始运行单元测试,并产生测试报告。注意到,第三个函数不是以test开头的函数,所以pytest将不会对第三个函数进行测试。

使用”-v”(verbose)参数可以打印更多的信息。

pytest选择执行文件

在上例的基础上,再创建一个名叫”test_second.py”的文件,文件的内容如下:

1
2
3
4
5
6
7
8
9
10
11
def test_greater():
num = 100
assert num > 100

def test_greater_equal():
num = 100
assert num >= 100

def test_less():
num = 100
assert num < 200

此时,如果执行执行”pytest”命令,pytest将对test_first.py和test_second.py中的函数都进行测试。

如果只想对”test_scond.py”文件进行测试,可以执行下面的命令:

1
pytest test_second.py

指定测试函数搜索名称

在pytest命令中,可以使用”-k”参数指定关键字过滤,pytest只会测试那些含有关键字的函数。注意,即使指定了关键字,仍然要求函数以test开头,否则即使有关键字也不会对该函数进行测试。例如在文件中有函数的名称为”keyword”,即使使用命令:

1
pytest -k keyword

pytest也不会对”keyword”这个函数进行测试。

将测试函数分组

pytest运行用户对测试函数使用”marker”,”marker”可以给测试函数添加多种特性,mark本质上是一个函数装饰器。pytest自身提供了一些内建的”marker”,另外用户也可以自定义”marker”。marker在代码中的使用方法如下:

1
2
3
4
import pytest
@pytest.mark.<markname>
def test_xxxx():
pass

在测试时,可以对pytest命令添加”-m”参数来指定marker,pytest将只会运行有相同marker标记的测试函数。

1
pytest -m <markname>
注意函数名仍然需要以test起始。

Fixture

Fixture是一个自定义的函数,这个函数在每个测试函数被执行前,都会执行一遍这个fixture函数。fixture函数通常可以用来给测试函数提供数据源,例如从数据库获取数据等。

声明一个Fixture函数

1
2
3
4
import pytest
@pytest.fixture
def input_value():
return 30

使用Fixture函数:在测试函数中使用fixture函数,需要将fixture函数的函数名作为输入参数:

1
2
def test_input(input_value):
assert input_value % 3 == 0

conftest.py

conftest.py在使用了pytest的项目中是一个特殊的文件,我们可以在这个文件中定义fixture函数,而在其他所有测试函数中使用定义的fixture函数,并且不必在代码中显示地import这个文件。

1
2
3
4
5
6
7
8
9
#in conftest.py
import pytest
@pytest.fixture
def input_value():
return 30

#in other test file
def test_input(input_value):
assert input_value % 3 == 0

Parameterizing Tests

Parameterizing Tests可以给测试函数指定多个输入参数的值,直接看例子:

1
2
3
4
5
import pytest

@pytest.mark.parametrize("num", "output", [(1, 11), (2, 22), (3,35), (4, 44)])
def test_multiplication_11(num, output):
assert num * 11 == output

Xfail/Skip Tests

使用xfail “marker”标记的测试函数,会被pytest执行,但是不会进入pytest的统计,即使测试函数失败了也不会被打印出来。

1
2
3
4
import pytest
@pytest.mark.xfail
def test_something():
pass

使用skip “marker”标记的测试函数,不会被pytest执行。

指定N个测试失败后结束测试

可以在pytest命令中使用”—maxfail”参数来指定测试多少个函数失败后就停止测试。

1
pytest --maxfail=3

一般在测试用例较多,测试时间较长时使用。

并行测试

默认情况下,pytest是串行运行测试函数的,当测试函数数量较多时,可能需要并行运行测试函数。要并行运行测试函数,需要下载pytest-xdist插件

1
pip install pytest-xdist

现在可以使用 pytest -n \来指定并行度

1
pytest -n 3