一、前置和后置的方法

模块级(setup_module/teardown_module):开始于模块始末,作用于全局(总用各执行一次。)
函数级(setup_function/teardown_function):仅对函数用例生效。(即不在类中。每个函数执行一次)
类级(setup_class/teardown_class):只在类中前后运行一次。(在类中)
方法级(setup_method/teardown_method):开始于方法始末(在类中。每个方法执行一次)
*类里面的(setup/teardown):运行在调用方法的前后(每个方法执行一次)
注:类里面按优先级排序的话:setup_class > setup_method > setup >用例> teardown > teardown_method > teardown_class(即执行顺序)

二、举个例子

  1. -- coding: utf-8 --
  2. import pytest
  3. def setup_module():
  4. print("=整个.py模块开始前只执行一次:打开浏览器=")
  5. def teardown_module():
  6. print("=整个.py模块结束后只执行一次:关闭浏览器=")
  7. def setup_function():
  8. print("=每个函数级别用例开始前都执行setup_function=")
  9. def teardown_function():
  10. print("=每个函数级别用例结束后都执行teardown_function==")
  11. def test_one():
  12. print("one")
  13. def test_two():
  14. print("two")
  15. class TestCase():
  16. def setup_class(self):
  17. print("整个测试类开始前只执行一次setup_class")
  18. def teardown_class(self):
  19. print("====整个测试类结束后只执行一次teardown_class====")
  20. def setup_method(self):
  21. print("==类里面每个用例执行前都会执行setup_method==")
  22. def teardown_method(self):
  23. print("==类里面每个用例结束后都会执行teardown_method==")
  24. def setup(self):
  25. print("=类里面每个用例执行前都会执行setup=")
  26. def teardown(self):
  27. print("=类里面每个用例结束后都会执行teardown=")
  28. def test_three(self):
  29. print("three")
  30. def test_four(self):
  31. print("four")
  32. if name == 'main':
  33. pytest.main(["-q", "-s", "-ra", "test_two.py"])

执行结果
image.png