一、使用場景:
接口A:查詢商品列表,商品列表中的商品返回的有商品id;
接口B: 根據看接口A返回的商品id,進入商品詳情中,對商品進行編輯並保存。
二、設計預期:
1、將接口A的操作放在前置(setup_class(),因為這個接口只有一個地方使用一次且沒有更新,所以我用的是class級別的前置)中,接口B是被測對象,即為測試案例。即,在對接口B進行測試的時候需要用到前置中接口A返回的商品Id數據
2、需要滿足擴展性,萬一后邊再有需要,可以直接拿來用,且可以不修改原有部分
3、操作簡單,不影響現有案例執行
三、使用解釋:
因為setup_class()是一個類函數,接受的參數是一個類對象,而每個測試用例是一個實列函數,接受實列對象,想要保證每個測試用例都能接受着這個一次性操作運行,就需要setup_class中使用的實列對象和每一個測試用例中使用的實列對象相同。
四、實現過程:

五、下一步改造想法:
將body數據存入數據庫,尋找一種合理合適的方式將的前置中獲取的數據與測試案例中的body數據關聯起來並完成傳參。
六、知識擴展:
匯總關於前/后置使用
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("-------------- 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'])
執行結果:

