[The Python] unit testing using pytest

Installation pytest

pipenv install pytest

Verify installed version:

 pytest --version
This is pytest version 5.3.1, imported from /home/wangju/.virtualenvs/demo_pytest-0JOM2vOx/lib/python3.6/site-packages/pytest.py

Then through the use of a few examples of familiar pytest

Example 1: 

Create a py file, as follows: Run only one case

Note: py file you want to start with test_, otherwise run pytest not run the test method py file

import pytest

def func(x):
    return x+1

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

Perform the test:

When performing the test, we only need to test files in the directory where the test_demo1, you can run pytest. pytest will be in the current directory, look for the file (ie, test files) at the beginning of the test, after finding test files, test files into a beginning test_ test function and perform. 

effect:

 Analysis shows:

Mark 1 test run using a command pytest 

Numeral 2 can be seen that the assertion failure reasons: assert 4 == 5 failed

 Example 2:

Pytest execute commands run in a terminal:

pytest -q test_demo2.py

效果:

分析说明:

标记1处:

-q即-quiet,作用是减少冗长,具体就是不再展示pytest的版本信息。

因为我们已经创建了1个test_demo1这个py文件,此时我只想运行test_demo2这个文件,所以在此指明pytest只运行test_demo.py

标记2处:

可以看到,运行成功的case会显示为1个绿色的点,运行失败的case显示为F

标记3处:

可以看到断言失败的原因

不熟悉hasattr的用法,可以看这里:Python hasattr() 函数

如果case全部运行成功,则显示如下:

 

 

 

如何编写pytest测试样例

通过上面2个实例,我们发现编写pytest测试样例非常简单,只需要按照下面的规则:

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

参考文档:

这篇内容不错,有pytest使用实例,适合入门

【Pytest】python单元测试框架pytest简介

全功能Python测试框架:pytest

Pytest - 使用介绍

Guess you like

Origin www.cnblogs.com/kaerxifa/p/12009117.html