Python 測試入門
Alexander Levin
Data Scientist
常見問題:
以上問題都可能為了修復而大幅增加成本。
測試有助於:
需要測試以確保符合規格需求
Test:用來驗證軟體或系統正確性的步驟
assert 敘述想想飛機:
以上都是測試!而且為了安全必不可少。

assert condition:用來測試 condition 是否為 True。condition 為 False,Python 會拋出 AssertionError。pytest:Python 中常用的測試框架,能以簡潔方式撰寫測試。
以 pytest 撰寫的「assert」測試範例(Python):
import pytest
# A function to test
def squared(number):
return number * number
# A test function always starts with "test"
def test_squared():
assert squared(-2) == squared(2)
with 敘述使用的 Python 物件# 寫入檔案範例
with open("hello_world.txt", 'w') as hello_file:
hello_file.write("Hello world \n")
pytest.raises:當你預期測試會拋出 Exception 時使用
import pytest
# A function to test
def division(a, b):
return a / b
# A test function
def test_raises():
with pytest.raises(ZeroDivisionError):
division(a=25, b=0)
Testing 重點:
測試實作:
pytest:強大的 Python 框架,簡化測試流程assert:Python 關鍵字,在 pytest 中用於驗證條件、建立基本測試pytest.raises:情境管理器,用於建立預期會拋出 Exception 的測試Python 測試入門