- 安装
pip install pytest
- 查看版本
pytest --version
-
编写规则
1. 测试文件以 test 开头(或以 test 结尾也可以)
2. 测试类以 Test 开头,并且不能带有 __init __ 方法
3. 测试用例以 test 开头 -
运行入口
unittest.main() 方法会运行所有测试集Test Suite中的用例
pytest.main() 则需要传入参数,参数形式为list,list包含需要运行测试的module名字
# 此 py 文件名为 test1.py
import pytest
class TestDemo:
def test1(self):
assert 1 == 1
print('test - 1')
def test2(self):
assert 2 == 2
print('test - 2')
if __name__ == '__main__':
# 没有传参
pytest.main()
运行结果
传入参数
if __name__ == '__main__':
pytest.main(['test1.py'])
再次运行
还可以看到下面的 test1.py ..
后面跟着两个点,.
表示测试用例通过Passed,修改用例代码再运行
============================= test session starts =============================
platform win32 -- Python 3.7.3, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: E:\python_lianxi
collected 2 items
test1.py F. [100%]
================================== FAILURES ===================================
_________________________________ Test1.test1 _________________________________
self = <test1.Test1 object at 0x0000023D00EAC2B0>
def test1(self):
> assert 1 == 2
E assert 1 == 2
test1.py:5: AssertionError
=========================== short test summary info ===========================
FAILED test1.py::Test1::test1 - assert 1 == 2
========================= 1 failed, 1 passed in 0.25s =========================
Process finished with exit code 0
可以看到结果变为 test1.py .F
,第一个用例 F
Failed,第二个用例 .
Passed,下面是详细失败信息
在运行结果中还有一个问题,控制台没有任何测试用例中的打印输出,用下面的参数解决
- 参数
- -v 用于显示每个测试用例的执行结果
- -q 只显示整体测试结果
- -s 用于显示测试用例中 print() 输出
- -x 在第一个错误或失败时立即退出
- -h 帮助
- -r 显示摘要信息,后面还可以加以下参数
- f failedd - 只看 failed 的信息
- E error - 只看有 error 的信息
- s skipped - 只看被跳过的信息
- x xfailed - 只看 xfailed 的信息
- X xpassed - 只看 xpassed 的信息
- p passed - 只看 passed 的信息
- P passed with output - 只看 passed 并且有输出的信息
给上面的main()加上参数
if __name__ == '__main__':
pytest.main(['test1.py', '-sv'])
运行结果
============================= test session starts =============================
platform win32 -- Python 3.7.3, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 -- E:\python_lianxi\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: E:\python_lianxi
collecting ... collected 2 items
test1.py::Test1::test1 test1
PASSED
test1.py::Test1::test2 test2
PASSED
============================== 2 passed in 0.03s ==============================
Process finished with exit code 0
- Terminal 运行
- 使用 pytest 命令
pytest -sc test1.py
-使用 python 命令
python -m pytest test1.py
- 使用 pytest 命令