Contents

pytest

建立自動化測試流程。

基本結構

測試文件以test_開頭,在更複雜的專案中可將整體鏡像放置在tests/資料夾中。

1
2
3
src/
├───calculate.py
└───test_calculate.py

編寫 pytest

calculate.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Calculator:
    def add(self, a, b):
        return a + b

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

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

    def divide(self, a, b):
        if b == 0:
            raise ValueError("Cannot divide by zero.")
        return a / b

test_calculate.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from calculate import Calculator
import pytest

# 工廠函式,名稱需與 test_ 函式的參數名稱相同
@pytest.fixture
def calc() -> Calculator:
    ret = Calculator()
    return ret
    # or yield ret, 如需要清理記憶體刪除操作。

# 函式需以`test_`開頭
@pytest.mark.parametrize("n1, n2, expected", [
    [1, 2, 3],
    [-1, -2, -3],
    [4, 5, 9]
])
def test_add(calc: Calculator, n1: int, n2: int, expected: int) -> None:
    assert calc.add(n1, n2) == expected

可搭配 VScode、pycharm 的 UI 介面服用。

References