“Project 1: Flight Booking Automation with Playwright Python (Beginner)”
Lessons teach one skill at a time; projects show how the skills fit together. In this first project you will automate the SQA Tools dummy flight booking website from scratch with Playwright and pytest: a clean project folder, fixtures for logging in, data-driven login and search-validation tests, a complete end-to-end booking (search, flight, traveller details, seats, promo code, card payment and PNR), fare calculations checked to the rupee, and an HTML report with screenshots of failures. Every file is shown in full and every test was run before publishing.
📖 What You’ll Learn: planning test scenarios from an application, setting up the project folder, pytest.ini, conftest.py fixtures for login and search, data-driven login tests, search validation messages, an end-to-end booking test, reading money values and checking fare arithmetic, payment success and failure paths, an HTML report, and extension tasks to continue on your own.
🎯 The Application and the Plan
The SQA Tools dummy booking website is a practice flight-booking app with a realistic five-step flow:
- Login (
testuser/Test@123;lockeduseris locked) - Search: one-way or round trip, cities, dates, travellers, cabin
- Flights: results with prices, sorting, select a flight
- Travellers: names, dates of birth, nationality, contact details
- Seats and Payment: seat map, promo code
SQA100(₹100 off), test cards (4111 1111 1111 1111succeeds,4000 0000 0000 0002is declined), then a confirmation with PNR
Every element has a data-testid, so locators are simple. Before writing code, turn the app into test scenarios:
| Area | Scenarios |
|---|---|
| Login | valid user; wrong password; locked user; empty fields |
| Search validation | same origin and destination; past date; more infants than adults; more than 9 travellers |
| Booking | one-way booking ends with a PNR; promo code reduces the total by ₹100 |
| Fares | total = base fare + taxes + convenience fee − promo |
| Payment | declined card shows an error and no booking |
🗂️ Project Setup
flight-booking-tests/
├── pytest.ini
├── requirements.txt
├── conftest.py
└── tests/
├── test_login.py
├── test_search_validation.py
├── test_booking.py
└── test_payment.py
📄 requirements.txt
playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0
pytest-html==4.2.0
⌨️ Terminal
python -m venv .venv
.venv\Scripts\activate # Windows (macOS/Linux: source .venv/bin/activate)
pip install -r requirements.txt
playwright install chromium
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in --screenshot only-on-failure
testpaths = tests
🧩 conftest.py: Shared Fixtures
Three fixtures remove repetition from every test: the app’s URL, a logged-in page and a helper that runs a search. A money() helper turns "₹3,313" into the number 3313.
📄 conftest.py
import re
from datetime import date, timedelta
import pytest
from playwright.sync_api import Page, expect
APP = "/dummy-booking-website/"
def money(text: str) -> int:
"""'₹3,313' -> 3313 (also works for '-₹100')."""
return int(re.sub(r"[^\d]", "", text))
def future(days: int) -> str:
return (date.today() + timedelta(days=days)).isoformat()
@pytest.fixture
def logged_in(page: Page) -> Page:
page.goto(APP)
page.get_by_test_id("login-username").fill("testuser")
page.get_by_test_id("login-password").fill("Test@123")
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("step-search")).to_be_visible()
return page
@pytest.fixture
def search(logged_in: Page):
"""search(origin, destination, days_ahead=14, adults=1, infants=0) fills and submits the search form."""
def _search(origin="DEL", destination="BOM", days_ahead=14, adults=1, children=0, infants=0):
p = logged_in
p.get_by_test_id("from-city").select_option(origin)
p.get_by_test_id("to-city").select_option(destination)
p.get_by_test_id("depart-date").fill(future(days_ahead))
p.get_by_test_id("adults").select_option(str(adults))
p.get_by_test_id("children").select_option(str(children))
p.get_by_test_id("infants").select_option(str(infants))
p.get_by_test_id("search-button").click()
return p
return _search
search is a factory fixture (Lesson 58): it returns a function, so each test can search with its own values while the form-filling code exists once.
🔐 Login Tests (Data-Driven)
📄 tests/test_login.py
import pytest
from playwright.sync_api import Page, expect
from conftest import APP
@pytest.mark.parametrize("username, password, error", [
pytest.param("testuser", "wrong", "Invalid username or password.", id="wrong-password"),
pytest.param("lockeduser", "Test@123", "This account is locked. Please contact support.", id="locked-user"),
pytest.param("", "", "Username and password are required.", id="empty-fields"),
])
def test_login_errors(page: Page, username, password, error):
page.goto(APP)
page.get_by_test_id("login-username").fill(username)
page.get_by_test_id("login-password").fill(password)
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("login-error")).to_have_text(error)
expect(page.get_by_test_id("step-search")).to_be_hidden()
def test_valid_login_shows_user(logged_in: Page):
expect(logged_in.get_by_test_id("user-bar")).to_contain_text("Signed in as Test User")
🔎 Search Validation Tests
Each validation rule gets one case. The expected messages come from the application, so a changed message is detected immediately.
📄 tests/test_search_validation.py
import pytest
from playwright.sync_api import expect
@pytest.mark.parametrize("kwargs, message", [
pytest.param({"origin": "DEL", "destination": "DEL"}, "Origin and destination cannot be the same city.", id="same-city"),
pytest.param({"days_ahead": -1}, "Depart date cannot be in the past.", id="past-date"),
pytest.param({"days_ahead": 400}, "You can book up to 365 days ahead.", id="too-far-ahead"),
pytest.param({"adults": 1, "infants": 2}, "Each infant must travel with an adult.", id="infants-over-adults"),
pytest.param({"adults": 6, "children": 4}, "You can book up to 9 travellers (adults and children) at a time.", id="ten-travellers"),
])
def test_search_validation(search, kwargs, message):
page = search(**kwargs)
expect(page.get_by_test_id("search-error")).to_have_text(message)
expect(page.get_by_test_id("step-flights")).to_be_hidden()
def test_valid_search_lists_flights(search):
page = search("DEL", "BOM")
expect(page.get_by_test_id("step-flights")).to_be_visible()
expect(page.get_by_test_id("flight-card").first).to_be_visible()
expect(page.get_by_test_id("flights-count")).to_contain_text("flights found")
⌨️ Terminal
pytest tests/test_login.py tests/test_search_validation.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 10 items
tests/test_login.py::test_login_errors[chromium-wrong-password] PASSED [ 10%]
tests/test_login.py::test_login_errors[chromium-locked-user] PASSED [ 20%]
tests/test_login.py::test_login_errors[chromium-empty-fields] PASSED [ 30%]
tests/test_login.py::test_valid_login_shows_user[chromium] PASSED [ 40%]
tests/test_search_validation.py::test_search_validation[chromium-same-city] PASSED [ 50%]
tests/test_search_validation.py::test_search_validation[chromium-past-date] PASSED [ 60%]
tests/test_search_validation.py::test_search_validation[chromium-too-far-ahead] PASSED [ 70%]
tests/test_search_validation.py::test_search_validation[chromium-infants-over-adults] PASSED [ 80%]
tests/test_search_validation.py::test_search_validation[chromium-ten-travellers] PASSED [ 90%]
tests/test_search_validation.py::test_valid_search_lists_flights[chromium] PASSED [100%]
============================= 10 passed in 17.85s =============================
✈️ The End-to-End Booking
The main test walks the whole journey. Each step is a small helper function inside the test module, so the test body reads like the user’s story:
📄 tests/test_booking.py
import re
from playwright.sync_api import Page, expect
from conftest import money
def choose_first_flight(page: Page):
page.get_by_test_id("select-flight").first.click()
expect(page.get_by_test_id("step-passengers")).to_be_visible()
def fill_travellers(page: Page):
page.get_by_test_id("pax-continue").click() # empty form first: validation
expect(page.get_by_test_id("pax-error")).to_contain_text("Please fix")
page.get_by_test_id("fill-dummy").click() # the app's "fill test data" button
expect(page.get_by_test_id("contact-email")).to_have_value("test.user@example.com")
page.get_by_test_id("pax-continue").click()
expect(page.get_by_test_id("step-seats")).to_be_visible()
def choose_seats(page: Page):
page.get_by_test_id("auto-assign-seats").click()
page.get_by_test_id("seats-continue").click()
expect(page.get_by_test_id("step-payment")).to_be_visible()
def pay_with_card(page: Page, number="4111 1111 1111 1111"):
page.get_by_test_id("card-name").fill("Test User")
page.get_by_test_id("card-number").fill(number)
page.get_by_test_id("card-expiry").fill("12/30")
page.get_by_test_id("card-cvv").fill("123")
page.get_by_test_id("accept-terms").check()
page.get_by_test_id("pay-button").click()
def test_one_way_booking_with_promo(search):
page = search("DEL", "BOM")
choose_first_flight(page)
fill_travellers(page)
choose_seats(page)
total_before = money(page.get_by_test_id("fare-summary-payment").get_by_test_id("total-price").inner_text())
page.get_by_test_id("promo-code").fill("SQA100")
page.get_by_test_id("apply-promo").click()
expect(page.get_by_test_id("promo-message")).to_have_text("Promo applied: ₹100 off.")
pay_with_card(page)
expect(page.get_by_test_id("confirm-title")).to_have_text("Booking confirmed!", timeout=10_000)
expect(page.get_by_test_id("pnr")).to_have_text(re.compile(r"^[A-Z2-9]{6}$"))
expect(page.get_by_test_id("booking-id")).to_have_text(re.compile(r"^SQA-\d{8}-\d{5}$"))
assert money(page.get_by_test_id("amount-paid").inner_text()) == total_before - 100
expect(page.get_by_test_id("confirm-passengers")).to_contain_text("Mr Ravi Sharma")
print(f"\nPNR {page.get_by_test_id('pnr').inner_text()} paid {page.get_by_test_id('amount-paid').inner_text()}")
def test_fare_breakdown_adds_up(search):
page = search("DEL", "BLR", adults=2)
choose_first_flight(page)
breakdown = page.get_by_test_id("fare-summary-passengers").get_by_test_id("fare-breakdown")
values = dict(zip(breakdown.locator("dt").all_inner_texts(), breakdown.locator("dd").all_inner_texts()))
print("\n", values)
base, taxes, fee, total = (money(values[k]) for k in ("Base fare", "Taxes and fees", "Convenience fee", "Total"))
assert total == base + taxes + fee
assert fee == 199
⌨️ Terminal
pytest tests/test_booking.py -v -s
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 2 items
tests/test_booking.py::test_one_way_booking_with_promo[chromium]
PNR LRWLS6 paid ₹3,213
PASSED
tests/test_booking.py::test_fare_breakdown_adds_up[chromium]
{'Base fare': '₹6,080', 'Taxes and fees': '₹730', 'Convenience fee': '₹199', 'Total': '₹7,009'}
PASSED
============================== 2 passed in 7.27s ==============================
Notes on the techniques used:
- Waiting for steps: each helper ends with an
expect(...).to_be_visible()on the next step, so the following helper never starts too early (the same synchronisation idea as Lesson 56). - Money parsing: comparing numbers (
total_before - 100) is more meaningful than comparing strings, and it catches rounding bugs. - Regex assertions: a PNR is random, but its format (six letters/digits, no confusable
0,1,I,O) is a requirement you can test. timeout=10_000on the confirmation: the app shows a 2-second “processing” overlay, so the default 5 seconds is enough today but the larger timeout documents that this step is slow by design.
💳 Payment Failure Path
A good suite tests what happens when things go wrong, not just the happy path:
📄 tests/test_payment.py
from playwright.sync_api import expect
from tests.test_booking import choose_first_flight, choose_seats, fill_travellers, pay_with_card
def go_to_payment(search):
page = search("BOM", "GOI")
choose_first_flight(page)
fill_travellers(page)
choose_seats(page)
return page
def test_declined_card(search):
page = go_to_payment(search)
pay_with_card(page, number="4000 0000 0000 0002")
expect(page.get_by_test_id("pay-error")).to_contain_text("Payment declined by the bank", timeout=10_000)
expect(page.get_by_test_id("confirm-title")).to_have_count(0)
def test_terms_are_required(search):
page = go_to_payment(search)
page.get_by_test_id("card-name").fill("Test User")
page.get_by_test_id("card-number").fill("4111 1111 1111 1111")
page.get_by_test_id("card-expiry").fill("12/30")
page.get_by_test_id("card-cvv").fill("123")
page.get_by_test_id("pay-button").click() # terms not accepted
expect(page.get_by_test_id("pay-error")).to_have_text("Please check the payment details.")
📊 Run Everything with a Report
⌨️ Terminal
pytest --html=reports/report.html --self-contained-html -q
🖥️ Output
.............. [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/report.html -
14 passed in 31.98s
All tests pass, and reports/report.html holds the results (with a screenshot for any failure, thanks to --screenshot only-on-failure and Lesson 63’s hook if you add it). Open it in a browser and share it.
💡 Tip: Run the suite in parallel once you are confident the tests are independent: pip install pytest-xdist and pytest -n 4 (Lesson 65). Every test here logs in with its own browser context, so they can run side by side.
🧠 What This Project Practised
| Skill | Where |
|---|---|
| Fixtures and factory fixtures | logged_in, search in conftest.py (Lessons 25, 58) |
| Data-driven tests with ids | login errors, search validation (Lesson 45) |
| Locators by test id, scoped locators | fare-summary-payment → total-price (Lessons 31, 32) |
| Web-first assertions and regex matching | to_have_text(re.compile(...)) (Lesson 37) |
| Synchronising multi-step flows | step helpers ending with expect (Lessons 38, 56) |
| Reporting | pytest-html, screenshots on failure (Lessons 39, 63) |
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Add a test for a round trip DEL → BOM with a return date 5 days after departure. Which extra steps does the flow need? Write the search part.
Show answer
def test_round_trip_search(logged_in):
p = logged_in
p.get_by_test_id("trip-round").check()
p.get_by_test_id("from-city").select_option("DEL")
p.get_by_test_id("to-city").select_option("BOM")
p.get_by_test_id("depart-date").fill(future(14))
p.get_by_test_id("return-date").fill(future(19))
p.get_by_test_id("search-button").click()
expect(p.get_by_test_id("step-flights")).to_be_visible()A round trip has two legs, so you select an outbound and a return flight, and the seat step asks for seats on both legs. Also add a validation case: a return date before the depart date must show “Return date cannot be before the depart date.”
Exercise 2: Write a test that sorts the results by “Lowest price” and checks that the flight prices are in ascending order.
Show answer
def test_sort_by_price(search):
page = search("DEL", "BOM")
page.get_by_test_id("sort-by").select_option(label="Lowest price")
prices = [money(t) for t in page.get_by_test_id("flight-price").all_inner_texts()]
assert prices == sorted(prices)Exercise 3: Pay with UPI instead of a card. The UPI radio has test id pay-upi, the field upi-id; success@upi succeeds and failure@upi is declined. Write the helper.
Show answer
def pay_with_upi(page, upi="success@upi"):
page.get_by_test_id("pay-upi").check()
page.get_by_test_id("upi-id").fill(upi)
page.get_by_test_id("accept-terms").check()
page.get_by_test_id("pay-button").click()Use it in a parametrized test with ("success@upi", "Booking confirmed!") and ("failure@upi", "Payment declined").
Exercise 4: The project repeats the steps from search to payment in two test modules. How would you refactor it as the suite grows?
Show answer
Move the step helpers into page objects (one class per step: SearchPage, FlightsPage, TravellersPage, SeatsPage, PaymentPage) and add a fixture such as payment_page that returns the payment step ready to use. That is exactly what Project 2 does for the e-commerce site (Lessons 56 and 58 show the patterns).
🧠 MCQ Quiz: Project 1: Flight Booking Automation (Beginner)
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Why does each step helper end with an
expect(...).to_be_visible()on the next step?Answer: To synchronise: the next helper starts only when its step is on screen. Waiting for the next step prevents actions on a page that has not rendered yet. - What is the
searchfixture in conftest.py?Answer: A factory fixture that returns a function to run searches with different values. Returning a function lets each test choose its own search inputs. - Why convert “₹3,313” to an integer before comparing?Answer: To check arithmetic such as “total before minus ₹100 equals the amount paid”. Numbers let you verify calculations, not just text.
- How does the test check a random PNR?Answer: With a regular expression for the required format. Random values still have a testable format.
- Why test a declined card?Answer: Error paths are requirements too: the user must see an error and no booking. Negative scenarios catch bugs the happy path never exercises.
- What does
--screenshot only-on-failurein pytest.ini do?Answer: Saves a screenshot in test-results/ for each failed test. pytest-playwright keeps evidence only for failures. - How are the search-validation cases kept readable?Answer:
pytest.param(..., id=...)with a short id per rule. Each case shows up with its own name in the results. - Which locator gets the total price on the payment step only?Answer:
page.get_by_test_id("fare-summary-payment").get_by_test_id("total-price"). The fare summary appears on several steps; scoping to the payment summary avoids ambiguity. - Why does the confirmation assertion use
timeout=10_000?Answer: The app shows a processing overlay before confirming, and the longer timeout documents a slow step. Raise timeouts only for steps that are slow by design, not everywhere. - What is the natural next step as this suite grows?Answer: Move steps into page objects and fixtures. Page objects keep locators and flows in one place (Project 2).
Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).
❓ Frequently Asked Questions
🤔 Can I run this project against another booking site?
The structure, yes; the locators and messages are specific to the SQA Tools app. Real sites usually need test accounts, test payment modes and permission to automate them.
🤔 Why do tests import from conftest.py?
money(), future() and APP are small shared helpers. Importing them from conftest.py is fine for a small project; in a bigger one, move them into a utils/ package (Lesson 57).
🤔 Will these tests break when dates change?
No: dates are computed relative to today (future(14)), and the app’s flights are generated for any date. Never hard-code dates in tests that check “past” or “future” rules.
🤔 How long does the suite take?
About a minute on one worker. With pytest-xdist and four workers it drops to around 20 seconds.
🤔 Where can I compare my solution?
Run your tests against the same app and compare the results with the outputs above. The practice questions extend the project with round trips, sorting and UPI payments.
🏁 Summary
- You planned scenarios from the app, then built a small, clean pytest project with shared fixtures.
- Login and search validation are data-driven with readable ids; the end-to-end test books a flight and checks the PNR format and the money arithmetic.
- Step helpers synchronise with
expect, and negative paths (declined card, missing terms) are tested too. - The suite produces an HTML report with failure screenshots.
- Next: Project 2 turns these ideas into a full page-object framework for an e-commerce site.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page