使用 doctest 模組在 Python 中進行測試
我們知道 **文件字串** 提供了有關 Python 中函式和類的額外資訊。我們還可以使用 **doctest** 模組來測試這些函式。**doctest** 模組執行以 >>> 開頭的程式碼,並將其與預期輸出進行比較。
請按照以下步驟使用 **doctest** 編寫函式。
匯入 **doctest** 模組。
使用文件字串編寫函式。在文件字串中,編寫以下兩行用於測試同一函式。
>>>function_name(*args)。
預期 **輸出**。
編寫函式程式碼。
現在,呼叫 doctest.testmod(name=function_name, verbose=True) 函式進行測試。如果 verbose 設定為 False 並且所有測試都透過,則看不到測試結果。最好將其設定為 True。
示例
讓我們使用 doctest 編寫一個簡單的函式。
# importing the module import doctest # function def numbers_sum(*args) -> int: """ This function returns the sum of all the argumets Shell commands for testing incoking the function followed by expected output: >>> numbers_sum(1, 2, 3, 4, 5) 15 >>> numbers_sum(6, 7, 8) 21 """ return sum(args) # invoking the testmod function doctest.testmod(name='numbers_sum', verbose=True)
如果執行以上程式碼,您將獲得以下結果。
Trying: numbers_sum(1, 2, 3, 4, 5) Expecting: 15 ok Trying: numbers_sum(6, 7, 8) Expecting: 21 ok 1 items had no tests: numbers_sum 1 items passed all tests: 2 tests in numbers_sum.numbers_sum 2 tests in 2 items. 2 passed and 0 failed. Test passed. TestResults(failed=0, attempted=2)
如果檢視輸出,每個測試之後都有一個單詞 ok。這意味著預期輸出和實際輸出匹配。您可以在輸出的末尾檢查測試結果。
示例
讓我們看看測試失敗時會發生什麼。使用錯誤的輸出執行相同的示例。
# importing the module import doctest # function def numbers_sum(*args) -> int: """ This function returns the sum of all the argumets Shell commands for testing incoking the function followed by expected output: >>> numbers_sum(1, 2, 3, 4, 5) 10 >>> numbers_sum(6, 7, 8) 23 """ return sum(args) # invoking the testmod function doctest.testmod(name='numbers_sum', verbose=True)
輸出
如果執行上述程式,您將獲得以下結果。
Trying: numbers_sum(1, 2, 3, 4, 5) Expecting: 10 ********************************************************************** File "__main__", line 10, in numbers_sum.numbers_sum Failed example: numbers_sum(1, 2, 3, 4, 5) Expected: 10 Got: 15 Trying: numbers_sum(6, 7, 8) Expecting: 23 ********************************************************************** File "__main__", line 12, in numbers_sum.numbers_sum Failed example: numbers_sum(6, 7, 8) Expected: 23 Got: 21 1 items had no tests: numbers_sum ********************************************************************** 1 items had failures: 2 of 2 in numbers_sum.numbers_sum 2 tests in 2 items. 0 passed and 2 failed. ***Test Failed*** 2 failures. TestResults(failed=2, attempted=2)
如果檢視測試結果,2 個測試失敗了。您還可以檢視輸出中的 **預期** 和 **實際** 輸出。
結論
如果您在本教程中有任何疑問,請在評論部分中提出。
廣告