今天要開始來寫測試了!
讓我們一步一步來,會從建立專案到撰寫測試。
建立專案資料夾
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
指令檢查是否正常,全亮綠燈表示正常,有錯誤會顯示讓你知道。
ImportError: No module named 'src'
先檢查 src 資料夾中是不是有__init__py
檔案。pytest
指令後發現找不到檔案,請檢查測試檔案名稱是否為test_
開頭,或是測試函數是不是test_
開頭,這些內容都在開頭的pytest.ini
檔案中設定。pytest 提供了些輸出種類:
pytest -v
2. 覆蓋率
pytest --cov=src
3. 停在第一個失敗點
pytest -x
那麼今天就介紹到這,明天見ㄅㄅ!