“Project 4: Banking App Test Suite with Playwright Python (Data-Driven, Auth, Reports)”

Banking applications are where test automation has to be precise: two-step logins, account lockouts, transfer limits, fees and balances that must be correct to the paisa. This project tests SQA Bank, the practice net-banking site on SQA Tools, with Playwright Python. You will automate a login with a captcha and an OTP the honest way, test lockout rules, log in once per run even though the bank keeps its session in sessionStorage, drive transfers between accounts and to beneficiaries, check every limit and fee rule with data-driven tests, verify balances with Decimal, download the statement CSV and check its arithmetic, and produce an HTML report.

Advertisement

📖 What You’ll Learn: test design for a banking app, solving a test captcha and OTP in a fixture, field-level and page-level login errors, lockout after failed attempts, logging in once with storage_state plus restored sessionStorage, page helpers for transfers, exact money with Decimal, receipt and reference checks, data-driven transfer validation (zero amount, beneficiary limit, IMPS maximum, RTGS minimum, insufficient balance), fees on the review screen, downloading and validating a CSV statement, and an HTML report.


🏦 The Application and the Rules

SQA Bank is a client-side practice bank. Its test data is printed on the login page:

Item Value
Customer 100001 / Bank@123 (Asha Verma); 100099 is locked
Login customer ID + password + a math captcha, then a 6-digit OTP (123456)
Lockout 3 wrong passwords lock net banking
Transaction PIN 1234
Accounts Savings …0001 (₹2,45,000.50) and Current …0001 (₹8,75,500.00)
Transfer rules IMPS max ₹5,00,000 (fee ₹5), RTGS min ₹2,00,000 (fee ₹25), NEFT free, per-beneficiary limits

Every account, balance and transaction lives in the browser’s storage, so each new browser context starts from the same data: perfect for repeatable tests.

📌 Note: About the captcha. A real captcha exists to stop bots, and you should never try to defeat one on a production site. Test environments either disable it, use a fixed test answer, or (as here) a trivial practice question. In your own projects, ask developers for a test bypass instead of automating real captchas.


🗂️ Project Layout

bank-tests/
├── pytest.ini
├── conftest.py            login helpers, login-once fixtures, report screenshots
├── bank.py                page helpers: login, transfer, money parsing
└── tests/
    ├── test_login.py
    ├── test_transfers.py
    └── test_statement.py

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in -ra
pythonpath = .
testpaths = tests

🧰 bank.py: Helpers and Exact Money

Money is never a float in banking tests: 0.1 + 0.2 != 0.3 in binary floating point. Decimal keeps paise exact.

📄 bank.py

import re
from decimal import Decimal

from playwright.sync_api import Page, expect

APP = "/dummy-banking-website/"
CUSTOMER, PASSWORD, OTP, PIN = "100001", "Bank@123", "123456", "1234"
SAVINGS, CURRENT = "501000100001", "502000100001"


def money(text: str) -> Decimal:
    """'₹2,45,000.50' -> Decimal('245000.50')."""
    return Decimal(re.sub(r"[^\d.]", "", text))


def solve_captcha(page: Page) -> str:
    a, b = map(int, re.findall(r"\d+", page.get_by_test_id("captcha-question").inner_text()))
    return str(a + b)


def submit_credentials(page: Page, customer=CUSTOMER, password=PASSWORD, captcha: str | None = None):
    page.get_by_test_id("login-cid").fill(customer)
    page.get_by_test_id("login-password").fill(password)
    page.get_by_test_id("login-captcha").fill(captcha if captcha is not None else solve_captcha(page))
    page.get_by_test_id("login-button").click()


def login(page: Page, customer=CUSTOMER, password=PASSWORD):
    page.goto(APP)
    submit_credentials(page, customer, password)
    page.get_by_test_id("login-otp").fill(OTP)
    page.get_by_test_id("otp-submit").click()
    expect(page).to_have_url(re.compile(r"#/dashboard$"))


def balance(page: Page, account: str) -> Decimal:
    page.get_by_test_id("nav-dashboard").click()
    return money(page.get_by_test_id(f"balance-{account}").inner_text())


def start_transfer(page: Page, tab: str, amount: str, from_index: int = 0, to_index: int = 1,
                   beneficiary: str | None = None, mode: str | None = None):
    page.get_by_test_id("nav-transfer").click()
    page.get_by_test_id(f"tr-tab-{tab}").click()
    page.get_by_test_id("tr-from").select_option(index=from_index)
    if tab == "own":
        page.get_by_test_id("tr-to").select_option(index=to_index)
    if beneficiary:
        page.get_by_test_id("tr-bene").select_option(label=beneficiary)
    if mode:
        page.get_by_test_id(f"tr-mode-{mode.lower()}").check()
    page.get_by_test_id("tr-amount").fill(amount)
    page.get_by_test_id("tr-continue").click()


