Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ on:

env:
PYTHON_VERSION: "3.12"
# How hard CI may hit the shared public demo site. All jobs together used to keep 13 sessions
# open at once (API -n 4, plus three browsers at -n 3), and in Nov 2026 those runs kept timing
# out against it. Now: 2 API workers, 2 UI workers, and one browser job at a time (max-parallel).
API_WORKERS: 2
UI_WORKERS: 2

jobs:
lint:
Expand Down Expand Up @@ -48,9 +53,9 @@ jobs:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
- run: pip install -r requirements.txt
# API tests need no browser; 4 workers, every test has its own user
# API tests need no browser; every test has its own user, so workers never collide
- name: pytest -m api
run: pytest -m "api and (${{ inputs.markers || 'not demo' }})" -n 4 --junitxml=reports/junit.xml
run: pytest -m "api and (${{ inputs.markers || 'not demo' }})" -n ${{ env.API_WORKERS }} --junitxml=reports/junit.xml
- name: Summary
if: always()
run: python .github/scripts/summary.py "API tests" reports/junit.xml >> "$GITHUB_STEP_SUMMARY"
Expand All @@ -68,6 +73,8 @@ jobs:
runs-on: ubuntu-latest
strategy:
fail-fast: false
# One browser at a time, so the demo site never serves three browser jobs at once
max-parallel: 1
matrix:
browser: [chromium, firefox, webkit]
steps:
Expand All @@ -83,7 +90,7 @@ jobs:
- name: pytest -m "ui or e2e" on ${{ matrix.browser }}
run: >
pytest -m "(ui or e2e) and (${{ inputs.markers || 'not demo' }})"
--browser ${{ matrix.browser }} -n 3 --junitxml=reports/junit.xml
--browser ${{ matrix.browser }} -n ${{ env.UI_WORKERS }} --junitxml=reports/junit.xml
- name: Summary
if: always()
run: python .github/scripts/summary.py "UI + hybrid tests on ${{ matrix.browser }}" reports/junit.xml >> "$GITHUB_STEP_SUMMARY"
Expand Down
32 changes: 26 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ and also both together: hybrid tests set up data through the API and check it in
| Browsers | Chromium, Firefox, WebKit (Safari's engine) |
| Speed | about 1 m 45 s for the 46 tests with 4 parallel workers (pytest-xdist) |
| Reports | one self-contained HTML file; a failed UI test gets an embedded screenshot, plus a trace and video in `test-results/` |
| CI | GitHub Actions: lint first, then API tests, then UI + hybrid tests on all three browsers in parallel; also runs nightly |
| CI | GitHub Actions: lint first, then API tests, then UI + hybrid tests on all three browsers, one browser at a time; also runs nightly |

## Tech stack

Expand All @@ -33,11 +33,13 @@ and also both together: hybrid tests set up data through the API and check it in
```
python-pytest-framework
├── framework/ reusable code, no tests and no assertions
│ ├── config.py Settings: URLs and timeouts from environment variables
│ ├── config.py Settings: URLs, timeouts and attempts from environment variables
│ ├── retry.py with_retries: tries a slow page load or API call again
│ ├── api/
│ │ ├── notes_client.py NotesApiClient: one method per API endpoint (requests.Session)
│ │ └── models.py pydantic models: the API's contract (User, Note, ApiResponse[T])
│ ├── pages/
│ │ ├── navigation.py open_page: page load with its own timeout, retried when slow
│ │ ├── login_page.py LoginPage: Page Object of the login form
│ │ └── notes_page.py NotesPage: Page Object of the notes list, form, search, filters
│ └── data/
Expand Down Expand Up @@ -158,7 +160,20 @@ The public demo needs no settings. To run against another copy of the app, set t
| `NOTES_APP_URL` | `https://practice.expandtesting.com/notes/app` |
| `NOTES_API_URL` | `https://practice.expandtesting.com/notes/api` |
| `NOTES_API_TIMEOUT` | `30` (seconds per API request) |
| `NOTES_UI_TIMEOUT_MS` | `15000` (Playwright wait for actions such as click, fill and `wait_for`; `expect` keeps its own 5 s default) |
| `NOTES_UI_TIMEOUT_MS` | `15000` (Playwright wait for actions such as click and fill) |
| `NOTES_UI_NAVIGATION_TIMEOUT_MS` | `30000` (one page load) |
| `NOTES_UI_SERVER_TIMEOUT_MS` | `30000` (what the app shows after a server round trip: a saved or deleted note, the loaded list; also the default of `expect`) |
| `NOTES_ATTEMPTS` | `3` (tries in total for a page load or API call that timed out; `1` turns retrying off) |

The public demo is sometimes slow, so a page load or API call that **times out** is tried again,
with a short pause in between (`framework/retry.py`). A wrong answer is never retried: a 400, a
wrong body or a missing element fails the test at once. API calls are only repeated when that is
harmless (GET, PUT, PATCH, DELETE and login); a timed-out registration in a fixture starts over
with a new user. Every retry is logged and shows up in the report of a test that still failed.

Steps inside a test (submitting a form, a check with `expect`) are not retried; they get a longer
wait instead (`NOTES_UI_SERVER_TIMEOUT_MS`). A longer wait never lets a wrong result pass: the
check still fails if the page does not match in time, it only takes longer to say so.

## Running

Expand Down Expand Up @@ -205,10 +220,15 @@ The report demo (`pytest -m demo`) shows:
nightly run catches changes to the public site. The jobs are:

1. **lint** runs `ruff check` and `ruff format --check`. The tests only start when the code is clean.
2. **api** runs `pytest -m api -n 4`.
2. **api** runs `pytest -m api -n 2`.
3. **ui** is a matrix of three jobs: Chromium, Firefox and WebKit. Each one installs only its own
browser, then runs `pytest -m "ui or e2e" --browser <name> -n 3`. With `fail-fast: false`, a
failure on one browser does not cancel the others.
browser, then runs `pytest -m "ui or e2e" --browser <name> -n 2`. With `fail-fast: false`, a
failure on one browser does not cancel the others. `max-parallel: 1` runs the browsers one
after another.

CI is gentle with the shared public site on purpose: at most 4 test sessions at once (`API_WORKERS`
and `UI_WORKERS` at the top of the workflow). With 13 at once, runs in Nov 2026 kept
timing out against it.

Each test job writes a pass/fail table to the run's summary page. It also keeps its HTML report and
traces as an artifact. A manual run (Run workflow) can choose the `demo` markers, to see failures in
Expand Down
40 changes: 34 additions & 6 deletions framework/api/notes_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,54 @@
import requests

from framework.config import Settings
from framework.retry import with_retries

# Header the API reads the session token from
TOKEN_HEADER = "x-auth-token"

# Methods that may be sent again after a timeout: repeating them leaves the server in the same state.
# POST is left out: a repeated create_note would make two notes, a repeated change_password would
# fail because the first one already changed it. A single call can still opt in or out (retry=...).
SAFE_TO_REPEAT = frozenset({"GET", "PUT", "PATCH", "DELETE"})

# The errors of a slow or unreachable server; anything the server actually answers is not retried
NETWORK_ERRORS = (requests.Timeout, requests.ConnectionError)


class NotesApiClient:
"""A requests.Session pointed at the Notes API, optionally logged in."""

def __init__(self, settings: Settings) -> None:
self._base_url = settings.api_url
self._timeout = settings.api_timeout
self._attempts = settings.attempts
# One session per client: keeps the connection open between calls
self._session = requests.Session()
self.token: str | None = None

# --- plumbing -------------------------------------------------------------------------------

def _request(self, method: str, path: str, **kwargs) -> requests.Response:
"""Sends a request; adds the token header when the client is logged in."""
def _request(self, method: str, path: str, *, retry: bool | None = None, **kwargs) -> requests.Response:
"""Sends a request; adds the token header when the client is logged in.

After a timeout or a lost connection the request is sent again (settings.attempts in total)
if repeating it is harmless: by default for SAFE_TO_REPEAT methods, or as `retry` says.
"""
headers = kwargs.pop("headers", {})
if self.token is not None:
headers.setdefault(TOKEN_HEADER, self.token)
return self._session.request(
method, f"{self._base_url}{path}", headers=headers, timeout=self._timeout, **kwargs

def send() -> requests.Response:
return self._session.request(
method, f"{self._base_url}{path}", headers=headers, timeout=self._timeout, **kwargs
)

repeatable = method in SAFE_TO_REPEAT if retry is None else retry
return with_retries(
send,
retry_on=NETWORK_ERRORS,
attempts=self._attempts if repeatable else 1,
what=f"{method} {path}",
)

def close(self) -> None:
Expand All @@ -57,7 +81,10 @@ def login(self, email: str, password: str) -> requests.Response:

On success the client keeps the token and sends it with every later call.
"""
response = self._request("POST", "/users/login", data={"email": email, "password": password})
# A POST, but safe to repeat: logging in again only hands out another token
response = self._request(
"POST", "/users/login", data={"email": email, "password": password}, retry=True
)
if response.status_code == 200:
self.token = response.json()["data"]["token"]
return response
Expand Down Expand Up @@ -85,7 +112,8 @@ def logout(self) -> requests.Response:

The client keeps the old token on purpose, so a test can prove it is now refused.
"""
return self._request("DELETE", "/users/logout")
# Not repeated: if the first logout got through, a second one is refused (401) and fails the test
return self._request("DELETE", "/users/logout", retry=False)

def delete_account(self) -> requests.Response:
"""DELETE /users/delete-account: removes the logged-in user and all their notes (used by clean-up)."""
Expand Down
12 changes: 11 additions & 1 deletion framework/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,15 @@ class Settings:
api_url: str
# Seconds for one HTTP call (connect + read) to the API
api_timeout: float
# Milliseconds Playwright waits for an element or a navigation
# Milliseconds Playwright waits for an element (click, fill, wait_for)
ui_timeout_ms: int
# Milliseconds one page load may take; longer than ui_timeout_ms, the demo is sometimes slow
ui_navigation_timeout_ms: int
# Milliseconds to wait for what the app shows after a server round trip: a saved or deleted
# note, the loaded list, a search result, the progress text (also expect()'s default)
ui_server_timeout_ms: int
# How often a timed-out page load or API call is tried in total (framework/retry.py); 1 = no retry
attempts: int


def load_settings() -> Settings:
Expand All @@ -27,4 +34,7 @@ def load_settings() -> Settings:
api_url=os.getenv("NOTES_API_URL", "https://practice.expandtesting.com/notes/api").rstrip("/"),
api_timeout=float(os.getenv("NOTES_API_TIMEOUT", "30")),
ui_timeout_ms=int(os.getenv("NOTES_UI_TIMEOUT_MS", "15000")),
ui_navigation_timeout_ms=int(os.getenv("NOTES_UI_NAVIGATION_TIMEOUT_MS", "30000")),
ui_server_timeout_ms=int(os.getenv("NOTES_UI_SERVER_TIMEOUT_MS", "30000")),
attempts=max(1, int(os.getenv("NOTES_ATTEMPTS", "3"))),
)
4 changes: 3 additions & 1 deletion framework/pages/login_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
from playwright.sync_api import Page

from framework.config import Settings
from framework.pages.navigation import open_page


class LoginPage:
"""Login form: email, password, submit, and the messages it shows."""

def __init__(self, page: Page, settings: Settings) -> None:
self.page = page
self.settings = settings
self.url = f"{settings.app_url}/login"
# Locators: the app gives every control a data-testid, the most stable choice
self.email = page.get_by_test_id("login-email")
Expand All @@ -22,7 +24,7 @@ def __init__(self, page: Page, settings: Settings) -> None:

def open(self) -> "LoginPage":
"""Opens the login page; returns itself, so a fixture can write LoginPage(...).open()."""
self.page.goto(self.url)
open_page(self.page, self.url, self.settings)
return self

def login(self, email: str, password: str) -> None:
Expand Down
30 changes: 30 additions & 0 deletions framework/pages/navigation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Opening a page of the app, shared by all page objects."""

from collections.abc import Callable

from playwright.sync_api import Page
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError

from framework.config import Settings
from framework.retry import with_retries


def open_page(
page: Page, url: str, settings: Settings, wait_until_ready: Callable[[], None] | None = None
) -> None:
"""Loads url and waits until the page is usable; tries again if the demo is too slow.

The page load gets its own, longer timeout (settings.ui_navigation_timeout_ms) than clicks and
fills. wait_until_ready (e.g. "the notes list has loaded") belongs to the same attempt, so a
page that arrived but never finished loading its data is loaded again too. Reloading is always
safe: opening a page changes nothing in the app.
"""

def attempt() -> None:
page.goto(url, timeout=settings.ui_navigation_timeout_ms)
if wait_until_ready is not None:
wait_until_ready()

with_retries(
attempt, retry_on=(PlaywrightTimeoutError,), attempts=settings.attempts, what=f"opening {url}"
)
16 changes: 11 additions & 5 deletions framework/pages/notes_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@

from framework.config import Settings
from framework.data.factories import NoteData
from framework.pages.navigation import open_page


class NotesPage:
"""Home page of a logged-in user."""

def __init__(self, page: Page, settings: Settings) -> None:
self.page = page
self.settings = settings
# The home page of the app is the notes list
self.url = settings.app_url
# List and its states
Expand All @@ -35,15 +37,17 @@ def __init__(self, page: Page, settings: Settings) -> None:

def open(self) -> "NotesPage":
"""Opens the home page and waits until the list has loaded (cards or the empty message)."""
self.page.goto(self.url)
self.wait_until_loaded()
open_page(self.page, self.url, self.settings, wait_until_ready=self.wait_until_loaded)
return self

def wait_until_loaded(self) -> None:
"""Waits until the notes list has finished loading (with or without notes)."""
# The app shows a spinner first; either the progress line or the empty message ends it.
# Both are always in the page, one of them hidden (d-none), so wait for the visible one.
self.progress.or_(self.no_notes_message).filter(visible=True).first.wait_for()
# The list comes from the server, so this waits as long as a server round trip may take.
self.progress.or_(self.no_notes_message).filter(visible=True).first.wait_for(
timeout=self.settings.ui_server_timeout_ms
)

def card(self, title: str) -> Locator:
"""The card of the note with exactly this title."""
Expand All @@ -64,7 +68,8 @@ def add_note(self, note: NoteData, completed: bool = False) -> None:
self.form_title.fill(note.title)
self.form_description.fill(note.description)
self.form_submit.click()
self.card(note.title).wait_for()
# The card appears once the server has saved the note
self.card(note.title).wait_for(timeout=self.settings.ui_server_timeout_ms)

def toggle_completed(self, title: str) -> None:
"""Flips the completed switch on the note's card."""
Expand All @@ -74,7 +79,8 @@ def delete_note(self, title: str) -> None:
"""Deletes the note: delete button, then confirm in the dialog."""
self.card(title).get_by_test_id("note-delete").click()
self.delete_confirm.click()
self.card(title).wait_for(state="detached")
# The card goes once the server has deleted the note
self.card(title).wait_for(state="detached", timeout=self.settings.ui_server_timeout_ms)

def search(self, text: str) -> None:
"""Types the text into the search box and submits it; the list then shows only the matching notes."""
Expand Down
52 changes: 52 additions & 0 deletions framework/retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Retry for slow answers from the public demo site.

practice.expandtesting.com is a free shared demo and sometimes takes longer than the timeout to
answer a page load or an API call. Without a retry, one slow moment fails a whole batch of tests
that have nothing wrong with them.

Only timeouts and lost connections are retried, never a wrong answer: a 400, a wrong body or a
missing element still fails the test at once. And a call is only retried when sending it twice is
harmless (see NotesApiClient for which API calls qualify).
"""

import logging
import time
from collections.abc import Callable
from typing import TypeVar

T = TypeVar("T")

log = logging.getLogger(__name__)


def with_retries(
action: Callable[[], T],
*,
retry_on: tuple[type[BaseException], ...],
attempts: int,
what: str,
backoff_seconds: float = 2.0,
) -> T:
"""Runs action() up to `attempts` times while it raises one of `retry_on`; returns its result.

Waits backoff_seconds, then twice that, and so on between attempts, so a busy server gets a
moment to recover. The last error is raised unchanged, so a real outage still shows its cause.
Every retry is logged; pytest shows these lines in the report of a test that still failed.
"""
for attempt in range(1, attempts + 1):
try:
return action()
except retry_on as error:
if attempt == attempts:
raise
wait = backoff_seconds * attempt
log.warning(
"%s: attempt %d of %d failed (%s), retrying in %.0f s",
what,
attempt,
attempts,
type(error).__name__,
wait,
)
time.sleep(wait)
raise AssertionError("unreachable: the loop returns or raises") # keeps type checkers happy
Loading