Catch the Bug, Then Fix It چالش 6 از جلسهی 30، سخت
(سختتر) سرور کتابهای این کد یک باگ در راه بد دارد: کتابی با عنوان خالی ({"title": ""}) را قبول میکند. دو کار بکن:
1. یک تابع تست تازه به اسم test_empty_title بنویس که {"title": ""} را POST کند و بررسی کند وضعیت 400 است، و آن را آخر لیست tests بگذار. اجرا کن تا FAIL را ببینی.
2. حالا سرور را درست کن (نه تست را!) تا عنوان خالی هم 400 با {"error": "title is required"} بگیرد.
خروجی باید سه خط PASS (test_add، test_no_title، test_empty_title)، بعد 3 of 3 tests passed و آخر جواب askی باشد که در کد هست و عنوان خالی را میفرستد: POST /api/v1/books → 400 Bad Request و {"error": "title is required"}.
from server import app, ask, request, abort
books = [{"id": 1, "title": "Wonder"}, {"id": 2, "title": "Matilda"}]
@app.get("/api/v1/books")
def all_books():
return books
@app.post("/api/v1/books")
def add_book():
data = request.json or {}
if "title" not in data:
abort(400, "title is required")
book = {"id": len(books) + 1, "title": data["title"]}
books.append(book)
return book, 201
def test_add():
r = ask("POST /api/v1/books", {"title": "Coraline"}, quiet=True)
assert r.status == 201, "a new book should give 201"
assert r.json["id"] == 3, "the new book should be number 3"
def test_no_title():
r = ask("POST /api/v1/books", {"pages": 120}, quiet=True)
assert r.status == 400, "no title should give 400"
# write test_empty_title here
tests = [test_add, test_no_title]
passed = 0
for test in tests:
try:
test()
print("PASS", test.__name__)
passed += 1
except AssertionError as err:
print("FAIL", test.__name__, "-", err)
print(passed, "of", len(tests), "tests passed")
ask("POST /api/v1/books", {"title": ""})
راهنما و جواب این چالش · برگشت به درس جلسهی 30: تست کردن سرور
بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال