Skip to content

Latest commit

 

History

History

README.md

07. Pytest — 自動化測試入門

本章節介紹如何使用 pytest 為 Python 程式撰寫自動化測試,涵蓋單元測試、API 測試與測試覆蓋率報告。

📒 教材清單

教材 說明 開啟方式
Pytest_Demo.ipynb pytest 入門示範 Open In Colab

📁 檔案說明

檔案 說明
Pytest_Demo.ipynb pytest 互動式教學筆記本
my_module.py 受測試的模組範例
test_my_module.py 對應的單元測試檔案
test_tasks_api.py Tasks API 測試
requirements.txt 相依套件清單

🚀 快速開始

安裝套件

# 使用 uv (推薦)
uv pip install -r requirements.txt

# 或使用傳統方式
pip install -r requirements.txt

執行測試

# 執行全部測試
pytest

# 執行並顯示詳細資訊
pytest -v

# 執行並產生測試覆蓋率報告
pytest --cov=./

# 產生 HTML 格式的覆蓋率報告
pytest --cov-report=html

📚 學習重點

  • pytest 基本測試寫法
  • 測試函式命名慣例 (test_ 前綴)
  • Fixture 的使用
  • 參數化測試 (@pytest.mark.parametrize)
  • API 端點測試
  • 測試覆蓋率 (Coverage) 分析

🔗 相關資源