时间:2023-03-17 13:21:40 | 栏目:Python代码 | 点击:次
Pytest 是 Python 的一种单元测试框架,与 Python 自带的 unittest 测试框架类似,但是比 unittest 框架使用起来更简洁,效率更高。
Pytest是一个非常成熟的Python测试框架,主要特点有以下几点:
pip install pytest

pytest --version

pip install pytest-html
这里已经安装过,所以输出信息和第一次安装不一样。

File->Settings->Tools->Python Integrated Tools

点击Edit Configurations。

依次点击"+" --》 Python tests --》pytest
如下:

用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的。
文件名以 test_*.py 文件或*_test.py;
以 test_ 开头的函数;
以 Test 开头的类,不能包含 __init__ 方法;
以 test_ 开头的类里面的方法;
所有的包(package)必项要有__init__.py 文件。
环境都准备好了,尝试下使用pytest运行用例。
新建py文件
写两条测试用例
import pytest
def test_demo1():
assert 3 == 3
def test_demo2():
assert 3 == 5
if __name__ == '__main__':
pytest.main()
运行之后,结果如下:
Testing started at 12:37 ...
C:\Users\96984\Desktop\code\learn_pytest\venv\Scripts\python.exe "C:\ruanjian\pycharm2019.3\PyCharm 2019.3.1\plugins\python\helpers\pycharm\_jb_pytest_runner.py" --path C:/Users/96984/Desktop/code/learn_pytest/demo/demo_pytest.py
Launching pytest with arguments C:/Users/96984/Desktop/code/learn_pytest/demo/demo_pytest.py in C:\Users\96984\Desktop\code\learn_pytest\demo
============================= test session starts =============================
platform win32 -- Python 3.6.8, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 -- C:\Users\96984\Desktop\code\learn_pytest\venv\Scripts\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.6.8', 'Platform': 'Windows-10-10.0.18362-SP0', 'Packages': {'pytest': '5.4.3', 'py': '1.9.0', 'pluggy': '0.13.1'}, 'Plugins': {'html': '2.1.1', 'metadata': '1.10.0'}, 'JAVA_HOME': 'C:\\Program Files\\Java\\jdk1.8.0_77'}
rootdir: C:\Users\96984\Desktop\code\learn_pytest\demo
plugins: html-2.1.1, metadata-1.10.0
collecting ... collected 2 items
demo_pytest.py::test_demo1 PASSED [ 50%]
demo_pytest.py::test_demo2 FAILED [100%]
demo_pytest.py:8 (test_demo2)
def test_demo2():
> assert 3 == 5
E AssertionError
demo_pytest.py:10: AssertionError
================================== FAILURES ===================================
_________________________________ test_demo2 __________________________________
def test_demo2():
> assert 3 == 5
E AssertionError
demo_pytest.py:10: AssertionError
=========================== short test summary info ===========================
FAILED demo_pytest.py::test_demo2 - AssertionError
========================= 1 failed, 1 passed in 0.05s =========================
Process finished with exit code 0