pytest优点

1.简单灵活,像写Python代码一样写测试⽤例;
2.为测试⽅方法输⼊入不不同参数化;
3.自动重试失败的测试⽤用例例;
4.支持allure2测试报告;
5.具有很多第三⽅方插件 (http://plugincompat.herokuapp.com/),并且可以⾃自定义扩展;

pytest规范

1.测试文件以 test 开头(以 _test 结尾也可以)
2.测试类名以 Test 开头驼峰式(TestDemo),并且不能带有 __init
方法
3.测试函数以 test_ 开头

生成测试报告

方法一:在本地生成

  1. # 1.生成xml数据
  2. pytest --alluredir=./log/report/xml
  3. # 2.解析xml为html文件
  4. allure generate --clean-alluredir ./log/report/xml --output ./log/report/html
  5. # 3.在浏览器中打开html文件
  6. # 一定要在pycharm中,右键选择open in browser打开,直接在文件所在目录中打开数据无法显示

方法二:在线生成

  1. # 在测试执行期间收集结果
  2. 方法一:在终端执行
  3. pytest -s --alluredir=./result/
  4. 方法二:在py文件的主方法添加参数
  5. if __name__ == '__main__':
  6. pytest.main(['--alluredir', './result', 'test_severity.py'])
  7. # 测试完成后查看实际报告, 在线看报告。
  8. allure serve ./result/

pytest特性

1.assume, 有多个assert时,其中一个失败,后面不受影响会继续运行

  1. import pytest
  2. def test_multiple_assert():
  3. # assert 1 == 2 # 有多个assert时,其中一个失败,后面的则不会执行
  4. # assert 2 == 4
  5. # assert 3 == 4
  6. pytest.assume(1 == 2) # 使用assume,其中一个失败,其他也会执行
  7. pytest.assume(2 == 2)
  8. pytest.assume(3 == 4)

2.order,指定用例的运行顺序

  1. '''
  2. 使用场景:修改账号信息,需要依赖前面创建好的信息,需指明运行的先后顺序
  3. '''
  4. import pytest
  5. @pytest.mark.run(order=2)
  6. def test_add2():
  7. assert value == 10
  8. @pytest.mark.run(order=1)
  9. def test_add1():
  10. global value
  11. value = 10
  12. assert value == 10

3.suger,显示用例执行的进度条 ⚠️该组建生效,必须在命令行运行py文件(pytest xx.py) 如图所示

image.png

4.parameter,参数化

pytest特性和报告生成 - 图2

5.运行失败重试(在终端运行pytest —reruns 4 xx.py)

  1. import random
  2. '''
  3. 运行失败重试
  4. 在终端使用参数--reruns指定重试的次数(本用例运行:pytest --reruns 4 test_rerunfails.py)
  5. '''
  6. def add(x, y):
  7. return x+y
  8. def test_add():
  9. num = random.randint(3, 10)
  10. print('the random value is:', str(num))
  11. assert add(1, 3) == num

image.png