如何在 Pytest 中執行選定的測試用例?


我們可以在 Pytest 中執行選定的測試用例。Pytest 是一個 Python 測試框架。要安裝 pytest,我們需要使用命令 **pip install pytest**。安裝後,我們可以使用命令 **pytest –version** 驗證 Python 是否已安裝。 pytest 的版本將被顯示。

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

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

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

def test_CalculateLoan():
   print("Loan calculation")
def test_CalculateLease():
   print("Lease calculation")

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

def test_CalculateRepay():
   print("Loan calculation")
def test_FindLease():
   print("Lease search")

要執行名稱中包含特定字串的測試方法,我們需要執行命令 **pytest -k <子字串> -v**。這裡 -k <子字串> 是在測試方法中查詢的子字串,v 表示詳細模式。

對於我們的例子,命令應該是 **pytest -k Calculate –v**。名稱中包含 "Calculate" 的測試方法將被選中執行。在本例中,**CalculateLoan(),CalculateLease() 和 CalculateRepay()** 將被執行。

更新於:2021年11月19日

580 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告