🔌 Automation Testing · Chương 7 · Mục 7.4
Đọc dữ liệu từ response
Thêm fixture lấy 1 id booking có thật (vì dữ liệu Restful-Booker tự reset định kỳ, không được đoán đại 1 id cố định):
Tệp tests/conftest.py (thêm bên dưới api_context):
FILE tests/conftest.py
@pytest.fixturedef mot_booking_id_co_that(api_context):"""Lay 1 bookingid dang ton tai that trong he thong.KHONG duoc doan dai mot id co dinh (vd id=1) vi du lieu Restful-Bookertu dong reset dinh ky, danh sach id con lai thay doi lien tuc."""response = api_context.get("/booking")danh_sach = response.json()return danh_sach[0]["bookingid"]
response.json() chuyển response (dạng JSON, học ở Chương 2) thành list/dict Python để dùng trực tiếp — ở đây /booking trả về 1 list các dict {"bookingid": ...}, lấy phần tử đầu tiên.
Thêm test dùng fixture này, đọc chi tiết 1 booking:
Tệp tests/test_02_api_co_ban.py (thêm bên dưới hàm test_ping...):
FILE tests/test_02_api_co_ban.py
def test_lay_chi_tiet_1_booking_dung_cau_truc(api_context, mot_booking_id_co_that):"""GET /booking/{id} voi id co that phai tra ve du cac field theo dung 'hop dong' cua API."""response = api_context.get(f"/booking/{mot_booking_id_co_that}")expect(response).to_be_ok()body = response.json()assert "firstname" in body # co du field firstnameassert "lastname" in body # co du field lastnameassert "totalprice" in body # co du field totalpriceassert "bookingdates" in body # co du field bookingdatesassert isinstance(body["totalprice"], (int, float)) # totalprice dung kieu so, khong phai chuoi
| Dòng | Giải thích |
|---|---|
| f"/booking/{mot_booking_id_co_that}" | f-string (Chương 2) ghép id thật vào đường dẫn |
| body = response.json() | Chuyển response thành dict |
| assert "firstname" in body | assert thường của Python — kiểm tra dict có đúng field mong đợi, không cần web-first assertion vì đây không phải giao diện có độ trễ render |
| isinstance(body["totalprice"], (int, float)) | Kiểm tra kiểu dữ liệu đúng là số, không phải chuỗi |
Chạy toàn bộ file:
TERMINAL
pytest tests/test_02_api_co_ban.py -v
Kết quả:
KẾT QUẢ
tests/test_02_api_co_ban.py::test_ping_xac_nhan_api_con_song PASSED [ 50%]tests/test_02_api_co_ban.py::test_lay_chi_tiet_1_booking_dung_cau_truc PASSED [100%]============================== 2 passed in 2.96s ==============================
⚡ GHI NHỚ NHANH
- –
APIRequestContext: gửi thẳng HTTP request, không cần mở trình duyệt — nhanh hơnPage. - –
base_url: địa chỉ gốc gán sẵn cho context, các lệnh gọi sau chỉ cần ghi đường dẫn ngắn. - –
conftest.py: file đặc biệt chứa fixture dùng chung, pytest tự nhận diện không cầnimport.
Chương sau: expect(response) — các cách kiểm tra response hay dùng.