Pytest 中的 fixture 是什麼?


fixture 是在與之關聯的每個測試方法之前執行的方法,pytest 是 Python 中的一個測試框架。要安裝 pytest,我們需要使用命令 pip install pytest。安裝後,我們可以透過命令 pytest –version 驗證 Python 是否已安裝。pytest 的版本將被顯示。

Pytest 可用於建立和執行測試用例。它可以用於各種測試,如 API 測試、UI 測試、資料庫測試等等。pytest 的測試檔案有一個命名約定,即以 test_ 開頭或以 _test 結尾,並且每行程式碼都應該在以 test 關鍵詞開頭的方法內。此外,每個方法都應該具有唯一的名稱。

為了列印控制檯日誌,我們需要使用命令 **py.test –v –s**。同樣,如果我們想從特定的 pytest 檔案執行測試,則命令為 **py.test <filename> -v**。

fixture 與負責 URL 宣告、處理一些輸入資料、資料庫連線等的測試方法相關聯。因此,它可以被視為每個測試方法的預處理方法。

具有 fixture 的方法應該具有以下語法:**@pytest.fixture**。要訪問 fixture 方法,測試方法必須將 fixture 的名稱指定為輸入引數。

此外,要使用 fixture,我們必須將 **pytest** 匯入到我們的測試檔案。

示例

讓我們考慮一個包含測試方法的 pytest 檔案。

import pytest
@pytest.fixture
def Login():
   print("Login is successful")
def test_CalculateLease(Login):
   print("Lease calculation")
def test_CalculateLoan(Login):
   print("Loan calculation")

在上面的示例中,我們有一個 fixture 方法 Login(),它作為引數傳遞給測試方法 CalculateLease() 和 CalculateLoan()。首先,將執行 Login() fixture 方法,然後執行其他方法。

要執行上述測試方法,我們需要執行命令 **py.test -k Calculate –v**。

fixture 的缺點是其作用域僅限於其提到的測試檔案,而不在其外部。

更新於: 2021 年 11 月 19 日

235 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.