pytest- fixture 測試的固定配置,使不同範圍的測試都能夠獲得統一的配置
阿新 • • 發佈:2021-06-13
fixture為可靠的和可重複執行的測試提供固定的基線(可以理解為測試的固定配置,使不同範圍的測試都能夠獲得統一的配置),fixture提供了區別於傳統單元測試(setup/teardown)風格的令人驚喜的功能,而且pytest做得更炫。
1. fixture 可以作為一個函式的引數被呼叫
test_fixture.py:
1 @pytest.fixture 2 def numbers(): 3 a = 10 4 b = 20 5 c = 30 6 return [a, b, c] 7 8 9 def test_method1(numbers):10 x = 15 11 assert numbers[0] == x 12 13 14 def test_method2(numbers): 15 y = 20 16 assert numbers[1] == y
test_fixture.py 中的所有test_*()測試方法在執行前都會先執行 numbers()
程式碼執行過程:
- pytest 找到
test_
開頭的函式,於是找到了test_method1() 和 test_method2()
test_method1() 和 test_method2()
測試函式,需要一個引數numbers,於是pytest找到並且呼叫這個用@pytest.fixture
numbers()
函式- numbers()被呼叫來建立一個例項
2. fixture可以在一個類、或者一個模組、或者整個session中被共享,加上範圍即可:
@pytest.fixture(scope = "module")
https://zhuanlan.zhihu.com/p/87775743