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

A Test Against Leaks چالش 6 از جلسه‌ی 31، سخت

(سخت‌تر) مسیر GET /api/v1/questions در این کد یک نشت دارد: با SELECT * جواب درست را هم می‌فرستد. (این‌جا ردیف‌ها همان‌طور که هستند فرستاده می‌شوند، بی public.) دو کار بکن:
1. تابع تست test_no_answers را بنویس: GET /api/v1/questions را بپرسد و برای هر سؤال assert "answer" not in q, "the answers leak". آن را آخر لیست tests بگذار و اجرا کن تا FAIL test_no_answers - the answers leak را ببینی.
2. حالا سرور را درست کن: SELECT فقط id, text, c1, c2, c3 را بیاورد.
خروجی باید سه خط PASS (test_count، test_missing، test_no_answers)، بعد 3 of 3 tests passed، و آخر جواب ask("GET /api/v1/questions") باشد: سه سؤال بدون answer.

from server import app, ask, request, abort, db

db.script("""
CREATE TABLE questions (id INTEGER PRIMARY KEY, text TEXT, c1 TEXT, c2 TEXT, c3 TEXT, answer INTEGER);
INSERT INTO questions (text, c1, c2, c3, answer) VALUES
    ('Which code means Not Found?', '200', '404', '500', 2),
    ('Which method makes a new thing?', 'POST', 'GET', 'DELETE', 1),
    ('What do APIs usually send?', 'Photos', 'Python', 'JSON', 3);
""")

@app.get("/api/v1/questions")
def all_questions():
    return db.all("SELECT * FROM questions ORDER BY id")

@app.get("/api/v1/questions/<int:qid>")
def one_question(qid):
    q = db.one("SELECT id, text, c1, c2, c3 FROM questions WHERE id = ?", qid)
    if q is None:
        abort(404, "no such question")
    return q

def test_count():
    r = ask("GET /api/v1/questions", quiet=True)
    assert r.status == 200, "the list should answer 200"
    assert len(r.json) == 3, "there should be 3 questions"

def test_missing():
    r = ask("GET /api/v1/questions/9", quiet=True)
    assert r.status == 404, "question 9 should be missing"

# write test_no_answers here


tests = [test_count, test_missing]
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("GET /api/v1/questions")

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 31: سرور کوییز، بخش ۱

بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال