The user wants an "integration test suite" that is "deterministic" and covers three distinct areas:
- UI Flows: Testing the frontend interactions.
- API Contracts: Testing the communication between frontend and backend, or client and server.
- Inference Outputs: Testing the core AI/ML model outputs.
This is a comprehensive request that spans full-stack development and MLOps.
1. Deconstructing the Request:
- "Architect": I need to provide a structural plan, design patterns, technology choices, and workflow, not just a single code snippet. It needs to be a system.
- "Deterministic": This is the hardest part, especially for "Inference Outputs." AI models are often probabilistic. I need to explain how to mock, seed, or isolate these to make tests repeatable.
- "UI Flows": Needs browser automation or component testing (e.g., Playwright, Cypress, Storybook).
- "API Contracts": Needs API testing (e.g., Postman, Pytest, Pact). Ideally, schema validation.
- "Inference Outputs": Needs model evaluation pipelines or mock inference services.
2. High-Level Architecture:
I should propose a layered architecture.
- Layer 1: Test Strategy & Philosophy (Determinism, Mocking, Isolation).
- Layer 2: Technology Stack (Concrete tools).
- Layer 3: Implementation Structure (Folder layout, specific test types).
- Layer 4: CI/CD Integration (Running it automatically).
3. Addressing "Determinism" in Specific Areas:
- UI: Timeouts, asynchronous rendering, and dynamic data are enemies.
- Solution: Mock the API at the network layer or use a dedicated test environment with seeded data. Use stable selectors (data-testid).
- API: Flaky networks, database state.
- Solution: Database transactions/rollbacks, in-memory databases, or contract testing (Pact) to avoid integration over the network entirely.
- Inference: Random seeds, GPU non-determinism, floating point variations.
- Solution:
- Unit Level: Fix random seeds (
torch.manual_seed, numpy.random.seed).
- Integration Level: Mock the model entirely (echo server) or use a "Golden Master" approach with a frozen model version and fixed inputs.
- Fuzzy Matching: Don't check
output == expected. Check cosine_similarity > 0.99.
4. Structuring the Solution:
I will organize the response into logical sections:
- Principles: The "Why" and "How" of determinism.
- The Stack: Recommended tools (Playwright, Pytest, etc.).
- Component 1: API Contracts (The Foundation): Contract testing, schema validation.
- Component 2: Inference Testing (The Core): Golden sets, mocking, seeding.
- Component 3: UI Flows (The Interface): E2E with mocked backend or seeded backend.
- Infrastructure: Docker, CI pipelines.
5. Drafting the Content - Specific Technical Details:
- API: Let's suggest OpenAPI/Swagger validation. Pytest is the standard for Python backends.
- UI: Playwright is currently the industry leader for reliability and speed. I should mention "Component Testing" vs "E2E".
- Inference: This is specific.
- Scenario A (Mock): The UI shouldn't care about the actual model logic during UI tests. Use a mock inference server.
- Scenario B (Real): Use a reference dataset (Golden Dataset). Check for output shape, type, and approximate value.
6. Refining the "Deterministic" aspect for Inference:
This is the trickiest part. If I run a real LLM, it's slow and non-deterministic (usually).
- Approach: Virtualized Inference Layer.
- Create an interface
InferenceEngine.
- Have
RealEngine (prod) and MockEngine (testing).
MockEngine takes input, hashes it, returns a pre-canned response from a lookup table. This guarantees UI flows don't flake due to hallucinations.
7. Putting it together (Mental Draft of the output):
- Introduction: Define the goal.
- Section 1: The Determinism Protocol. (Seeding, Mocking, Isolation).
- Section 2: API Contract Testing. (Pytest + Schemathesis).
- Section 3: Inference Validity. (Golden Sets + Mock Server).
- Section 4: UI Flow Testing. (Playwright + Network Mocking).
- Section 5: The Glue (CI/CD).
8. Review against User Constraints:
- UI Flows? Yes (Playwright).
- API Contracts? Yes (OpenAPI/Pytest).
- Inference Outputs? Yes (Golden Set/Mock).
- Deterministic? Yes, emphasized via seeds, mocks, and network control.
9. Adding Code Examples:
Abstract descriptions are hard to follow. I will add:
- A
conftest.py fixture for the API client.
- A snippet of a Playwright test intercepting network calls.
- A snippet showing how to fix seeds for PyTorch/TensorFlow.
10. Final Polish:
Make the tone professional and architectural. Use diagrams (text-based) if helpful.
(Self-Correction during drafting): Initially, I thought about testing the real model in the integration suite. But "Deterministic" and "Real ML Model" are oxymorons in a strict test suite due to temperature/timeout issues.
Decision: I will explicitly separate Model Integration Tests (validating the model logic, separate from UI) from System Integration Tests (validating the whole app, where the model is mocked). This is crucial for speed and reliability.
Let's write the response.
To architect a deterministic integration test suite for a system involving UI, API, and Machine Learning inference, you must solve the core problem of non-determinism.
In this context, non-determinism comes from:
- UI: Async rendering, network latency, animation timing.
- API: Database state pollution, race conditions.
- Inference: Floating point precision, random seeds, GPU non-determinism.
Here is the architectural blueprint for the "Deterministic Trinity" test suite.
1. High-Level Architecture
We will decouple the tests into three layers that run in isolation but share a common "Determinism Contract."
- Layer A: Contract Testing (API): Validates schema and logic without state.
- Layer B: Regression Testing (Inference): Validates model outputs against "Golden Master" artifacts.
- Layer C: Flow Testing (UI): Validates user journeys by mocking the API/Inference layers entirely.
2. Technology Stack Recommendation
- API/Backend:
Pytest (Python) or Jest (Node).
- Inference:
Pytest with numpy/torch.
- UI:
Playwright (Web) or Detox (Mobile).
- Mocking:
Wiremock (Standalone) or MSW (Service Worker).
- Infrastructure: Docker Compose (for local parity).
3. Layer 1: The API Contract (The Foundation)
Determinism here means the API response structure never changes unexpectedly, and the database state is reset between tests.
Strategy:
- Schema Validation: Do not assert on specific data values (which change), assert on the JSON Schema.
- Database Sandbox: Use transaction rollbacks. Every test starts a transaction and rolls it back at the end.
Implementation Pattern (Pytest):
# test_api_contracts.py
import pytest
from jsonschema import validate
# Fixture to handle DB state deterministically
@pytest.fixture(autouse=True)
def db_session(db_engine):
connection = db_engine.connect()
transaction = connection.begin()
yield connection
# Rollback ensures the DB is clean for the next test
transaction.rollback()
connection.close()
def test_predict_endpoint_contract(api_client, schema_store):
response = api_client.post("/v1/predict", json={"text": "hello world"})
assert response.status_code == 200
# Validate against the stored OpenAPI/JSON Schema
# This catches if a developer changes a field type from int to float
validate(instance=response.json(), schema=schema_store["PredictionResponse"])
4. Layer 2: Deterministic Inference (The Brain)
ML models are inherently probabilistic. To test them deterministically, we must separate Model Logic (does it run?) from Model Weights (is it accurate?).
Strategy:
- Fix Random Seeds: Force NumPy, Python's
random, and PyTorch/TensorFlow to use a static seed.
- Golden Master Testing: Record the output of a specific input on a "blessed" version of the model. Future tests compare current output against this recorded "Golden" file using a tolerance threshold (e.g., cosine similarity).
Implementation Pattern:
# test_inference_determinism.py
import torch
import numpy as np
import json
import pytest
from my_app.model import load_inference_engine
# Force determinism globally
torch.manual_seed(42)
np.random.seed(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def test_inference_output_stability():
# 1. Load specific model version
engine = load_inference_engine(version="v1.2.0")
# 2. Load static input (The "Probe")
with open("tests/fixtures/static_input.json") as f:
input_data = json.load(f)
# 3. Load expected output (The "Golden Master")
with open("tests/golden_outputs/v1.2.0_expected.json") as f:
expected_output = json.load(f)
# 4. Run Inference
actual_output = engine.predict(input_data)
# 5. Assert with Tolerance (Floating point ops differ between CPU/GPU)
# Check if vectors are pointing in the same direction
cos_sim = np.dot(actual_output, expected_output) / (np.linalg.norm(actual_output) * np.linalg.norm(expected_output))
assert cos_sim > 0.999, "Model output drift detected"
5. Layer 3: UI Flows (The Interface)
UI tests are the flakiest. To make them deterministic, do not let the UI talk to the real backend or model.
Strategy:
- Hermetic Testing: The UI should run in a container with the API mocked.
- State Snapshots: Instead of clicking "Login" and waiting for the server, mock the API to return a "Logged In" cookie immediately upon hitting the endpoint.
- Retry/Timeout Logic: Use smart selectors (e.g., Playwright's
await page.waitForSelector) rather than fixed sleep calls.
Implementation Pattern (Playwright):
// test_ui_flow.spec.js
const { test, expect } = require('@playwright/test');
test.describe('Prediction Flow', () => {
test.beforeEach(async ({ page }) => {
// MOCK THE API: Intercept the call and return a deterministic fixture
await page.route('**/v1/predict', route => {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
result: "Positive Sentiment",
confidence: 0.98
}) // Static response ensures UI test doesn't flake on model randomness
});
});
});
test('User can submit text and see result', async ({ page }) => {
await page.goto('/');
// Interact
await page.fill('#input-text', 'This is a test');
await page.click('#submit-btn');
// Validate UI state based on the Mocked API response
await expect(page.locator('.result-card')).toContainText('Positive Sentiment');
await expect(page.locator('.confidence-bar')).toHaveValue('98');
});
});
6. The Glue: CI/CD Pipeline Architecture
How you run these is as important as how they are written.
- Static Analysis (Lint/Types): Run first (fail fast).
- Contract Tests: Run in parallel. Spin up a DB in Docker, apply migrations, run tests, tear down.
- Inference Tests: Run on CPU (for determinism) or specific GPU instance. If the test fails, it blocks the deployment and alerts the Data Science team (Drift Alert).
- UI Tests: Run in headless browsers (Chromium, WebKit, Firefox).
7. Summary of Determinism Tactics
| Layer | Source of Entropy | Determinism Tactic |
|---|
| API | DB State | Transaction Rollbacks (Reset state after every test) |
| API | Schema Drift | JSON Schema Validation |
| Inference | Random Init | Global Seed Fixing (Seed=42) |
| Inference | Model Updates | Golden Master Artifacts (Check output vectors) |
| UI | Network Latency | Service Virtualization (Mock the API) |
| UI | Rendering Time | Smart Wait Selectors (No sleep) |
8. Directory Structure
/project
├── /api
├── /model
├── /ui
├── /tests
│ ├── /api # Pytest + Schemathesis
│ ├── /inference # Pytest + Golden Files
│ ├── /ui # Playwright
│ ├── /fixtures # Static input data
│ └── /mocks # API response definitions
├── docker-compose.test.yml # Orchestrates DB, API Mock, and Selenium
└── Makefile # Commands like `make test-contracts`, `make test-ui`