def confirm_with_pin(page: Page, pin: str = PIN):
    page.get_by_test_id("review-confirm").click()
    page.locator("#vf-code").fill(pin)
    page.get_by_test_id("verify-submit").click()
    expect(page.get_by_test_id("receipt")).to_be_visible(timeout=10_000)   # the bank "processes" for ~1 s

Advertisement

🔐 Login Tests

📄 tests/test_login.py

import pytest
from playwright.sync_api import Page, expect

from bank import APP, OTP, login, submit_credentials


def test_valid_login_shows_dashboard(page: Page):
    login(page)
    expect(page.get_by_test_id("user-bar")).to_contain_text("Welcome, Asha Verma")
    expect(page.get_by_test_id("account-tile").first).to_be_visible()


@pytest.mark.parametrize("customer, password, captcha, field, message", [
    pytest.param("12ab", "Bank@123", None, "login-cid", "Customer ID must be 6 digits.", id="bad-customer-id"),
    pytest.param("100001", "", None, "login-password", "Password is required.", id="no-password"),
    pytest.param("100001", "Bank@123", "999", "login-captcha", "Incorrect answer. Try the new question.", id="wrong-captcha"),
])
def test_field_errors(page: Page, customer, password, captcha, field, message):
    page.goto(APP)
    submit_credentials(page, customer, password, captcha)
    expect(page.locator(f"#{field}-err")).to_have_text(message)


def test_wrong_otp(page: Page):
    page.goto(APP)
    submit_credentials(page)
    page.get_by_test_id("login-otp").fill("000000")
    page.get_by_test_id("otp-submit").click()
    expect(page.locator("#login-otp-err")).to_have_text("Incorrect OTP. Please try again.")
    assert OTP != "000000"


def test_three_wrong_passwords_lock_access(page: Page):
    page.goto(APP)
    message = page.get_by_test_id("login-message")
    submit_credentials(page, password="wrong-1")
    expect(message).to_have_text("Invalid customer ID or password. 2 attempts left before your access is locked.")
    submit_credentials(page, password="wrong-2")
    expect(message).to_contain_text("1 attempt left")
    submit_credentials(page, password="wrong-3")
    expect(message).to_contain_text("locked after too many failed attempts")
    submit_credentials(page)                                               # even the right password is refused now
    expect(message).to_contain_text("locked after too many failed attempts")


def test_locked_customer(page: Page):
    page.goto(APP)
    submit_credentials(page, customer="100099")
    expect(page.get_by_test_id("login-message")).to_contain_text("locked after too many failed attempts")

⌨️ Terminal

pytest tests/test_login.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 7 items

tests/test_login.py::test_valid_login_shows_dashboard[chromium] PASSED   [ 14%]
tests/test_login.py::test_field_errors[chromium-bad-customer-id] PASSED  [ 28%]
tests/test_login.py::test_field_errors[chromium-no-password] PASSED      [ 42%]
tests/test_login.py::test_field_errors[chromium-wrong-captcha] PASSED    [ 57%]
tests/test_login.py::test_wrong_otp[chromium] PASSED                     [ 71%]
tests/test_login.py::test_three_wrong_passwords_lock_access[chromium] PASSED [ 85%]
tests/test_login.py::test_locked_customer[chromium] PASSED               [100%]

============================= 7 passed in 15.26s ==============================

The lockout test changes data (the failure counter) in its own browser context, so it cannot affect other tests: the next test’s context starts with a fresh bank.


⚡ Log In Once per Run

Every transfer test needs a logged-in user, and the full login (captcha + OTP) takes several seconds. Lesson 51’s storage state helps, with one catch: SQA Bank keeps the session in sessionStorage, which storage_state() does not save (the accounts in localStorage are saved). The fixture below saves both and restores sessionStorage with an init script:

📄 conftest.py

import base64
import json

import pytest
import pytest_html
from playwright.sync_api import Browser, BrowserContext, Page

from bank import APP, login


@pytest.fixture(scope="session")
def bank_state(browser: Browser, base_url):
    """Log in once; keep localStorage (accounts) and sessionStorage (the login session)."""
    context = browser.new_context(base_url=base_url)
    page = context.new_page()
    login(page)
    state = {"storage": context.storage_state(), "session": page.evaluate("JSON.stringify(sessionStorage)")}
    context.close()
    return state


