iT邦幫忙

2025 iThome 鐵人賽

DAY 26
0
佛心分享-IT 人自學之術

Python 學習筆記系列 第 26

筆記Day26:動手寫測試

  • 分享至 

  • xImage
  •  

今天要開始來寫測試了!
讓我們一步一步來,會從建立專案到撰寫測試。

建立專案資料夾

mkdir python_tdd

進入專案資料夾

cd python_tdd

建立虛擬環境

uv init --no-workspace
uv venv --python=3.12
source .venv/bin/activate

安裝測試所需套件

uv add pytest pytest-cov

建立requirements.txt

pytest>=8.4.2
pytest-cov>=6.3.0

建立pytest.ini

[tool:pytest]
testpaths = tests
python_files = test_*.py
python_function = test_*
addopts = 
    -v
    --tb=short
    --strict-markers
    --disable-warnings

資料結構

python_tdd
├─ .pytest_cache
│  ├─ CACHEDIR.TAG
│  ├─ README.md
│  └─ v
│     └─ cache
│        ├─ lastfailed
│        └─ nodeids
├─ .python-version
├─ README.md
├─ main.py
├─ pyproject.toml
├─ pytest.ini
├─ requirements.txt
├─ src
│  ├─ __init__.py
│  └─ calculator.py
├─ tests
│  ├─ __init__.py
│  └─ test_calculator.py
└─ uv.lock

寫測試

# tests/test_calculator.py

import pytest
from src.calculator import add, subtract, multiply, divide

def test_add():
    result = add(1, 2)
    assert result == 3

def test_subtract():
    result = subtract(1, 1)
    assert result == 0

def test_multiplie():
    result = multiply(2, 2)
    assert result == 4

def test_divide():
    result = divide(10, 2)
    assert result == 5
    
def test_modulo():
    result = modulo(3, 2)
    assert result == 1

def power():
    result = power(2, 3)
    assert result == 8
# src/calculator.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

def modulo(a, b):
    return a % b

def power(a, b):
    return a ** b

執行pytest指令檢查是否正常,全亮綠燈表示正常,有錯誤會顯示讓你知道。
截圖 2025-09-09 15.37.35
截圖 2025-09-09 15.38.25

  • 如果發現顯示錯誤ImportError: No module named 'src' 先檢查 src 資料夾中是不是有__init__py檔案。
  • 如果執行pytest指令後發現找不到檔案,請檢查測試檔案名稱是否為test_開頭,或是測試函數是不是test_開頭,這些內容都在開頭的pytest.ini檔案中設定。

pytest 提供了些輸出種類:

  1. 詳細內容
pytest -v

截圖 2025-09-09 16.52.47
2. 覆蓋率

pytest --cov=src

截圖 2025-09-09 16.53.29
3. 停在第一個失敗點

pytest -x

截圖 2025-09-09 16.55.27

那麼今天就介紹到這,明天見ㄅㄅ!


上一篇
筆記Day25:測試能幹嘛?
下一篇
筆記Day27:框架三本柱之第一柱 - Django
系列文
Python 學習筆記27
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言