The Test Runner چالش 5 از جلسهی 30، سخت
(سختتر) در کد یک سرور کتاب هست که یک باگ دارد، و سه تابع تست و لیست tests. حلقهای بنویس که هر تست را به ترتیب لیست اجرا کند: اگر قبول شد PASS و اسم تابع را چاپ کند، اگر AssertionError داد FAIL، اسم تابع، - و پیام خطا را، و آخر هم تعداد قبولشدهها را. خروجی باید دقیقاً این باشد:PASS test_listFAIL test_add - a new book should give 201PASS test_no_title2 of 3 tests passed
(باگ را اینجا درست نکن؛ فقط پیدایش کن.)
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 not data.get("title"):
abort(400, "title is required")
book = {"id": len(books) + 1, "title": data["title"]}
books.append(book)
return book
def test_list():
r = ask("GET /api/v1/books", quiet=True)
assert r.status == 200, "the list should answer 200"
assert len(r.json) == 2, "there should be 2 books"
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"
tests = [test_list, test_add, test_no_title]
passed = 0
___
راهنما و جواب این چالش · برگشت به درس جلسهی 30: تست کردن سرور · چالش بعدی: Catch the Bug, Then Fix It
بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال