四、聊聊 pytest 的模块级、函数级、类级、方法级

1.pytest的框架结构:

模块级、函数级、类级、方法级:

  类似 unittest 框架中的 setUp 和 tearDown,主要应用在测试方法之前或者测试方法之后,为测试过程提供前置或后置条件。可以装置数据,也可以完成环境配置等操作。

pytest支持 5 个层次的 setup 和 teardown,包括:session会话级、module模块级、function函数级、class类级、method方法级
(1)模块级(setup_module/teardown_module):开始于模块始末(不在类中),整个模块只执行一次
(2)函数级(setup_function/teardown_function):对函数用例生效(不在类中),每个测试方法前后都会执行

(3)类级(setup_class/teardown_class):测试类中,所有测试用例执行之前、执行之后只执行一次
(4)方法级(setup_method/teardown_method):测试类中,每个测试用例执行之前、执行之后会执行一次,setup/teardown效果相同,二者用其一。

def setup_module():
print("setup_module:整个 .py 模块只执行一次")
print("例如:所有用例开始前只打开一次浏览器")


def teardown_module():
print("teardown_module:整个 .py 模块只执行一次")
print("例如:所有用结束后关闭浏览器")


def setup_function():
print("setup_function:每个用例开始前都会执行")


def teardown_function():
print("teardown_function:每个用例结束后都会执行")


def test_one():
print("正在执行----test_one")
x = "this"
assert 'h' in x


def test_two():
print("正在执行----test_two")
assert 2 == 2


class TestCase(object):
def setup_class(self):
print("setup_calss:测试类中所有用例执行之前执行")

def teardown_class(self):
print("teardown_class:测试类中所有用例执行之后执行")

def setup_method(self):
print("setup_method:测试类中每个用例执行前都会执行一次")

def teardown_method(self):
print("teardown_method:测试类中每个用例执行后都会执行一次")

def test_three(self):
print('正在执行----test_three')
x = 'this'
assert 'h' in x

def test_four(self):
print('正在执行----test_four')
assert 1 + 1 == 2


if __name__ == '__main__':
pytest.main()
posted @   努力的小测试  阅读(138)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示