如何在 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()** 將被執行。
廣告