開始使用免費開始

條件式跳過

有時你會想在滿足某個條件時跳過測試。舉例來說,你想在今天不是星期六時才執行測試。這種情況下,你可以使用 datetime 函式庫取得當前是週幾,並搭配 pytest 的標記(marker)來有條件地跳過測試函式。若要將條件傳入條件式跳過的 pytest 標記,你可以使用 @pytest.mark.skipif(condition)pytest 函式庫已替你匯入。

本練習屬於課程

Python 測試入門

檢視課程

練習說明

  • 加上「條件式跳過」裝飾器讓它生效。
  • condition_string 加入裝飾器呼叫。
  • 完成斷言測試。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

day_of_week = datetime.now().isoweekday()

def get_unique_values(lst):
    return list(set(lst))

condition_string = 'day_of_week == 6'
# Add the conditional skip marker and the string here
____.____.____(____)
def test_function():
	# Complete the assertion tests here
    ____ ____([1,2,3]) == [1,2,3]
    ____ ____([1,2,3,1]) == [1,2,3]
編輯並執行程式碼