pytest 测试用例收集规则+运行

1.用例收集规则

  • 从一个或者多个目录开始查找,你可以在命令行指定文件或者目录,如果未指定那么从当前目录开始收集用例;
  • 在该目录和所有子目录下递归查找测试模块;
  • 测试模块是指文件名为test_*.py或者*_test.py的文件;
  • 在测试模块中查找以test_开头的函数;
  • 查找名字以Test开头的类。其中首先筛选掉包含__init__()函数的类,再查找类中以test_开头的类方法。

2.运行收集的用例

  • 切换到项目路径,在命令行输入:

pytest -v

可以输出用例更加详细的执行信息,比如用例所在的文件及用例名称等

 

  •  pytest -s

输出用例中的调式信息,比如print的打印信息等

  • pytest -m 

用于标记测试并分组,执行特定的测试用例

每个方法前注入(按mark_name进行分组):

@pytest.mark.mark_name

 1  @pytest.mark.make_name
 2     def test_add(self):
 3         x =  4
 4         y = 5
 5         if x+ y != 10:
 6             raise AssertionError(f'{x} not equal to {y}')
 7 
 8     @pytest.mark.make_name
 9     def test_mult(self):
10         x = 4
11         y = 5
12         if x * y != 10:
13             raise AssertionError(f'{x} not equal to {y}')
$ py.test -m mark_name

  • pytest -k 方法名

可以通过表达式运行指定的测试用例

比如使用命令:pytest -k "test_demo01 or test_demo02",就会指定运行test_demo01和test_demo02两条用例

或者运行:

py.test -k test_demo01
  • pytest -q 在当前测试用例文件夹下运行

简化输出信息

  • pytest -x

遇到错误或者用例不通过,则退出执行

  • pytest -v -x

可以输出用例更加详细的执行信息,比如用例所在的文件及用例名称等,遇到错误或者用例不通过,则退出执行

  • pytest --lf

--last-failed 只重新运行上次运行失败的用例(或如果没有失败的话会全部跑)。

命令行输入: pytest -v --lf 

  • pytest --ff

--failed-first,先执行完上次失败的测试后,再执行上次正常的测试用例

输入命令:pytest -v --ff

  • pytest --maxfail=num

用例运行时,允许的最大失败次数,超过则立即停止执行

输入命令:pytest -v --maxfail=2

  • 运行指定用例

模块、类、函数及方法之间用::进行分割。

比如想运行TestLogin类下的测试用例。

使用命令:pytest -v login/test_login.py::TestLogin

 

生成HTML格式报告:

pytest -v src/testcase/pytest_test.py  --html=log/pytest_test.html 

或者:

pytest -v src/testcase/pytest_test.py --html=./log/pytest_test.html

posted @ 2021-06-11 21:02  jane21  阅读(604)  评论(0)    收藏  举报