跳轉至

建立 2026-10-11 更新 2026-10-11

安裝與第一個測試

寫第一個 pytest 測試只需要三步:安裝 pytest、建立一個以 test_ 開頭的檔案並在函式裡寫 assert、在終端機執行 pytest。本頁帶你走完這三步,並說明如何閱讀通過與失敗時的輸出。

安裝 pytest

pytest 目前的主要版本是 9.x,需要 Python 3.10 以上。測試工具只在開發時使用,所以建議安裝成開發依賴(development dependency),不要放進正式執行需要的依賴清單。

uv add --dev pytest
uv run pytest --version
python -m venv .venv
source .venv/bin/activate   # Windows:.venv\Scripts\activate
pip install pytest
pytest --version

uv add --dev 會把 pytest 寫進 pyproject.toml 的開發依賴群組,團隊成員執行 uv sync 就能裝到相同版本。

寫第一個測試

假設專案裡有一個計算折扣的函式:

shop.py
def apply_discount(price: float, percent: float) -> float:
    """回傳打折後的價格,percent 為 0~100。"""
    if not 0 <= percent <= 100:
        raise ValueError("percent 必須介於 0 到 100")
    return round(price * (1 - percent / 100), 2)

在同一層建立 test_shop.py:

test_shop.py
from shop import apply_discount


def test_apply_discount():
    assert apply_discount(100, 20) == 80


def test_no_discount():
    assert apply_discount(59.9, 0) == 59.9

重點只有兩個:檔名以 test_ 開頭、函式名稱以 test_ 開頭,pytest 就會自動找到它們。驗證結果直接用 Python 的 assert,不需要學任何特殊的斷言方法。

執行測試

在專案根目錄執行:

uv run pytest   # 用 pip 安裝者直接執行 pytest
============================= test session starts ==============================
collected 2 items

test_shop.py ..                                                          [100%]

============================== 2 passed in 0.01s ===============================

每個 . 代表一個通過的測試。常見的狀態符號:

符號 意義
. 通過(passed)
F 失敗(failed),assert 不成立
E 錯誤(error),測試本身以外的地方出錯,例如 fixture 拋出例外
s 跳過(skipped)
x 預期失敗且真的失敗(xfailed)

看懂失敗訊息

把第一個測試的預期值故意改錯成 75,再執行一次:

___________________________ test_apply_discount ___________________________

    def test_apply_discount():
>       assert apply_discount(100, 20) == 75
E       assert 80.0 == 75
E        +  where 80.0 = apply_discount(100, 20)

test_shop.py:5: AssertionError
========================= short test summary info ==========================
FAILED test_shop.py::test_apply_discount - assert 80.0 == 75

pytest 會改寫(rewrite)assert 敘述,因此失敗時能顯示每個子運算式的實際值:apply_discount(100, 20) 實際回傳 80.0,而不是預期的 75。這就是 pytest 不需要 assertEqual 這類方法也能給出清楚訊息的原因。

在編輯器裡執行

VS Code 安裝 Python 擴充功能後,在「Testing」面板選擇 pytest,就能點選單一測試執行或除錯;PyCharm 也內建 pytest 支援。

推薦影音

Pytest Tutorial(Tech With Tim)

約 33 分鐘的入門教學,依序示範安裝、第一個測試與 assert、fixture 的準備與清理、參數化,適合搭配本頁與後續「核心技巧」一起看。

下一步