Python เขียน Unit Test (pytest)
Unit test คือโค้ดที่เขียนขึ้นเพื่อตรวจว่าโค้ดอีกส่วนหนึ่งทำงานถูกต้อง เขียนไว้แล้วรันซ้ำได้ตลอด พอแก้โค้ดแล้วรันเทสต์ ถ้าผ่านหมดก็มั่นใจได้ว่าไม่ได้ทำอะไรพัง Python มี unittest มาให้ในตัว แต่ pytest เขียนสั้นและอ่านง่ายกว่ามาก จึงเป็นที่นิยมกว่า
ติดตั้ง
คำสั่ง
pipและpytestในบทนี้พิมพ์ใน เทอร์มินัล / command prompt ไม่ใช่ใน Python shell (ที่ขึ้น>>>)
pip install pytestเทสต์แรก
สมมติมีไฟล์ calculator.py
# calculator.py
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("หารด้วยศูนย์ไม่ได้")
return a / bสร้างไฟล์ test_calculator.py (ชื่อต้องขึ้นต้นด้วย test_)
# test_calculator.py
from calculator import add, divide
def test_add_positive():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, -1) == -2
def test_add_zero():
assert add(0, 5) == 5
def test_divide():
assert divide(10, 2) == 5.0รันด้วย
pytestผลลัพธ์
test_calculator.py .... [100%]
4 passed in 0.02sหลักการ: ฟังก์ชันเทสต์
- ชื่อไฟล์ขึ้นต้น
test_หรือลงท้าย_test.py - ฟังก์ชันเทสต์ขึ้นต้น
test_ - ใช้
assertธรรมดา ถ้าเงื่อนไขเป็น False เทสต์นั้น fail - หนึ่งเทสต์ควรตรวจพฤติกรรมเดียว ตั้งชื่อให้บอกว่าตรวจอะไร
เทียบ exception
import pytest
from calculator import divide
def test_divide_by_zero_raises():
with pytest.raises(ValueError):
divide(10, 0)
def test_divide_by_zero_message():
with pytest.raises(ValueError, match="หารด้วยศูนย์"):
divide(10, 0)pytest.raises จะทำให้เทสต์ผ่านก็ต่อเมื่อโค้ดในบล็อกโยน exception ตามที่ระบุ
เทียบทศนิยม
ทศนิยมมีความคลาดเคลื่อน อย่าเทียบตรง ๆ ด้วย ==
import pytest
def test_float():
assert 0.1 + 0.2 == pytest.approx(0.3)parametrize: เทสต์เดียว หลายชุดข้อมูล
แทนที่จะเขียนฟังก์ชันเทสต์ซ้ำ ๆ
import pytest
from calculator import add
@pytest.mark.parametrize("a, b, expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
(100, 200, 300),
])
def test_add(a, b, expected):
assert add(a, b) == expectedpytest จะรันเป็น 4 เทสต์แยกกัน ถ้าชุดไหน fail จะบอกชัดว่าชุดไหน
fixture: เตรียมข้อมูลที่ใช้ร่วมกัน
import pytest
@pytest.fixture
def sample_users():
return [
{"name": "สมชาย", "age": 25},
{"name": "สมหญิง", "age": 30},
]
def test_count(sample_users):
assert len(sample_users) == 2
def test_first_name(sample_users):
assert sample_users[0]["name"] == "สมชาย"ฟังก์ชันเทสต์ที่รับพารามิเตอร์ชื่อตรงกับ fixture จะได้ค่าที่ fixture return มาโดยอัตโนมัติ
fixture กับไฟล์ชั่วคราว
pytest มี fixture tmp_path ให้โฟลเดอร์ชั่วคราวที่ล้างให้เองหลังเทสต์
def test_write_file(tmp_path):
file = tmp_path / "output.txt"
file.write_text("hello", encoding="utf-8")
assert file.read_text(encoding="utf-8") == "hello"จัดกลุ่มด้วยคลาส
class TestShoppingCart:
def test_empty_cart_total_is_zero(self):
cart = Cart()
assert cart.total() == 0
def test_add_item_increases_total(self):
cart = Cart()
cart.add("กาแฟ", 45)
assert cart.total() == 45คำสั่ง pytest ที่ใช้บ่อย
pytest # รันทั้งหมด
pytest test_calculator.py # รันไฟล์เดียว
pytest -v # แสดงชื่อเทสต์แต่ละตัว
pytest -k "divide" # รันเฉพาะเทสต์ที่ชื่อมีคำว่า divide
pytest -x # หยุดทันทีที่เจอ fail แรก
pytest --lf # รันเฉพาะที่ fail รอบที่แล้ววัด coverage
pip install pytest-cov
pytest --cov=calculatorบอกว่าเทสต์ครอบคลุมโค้ดกี่เปอร์เซ็นต์ บรรทัดไหนยังไม่ถูกเทสต์
เขียนโค้ดให้เทสต์ง่าย
- ฟังก์ชันที่รับ input คืน output ชัดเจน (ไม่พึ่ง global, ไม่พิมพ์ออกจอ) เทสต์ง่ายที่สุด
- แยกส่วน “ตรรกะ” ออกจากส่วน “I/O” (อ่านไฟล์ เรียก API) เทสต์ตรรกะได้โดยไม่ต้องแตะของจริง
- ถ้าเทสต์ยากมาก มักเป็นสัญญาณว่าโค้ดออกแบบไม่ดี
# เทสต์ยาก — ผูกกับ input() และ print()
def calculate_bmi():
w = float(input("น้ำหนัก: "))
h = float(input("ส่วนสูง: "))
print(w / h ** 2)
# เทสต์ง่าย — แยกตรรกะออกมา
def bmi(weight, height):
return weight / height ** 2
def main():
w = float(input("น้ำหนัก: "))
h = float(input("ส่วนสูง: "))
print(bmi(w, h))ตัวอย่างรวม
# validators.py
def is_valid_email(email):
if email.count("@") != 1:
return False
local, domain = email.split("@")
return bool(local) and "." in domain
# test_validators.py
import pytest
from validators import is_valid_email
@pytest.mark.parametrize("email, expected", [
("test@example.com", True),
("user.name@company.co.th", True),
("no-at-sign.com", False),
("@example.com", False),
("two@@at.com", False),
("noduser@nodot", False),
])
def test_is_valid_email(email, expected):
assert is_valid_email(email) == expectedเช็คความเข้าใจก่อนข้ามบท
- เขียน test function ที่ขึ้นต้นด้วย
test_และใช้assertได้ - ทดสอบ exception ด้วย
pytest.raises()ได้ - ลองใช้
parametrizeลดโค้ดซ้ำเมื่อมี input/output หลายชุด
สรุป
- ไฟล์
test_*.pyฟังก์ชันtest_*ใช้assertธรรมดา รันด้วยpytest pytest.raisesเทียบ exception,pytest.approxเทียบทศนิยม@pytest.mark.parametrizeรันเทสต์เดียวหลายชุดข้อมูลfixtureเตรียมข้อมูลร่วม; แยกตรรกะออกจาก I/O เพื่อให้เทสต์ง่าย
บทถัดไปว่าด้วย logging และการ debug