@pytest.fixture
def bank(browser: Browser, base_url, bank_state) -> Page:
    context: BrowserContext = browser.new_context(base_url=base_url, storage_state=bank_state["storage"])
    context.add_init_script(f"""
        if (location.hostname === 'sqatools.in' && !sessionStorage.getItem('sbSession')) {{
            const saved = JSON.parse({json.dumps(bank_state["session"])});
            for (const [k, v] of Object.entries(saved)) sessionStorage.setItem(k, v);
        }}""")
    page = context.new_page()
    page.goto(APP + "#/dashboard")
    yield page
    context.close()


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    """Attach a screenshot to the HTML report for failed tests (Lesson 63)."""
    report = yield
    if report.when == "call" and report.failed:
        page = item.funcargs.get("bank") or item.funcargs.get("page")
        if page is not None and not page.is_closed():
            extras = getattr(report, "extras", [])
            extras.append(pytest_html.extras.png(base64.b64encode(page.screenshot()).decode(), name="screenshot"))
            report.extras = extras
    return report

Each test gets a new context from the saved state: logged in, with the original balances, and isolated from every other test.


💸 Transfer Tests

📄 tests/test_transfers.py

import re
from decimal import Decimal

import pytest
from playwright.sync_api import Page, expect

from bank import CURRENT, SAVINGS, balance, confirm_with_pin, money, start_transfer


def test_own_account_transfer_moves_exact_amount(bank: Page):
    savings_before, current_before = balance(bank, SAVINGS), balance(bank, CURRENT)
    start_transfer(bank, "own", "1500.25")
    expect(bank.get_by_test_id("review-total-debit")).to_have_text("₹1,500.25")
    confirm_with_pin(bank)

    expect(bank.get_by_test_id("receipt-status")).to_have_text("Transfer successful")
    expect(bank.get_by_test_id("receipt-ref")).to_have_text(re.compile(r"^INT\d{14}$"))
    assert balance(bank, SAVINGS) == savings_before - Decimal("1500.25")
    assert balance(bank, CURRENT) == current_before + Decimal("1500.25")


def test_imps_fee_is_charged(bank: Page):
    savings_before = balance(bank, SAVINGS)
    start_transfer(bank, "bene", "1000", beneficiary="Priya · Demo National Bank · XXXX9012", mode="IMPS")
    expect(bank.get_by_test_id("review-charges")).to_contain_text("₹5")
    expect(bank.get_by_test_id("review-total-debit")).to_have_text("₹1,005.00")
    confirm_with_pin(bank)
    assert balance(bank, SAVINGS) == savings_before - Decimal("1005")


def test_wrong_pin_keeps_money(bank: Page):
    before = balance(bank, SAVINGS)
    start_transfer(bank, "own", "100")
    bank.get_by_test_id("review-confirm").click()
    bank.locator("#vf-code").fill("0000")
    bank.get_by_test_id("verify-submit").click()
    expect(bank.locator("#vf-code-err")).to_contain_text("Incorrect PIN")
    bank.get_by_test_id("verify-cancel").click()
    assert balance(bank, SAVINGS) == before


LANDLORD = "Landlord · Practice Bank of India · XXXX5544"
RAHUL = "Rahul · SQA Bank · XXXX0002"


@pytest.mark.parametrize("kwargs, where, message", [
    pytest.param(dict(amount="0", beneficiary=LANDLORD, mode="NEFT"), "#tr-amount-err",
                 "Enter an amount greater than zero.", id="zero"),
    pytest.param(dict(amount="250000", beneficiary=RAHUL), "#tr-amount-err",
                 "Amount exceeds the limit for this beneficiary (₹2,00,000.00).", id="beneficiary-limit"),
    pytest.param(dict(amount="600000", beneficiary=LANDLORD, mode="IMPS", from_index=1), "#tr-msg",
                 "IMPS transfers are limited to ₹5,00,000.00 per transaction. Use NEFT or RTGS.", id="imps-max"),
    pytest.param(dict(amount="50000", beneficiary=LANDLORD, mode="RTGS"), "#tr-msg",
                 "RTGS needs a minimum of ₹2,00,000.00. Use NEFT or IMPS for smaller amounts.", id="rtgs-min"),
    pytest.param(dict(amount="300000", beneficiary=LANDLORD, mode="NEFT"), "#tr-msg",
                 "Insufficient balance. Available: ₹2,45,000.50, required: ₹3,00,000.00.", id="insufficient"),
])
def test_transfer_rules(bank: Page, kwargs, where, message):
    start_transfer(bank, "bene", **kwargs)
    expect(bank.locator(where)).to_have_text(message)
    expect(bank.get_by_test_id("transfer-review")).to_have_count(0)        # never reaches the review step

