LESSON 6

Integration and Contract Testing

Test components working together against real infrastructure: databases, APIs, queues, tenant isolation, and the contracts between modules and services.

Introduction

Most production failures are not inside a single function. They happen at the seams: a query that violates a constraint, a serialization mismatch, a transaction that does not roll back, a migration that does not match the model, an API whose behavior differs from its documentation.

Integration tests exercise those seams with real components. They are slower than unit tests and far more realistic, and they are where the highest-risk SignalDesk behaviors (tenant isolation, import correctness, job reliability) are best verified.

Learning Objectives

  • Decide what to test at the integration level and what to leave to unit tests.
  • Test database behavior against a real database, including migrations and constraints.
  • Test HTTP APIs, including errors, authorization, and tenant isolation.
  • Test background jobs, failures, retries, and idempotency.
  • Use contract tests to verify agreements between modules and services.
  • Manage test data and isolation between tests.

1. What Integration Tests Are For

Integration tests verify that real components cooperate correctly:

Seam What can go wrong SignalDesk example
Code and database Constraint violations, wrong queries, transaction bugs Duplicate fingerprint handling
API layer and service Validation, status codes, serialization, authorization 403 for another workspace’s item
Service and queue/worker Lost, duplicated, or stuck jobs Import job crashes mid-batch
Module and module Boundary violations, mismatched assumptions Evidence module reads imported feedback
System and external service Timeouts, error responses, changed formats Model provider failure during summary

Keep them focused. Test the seam, not every business rule again; rules are cheaper to test in units.

2. Use Real Infrastructure

Replacing the database with a mock removes exactly what makes the test valuable. Prefer:

  • A disposable real database per test run, started by the CI service or by a container helper library, using the same engine and major version as production.
  • Real migrations applied to build the schema, so migrations are tested too.
  • A real queue or the real in-process worker, if feasible.

Isolation between tests is essential:

  • Transaction rollback per test (fast; works when the code under test does not manage its own transactions).
  • Truncate tables between tests (simple; slower).
  • Unique data per test (for example, a fresh workspace each time), allowing tests to run in parallel.

3. Database Tests

Test the things the database is responsible for:

1
2
3
4
5
6
7
8
9
10
def test_duplicate_fingerprint_is_rejected_by_the_database(db):
    repo = FeedbackRepository(db, workspace_id=WS_A)
    repo.insert(make_item(fingerprint="abc"))

    with pytest.raises(UniqueViolation):
        repo.insert_raw(make_item(fingerprint="abc"))   # bypass app-level check

def test_same_fingerprint_allowed_in_different_workspaces(db):
    FeedbackRepository(db, WS_A).insert(make_item(fingerprint="abc"))
    FeedbackRepository(db, WS_B).insert(make_item(fingerprint="abc"))   # no error

Also test:

  • Migrations: apply to an empty database and to a populated one; verify rollback if you provide it.
  • Constraints: NOT NULL, CHECK, foreign keys.
  • Queries: ordering, pagination boundaries, and scoping.
  • Performance sanity: a query on 100,000 rows uses the expected index (inspect the query plan in a dedicated test or script).

4. API Tests

Call the API as a client would, through the HTTP layer (a test client or the running app):

  • Happy path and the documented success status codes.
  • Validation errors: 400/422 with the standard error shape.
  • Authentication and authorization: missing credentials, wrong role, wrong workspace.
  • Pagination, filtering, and sorting boundaries.
  • Idempotency and conflicts: repeated requests, concurrent requests.
  • Contract conformance: responses validate against the OpenAPI document.

Tenant isolation deserves a systematic test, run for every endpoint that touches tenant data:

1
2
3
4
5
6
@pytest.mark.parametrize("method, path", TENANT_SCOPED_ENDPOINTS)
def test_workspace_b_cannot_access_workspace_a_data(client, method, path):
    item_id = create_item(workspace=WS_A)
    response = client.request(method, path.format(id=item_id), user=USER_IN_WS_B)
    assert response.status_code in (403, 404)
    assert item_still_unchanged(item_id)

