conftest.py 脚手架工具

在做自动化测试的时候,需要进行接口的执行时的控制,比如接口运行之前,以及接口运行之后的进行操作。

在pytest中,可以将这些操作都放在 conftest.py 文件中进行配置。

注意: conftest.py 文件名为固定用法。(文件名必须要这样定义)

conftest.py

  1. """
  2. pytest 运行时的配置文件
  3. """
  4. import pytest
  5. # 定义函数级别的脚手架
  6. @pytest.fixture(scope='function',autouse=True)
  7. def func():
  8. print('测试用例执行之前操作')
  9. yield
  10. print('测试用例执行之后的操作')

test_cases.py

  1. def test_01():
  2. print('test_01')
  3. def test_02():
  4. print('test_02')
  5. def test_03():
  6. print('test_03')

执行效果

运行 test_cases.py 文件

  1. pytest -s -v test_cases.py

可以看到,会自动执行 conftest.py 文件中定义的操作。
image.png

conftest.py

  1. """
  2. pytest 运行时的配置文件
  3. """
  4. import pytest
  5. # 函数的运行级别
  6. @pytest.fixture(scope='function',autouse=True)
  7. def func():
  8. print('测试用例执行之前操作')
  9. yield
  10. print('测试用例执行之后的操作')
  11. # 类运行之前,之后执行
  12. @pytest.fixture(scope='class',autouse=True)
  13. def classes():
  14. print('类运行之前执行')
  15. yield
  16. print('类运行之后操作')
  17. # 整个py文件执行
  18. @pytest.fixture(scope='module',autouse=True)
  19. def module():
  20. print('py文件执行之前')
  21. yield
  22. print('py文件执行之后')
  23. # 整个包执行
  24. @pytest.fixture(scope='package',autouse=True)
  25. def package ():
  26. print('包执行之前')
  27. yield
  28. print('包执行之后')
  29. # 所有的用例执行之前
  30. @pytest.fixture(scope='session',autouse=True)
  31. def session():
  32. print('所有用例执行之前')
  33. yield
  34. print('所有的用例执行之后')

conftest.py 文件主要就是定义了测试用例执行的先后顺序。

主要的级别有:

  • function 函数级别
  • class 类级别
  • module 模块级别
  • package 包级别
  • session 所有用例级别

pytest-order 执行测试用例的执行顺序

默认的测试用例执行的顺序是按照编写测试用例的先后顺序来执行。

pytest-order 可以用看控制测试用例的执行顺序。

安装pytest-order

image.png

也可以在命令行模式下进行安装

  1. pip install pytest-order

如何使用

在测试用例上面指定执行顺序。

test_cases.py

  1. import pytest
  2. @pytest.mark.order(2)
  3. def test_01():
  4. print('test_01')
  5. @pytest.mark.order(3)
  6. def test_02():
  7. print('test_02')
  8. @pytest.mark.order(1)
  9. def test_03():
  10. print('test_03')

在用例上面 通过 使用 pytest.mark.order() 指定执行的先后顺序。

@pytest.mark.order(1) 第一个执行。