diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e6b706..860a3c8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: @@ -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" @@ -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: @@ -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" diff --git a/README.md b/README.md index 8674925..17af2d2 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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/ @@ -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 @@ -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 -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 -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 diff --git a/framework/api/notes_client.py b/framework/api/notes_client.py index a193093..9b2ee1e 100644 --- a/framework/api/notes_client.py +++ b/framework/api/notes_client.py @@ -8,10 +8,19 @@ 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.""" @@ -19,19 +28,34 @@ class NotesApiClient: 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: @@ -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 @@ -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).""" diff --git a/framework/config.py b/framework/config.py index d2f8372..8338b74 100644 --- a/framework/config.py +++ b/framework/config.py @@ -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: @@ -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"))), ) diff --git a/framework/pages/login_page.py b/framework/pages/login_page.py index 34473b4..06e2463 100644 --- a/framework/pages/login_page.py +++ b/framework/pages/login_page.py @@ -3,6 +3,7 @@ from playwright.sync_api import Page from framework.config import Settings +from framework.pages.navigation import open_page class LoginPage: @@ -10,6 +11,7 @@ class LoginPage: 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") @@ -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: diff --git a/framework/pages/navigation.py b/framework/pages/navigation.py new file mode 100644 index 0000000..0bd01bd --- /dev/null +++ b/framework/pages/navigation.py @@ -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}" + ) diff --git a/framework/pages/notes_page.py b/framework/pages/notes_page.py index f468e1c..6f7c928 100644 --- a/framework/pages/notes_page.py +++ b/framework/pages/notes_page.py @@ -4,6 +4,7 @@ from framework.config import Settings from framework.data.factories import NoteData +from framework.pages.navigation import open_page class NotesPage: @@ -11,6 +12,7 @@ class NotesPage: 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 @@ -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.""" @@ -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.""" @@ -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.""" diff --git a/framework/retry.py b/framework/retry.py new file mode 100644 index 0000000..f33b5d8 --- /dev/null +++ b/framework/retry.py @@ -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 diff --git a/tests/conftest.py b/tests/conftest.py index 086bdb6..94dc11e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,7 +11,8 @@ from dataclasses import dataclass import pytest -from playwright.sync_api import Page, Route +import requests +from playwright.sync_api import Page, Route, expect from pytest_html import extras from framework.api.notes_client import NotesApiClient @@ -19,6 +20,7 @@ from framework.data.factories import new_user from framework.pages.login_page import LoginPage from framework.pages.notes_page import NotesPage +from framework.retry import with_retries @dataclass @@ -57,15 +59,37 @@ def _delete_account(settings: Settings, email: str, password: str) -> None: client.close() +def _register_new_account(settings: Settings) -> Account: + """Registers a brand-new user through the API. + + Registering is a POST and the client does not repeat it (a repeat with the same email would get + 409 if the first one got through). So after a timeout this tries again with a *new* user. The + timed-out one may exist on the server without us knowing its password was accepted; it is a + throwaway account on the public demo, so that is acceptable. + """ + + def register_once() -> Account: + credentials = new_user() + client = NotesApiClient(settings) + try: + response = client.register(credentials.name, credentials.email, credentials.password) + finally: + client.close() + assert response.status_code == 201, f"Could not register a test user: {response.text}" + return Account(credentials.name, credentials.email, credentials.password) + + return with_retries( + register_once, + retry_on=(requests.Timeout, requests.ConnectionError), + attempts=settings.attempts, + what="registering a test user", + ) + + @pytest.fixture def account(settings: Settings) -> Iterator[Account]: """A freshly registered user, deleted after the test.""" - credentials = new_user() - client = NotesApiClient(settings) - response = client.register(credentials.name, credentials.email, credentials.password) - client.close() - assert response.status_code == 201, f"Could not register a test user: {response.text}" - registered = Account(credentials.name, credentials.email, credentials.password) + registered = _register_new_account(settings) yield registered _delete_account(settings, registered.email, registered.password) @@ -73,12 +97,7 @@ def account(settings: Settings) -> Iterator[Account]: @pytest.fixture def second_account(settings: Settings) -> Iterator[Account]: """Another registered user, for tests about what one user may see of another's data.""" - credentials = new_user() - client = NotesApiClient(settings) - response = client.register(credentials.name, credentials.email, credentials.password) - client.close() - assert response.status_code == 201, f"Could not register a second test user: {response.text}" - registered = Account(credentials.name, credentials.email, credentials.password) + registered = _register_new_account(settings) yield registered _delete_account(settings, registered.email, registered.password) @@ -124,6 +143,18 @@ def _block_ads(route: Route) -> None: route.continue_() +@pytest.fixture(scope="session", autouse=True) +def expect_timeout(settings: Settings) -> None: + """expect() waits as long as a server round trip may take (settings.ui_server_timeout_ms). + + UI checks mostly look at what the app shows after it talked to the server (progress text, + search results, a URL after login), and the public demo is sometimes slow. A longer wait + never makes a wrong result pass: expect() still fails if the page does not match in time, + it only takes longer to say so. A test can still pass its own timeout=... + """ + expect.set_options(timeout=settings.ui_server_timeout_ms) + + @pytest.fixture(scope="session") def browser_context_args(browser_context_args: dict) -> dict: """pytest-playwright hook: every browser context gets a desktop-size window."""