Python 測試入門

Python 測試入門

Alexander Levin

Data Scientist

為什麼測試很重要?

常見問題:

  • 程式錯誤與瑕疵
  • 硬體故障
  • 非預期或不可預測的行為

以上問題都可能為了修復而大幅增加成本

測試有助於:

  • 找出缺陷、錯誤與瑕疵
  • 降低軟體失效風險
  • 提升軟體的可靠度、功能性與效能
Python 測試入門

什麼是測試?

  • Testing:評估系統或軟體的過程
  • 需要測試以確保符合規格需求

  • Test:用來驗證軟體或系統正確性的步驟

Python 測試入門

課程先備知識

  • 進階 Python 程式設計
  • assert 敘述
  • 裝飾器(decorator)
  • 物件導向觀念(類別、方法、繼承)
Python 測試入門

真實世界的測試

想想飛機:

  • 目視檢查
  • 電子與機械檢測
  • 燃料檢查
  • 乘客檢查
  • 天氣檢查
  • 空管允許起飛

以上都是測試!而且為了安全必不可少。

起飛前的飛機

Python 測試入門

Python 中的 assert

  • assert condition:用來測試 condition 是否為 True
  • conditionFalse,Python 會拋出 AssertionError
Python 測試入門

使用 pytest 測試:簡單範例

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)
Python 測試入門

情境管理器複習

  • Context manager:透過 with 敘述使用的 Python 物件
  • 使用情境管理器來設定與清除暫時情境
# 寫入檔案範例
with open("hello_world.txt", 'w') as hello_file:
    hello_file.write("Hello world \n")
Python 測試入門

認識 pytest:raises

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)
Python 測試入門

重點整理

Testing 重點:

  • 評估軟體是否如預期運作
  • 日常生活中處處可見
  • 對解決軟體開發挑戰至關重要
  • 幫助妥善處理問題

測試實作:

  • pytest:強大的 Python 框架,簡化測試流程
  • assert:Python 關鍵字,在 pytest 中用於驗證條件、建立基本測試
  • pytest.raises:情境管理器,用於建立預期會拋出 Exception 的測試
Python 測試入門

一起來練習吧!

Python 測試入門

Preparing Video For Download...