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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ temp
.venv
# Ignore dynaconf secret files
.secrets.*
/tests/test-results/
test-results/
45 changes: 32 additions & 13 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,26 @@ poetry run playwright install --with-deps

### Run tests
```bash
# All tests (headed, screenshots on failure)
# All tests (headless, screenshots on failure)
pytest tests

# Single test file
pytest tests/test_api.py
# API only (no browser) / UI only
pytest tests/api -n auto
pytest tests/ui

# Single test by name
pytest tests/test_api.py::test_get_product_list
pytest tests/api/test_verify_login.py::test_verify_login_with_valid_credentials

# By marker
pytest -m smoke
pytest -m "not single"
pytest -m "api and negative"

# Parallel execution (skip tests marked `single`)
pytest -n auto -m "not single"

# Browser selection: pytest-playwright's built-in options
pytest tests/ui --headed --browser firefox
pytest tests/ui --browser-channel chrome
```

### Linting
Expand All @@ -58,17 +62,32 @@ Use comments sparingly — only for complex or non-obvious logic.
- `page_objects/page_creator.py` — **PageCreator** is a facade injected into tests via the `ui` fixture. Tests call `ui.main_page()`, `ui.products_page()`, etc. rather than instantiating page objects directly.
- Each page class (e.g., `page_objects/main.py`) exposes selectors as properties (Playwright locators) and navigation methods like `open()`.

### Fixtures (`tests/conftest.py`)
| Fixture | Scope | Purpose |
|---------|-------|---------|
| `browser` | session | Headless browser instance |
| `context` | function | Isolated browser context per test |
| `ui` | function | `PageCreator` instance for UI tests |
| `api` | session | Playwright `APIRequestContext` pointed at `/api` |
| `faker` | function | Faker instance for test data |
### API layer (`api/`)
- `api/client/` — `BaseApiClient.request()` wraps `APIRequestContext.fetch` and returns an `ApiResponse` snapshot. `ProductsClient` / `AccountsClient` expose one method per endpoint; tests never build paths or form payloads themselves.
- `api/models/responses.py` — Pydantic response contracts (`extra="forbid"`). `api/models/user.py` — `UserData` request payload; `expected_user_detail()` maps request field names to the names the API returns.
- `api/assertions.py` — `assert_api_response(resp, code=, message=, http_status=, model=)`. The API returns HTTP 200 for most errors with the real status in the body `responseCode`; always assert through this helper, not `response.ok`.
- `api/data/factories.py` — `build_user(faker, **overrides)`; emails are UUID-based for parallel safety.
- The `api_context` base URL must end with `/api/` and client paths must be relative (no leading slash). Otherwise Playwright resolves them against the site root.

### Fixtures
| Fixture | Scope | Where | Purpose |
|---------|-------|-------|---------|
| `api_context` | session | `tests/conftest.py` | Playwright `APIRequestContext` pointed at `/api/` |
| `products_client`, `accounts_client` | session | `tests/conftest.py` | API clients |
| `new_user` | function | `tests/conftest.py` | Unregistered `UserData` |
| `registered_user` | function | `tests/conftest.py` | User created via API, deleted after the test |
| `cleanup_user` | function | `tests/conftest.py` | Callable; registers a user for deletion after the test |
| `faker_seed` | function | `tests/conftest.py` | Random, logged seed for the faker plugin's `faker` (override with `FAKER_SEED`) |
| `ui` | function | `tests/ui/conftest.py` | `PageCreator` built on pytest-playwright's `page` |

Browser, context and page come from pytest-playwright. Don't redefine them, or `--screenshot`/`--tracing`/`--video` stop working.

### Test Markers
- `api` / `ui` — applied automatically from the test folder
- `smoke` — smoke tests
- `regression` — full regression suite
- `contract` — strict schema checks
- `negative` — negative / error-handling tests
- `single` — must not run in parallel
- `mobile` — mobile-only tests
- `quality_gate` — quality gate tests
Expand Down
111 changes: 101 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,35 +158,119 @@ poetry run pytest -m smoke
## Running Tests