⌨️ Terminal

pytest tests/test_transfers.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 8 items

tests/test_transfers.py::test_own_account_transfer_moves_exact_amount[chromium] PASSED [ 12%]
tests/test_transfers.py::test_imps_fee_is_charged[chromium] PASSED       [ 25%]
tests/test_transfers.py::test_wrong_pin_keeps_money[chromium] PASSED     [ 37%]
tests/test_transfers.py::test_transfer_rules[chromium-zero] PASSED       [ 50%]
tests/test_transfers.py::test_transfer_rules[chromium-beneficiary-limit] PASSED [ 62%]
tests/test_transfers.py::test_transfer_rules[chromium-imps-max] PASSED   [ 75%]
tests/test_transfers.py::test_transfer_rules[chromium-rtgs-min] PASSED   [ 87%]
tests/test_transfers.py::test_transfer_rules[chromium-insufficient] PASSED [100%]

============================= 8 passed in 23.74s ==============================

Highlights:

  • 1500.25 (with paise) and Decimal comparisons catch rounding bugs that whole-rupee amounts would hide.
  • The IMPS test checks the fee on the review screen and in the balance afterwards: ₹1,000 + ₹5.
  • The wrong-PIN test checks a side effect: the money did not move.
  • Five business rules live in one parametrized test; each id says which rule it covers, and the last assertion makes sure an invalid transfer never reaches the review step.

Advertisement

📄 Statement CSV: Download and Validate

A bank statement must be internally consistent: going down the list (newest first), each row’s balance equals the next row’s balance plus a credit or minus a debit. Download the CSV after a transfer and check every row:

📄 tests/test_statement.py

import csv
from decimal import Decimal

from playwright.sync_api import Page, expect

from bank import confirm_with_pin, start_transfer


def download_statement(page: Page, tmp_path) -> list[dict]:
    page.get_by_test_id("nav-accounts").click()
    with page.expect_download() as info:
        page.get_by_test_id("download-csv").click()
    download = info.value
    target = tmp_path / download.suggested_filename
    download.save_as(target)
    print(f"\ndownloaded {download.suggested_filename}")
    with open(target, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))


def test_statement_contains_new_transfer(bank: Page, tmp_path):
    start_transfer(bank, "own", "2500")
    confirm_with_pin(bank)
    reference = bank.get_by_test_id("receipt-ref").inner_text()

    rows = download_statement(bank, tmp_path)
    newest = rows[0]
    assert newest["Reference"] == reference
    assert newest["Type"] == "DR" and Decimal(newest["Amount"]) == Decimal("2500.00")


def test_statement_balances_are_consistent(bank: Page, tmp_path):
    rows = download_statement(bank, tmp_path)
    assert len(rows) > 3
    for newer, older in zip(rows, rows[1:]):
        amount = Decimal(newer["Amount"])
        expected = Decimal(older["Balance"]) + (amount if newer["Type"] == "CR" else -amount)
        assert Decimal(newer["Balance"]) == expected, f"row {newer['Reference']}: {newer['Balance']} != {expected}"
    print(f"checked {len(rows) - 1} balance steps")

⌨️ Terminal

pytest tests/test_statement.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_statement.py::test_statement_contains_new_transfer[chromium] 
downloaded statement_501000100001_2026-10-25_to_2026-11-24.csv
PASSED
tests/test_statement.py::test_statement_balances_are_consistent[chromium] 
downloaded statement_501000100001_2026-10-25_to_2026-11-24.csv
checked 11 balance steps
PASSED

============================== 2 passed in 8.84s ==============================

page.expect_download() waits for the file, download.suggested_filename keeps the bank’s name for it, and save_as() stores it in pytest’s per-test tmp_path. The consistency check is the kind of data validation that is impossible by eye and trivial in code.


📊 The Whole Suite with a Report

⌨️ Terminal

pytest -n 4 -q --html=reports/bank-report.html --self-contained-html

🖥️ Output

bringing up nodes...
bringing up nodes...

