本系列一共会有四篇文章,上篇,中篇,下篇,终篇。
「本章知识点」
官网地址:https://docs.pytest.org/en/latest/contents.html
Pytest官方介绍:
The
pytestframework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries.
Pytest安装要求:Python 3.7+
pip install pytest
「验证安装」
pytest --version #会显示当前已安装的版本
1、所有的单测文件名都需要满足
test_*.py格式或*_test.py格式。 2、在单测文件中,测试类以Test开头,并且不能带有 「init」 方法(注意:定义class时,需要以T开头,不然pytest是不会去运行该class的) 3、在单测类中,可以包含一个或多个test_开头的函数。 4、在执行pytest命令时,会自动从当前目录及子目录中寻找符合上述约束的测试函数来执行。
在pycharm运行,默认是使用Autodetect方式进行测试,这里我们可以更改为pytest
settings --> Tools --> Python Integrated Tools --> Testing --> Default test runne

Exit code 0 所有用例执行完毕,全部通过
Exit code 1 所有用例执行完毕,存在Failed的测试用例
Exit code 2 用户中断了测试的执行
Exit code 3 测试执行过程发生了内部错误
Exit code 4 pytest 命令行使用错误
Exit code 5 未采集到可用测试用例文件
新建test_a.py文件,编写如下代码:
def test_001():
print("pytest执行的第一个测试用例")
「右键执行」,启动项显示「Pytest」

「运行结果如下:」

「新建test_b.py」文件,编写如下代码:
class TestB():
def test_b_001(self):
print("我是TestB下的test_b_001")
def test_b_002(self):
print("我是TestB下的test_b_002")
执行结果如下:
Testing started at 11:19 ...
Launching pytest with arguments D:/L_Learning/MyLearningCode/ApiTestProject/test_b.py --no-header --no-summary -q in D:\L_Learning\MyLearningCode\ApiTestProject
============================= test session starts =============================
collecting ... collected 2 items
test_b.py::TestB::test_b_001 PASSED [ 50%]我是TestB下的test_b_001
test_b.py::TestB::test_b_002 PASSED [100%]我是TestB下的test_b_002
============================== 2 passed in 0.01s ==============================
Process finished with exit code 0
「由上可知,类只要是符合Test开头,pytest都会收集下来并执行。」
「新建main.py文件」,编写代码如下:
import pytest
pytest.main()
当前项目目录如下:

「在main.py文件里面右键运行」,执行结果如下:
============================= test session starts =============================
platform win32 -- Python 3.8.8, pytest-7.2.1, pluggy-1.0.0
rootdir: D:\L_Learning\MyLearningCode\ApiTestProject
collected 3 items
test_a.py . [ 33%]
test_b.py .. [100%]
============================== 3 passed in 0.01s ==============================
Process finished with exit code 0
「由上可知,文件只要是符合Test开头,pytest都会收集下来并执行。」
到此,你算是简单入门pytest的使用啦。
pytest教程系列之前录制了视频,不过本人普通话不是很好,就不放出来了。