```bash
# All tests (headed browser, screenshots on failure by default)
# All tests (headless, screenshots on failure)
pytest tests

# Single file
pytest tests/test_api.py
# API tests only: no browser needed, ~20 s in parallel
pytest tests/api -n auto

# Single test by name
pytest tests/test_api.py::test_get_product_list
# UI tests only
pytest tests/ui

# Single file / single test
pytest tests/api/test_search_product.py
pytest tests/api/test_verify_login.py::test_verify_login_with_valid_credentials

# By marker
pytest -m smoke
pytest -m quality_gate
pytest -m "api and smoke"
pytest -m contract

# Parallel execution (skip tests marked `single`)
pytest -n auto -m "not single"

# Browser selection (pytest-playwright options)
pytest tests/ui --headed
pytest tests/ui --browser chromium --browser firefox
pytest tests/ui --browser-channel chrome # or msedge

# Debug artifacts on failure
pytest tests/ui --tracing retain-on-failure --video retain-on-failure

# Replay a run with the same generated test data (seed is logged per test)
FAKER_SEED=123456 pytest tests/api/test_account_lifecycle.py
```

Screenshots, traces and videos are written to `test-results/`.

### Test Markers

`api` and `ui` are applied automatically based on the test folder.

| Marker | Description |
|--------|-------------|
| `smoke` | Smoke tests |
| `smoke` | Smoke tests: one happy path per feature |
| `regression` | Full regression suite |
| `api` | API tests (no browser required) |
| `ui` | Browser-based UI tests |
| `contract` | Strict response schema checks |
| `negative` | Negative / error-handling tests |
| `single` | Must not run in parallel |
| `mobile` | Mobile-only tests |
| `quality_gate` | Quality gate tests |

---

## API Testing Approach

API tests use Playwright's `APIRequestContext`, the same tool as the UI tests. That means one dependency, one config, and API calls can set up UI tests directly.

### Layers

```
tests/api/*.py what is tested: one behaviour per test, no HTTP details
│
api/assertions.py how the API reports outcomes (HTTP status + body responseCode)
│
api/models/ Pydantic contracts for responses + request payload models
api/data/factories.py test data builders (Faker)
│
api/client/ one method per endpoint, plus raw request() for negative tests
│
APIRequestContext Playwright transport (session-scoped fixture)
```

- **Clients** (`ProductsClient`, `AccountsClient`) hide paths, methods and form encoding. `request()` stays public so negative tests can send any method or payload.
- **`ApiResponse`** is a snapshot of the exchange (method, URL, status, body, timing). Its string form is included in every assertion message, so a failure shows the full request and response without re-running the test.
- **Models** forbid unknown fields, so schema drift fails loudly. `assert_api_response(..., model=X)` validates the body and returns a typed object, which the tests then work with instead of raw dicts.

### Design decision: the status code is in the body

automationexercise.com answers **HTTP 200 for almost everything** and puts the real outcome in the body:

```json
{"responseCode": 405, "message": "This request method is not supported."}
```

A check like `response.ok` therefore proves nothing. `assert_api_response` checks the transport status and the body `responseCode` separately, and it's the only place in the framework that knows about this rule.

Exploring the API also showed that it **rejects unsupported methods in two different ways**: catalog endpoints return `200` + `responseCode: 405`, while account endpoints (and `PATCH` anywhere) return a real `HTTP 405` with a `{"detail": ...}` body. `test_unsupported_methods.py` pins both behaviours in one generated table.

### Test data lifecycle

- `new_user` builds a unique user (UUID-based email), so tests are safe to run in parallel and to re-run.
- `registered_user` creates the account through the API as a precondition.
- `cleanup_user` deletes every account a test registers after the test, whether it passed or failed. This includes accounts created through the UI.
- The Faker seed is random per test and logged, and `FAKER_SEED` replays it.

### Coverage

| Area | What is verified |
|------|------------------|
| Products / brands | Catalog content, unique IDs, known categories, product brands exist in `brandsList`, response time SLA |
| Search | Results match the term (name or category), case-insensitive, subset of catalog, empty/blank terms, missing parameter |
| Accounts | Create → read back field by field, update, delete, duplicate email, every required/optional field, wrong password does not modify or delete |
| Login | Valid credentials, wrong password, unknown email, email case sensitivity, missing parameters |
| Unsupported methods | Every endpoint × method combination |
| Contract | Strict schemas for all data payloads and error envelopes |

### API + UI together

- `tests/ui/test_login_with_api_user.py` creates the user through the API, so the UI test only exercises login.
- `tests/ui/test_sign_up.py` registers through the UI, then checks the result via the API and deletes the account.

---

## Project Structure

