一、前置和后置的方法
模块级(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(即执行顺序)
二、举个例子
-- coding: utf-8 --
import pytest
def setup_module():
print("=整个.py模块开始前只执行一次:打开浏览器=")
def teardown_module():
print("=整个.py模块结束后只执行一次:关闭浏览器=")
def setup_function():
print("=每个函数级别用例开始前都执行setup_function=")
def teardown_function():
print("=每个函数级别用例结束后都执行teardown_function==")
def test_one():
print("one")
def test_two():
print("two")
class TestCase():
def setup_class(self):
print("整个测试类开始前只执行一次setup_class")
def teardown_class(self):
print("====整个测试类结束后只执行一次teardown_class====")
def setup_method(self):
print("==类里面每个用例执行前都会执行setup_method==")
def teardown_method(self):
print("==类里面每个用例结束后都会执行teardown_method==")
def setup(self):
print("=类里面每个用例执行前都会执行setup=")
def teardown(self):
print("=类里面每个用例结束后都会执行teardown=")
def test_three(self):
print("three")
def test_four(self):
print("four")
if name == 'main':
pytest.main(["-q", "-s", "-ra", "test_two.py"])
执行结果