@autouse=True
autouse 控制固件是否制动使用,默认不写
  1. import pytest
  2. @pytest.fixture(autouse=True)
  3. def gujian01():
  4. # 不能定义返回值
  5. print('测试准备工作')
  6. yield
  7. print('测试准备结束')
  8. def test01():
  9. print('开始测试test01')
  10. if __name__ == '__main__':
  11. pytest.main(['-vs', '--tb=line', 'test.py'])
  12. # test.py::test01
  13. # 测试准备工作
  14. # 开始测试test01
  15. # PASSED测试结束
  1. import pytest
  2. @pytest.fixture()
  3. def gujian01():
  4. # 不能定义返回值
  5. print('测试准备工作')
  6. yield
  7. print('测试准备结束')
  8. def test01():
  9. print('开始测试test01')
  10. if __name__ == '__main__':
  11. pytest.main(['-vs', '--tb=line', 'test.py'])
  12. # test.py::test01
  13. # 开始测试test01
  14. # PASSED
参数 说明
scope 固件的作用范围,是指固件函数能够控制的范围:
session:会话,代表整个测试
module:模块,代表项目中的每一个py文件
class: 类,代表一个py文件中的每个函数或每个类整体
function:默认项,函数,代表一个py文件中的每个函数或每个方法

scope=function
  1. # 多固件
  2. import pytest
  3. @pytest.fixture(autouse=True)
  4. def firmware01():
  5. # 不能定义返回值
  6. print('测试准备工作')
  7. yield
  8. print('测试准备结束')
  9. # scope='function' 可不写
  10. @pytest.fixture(scope='function')
  11. def firmware02():
  12. print('测试准备工作01')
  13. yield
  14. print('测试准备结束01')
  15. def test01():
  16. print('开始测试test01')
  17. # 是想用,就传入固件的名称即可
  18. def test02(firmware02):
  19. print('开始测试test02')
  20. def test03():
  21. print('开始测试test03')
  22. if __name__ == '__main__':
  23. pytest.main(['-vs', '--tb=line', 'test.py'])
  24. # test.py::test01
  25. # 测试准备工作
  26. # 开始测试test01
  27. # 测试准备结束
  28. # PASSED
  29. # test.py::test02
  30. # 测试准备工作
  31. # 测试准备工作01
  32. # 开始测试test02
  33. # 测试准备结束01
  34. # 测试准备结束
  35. # PASSED
  36. # test.py::test03
  37. # 测试准备工作
  38. # 开始测试test03
  39. # PASSED测试准备结束

scope=class
  1. import pytest
  2. @pytest.fixture(scope='class')
  3. def firmware03():
  4. print('准备测试03')
  5. yield
  6. print('清理测试03')
  7. def test01(firmware03):
  8. print('执行测试test01')
  9. def test02(firmware03):
  10. print('执行测试test02')
  11. class TestA:
  12. def test01(self, firmware03):
  13. print('执行测试TestA-test01')
  14. def test02(self, firmware03):
  15. print('执行测试TestA-test02')
  16. class TestB:
  17. def test01(self, firmware03):
  18. print('执行测试TestA-test01')
  19. def test02(self, firmware03):
  20. print('执行测试TestA-test02')
  21. if __name__ == '__main__':
  22. pytest.main(['-vs', '--tb=line', 'test.py'])
  23. # test01 准备测试03
  24. # 执行方法测试test01
  25. # PASSED清理测试03
  26. # test.py::test02 准备测试03
  27. # 执行方法测试test02
  28. # PASSED清理测试03
  29. # test.py::TestA::test01 准备测试03
  30. # 执行测试TestA-test01
  31. # PASSED
  32. # test.py::TestA::test02 执行测试TestA-test02
  33. # PASSED清理测试03
  34. # test.py::TestB::test01 准备测试03
  35. # 执行测试TestA-test01
  36. # PASSED
  37. # test.py::TestB::test02 执行测试TestA-test02
  38. # PASSED清理测试03