[note] unittest and pytest
CLI
$ pytest --disable-warnings
# -s 把 print 的內容顯示出來
# -vv 輸出非常詳細的報告
# -W ignore: 不要輸出 warning
$ pytest -s -vv -W ignore test_xxx.py
$ python -m pytest <test_file_path.py>
$ python -m pytest -s -vv <test_file_path.py>::<TestClass>::<test_case_fn_name>
Unit testing framework (unittest)
官方文件
unittest @ Python Standard Library > Development Tools
內建的 asset keyword
assert <condition>, 'Message if condition is not met'
當 condition 是 false 時,會 raise AssertionError。
建立 Test Cases
keywords: unittest.TestCase
- 建立一個繼承
unittest.TestCase的類別 - 欲進行測試的項目(test cases)會定義成該 Class 中的 instance method,並以
test_作為方法名稱的前綴,例如,def test_square_of_zero(self) - 需要使用
unittest提供的assertEqual而不是內建的assert - 使用
unittest.main()可以執行測試
import unittest
class TestSquareFunction(unittest.TestCase):
def test_square_of_zero(self):
self.assertEqual(square(0), 0, 'Expected square(0) to return 0')
def test_square_of_large_number(self):
self.assertEqual(square(1000), 1000000, 'Expected square(1000) to return 1000000')
def test_square_of_negative_number(self):
self.assertEqual(square(-10), 100, 'Expected square(-10) to return 100')
# 執行測試
unittest.main()
常用的 assertions
TestCase
TestCase:所有可用的方法和 assertions @ 官方文件
assertEqual(a, b):檢查是不是相同,等同於a == bassertTrue(expr, msg=None):等同於bool(expr) is TrueassertIs(a, b):檢查是不是同一個物件,等同於a is bassertIsNone(x):等同於x is NoneassertIn(member, container, msg=None):等同於member in containerassertLess(a, b):等同於a < bassertAlmostEqual(a, b):等同於round(a - b) == 0assertRaises(exception, callable, *args, **kwds)exception是預期要看到的 Error 類別,例如TypeError、CustomErrorcallable帶入的是要測試的 function*args和**kwds則是會帶入callable的參數
assertWarns(warning, callable, *args, **kwds)