''' 模塊級(setup_module/teardown_module)開始於模塊始末, 全局的在類中不起作用 類級(setup_class/teardown_class)只在類中前后運行一次(在 類中) 方法級(setup_method/teardown_method)開始於方法始末 (在類中) 函數級(setup_function/teardown_function只對函數用例生 效(在類中不生效) setup_function teardown_function ''' import pytest def setup_function(): print() print("setup_function:class外的每個用例前開始執行") def teardown_function(): print("teardown_function:class外的每個個用例后開始執行") def setup_module(): """ 這是一個module級別的setup,它會在本module(test_fixt_class.py)里 所有test執行之前,被調用一次。 注意,它是直接定義為一個module里的函數""" print() print("-------------- setup before module --------------") def teardown_module(): """ 這是一個module級別的teardown,它會在本module(test_fixt_class.py)里 所有test執行完成之后,被調用一次。 注意,它是直接定義為一個module里的函數""" print("-------------- teardown after module --------------") def test_add(): print("正在執行test_fire") a = "hello" b = "hello word" assert a in b class TestCase(): def setup(self): print("setup: 每個用例開始前執行") def teardown(self): print("teardown: 每個用例結束后執行") 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 test_one(self): print("正在執行----test_one") x = "this" assert 'h' in x def test_three(self): print("正在執行test_two") a = "hello" b = "hello word" assert a in b def add(self,a, b): print("這是加減法") return a + b if __name__ == '__main__': pytest.main(['-s', 'test_fixt_class'])
運行結果:
============================= test session starts =============================
platform win32 -- Python 3.7.4, pytest-5.1.0, py-1.8.0, pluggy-0.12.0
rootdir: E:\py_pytest\interfacecollected 3 items
test_fixt_class.py
-------------- setup before module --------------
setup_function:class外的每個用例前開始執行
.正在執行test_fire
teardown_function:class外的每個個用例后開始執行
setup_class:所有用例執行之前
setup_method: 每個用例開始前執行
setup: 每個用例開始前執行
.正在執行----test_one
teardown: 每個用例結束后執行
teardown_method: 每個用例結束后執行
setup_method: 每個用例開始前執行
setup: 每個用例開始前執行
.正在執行test_two
teardown: 每個用例結束后執行
teardown_method: 每個用例結束后執行
teardown_class:所有用例執行之前
-------------- teardown after module --------------
[100%]
============================== 3 passed in 0.02s ==============================
結論1: 模塊級(setup_module/teardown_module)開始於模塊始末, 全局的在類中不起作用 函數級(setup_function/teardown_function只對函數用例生 效(在類中不生效) 結論2: 從結果看出,運行的優先級: setup_model>setup_class>setup_method> setup >用例case> teardown> teardown_method> teardown_class >teardown_model 結論3: 從運行結果看出, setup_module/teardown_module 的優先級 是最大的,然后函數里面用到的 setup_function/teardown_function 不類里面的 setup_class/teardown_class 互不干涉