pytest測試框架 -- setup和teardown等
阿新 • • 發佈:2020-07-29
一、用例執行級別
1、函式級別(setup、teardown 或 setup_function、teardown_function):
僅對處於同作用域的測試函式有效(該函式定義不在類中,則對非類中測試函式有效;若該函式定義在類中,則對類中測試函式有效)
def setup_function(): # setup()也一樣 print("setup_function") def teardown_function(): # teardown()也一樣 print("teardown_function") def test_01():print("---用例a執行---") class TestCase(): def test_02(self): print("---用例b執行---") def test_03(self): print("---用例c執行---") def test_04(): print("---用例d執行---")
輸出結果:
test_fixture2.py setup_function
---用例a執行---
.teardown_function
---用例b執行---
.---用例c執行---
.setup_function
---用例d執行---
.teardown_functio
2、方法級別(setup_method、teardown_method):
該函式只能定義在類中,且對類中的測試函式有效
def test_01(): print("---用例a執行---") class TestCase(): def setup_method(self): print("setup_method") def teardown_method(self): print("teardown_method") def test_02(self): print("---用例b執行---")def test_03(self): print("---用例c執行---")
輸出結果:
test_fixture2.py ---用例a執行---
.setup_method
---用例b執行---
.teardown_method
setup_method
---用例c執行---
.teardown_method
3、類級別(setup_class、teardown_class):
該函式只能定義在類中,且分別在類開始和結束前各執行一次
def test_01(): print("---用例a執行---") class TestCase(): def setup_class(self): print("setup_class") def teardown_class(self): print("teardown_class") def test_02(self): print("---用例b執行---") def test_03(self): print("---用例c執行---")
輸出結果:
test_fixture2.py ---用例a執行---
.setup_class
---用例b執行---
.---用例c執行---
.teardown_class
4、模組級別(setup_module、teardown_module):
該函式只可定義在非類中,且分別在所有測試函式開始和結束前各執行一次
def setup_module(): print("setup_module") def teardown_module(): print("teardown_module") def test_01(): print("---用例a執行---") class TestCase(): def test_02(self): print("---用例b執行---") def test_03(self): print("---用例c執行---") def test_04(): print("---用例d執行---")
輸出結果:
setup_module
---用例a執行---
.---用例b執行---
.---用例c執行---
.---用例d執行---
.teardown_modul
5、不同級別函式混合:
執行的優先順序:module > function > class > method > setup、teardown
def setup_module(): print("setup_module") def teardown_module(): print("teardown_module") def setup_function(): print("setup_function") def teardown_function(): print("teardown_function") def test_01(): print("---用例a執行---") class TestCase(): def setup(self): print("setup") def teardown(self): print("teardown") def setup_method(self): print("setup_method") def teardown_method(self): print("teardown_method") def setup_class(self): print("setup_class") def teardown_class(self): print("teardown_class") def test_02(self): print("---用例b執行---") def test_03(self): print("---用例c執行---")
輸出結果:
test_fixture2.py setup_module
setup_function
---用例a執行---
.teardown_function
setup_class
setup_method
setup
---用例b執行---
.teardown
teardown_method
setup_method
setup
---用例c執行---
.teardown
teardown_method
teardown_class
teardown_module
參考:https://www.cnblogs.com/yoyoketang/p/9374957.html