```
Expand All @@ -196,13 +280,20 @@ pytest-playwright-ui-api/
├── .secrets.toml # Secrets (git-ignored, create manually)
├── requirements.txt # pip dependencies
├── pyproject.toml # Project metadata + pytest config
├── api/
│ ├── client/ # BaseApiClient + ProductsClient, AccountsClient
│ ├── models/ # Pydantic response contracts and request payloads
│ ├── data/factories.py # Test data builders
│ └── assertions.py # assert_api_response, assert_response_time
├── page_objects/
│ ├── page_creator.py # PageCreator facade (injected via `ui` fixture)
│ └── *.py # Individual page object classes
└── tests/
├── conftest.py # Fixtures: browser, context, ui, api, faker
├── test_api.py
└── test_ui.py
├── conftest.py # Shared fixtures: API clients, test users, cleanup, faker seed
├── api/ # API tests
└── ui/
├── conftest.py # `ui` fixture (built on pytest-playwright's `page`)
└── test_*.py # UI and hybrid API+UI tests
```

---
Expand Down
Empty file added api/__init__.py
Empty file.
75 changes: 75 additions & 0 deletions api/assertions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from typing import overload

import pytest
from pydantic import BaseModel, ValidationError

from api.client.base_client import ApiResponse


@overload
def assert_api_response(
response: ApiResponse,
*,
code: int | None = 200,
message: str | None = None,
http_status: int = 200,
model: None = None,
) -> None: ...


@overload
def assert_api_response[M: BaseModel](
response: ApiResponse,
*,
code: int | None = 200,
message: str | None = None,
http_status: int = 200,
model: type[M],
) -> M: ...


def assert_api_response[M: BaseModel](
response: ApiResponse,
*,
code: int | None = 200,
message: str | None = None,
http_status: int = 200,
model: type[M] | None = None,
) -> M | None:
"""Single place that knows how this API reports outcomes.

``http_status`` is the transport status, ``code`` is the body's
``responseCode`` (pass ``None`` for responses without one). When ``model``
is given, the body is validated against it and the parsed model returned.
"""
__tracebackhide__ = True

assert response.http_status == http_status, (
f"Expected HTTP {http_status}, got {response.http_status}\n{response}"
)
if code is not None:
assert response.response_code == code, (
f"Expected responseCode {code}, got {response.response_code}\n{response}"
)
if message is not None:
assert response.message == message, (
f"Expected message {message!r}, got {response.message!r}\n{response}"
)
if model is None:
return None
try:
return model.model_validate(response.body)
except ValidationError as error:
validation_error = error
# Failing outside the except block avoids printing the error twice.
pytest.fail(
f"Response does not match {model.__name__} contract:\n"
f"{validation_error}\n{response}"
)


def assert_response_time(response: ApiResponse, max_ms: float) -> None:
__tracebackhide__ = True
assert response.elapsed_ms <= max_ms, (
f"Response took {response.elapsed_ms:.0f} ms, SLA is {max_ms} ms\n{response}"
)
5 changes: 5 additions & 0 deletions api/client/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from api.client.accounts_client import AccountsClient
from api.client.base_client import ApiResponse, BaseApiClient
from api.client.products_client import ProductsClient

__all__ = ["AccountsClient", "ApiResponse", "BaseApiClient", "ProductsClient"]
33 changes: 33 additions & 0 deletions api/client/accounts_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from api.client.base_client import ApiResponse, BaseApiClient
from api.models.user import UserData


class AccountsClient(BaseApiClient):
CREATE_ACCOUNT = "createAccount"
UPDATE_ACCOUNT = "updateAccount"
DELETE_ACCOUNT = "deleteAccount"
VERIFY_LOGIN = "verifyLogin"
USER_DETAIL_BY_EMAIL = "getUserDetailByEmail"

def create_account(self, user: UserData) -> ApiResponse:
return self.request("POST", self.CREATE_ACCOUNT, form=user.to_form())

def update_account(self, user: UserData) -> ApiResponse:
return self.request("PUT", self.UPDATE_ACCOUNT, form=user.to_form())

def delete_account(self, email: str, password: str) -> ApiResponse:
return self.request(
"DELETE",
self.DELETE_ACCOUNT,
form={"email": email, "password": password},
)

def verify_login(self, email: str, password: str) -> ApiResponse:
return self.request(
"POST",
self.VERIFY_LOGIN,
form={"email": email, "password": password},
)

def get_user_detail_by_email(self, email: str) -> ApiResponse:
return self.request("GET", self.USER_DETAIL_BY_EMAIL, params={"email": email})
Loading
Loading