1---2name: saleor-testing3description: Test Saleor applications — pytest setup, Django test client, GraphQL test patterns, App testing, factory_boy fixtures, and webhook testing. Use when writing tests for Saleor projects.4---56# Saleor Testing78## Before writing code910**Fetch live docs**:111. Web-search `site:github.com/saleor/saleor pytest conftest fixtures` for Saleor's test setup and existing fixtures122. Web-search `site:docs.saleor.io app testing webhooks` for App testing patterns and webhook verification133. Web-search `site:docs.saleor.io graphql API testing` for GraphQL query and mutation testing approaches144. Fetch `https://github.com/saleor/saleor/blob/main/conftest.py` and review root-level test configuration155. Web-search `site:docs.pytest.org fixtures factory_boy django` for pytest fixtures and factory_boy integration1617## Test Architecture1819Saleor follows a layered testing approach:2021| Layer | Tool | Purpose |22|-------|------|---------|23| Unit tests | pytest | Test individual functions, utilities, and model methods |24| Integration tests | Django test client | Test GraphQL API endpoints with database |25| App tests | pytest + httpx/requests-mock | Test App webhooks, signature verification |26| E2E tests | pytest + API client | Test full user flows through the API |2728## Pytest Setup2930### Core Configuration3132| File | Purpose |33|------|---------|34| `pytest.ini` / `pyproject.toml` | Pytest settings, markers, default flags |35| `conftest.py` (root) | Shared fixtures, database setup, API clients |36| `conftest.py` (per-app) | App-specific fixtures and helpers |3738### Essential pytest Settings3940| Setting | Value | Purpose |41|---------|-------|---------|42| `DJANGO_SETTINGS_MODULE` | `saleor.tests.settings` | Test-specific Django settings |43| `--reuse-db` | Flag | Reuse test database across runs for speed |44| `--no-migrations` | Flag | Skip migrations; create tables directly |45| `-x` | Flag | Stop on first failure during development |46| `-n auto` | Flag | Parallel execution with pytest-xdist |4748### Key pytest Plugins4950| Plugin | Purpose |51|--------|---------|52| `pytest-django` | Django integration, database access, settings override |53| `pytest-xdist` | Parallel test execution |54| `pytest-mock` | Mock and patch utilities |55| `pytest-asyncio` | Async test support |56| `pytest-vcr` | Record and replay HTTP interactions |57| `pytest-factoryboy` | factory_boy integration with pytest fixtures |5859## Django Test Client for GraphQL6061Saleor's GraphQL API is tested using Django's test client:6263### API Client Pattern6465| Component | Description |66|-----------|-------------|67| Test client | Django `Client` or `RequestFactory` for HTTP requests |68| Endpoint | POST to `/graphql/` with query and variables |69| Authentication | Set `HTTP_AUTHORIZATION` header with JWT or App token |70| Content type | `application/json` for standard queries |7172### Authenticated Request Patterns7374| Actor | Header | Token Source |75|-------|--------|--------------|76| Anonymous | None | No authentication |77| Customer | `Authorization: Bearer <jwt>` | `tokenCreate` or test fixture |78| Staff user | `Authorization: Bearer <jwt>` | Staff user fixture with permissions |79| App | `Authorization: Bearer <app-token>` | App token fixture |8081## GraphQL Test Helper Pattern8283### Response Assertion Patterns8485| Assertion | What to Check |86|-----------|---------------|87| Status code | `assert response.status_code == 200` |88| No errors | `assert "errors" not in content` or `content["data"]["mutation"]["errors"] == []` |89| Data present | `assert content["data"]["query"]["field"] == expected` |90| Permission denied | `assert content["errors"][0]["extensions"]["exception"]["code"] == "PermissionDenied"` |91| Validation error | Check `errors` array in mutation response for field-level errors |9293## factory_boy Factories for Saleor Models9495### Core Model Factories9697| Factory | Model | Key Fields |98|---------|-------|------------|99| `UserFactory` | `User` | email, first_name, last_name, is_staff |100| `ProductTypeFactory` | `ProductType` | name, has_variants, is_shipping_required |101| `ProductFactory` | `Product` | name, product_type, category, slug |102| `ProductVariantFactory` | `ProductVariant` | product, sku, track_inventory |103| `CategoryFactory` | `Category` | name, slug, parent |104| `CollectionFactory` | `Collection` | name, slug |105| `ChannelFactory` | `Channel` | name, slug, currency_code |106| `WarehouseFactory` | `Warehouse` | name, slug, address |107| `OrderFactory` | `Order` | user, channel, billing_address |108| `OrderLineFactory` | `OrderLine` | order, variant, quantity |109| `CheckoutFactory` | `Checkout` | channel, email, shipping_address |110| `VoucherFactory` | `Voucher` | code, type, discount_value |111| `ShippingZoneFactory` | `ShippingZone` | name, countries |112| `ShippingMethodFactory` | `ShippingMethod` | name, type, shipping_zone |113114## Testing Apps115116### Webhook Payload Validation117118| Test Aspect | What to Verify |119|-------------|----------------|120| Payload structure | JSON schema matches expected format |121| Required fields | All mandatory fields are present |122| Data accuracy | Payload values match the triggering event |123| Serialization | Dates, decimals, and enums serialize correctly |124125### Signature Verification Testing126127| Step | Description |128|------|-------------|129| 1. Get key material | For JWS (default): use test JWKS; for legacy HMAC: use App secret key |130| 2. Sign payload | Create valid JWS/HMAC signature for the test payload |131| 3. Set header | Include signature in the `Saleor-Signature` header |132| 4. Verify in App | App verifies signature and processes payload |133| 5. Test mismatch | Verify App rejects requests with invalid signatures |134135## Testing GraphQL Queries and Mutations136137### Query Test Pattern138139| Step | Description |140|------|-------------|141| 1. Create test data | Use factories to set up products, channels, etc. |142| 2. Execute query | Send GraphQL query via test client |143| 3. Assert results | Verify returned data matches created test data |144| 4. Test filtering | Verify filters, search, and pagination work |145| 5. Test permissions | Verify unauthorized users cannot access data |146147### Mutation Test Pattern148149| Step | Description |150|------|-------------|151| 1. Set up prerequisites | Create required related objects |152| 2. Execute mutation | Send mutation with valid input |153| 3. Assert success | Check response for data and no errors |154| 4. Verify database | Query the database to confirm changes persisted |155| 5. Test validation | Send invalid input and verify error messages |156| 6. Test permissions | Verify only authorized users can execute |157158## Fixture Patterns159160### Commonly Needed Test Fixtures161162| Fixture | Provides |163|---------|----------|164| `staff_user` | Authenticated staff user with configurable permissions |165| `customer_user` | Authenticated customer with address |166| `channel_USD` | Default USD channel |167| `product` | Product with type, category, variant, and channel listing |168| `order` | Order with lines, addresses, and payment |169| `checkout` | Checkout with lines and shipping address |170| `warehouse` | Warehouse with stock for test variants |171| `shipping_zone` | Shipping zone with methods and channel listing |172173## CI/CD Pipeline Integration174175| Stage | Tests | Configuration |176|-------|-------|---------------|177| Pre-commit | Linting, type checks | `pre-commit` hooks with `ruff`, `mypy` |178| Unit tests | Fast, isolated tests | `pytest -x --no-migrations -q` |179| Integration tests | API and database tests | `pytest --reuse-db -n auto` |180| Coverage | Code coverage report | `pytest --cov=saleor --cov-report=xml` |181| App tests | Webhook and App tests | `pytest tests/apps/ -v` |182183## Best Practices184185- Use factory_boy factories instead of manual object creation for consistency186- Test both success and error paths for every mutation187- Verify permissions by testing with unauthenticated, customer, and staff users188- Use `@pytest.mark.django_db` on all tests that access the database189- Mock external services (payment gateways, shipping carriers) in unit tests190- Test webhook signature verification (JWS/HMAC) with both valid and invalid signatures191- Keep test fixtures composable and avoid deeply nested dependencies192- Run tests in parallel with `pytest-xdist` for faster CI pipelines193- Use `assertNumQueries` to catch N+1 query problems in resolvers194195Fetch the Saleor testing and pytest documentation for exact fixture patterns, test client setup, and CI configuration before implementing.