在unittest中的前置和後置setup和teardown很好用,還有類前置與類後置方法 setupClass和teardownClass,當然需要配合@classmethod裝飾器使用。pytest中也提供了類似的函數,以及更多的函數:
模塊級別(setup_module/teardown_module) 全局的
函數級別(setup_function/teardown_function) 只對函數用例生效(不在類中的)
類級別 (setup_class/teardown_class) 只在類中前後運行一次(只在類中才生效)
方法級別 (setup_method/teardown_method) 開始後與方法始末(在類中)
類內用例初始化結束 (setup/teardown) 運行在測試用例的前後
產生作用的範圍如下:
setup_module
----setup_function
--------test_out_class #類外測試用例
----teardown_function
----setup_class
--------setup_method
------------setup
----------------test_in_class1 #類內測試用例一
------------teardown
--------teardown_method
--------setup_method
------------setup
----------------test_in_class2 #類內測試用例二
------------teardown
--------teardown_method
----teardown_class
teardown_module
示例代碼:
# setup_teardown.py # --encoding=utf-8 -- import pytest def setup_module(): print('\nsetup_module 執行') def teardown_module(): print('\nteardown_module 執行') def setup_function(): """函數方法(類外)初始化""" print('setup_function 執行') def teardown_function(): """函數方法(類外)初始化""" print('\nteardown_function 執行') def test_in_class(): """類(套件)外的測試用例""" print('類外測試用例') class Test_clazz(object): """測試類""" def setup_class(self): print('setup_class 執行') def teardown_class(self): print('teardown_class 執行') def setup_method(self): print('setup_method 執行') def teardown_method(self0): print('teardown_method 執行') def setup(self): print('\nsetup 執行') def teardown(self): print('\nteardown 執行') def test_case001(self): """測試用例一""" print('測試用例一') def test_case002(self): """測試用例二""" print('測試用例二')
輸出結果:
setup_teardown.py::test_in_class setup_module 執行 setup_function 執行 類外測試用例 PASSED teardown_function 執行 setup_teardown.py::Test_clazz::test_case001 setup_class 執行 setup_method 執行 setup 執行 測試用例一 PASSED teardown 執行 teardown_method 執行 setup_teardown.py::Test_clazz::test_case002 setup_method 執行 setup 執行 測試用例二 PASSED teardown 執行 teardown_method 執行 teardown_class 執行 teardown_module 執行