如何在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提供了在測試方法上使用標記的功能。標記用於為測試方法賦予屬性。一些預設的標記包括skip、xfail和parametrize。此外,還可以根據需要自定義更多標記。
在某些情況下,由於應用程式中已知的錯誤或某個特定功能仍在開發中,測試方法可能變得不相關。Pytest測試框架提供了跳過測試方法執行的選項。
跳過標記使用以下語法與測試方法關聯:**@py.test.mark.skip**。要使用標記,我們還必須將pytest匯入到我們的測試檔案中。一旦測試方法變得相關,我們需要從測試方法中刪除skip標記。
示例
讓我們考慮一個包含測試方法的pytest檔案。
import pytest @pytest.mark.loan @pytest.mark.skip def test_CalculateLoan(): print("Loan calculation") def test_CalculateLease(): print("Lease calculation")
示例
讓我們考慮另一個包含測試方法的pytest檔案。
import pytest @pytest.mark.loan @pytest.mark.skip def test_CalculateRepay(): print("Loan calculation") def test_FindLease(): print("Lease search")
現在要執行所有測試用例,我們需要使用命令**py.test –v**。標記為skip的測試方法將被排除在執行之外。在這種情況下,CalculateLoan()和**CalculateRepay()**測試方法將被跳過執行。