Pytest - Fixture



Fixture 是函式,它們會在應用於每個測試函式之前執行。Fixture 用於向測試提供一些資料,例如資料庫連線、要測試的 URL 和某種輸入資料。因此,與其為每個測試執行相同的程式碼,不如將 fixture 函式附加到測試,它將在執行每個測試之前執行並返回資料到測試。

一個函式透過以下方式標記為 fixture:

@pytest.fixture

測試函式可以透過將 fixture 名稱作為輸入引數來使用 fixture。

建立一個檔案test_div_by_3_6.py,並在其中新增以下程式碼

import pytest

@pytest.fixture
def input_value():
   input = 39
   return input

def test_divisible_by_3(input_value):
   assert input_value % 3 == 0

def test_divisible_by_6(input_value):
   assert input_value % 6 == 0

這裡,我們有一個名為input_value的 fixture 函式,它為測試提供輸入。為了訪問 fixture 函式,測試必須將 fixture 名稱作為輸入引數。

在測試執行過程中,Pytest 會看到 fixture 名稱作為輸入引數。然後它執行 fixture 函式,並將返回值儲存到輸入引數,測試可以使用該引數。

使用以下命令執行測試:

pytest -k divisible -v

以上命令將生成以下結果:

test_div_by_3_6.py::test_divisible_by_3 PASSED
test_div_by_3_6.py::test_divisible_by_6 FAILED
============================================== FAILURES
==============================================
________________________________________ test_divisible_by_6
_________________________________________
input_value = 39
   def test_divisible_by_6(input_value):
>  assert input_value % 6 == 0
E  assert (39 % 6) == 0
test_div_by_3_6.py:12: AssertionError
========================== 1 failed, 1 passed, 6 deselected in 0.07 seconds
==========================

但是,這種方法有其自身的侷限性。在測試檔案中定義的 fixture 函式的作用域僅限於該測試檔案。我們無法在另一個測試檔案中使用該 fixture。為了使 fixture 可用於多個測試檔案,我們必須在名為 conftest.py 的檔案中定義 fixture 函式。conftest.py將在下一章中進行解釋。

廣告