.................                                                        [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/bank-report.html -
17 passed in 18.46s

All tests run in parallel: each one gets its own browser context and therefore its own copy of the bank’s data. Failed tests would carry a screenshot in the report thanks to the hook in conftest.py.


🧠 What This Project Practised

Skill Lessons
Two-step login with captcha and OTP in helpers 31-33, 42
Lockout rules and field vs page messages 37, 45
Login once with storage state + restored sessionStorage 51
Decimal money checks and data-driven business rules 45, 46
Downloads and CSV validation 36, 46
Parallel runs and HTML reports with screenshots 63, 65

Advertisement

🏋️ 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 scheduled transfer: choosing “Later” with a date 100 days ahead must show “You can schedule up to 90 days ahead.” (The radio has test id tr-when-later, the date field tr-date.)

Show answer
from datetime import date, timedelta


def test_schedule_too_far(bank):
    bank.get_by_test_id("nav-transfer").click()
    bank.get_by_test_id("tr-tab-own").click()
    bank.get_by_test_id("tr-to").select_option(index=1)
    bank.get_by_test_id("tr-amount").fill("100")
    bank.get_by_test_id("tr-when-later").check()
    bank.get_by_test_id("tr-date").fill((date.today() + timedelta(days=100)).isoformat())
    bank.get_by_test_id("tr-continue").click()
    expect(bank.locator("#tr-date-err")).to_have_text("You can schedule up to 90 days ahead.")

Exercise 2: Why does test_three_wrong_passwords_lock_access not lock the account for the other tests?

Show answer

The failure counter and the lock are stored in the browser’s localStorage of that test’s own context. pytest-playwright creates a fresh context for every test, and the bank fixture creates contexts from the state saved right after a successful login, so every other test starts with an unlocked account.

Exercise 3: Write a test that a transfer to Rahul (an SQA Bank customer) is an internal transfer with no charges. What do you assert on the review screen?

Show answer
def test_internal_to_rahul(bank):
    start_transfer(bank, "bene", "500", beneficiary="Rahul · SQA Bank · XXXX0002")
    expect(bank.get_by_test_id("review-mode")).to_have_text("Within SQA Bank")
    expect(bank.get_by_test_id("review-charges")).to_have_text("Free")

Rahul only offers the internal mode, so no mode radio needs to be chosen.

Exercise 4: The statement check failed with row X: 1000.10 != 1000.1. Is this a bug?

Show answer

Not in the bank: it means the test compared strings or floats somewhere. Decimal("1000.10") == Decimal("1000.1") is True, so make sure both sides are converted with Decimal(...) before comparing, as in the lesson.


🧠 MCQ Quiz: Project 4: Banking App Test Suite

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why use Decimal for money in tests?
  2. What is the right attitude to captchas in test automation?
  3. Why does the login-once fixture save sessionStorage separately?
  4. How does the bank fixture keep tests isolated?
  5. What does the wrong-PIN test check besides the error message?
  6. Which locator receives page-level transfer errors such as “Insufficient balance”?
  7. How does the suite capture the downloaded CSV?
  8. What does the statement consistency test verify?
  9. Why is 1500.25 used instead of 1500 in the transfer test?
  10. Why can this suite run with -n 4?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


Advertisement

❓ Frequently Asked Questions

🤔 How do real banks let testers handle OTPs?

Test environments use fixed OTPs, an OTP API for testers, or a test SMS inbox that tests can read. Never automate a personal phone or real customer accounts.

🤔 Should a test suite ever run transfers on production?

No. Production checks for banking apps are read-only smoke tests with dedicated monitoring accounts, if any. Money-moving tests belong in test environments.

🤔 Why keep page helpers in functions instead of page-object classes?

For a project of this size, a module of clear functions is easy to read. Project 2 shows the class-based page-object style; both are valid, and you can move these helpers into classes as the suite grows.

🤔 How do I test the session timeout?

Use Playwright’s clock control (page.clock.install() and page.clock.fast_forward(...)) to move time forward instead of waiting, then check the logout message.

🤔 Can I reuse the login-once trick for my app?

Yes, whenever an app stores its session in sessionStorage. Save JSON.stringify(sessionStorage) after logging in and restore it with an init script that runs before the app’s scripts (Lesson 51).


🏁 Summary

  • A banking suite needs exact rules: lockout, limits, fees and balances to the paisa (Decimal).
  • Captcha and OTP are handled through the test environment’s practice values, in reusable helpers.
  • Logging in once uses storage state plus restored sessionStorage, while each test still gets a fresh context.
  • Data-driven tests cover every transfer rule and check side effects such as unchanged balances.
  • The statement CSV is downloaded and validated row by row, and the suite runs in parallel with an HTML report.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page