Lesson 11
Test with pytest
แก้โค้ดแล้วจะรู้ได้ยังไงว่าของเดิมไม่พัง เขียนเทสต์ 14 ตัวด้วย pytest แล้วลองถอด guard ออกให้เทสต์ Fail
ที่ผ่านมาเราเช็กโค้ดด้วย script อย่าง try_orders.py และ try_guards.py ที่รันแล้วอ่านผลด้วยตา บทนี้เปลี่ยนการเช็กเหล่านั้นเป็นเทสต์ที่รันครั้งเดียวแล้วบอกว่าผ่านหรือไม่ผ่าน แก้โค้ดเมื่อไรก็รันดูได้ว่า guard ที่เขียนไว้ยังทำงานอยู่
ทุกคำสั่งรันในโฟลเดอร์ cafe-mcp ที่ทำค้างไว้จากบทที่แล้ว
What to Test
เทสต์จะเรียก server ผ่าน Client ตัวเดียวกับที่ใช้ใน try_client.py ของบท Build Your First Tool
Client(mcp) ต่อกับ server ใน process เดียวกัน ไม่ผ่าน stdio หรือ HTTP แต่ server ยังตรวจ argument แปลง ToolError เป็นผลลัพธ์ที่ is_error เป็น True และถามผู้ใช้ด้วย elicitation เหมือนตอนต่อกับ client ตัวอื่น
เทสต์ 14 ตัวแบ่งเป็น 2 ไฟล์
| File | Tests | What It Checks |
|---|---|---|
test_cafe.py | list_menu | max_price_thb กรองเมนู |
create_order (4 ตัว) | ยอดคำนวณจากเมนูใน Database และ guard: รายการว่าง ชื่อลูกค้าว่าง เมนูที่ปิดขาย ขนาดที่ไม่มี จำนวน 0 | |
cancel_order (3 ตัว) | ผู้ใช้ยืนยัน ผู้ใช้ปฏิเสธ และ client ที่ไม่รองรับ elicitation ได้ -32021 | |
| resource | ออร์เดอร์ที่มีอยู่ และออร์เดอร์ที่ไม่มี | |
| prompt | daily_summary แนบยอดขาย และวันที่ผิดรูปแบบ | |
| completion | แนะนำชื่อเมนูตามตัวอักษรนำ และ size ตามเมนูที่เลือก | |
test_stock_notify.py | reorder (2 ตัว) | ใบสั่งซ้ำ และจำนวนนอกช่วง |
send_message | ช่องที่ไม่มี และข้อความที่เป็น SQL ถูกเก็บเป็นข้อความ |
Write the Code
- ติดตั้ง pytest
- ให้เทสต์แต่ละตัวมี Database ใหม่
- เขียนเทสต์ของ
cafe - เขียนเทสต์ของ
stockกับnotify
1. Install pytest
pytest เป็นตัวหาและรันเทสต์ ใช้ตอนพัฒนาเท่านั้น เลยเพิ่มเป็น dev dependency เทสต์ของเราเป็น async def ด้วย ต้องมี pytest-asyncio ช่วยรัน
uv add --dev pytest pytest-asyncio
uv add --dev เพิ่มกลุ่ม [dependency-groups] ท้าย pyproject.toml ส่วน dependencies ของ server ไม่เปลี่ยน
[dependency-groups]
dev = [
"pytest>=9.2.0",
"pytest-asyncio>=1.5.0",
]
เพิ่มการตั้งค่า pytest ต่อท้าย pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
pythonpath = ["."]
asyncio_mode = "auto"ให้async def test_...รันได้ทันทีโดยไม่ต้องติด@pytest.mark.asyncioทุกตัวasyncio_default_fixture_loop_scope = "function"กำหนดให้ async fixture ใช้ event loop (ตัวที่คอยรันโค้ดasync) แยกกันทีละเทสต์ ถ้าไม่ตั้ง pytest-asyncio แสดง deprecation warning ทุกครั้งที่รันpythonpath = ["."]ให้เทสต์ในtests/เขียนimport databaseและfrom cafe_server import mcpได้ เพราะโมดูลของเราอยู่ที่โฟลเดอร์โปรเจกต์
2. Fresh Databases
Database ของแต่ละ server ถูกกำหนดเป็นค่าคงที่ระดับโมดูล (DB_PATH) และ connect() อ่านค่านั้นทุกครั้งที่เรียก ถ้าเทสต์ไม่เปลี่ยนค่านี้ เทสต์จะเขียนลง cafe.db ที่ใช้อยู่ และผลของเทสต์หนึ่งจะค้างไปให้เทสต์ถัดไป
สร้างโฟลเดอร์ tests แล้วเพิ่ม conftest.py (ไฟล์ที่ pytest โหลดเองก่อนรันเทสต์ในโฟลเดอร์นั้น) ที่มี fixture (ฟังก์ชันที่เตรียมของให้ก่อนแต่ละเทสต์) ชี้ DB_PATH ของทั้งสามโมดูลไปที่โฟลเดอร์ชั่วคราวของเทสต์นั้น
import pytest
import database
import notify_server
import stock_server
@pytest.fixture(autouse=True)
def fresh_databases(tmp_path, monkeypatch):
monkeypatch.setattr(database, "DB_PATH", tmp_path / "cafe.db")
monkeypatch.setattr(stock_server, "DB_PATH", tmp_path / "stock.db")
monkeypatch.setattr(notify_server, "DB_PATH", tmp_path / "notify.db")
tmp_pathเป็นโฟลเดอร์ว่างที่ pytest สร้างใหม่ให้ทุกเทสต์monkeypatch.setattrเปลี่ยนค่าเฉพาะระหว่างเทสต์ แล้วคืนค่าเดิมให้เมื่อเทสต์จบautouse=Trueใช้กับทุกเทสต์โดยไม่ต้องเขียนชื่อ fixture ที่ parameter- ไฟล์ Database ยังไม่มีในโฟลเดอร์ใหม่
connect()เลยสร้างตารางและข้อมูลตั้งต้นให้เองทุกครั้ง ออร์เดอร์ 1 กับ 2 มีอยู่แล้ว ออร์เดอร์ที่สร้างในเทสต์เลยได้เลข 3 เสมอ
3. Cafe Tests
เทสต์หลายตัวข้างล่างต้องตอบคำถามยืนยันแทนผู้ใช้ และต้องเช็กสถานะออร์เดอร์หลังเรียก tool เลยเขียนสองเรื่องนี้เป็นฟังก์ชันไว้หัวไฟล์ก่อน
import json
from mcp import Client
from mcp.shared.exceptions import MCPError
from mcp_types import ElicitResult, ResourceTemplateReference
from cafe_server import mcp as cafe
ONE_LATTE = {"items": [{"menu": "latte", "size": "M", "quantity": 1}], "customer_name": "Somchai"}
def user_says(action: str):
async def callback(context, params):
content = {"confirm": True} if action == "accept" else None
return ElicitResult(action=action, content=content)
return callback
async def order_status(client: Client, order_id: int) -> str:
result = await client.read_resource(f"cafe://orders/{order_id}")
return json.loads(result.contents[0].text)["status"]
user_says("accept") สร้าง callback ที่ตอบคำถามของ server แทนผู้ใช้ ใส่เป็น elicitation_callback ตอนสร้าง Client ถ้าไม่ใส่ client จะไม่ประกาศว่าตอบ elicitation ได้ เทสต์ -32021 ด้านล่างอาศัยข้อนี้
เทสต์ของ list_menu และ create_order (ต่อท้ายไฟล์เดิม บล็อกถัด ๆ ไปของ tests/test_cafe.py ก็เช่นกัน)
async def test_list_menu_filters_by_price():
async with Client(cafe) as client:
result = await client.call_tool("list_menu", {"max_price_thb": 55})
names = [item["name"] for item in result.structured_content["result"]]
assert names == ["thai tea", "americano"]
async def test_create_order_calculates_total_from_menu():
order = {"items": [{"menu": "iced latte", "size": "M", "quantity": 2}], "customer_name": "Somchai"}
async with Client(cafe) as client:
result = await client.call_tool("create_order", order)
assert result.structured_content["id"] == 3
assert result.structured_content["total_thb"] == 130
async def test_create_order_rejects_empty_items():
async with Client(cafe) as client:
result = await client.call_tool("create_order", {"items": [], "customer_name": "Somchai"})
assert result.is_error
assert "at least one item" in result.content[0].text
async def test_create_order_rejects_blank_customer():
async with Client(cafe) as client:
result = await client.call_tool("create_order", {**ONE_LATTE, "customer_name": " "})
assert result.is_error
async def test_create_order_rejects_unavailable_unknown_size_and_zero_quantity():
bad_items = [
{"menu": "thai tea", "size": "M", "quantity": 1},
{"menu": "latte", "size": "XL", "quantity": 1},
{"menu": "latte", "size": "M", "quantity": 0},
]
async with Client(cafe) as client:
for item in bad_items:
result = await client.call_tool("create_order", {"items": [item], "customer_name": "Somchai"})
assert result.is_error, item
structured_content["result"]ในเทสต์แรกมีresultครอบเพราะlist_menuคืน list (ดูบท Build Your First Tool) ส่วนcreate_orderคืนออร์เดอร์ตัวเดียว เลยอ่าน["id"]ได้ตรง ๆ- ค่าที่คาดไว้ในเทสต์เขียนเป็นตัวเลขตรง ๆ (
130คือ65 x 2) ไม่คำนวณซ้ำด้วยสูตรเดียวกับโค้ด เพราะถ้าสูตรผิด เทสต์ที่ใช้สูตรเดียวกันจะผ่านไปด้วย - guard ของ tool ตอบเป็นผลลัพธ์ที่มี
is_errorเป็นTrueฝั่ง client ไม่มี exception assert result.is_error, itemพิมพ์itemออกมาเมื่อ Fail เพื่อบอกว่าเป็นรายการไหน
เทสต์ของ cancel_order ทั้งสามแบบ
async def test_cancel_order_after_user_accepts():
async with Client(cafe, elicitation_callback=user_says("accept")) as client:
result = await client.call_tool("cancel_order", {"order_id": 1})
assert result.content[0].text == "Order 1 cancelled."
assert await order_status(client, 1) == "cancelled"
async def test_cancel_order_does_nothing_after_user_declines():
async with Client(cafe, elicitation_callback=user_says("decline")) as client:
result = await client.call_tool("cancel_order", {"order_id": 1})
assert result.content[0].text == "Order 1 was not cancelled."
assert await order_status(client, 1) == "completed"
async def test_cancel_order_without_elicitation_support_is_refused():
async with Client(cafe) as client:
try:
await client.call_tool("cancel_order", {"order_id": 1})
except MCPError as error:
assert error.code == -32021
else:
raise AssertionError("expected error -32021")
สองตัวแรกเช็กข้อความที่ tool ตอบ แล้วอ่าน cafe://orders/1 เพื่อดูสถานะที่เก็บใน Database หลังเรียก ส่วนตัวที่สามไม่ได้รับผลลัพธ์ของ tool เพราะ -32021 เป็น error ระดับ protocol Client เลย raise MCPError ขึ้นมา
เทสต์ของ resource, prompt และ completion
async def test_order_resource_returns_items_and_unknown_order_fails():
async with Client(cafe) as client:
order = json.loads((await client.read_resource("cafe://orders/2")).contents[0].text)
assert order["customer"] == "Preecha"
assert order["items"] == [{"menu": "americano", "size": "L", "quantity": 2}]
try:
await client.read_resource("cafe://orders/999")
except MCPError as error:
assert "Order 999 not found" in error.message
else:
raise AssertionError("expected not found")
async def test_daily_summary_embeds_sales_and_rejects_bad_date():
async with Client(cafe) as client:
rendered = await client.get_prompt("daily_summary", {"day": "2027-06-15"})
assert rendered.messages[1].content.resource.uri == "cafe://sales/2027-06-15"
try:
await client.get_prompt("daily_summary", {"day": "yesterday"})
except MCPError as error:
assert "not a date" in error.message
else:
raise AssertionError("expected invalid params")
async def test_completion_suggests_by_prefix():
template = ResourceTemplateReference(uri="cafe://recipes/{menu}/{size}")
async with Client(cafe) as client:
menus = await client.complete(template, {"name": "menu", "value": "i"})
sizes = await client.complete(template, {"name": "size", "value": ""}, {"menu": "americano"})
assert menus.completion.values == ["iced latte"]
assert sizes.completion.values == ["L", "M"]
resource ที่ไม่มีกับ prompt ที่รับวันที่ผิดเป็น error ระดับ protocol เช่นกัน เทสต์เลยจับด้วย try ... except MCPError แล้วเช็กข้อความ
ส่วน else: raise AssertionError กันกรณี server ไม่ error เลย ซึ่งถ้าไม่มีบรรทัดนี้เทสต์จะผ่านทั้งที่ guard หายไป
4. Stock and Notify Tests
reorder กับ send_message ถามยืนยันก่อนทำ เทสต์ของสองตัวนี้ใช้ callback ที่ตอบ accept ทุกครั้ง
from mcp import Client
from mcp_types import ElicitResult
import notify_server
import stock_server
async def accept(context, params):
return ElicitResult(action="accept", content={"confirm": True})
async def test_reorder_allows_one_open_order_per_ingredient():
async with Client(stock_server.mcp, elicitation_callback=accept) as client:
first = await client.call_tool("reorder", {"ingredient": "milk", "amount": 5000})
second = await client.call_tool("reorder", {"ingredient": "milk", "amount": 5000})
assert first.content[0].text == "Reorder #1: 5000 of milk."
assert second.is_error
assert "already has an open reorder" in second.content[0].text
async def test_reorder_rejects_amount_out_of_range():
async with Client(stock_server.mcp, elicitation_callback=accept) as client:
for amount in (0, -3, 1e9):
result = await client.call_tool("reorder", {"ingredient": "milk", "amount": amount})
assert result.is_error, amount
async def test_send_message_rejects_unknown_channel_and_stores_sql_text_as_data():
sql_text = "'); DROP TABLE messages; --"
async with Client(notify_server.mcp, elicitation_callback=accept) as client:
unknown = await client.call_tool("send_message", {"channel": "general", "text": "hi"})
sent = await client.call_tool("send_message", {"channel": "staff-group", "text": sql_text})
assert unknown.is_error
assert sent.content[0].text == "Sent message #1 to staff-group."
with notify_server.connect() as db:
assert db.execute("SELECT text FROM messages").fetchone()["text"] == sql_text
ใบสั่งแรกได้เลข #1 เพราะตาราง reorders ใน stock.db ของเทสต์นี้ยังไม่มีแถว เทสต์สุดท้ายอ่านตาราง messages ตรง ๆ ผ่าน notify_server.connect() ซึ่งชี้ไปที่ Database ชั่วคราวเดียวกับที่ server เขียน
Run the Tests
- รันทั้งชุด
- ทำให้เทสต์ Fail
- รันอีกครั้งหลังแก้กลับ
Full Run
uv run pytest -q
.............. [100%]
14 passed in 0.11s
-q ย่อผลให้เหลือจุดละหนึ่งเทสต์ ถ้าอยากเห็นชื่อทุกตัวให้ใช้ -v เทสต์ทั้งหมดไม่แตะ cafe.db, stock.db และ notify.db ในโฟลเดอร์โปรเจกต์
Break a Guard
เทสต์ที่ไม่เคยเห็นมัน Fail ยังไม่ได้พิสูจน์ว่าจับอะไรได้ ลองเอา guard ออกดู ใน cafe_server.py ฟังก์ชัน create_order ลบ not items or ออกจากบรรทัด if not items or not customer_name.strip(): ให้เหลือแบบนี้
if not customer_name.strip():
raise ToolError("An order needs a customer name and at least one item.")
uv run pytest -q
..F........... [100%]
=================================== FAILURES ===================================
____________________ test_create_order_rejects_empty_items _____________________
async def test_create_order_rejects_empty_items():
async with Client(cafe) as client:
result = await client.call_tool("create_order", {"items": [], "customer_name": "Somchai"})
> assert result.is_error
E AssertionError: assert False
E + where False = CallToolResult(meta={'io.modelcontextprotocol/serverInfo': {'name': 'cafe', 'version': ''}}, content=[TextContent(type...'id': 3, 'customer': 'Somchai', 'status': 'open', 'total_thb': 0, 'items': []}, is_error=False, result_type='complete').is_error
tests/test_cafe.py:43: AssertionError
=========================== short test summary info ============================
FAILED tests/test_cafe.py::test_create_order_rejects_empty_items - AssertionE...
1 failed, 13 passed in 0.12s
ตัวที่ Fail คือ test_create_order_rejects_empty_items ตัวเดียว ใน result เห็น 'id': 3 และ 'total_thb': 0 คือ server สร้างออร์เดอร์ว่างยอด 0 บาทขึ้นมา
เทสต์อีก 13 ตัวผ่านต่อ เพราะแต่ละตัวมี Database ของตัวเอง ออร์เดอร์ว่างนี้เลยไม่รั่วไปตัวอื่น
Restore
ใส่ not items or กลับ แล้วรันอีกครั้ง
uv run pytest -q
.............. [100%]
14 passed in 0.11s
Pitfalls
Client(mcp)ข้าม transport ทั้งหมด เทสต์เหล่านี้ไม่เห็น headerMcp-MethodกับMcp-Nameไม่เห็น HTTP status (เช่น 400 ของ-32021) และไม่เห็นว่าprintลง stdout ทำให้ stdio พังหรือเปล่า สิ่งเหล่านี้ยังต้องเช็กด้วย curl อย่างในบท Confirm Actions with Elicitation หรือดัก request ดูอย่างในบท Intercept Requests and Responses- เทสต์ตรวจพฤติกรรมของ server การที่ AI เลือก tool ตัวไหนจาก description อยู่นอกขอบเขตของเทสต์เหล่านี้ ต้องลองใน Claude Code อย่างในบทก่อนหน้า
monkeypatch.setattr(database, "DB_PATH", ...)ได้ผลเพราะconnect()อ่านDB_PATHจากโมดูลตอนเรียก ถ้าโค้ดไหนเขียนfrom database import DB_PATHค่าจะถูกคัดลอกไปตอน import และการ patch ไม่ถึงตัวนั้นDB_PATHมีสามตัวในสามโมดูล ลืม patch ตัวไหน เทสต์ของ server นั้นจะเขียนลงไฟล์ในโฟลเดอร์โปรเจกต์ รอบแรกอาจผ่าน แต่รอบถัดไป Fail เพราะข้อมูลจากรอบก่อนค้างอยู่- ถ้าแก้ข้อมูลตั้งต้นใน
SCHEMAของdatabase.pyต้องแก้ค่าที่คาดไว้ในเทสต์ตามด้วย เช่นเลขออร์เดอร์ 3 assert result.is_errorผ่านกับ error ทุกชนิด รวมถึง error ที่ไม่เกี่ยวกับ guard ที่ตั้งใจเช็ก เทสต์ที่ guard แต่ละข้อมีข้อความของตัวเองควรเช็กข้อความด้วย อย่างในเทสต์รายการว่าง เทสต์ที่วนbad_itemsเช็กแค่is_errorเลยบอกได้เพียงว่า tool ปฏิเสธ ไม่ได้บอกว่าปฏิเสธเพราะข้อไหน- callback ในเทสต์ของ
stockกับnotifyตอบacceptโดยไม่อ่านคำถาม เทสต์เลยไม่เห็นว่าข้อความที่ถามผู้ใช้ตรงกับสิ่งที่จะทำหรือไม่ ถ้าต้องเช็กให้เก็บparams.messageใน callback แล้วassertกับมัน
Summary
เทสต์ 14 ตัวเรียก server ผ่าน Client ใน process เดียวกัน แต่ละตัวใช้ Database ของตัวเองด้วย fixture autouse และเราเห็นแล้วว่าเทสต์จับ guard ที่หายไปได้
จบคอร์สนี้ cafe-mcp มี tool, resource, prompt, completion, elicitation, server สามตัวที่ทำงานร่วมกัน และเทสต์ที่ผ่านทั้งหมด แต่ยังมีช่องที่ต้องปิดอีกสามข้อ
- HTTP server ไม่มี authentication ใครต่อถึง port ก็เรียก tool ได้
- ค่าที่ AI ส่งมาเป็น argument เชื่อไม่ได้ และข้อความที่คนพิมพ์ลง Database ก็ไปถึง AI ผ่าน resource
- server ของคนอื่นที่ติดตั้งเข้ามารันด้วยสิทธิ์ของเรา
คอร์ส ทำ MCP Server ให้ปลอดภัยตาม OWASP MCP Top 10 ทำต่อจากจุดนี้ เก็บโฟลเดอร์ cafe-mcp ไว้ เพราะเป็นจุดเริ่มของคอร์สนั้นครับ