pytest的setup和teardown函数(曾被一家云计算面试官问到过)。
pytest提供了fixture函数用以在测试执行前和执行后进行必要的准备和清理工作。与python自带的unitest测试框架中的setup、teardown类似,但是fixture函数对setup和teardown进行了很大的改进。
fixture函数可以使用在测试函数中,测试类中,测试文件中以及整个测试工程中。
fixture支持模块化,fixture可以相互嵌套
fixture支持参数化
fixture支持unittest类型的setup和teardown
1)模块级(setup_module/teardown_module)开始于模块始末:在所有测试用例开始执行setup_module和所有用例执行结束后执行teardown_module
2)类级(setup_class/teardown_class)开始于类的始末:在当前测试类的开始与结束执行
3)类里面的(setup/teardown)(运行在调用函数的前后)
4)功能级(setup_function/teardown_function)开始于功能函数始末(不在类中):用于每个测试用例开始执行时执行setup_function和在每个用例执行结束后执行teardown_function
5)方法级(setup_method/teardown_method)开始于方法始末(在类中):在每个测试方法开始与结束执行
1 defsetup_module(module):
2 print("setup_module module:%s" % module.__name__)
3
4
5 defteardown_module(module):
6 print("teardown_module module:%s" % module.__name__)
7
8
9 defsetup_function(function):
10 print("setup_function function:%s" % function.__name__)
11
12
13 defteardown_function(function):
14 print("teardown_function function:%s" % function.__name__)
15
16
17 deftest_numbers_3_4():
18 print('test_numbers_3_4 <============================ actual test code')
19 assert 3 * 4 == 12
20
21
22 deftest_strings_a_3():
23 print('test_strings_a_3 <============================ actual test code')
24 assert 'a' * 3 == 'aaa'
25
26
27 classTestUM:
28 defsetup(self):
29 print("setup class:TestStuff")
30
31 defteardown(self):
32 print("teardown class:TestStuff")
33
34 defsetup_class(cls):
35 print("setup_class class:%s" % cls.__name__)
36
37 defteardown_class(cls):
38 print("teardown_class class:%s" % cls.__name__)
39
40 defsetup_method(self, method):
41 print("setup_method method:%s" % method.__name__)
42
43 defteardown_method(self, method):
44 print("teardown_method method:%s" % method.__name__)
45
46 deftest_numbers_5_6(self):
47 print('test_numbers_5_6 <============================ actual test code')
48 assert 5 * 6 == 30
49
50 deftest_strings_b_2(self):
51 print('test_strings_b_2 <============================ actual test code')
52 assert 'b' * 2 == 'bb'
好好观察一下运行结果:
setup_module module:test_pytest_setup_teardown
setup_function function:test_numbers_3_4
test_numbers_3_4 <============================ actual test code
.teardown_function function:test_numbers_3_4
setup_function function:test_strings_a_3
test_strings_a_3 <============================ actual test code
.teardown_function function:test_strings_a_3
setup_class class:TestUM
setup_method method:test_numbers_5_6
setup class:TestStuff
test_numbers_5_6 <============================ actual test code
.teardown class:TestStuff
teardown_method method:test_numbers_5_6
setup_method method:test_strings_b_2
setup class:TestStuff
test_strings_b_2 <============================ actual test code
.teardown class:TestStuff
teardown_method method:test_strings_b_2
teardown_class class:TestUM
teardown_module module:test_pytest_setup_teardown