Generate TENANT_SCOPED_ENDPOINTS from the API contract so that a new endpoint cannot be added without isolation coverage. This turns a recurring human memory task into a structural guarantee.

5. Background Job Tests

Jobs fail in ways tests rarely simulate unless asked:

  • Idempotency: run the same job twice; the result equals running it once.
  • Crash and resume: make the job fail after batch 2 (inject a failing dependency); rerun; verify no duplicates and no lost rows.
  • Retry and backoff: a transient error is retried up to the limit, then marked failed with a summary.
  • Concurrency: two workers pick up the same job; only one processes it.
  • Poison input: a malformed row does not block the rest.
  • Visibility: status and progress are correct at each stage.

Control time and randomness in these tests (inject a clock and a backoff policy) so they are fast and deterministic.

6. Contract Testing

When two components agree on an interface, both must keep honoring it. A contract test checks the agreement from each side.

  • Within the monolith: tests (or dependency rules) verify that modules interact only through their public interfaces and that the interface behaves as documented.
  • With external services: run tests against a recorded or simulated version of the service, and periodically against the real one (or its sandbox) to detect drift.
  • Consumer-driven contracts: the consumer states what it needs, the provider verifies it. This is valuable when separate teams or deployable services are involved.

Test doubles for external systems should themselves be checked against the real system occasionally; otherwise the doubles drift and tests pass against a service that no longer exists.

Typical external case for SignalDesk: the model provider. Contract tests check request shape, error handling for timeouts and rate limits, and parsing of unexpected responses, with a stubbed provider in CI and a small, controlled live check outside the main pipeline.

7. Keeping Integration Tests Healthy

  • Keep them reasonably fast. Share a database container across the run, not per test.
  • Make failures diagnosable: log the request, response, and database state on failure.
  • Avoid order dependence and shared mutable state.
  • Avoid sleeps; poll for a condition with a timeout instead.
  • Separate by marker (integration) so developers can run them selectively and CI always runs them.
  • Do not duplicate unit coverage; one test per seam behavior is enough.

8. Using AI for Integration Tests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Act as a test engineer. Propose integration tests for the component
below, using a real database and the real HTTP layer.

Inputs:
- API contract excerpt: [paste]
- Schema and constraints: [paste]
- Authorization and tenant-isolation rules: [paste]
- Job lifecycle and retry rules: [paste]

Tasks:
1. List seam-level risks (constraints, transactions, authorization,
   concurrency, failures, contract mismatches).
2. For each, propose a test: setup, action, and assertion.
3. Identify tests that should instead be unit tests.
4. List failure injections needed (killed worker, duplicate request,
   slow dependency).
5. Mark expected results that are not defined in the inputs.

Review for unrealistic setups, missing cross-tenant cases, and the use of mocks where real components were requested.

9. Practical Exercise

For SignalDesk (or your project):

  1. Set up a disposable real database for tests, applying real migrations, with per-test isolation.
  2. Write database tests for the fingerprint uniqueness rule, tenant scoping, and one migration.
  3. Write API tests for upload, status, and list endpoints: success, validation errors, authorization, and pagination boundaries.
  4. Implement the parametrized tenant-isolation test, generated from the API contract.
  5. Write job tests for idempotency, crash-and-resume, and retry exhaustion.
  6. Write one contract test for the model provider interface with a stub.
  7. Run the AI prompt, verify the suggestions, and add the valid tests.

Verification

You are ready to continue when:

  • Integration tests use a real database and real migrations.
  • A cross-tenant test runs for every tenant-scoped endpoint, generated from the contract.
  • The job survives crash, retry, and duplicate execution tests.
  • Tests are isolated and pass in any order.
  • Failures show enough information to diagnose without rerunning.

Key Takeaways

  • Integration tests verify the seams, where many real failures occur.
  • Use real infrastructure; mocking the database removes the value of the test.
  • Make tenant isolation coverage structural by deriving tests from the contract.
  • Test jobs for idempotency, partial failure, and concurrency.
  • Contract tests keep both sides of an interface honest.

What’s Next?

Integration tests confirm that the parts connect. To confirm that the whole system delivers value to a user, we need end-to-end tests. Next, we cover how to write a small number of them well.