بتل کد Battle Codeدارد باز می‌شود…

جواب «The Test Runner» چالش 5 از جلسه‌ی 30

سؤال

(سخت‌تر) در کد یک سرور کتاب هست که یک باگ دارد، و سه تابع تست و لیست tests. حلقه‌ای بنویس که هر تست را به ترتیب لیست اجرا کند: اگر قبول شد PASS و اسم تابع را چاپ کند، اگر AssertionError داد FAIL، اسم تابع، - و پیام خطا را، و آخر هم تعداد قبول‌شده‌ها را. خروجی باید دقیقاً این باشد:
PASS test_list
FAIL test_add - a new book should give 201
PASS test_no_title
2 of 3 tests passed
(باگ را این‌جا درست نکن؛ فقط پیدایش کن.)

راهنما

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").

یک جواب درست

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
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")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن