Pytest (一)


为什么要选择Pytest

Pytest可以说是Unitest的高配版,不管了为了实用性、功能性、还是找工作都是最优解

安装Pytest

pip install pytest

执行一个简单的测试例子

1 def inc(x):
2     return x + 1
3 
4 
5 def test_answer():
6     assert inc(3) == 5

 随后在控制台直接输入 pytest即可执行

Pytest的使用规范(不符合的测试用例是会被跳过的):

  • 文件名以 test_*.py 文件和*_test.py
  • 以  test_ 开头的函数
  • 以  Test 开头的类,不能包含 __init__ 方法
  • 以  test_ 开头的类里面的方法
  • 所有的包 package 必须要有__init__.py 文件

Pytest用例运行规则:

#执行某个目录下所有的用例
pytest
#执行某一个 py 文件下用例
pytest   脚本名称.py
#运行testfile.py 模块里面的某个函数,或者某个类,某个类里面的方法
pytest testfile.py::test_mothod
pytest testfile.py::TestClass
#运行testfile.py 模块里面,测试类里面的某个方法
pytest testfile.py::TestClass::test_mothod
#-m 标记表达式
pytest -m testfile.py
#-q 简单打印,只打印测试用例的执行结果
pytest -q testfile.py
#-s 详细打印
pytest -s testfile.py
#-x 遇到错误时停止测试
pytest testfile.py -x 
#—maxfail=num,当用例错误个数达到指定数量时,停止测试
pytest testfile.py --maxfail=2
#-k 匹配用例名称
pytest -k demo testfile.py
#-k 根据用例名称排除某些用例
pytest -k "not demo" testfile.py
#-k 同时匹配不同的用例名称
pytest -k "demo or emo" testfile.py

相关