The user wants a "test fixtures bank" with "contract tests across services".
This sounds like a request for a software testing pattern or a code example.
I need to determine what exactly is being asked.
- "Test Fixtures Bank": This likely refers to a repository or a structured way of storing test data (fixtures) that can be shared or used to set up a specific state for testing. It's not a "bank" in the financial sense, but a "bank" as in a storage location or library.
- "Contract Tests across services": This refers to Consumer-Driven Contract (CDC) testing, commonly used in microservices architectures (e.g., using Pact). It ensures that if Service A calls Service B, they agree on the API structure (the contract).
Interpretation: The user wants an example of how to structure a shared library/repository (a "bank") that holds contract definitions and test fixtures, so that multiple services can use them to verify they don't break integration.
Plan:
- Define a scenario with two services (Consumer and Provider).
- Create a directory structure that simulates the "Bank".
- Show how to define a contract (fixture).
- Show how the Consumer writes a test using that fixture/contract.
- Show how the Provider verifies against that fixture/contract.
Constraint Check: The prompt is very short. I should provide a concrete code example (Python/Node.js) or a structural concept. I'll use a generic structure and perhaps Python with pact as it's a standard for contract testing.
Refining the "Bank" concept:
Instead of just running tests locally, the "Bank" implies a central place where these contracts live.
Structure:
contracts/: The bank.
service-a/: Contracts defined by Service A (Consumer).
service-b/: Contracts defined by Service B (Consumer).
fixtures/: Shared mock data.
Drafting the Code Example:
I'll use Python and pytest with pact-python as a concrete example, as it's a popular choice for this.
- Consumer Side:
- Define the expected interaction.
- Generate the contract file.
- Publish to the "Bank" (simulated as a directory or broker).
- Provider Side:
- Pull contracts from the "Bank".
- Run verification tests against the real Provider API using the shared fixtures.
Let's make it language-agnostic or use a mix to show flexibility, or stick to one stack for coherence. I'll stick to a conceptual overview + specific Python implementation.
Structure:
- Conceptual Architecture: Explain what a Fixtures Bank and Contract Testing are in this context.
- Directory Layout: Show the file structure.
- The Contract (Fixture): A JSON/YAML or code-based definition.
- Consumer Test: Code that uses the fixture.
- Provider Test: Code that validates the API against the fixture.
Let's focus on a scenario: OrderService (Consumer) calling InventoryService (Provider).
- Fixture: "Get Item Details".
- Request:
GET /items/123
- Response:
{ "id": 123, "name": "Widget", "stock": 10 }
This fits the "Test Fixtures Bank" idea perfectly—the response is the fixture.
I will provide a guide and code structure.
Output format:
- High-level explanation.
- Project structure.
- Code examples for the "Bank" (shared contracts), "Consumer", and "Provider".
Let's refine the "Bank" part. Usually, people use a Pact Broker. If the user means creating their own, I should show a file-based approach or a simple custom Broker logic. A file-based approach is easier to demonstrate in a single response.
Step-by-step Plan:
- Introduction: Define the pattern.
- Folder Structure: Central repo vs Service repos. I'll assume a Central Repo approach (The Bank).
- The Fixture/Contract: Define a shared schema (e.g., JSON Schema or OpenAPI snippet).
- Consumer Test: Unit test mocking the provider using the bank fixture.
- Provider Test: Integration test verifying the provider creates the fixture.
- CI/CD Integration: Brief mention.
Let's stick to a Python implementation using pytest and a shared JSON file to represent the bank. This is universally understandable.
Content Generation:
- Bank: A folder
tests/fixtures_bank/contracts.
- Contract:
inventory_get_item.json.
- Consumer: Uses
responses or httpretty to mock based on the contract.
- Provider: Uses
requests to hit the live endpoint and asserts the response matches the contract schema.
Wait, "Contract Testing" usually implies tools like Pact. Writing your own contract verifier is complex. I will write a simplified "Pact-like" implementation or just use standard JSON Schema validation to demonstrate the concept without needing a running Pact Broker. This makes the example runnable immediately.
Revised Plan:
Create a "Contract Bank" class that loads shared fixtures.
Show Consumer and Provider tests using this bank.
- Scenario: User Service (Provider) and Order Service (Consumer).
- Bank: Contains
user_schema.json.
- Provider Test: Generates data, validates it against
user_schema.json.
- Consumer Test: Mocks the API response using
user_schema.json (or a specific example from the bank).
Actually, strict Contract Testing (CDC) usually involves the Consumer defining the need.
Let's flip it:
- Consumer defines a contract (interaction).
- Bank stores it.
- Provider retrieves and validates.
I will simulate this flow.
This design creates a centralized Test Fixtures Bank that acts as the source of truth for API contracts and mock data. This ensures that when Service A (Consumer) talks to Service B (Provider), they both use the exact same data structures.
We will implement this using Python (pytest), but the architecture applies to Node.js, Java, or Go.
Architecture
- The Bank (Shared Library): A dedicated package containing:
- Schemas: Pydantic models or JSON schemas defining the data shape.
- Factories: Functions to generate valid (and invalid) mock data.
- Contract Fixtures: Pre-canned responses for specific scenarios (e.g., "User not found", "Success").
1. Project Structure
Imagine a monorepo or a shared git submodule structure:
/project-root
├── /fixtures_bank <-- The Central Bank
│ ├── __init__.py
│ ├── schemas.py <-- The "Law" (Data Models)
│ └── factories.py <-- The "Printers" (Data Generators)
├── /services
│ ├── /consumer_service <-- Uses the bank for mocks
│ │ └── test_client.py
│ └── /provider_service <-- Uses the bank for validation
│ └── test_api.py
└── conftest.py <-- Shared pytest configuration
2. The Fixtures Bank (The Source of Truth)
First, we define what our services agree on. We use Pydantic for schema validation, as it serves as both documentation and a validation tool.
fixtures_bank/schemas.py
from pydantic import BaseModel, Field
from typing import Optional, List
from enum import Enum
# --- CONTRACT DEFINITIONS ---
class OrderStatus(str, Enum):
PENDING = "pending"
SHIPPED = "shipped"
FAILED = "failed"
class OrderModel(BaseModel):
"""The contract for an Order object."""
id: int
item: str
quantity: int = Field(ge=1, description="Quantity must be at least 1")
status: OrderStatus
class ErrorModel(BaseModel):
"""Standard error response contract."""
code: str
message: str
fixtures_bank/factories.py
Here we create helper functions to generate data. This prevents tests from hardcoding huge JSON blobs.
from .schemas import OrderModel, OrderStatus
def create_order_fixture(**kwargs) -> dict:
"""
Generates a valid order payload.
Override defaults by passing kwargs.
"""
defaults = {
"id": 1,
"item": "Widget",
"quantity": 10,
"status": OrderStatus.PENDING.value
}
# Merge defaults with overrides
payload = {**defaults, **kwargs}
# Validate against the schema before returning
# This ensures our factory itself is correct
OrderModel(**payload)
return payload
3. Consumer Service Test (Mocking)
The Consumer (e.g., a frontend or another microservice) uses the bank to mock the Provider's response. This ensures the Consumer is coding against the correct data structure.
services/consumer_service/test_client.py
import pytest
from unittest.mock import patch
from fixtures_bank.factories import create_order_fixture
from fixtures_bank.schemas import OrderModel
# Simulated function in your consumer code
def process_order_response(api_response):
# If the API changes 'item' to 'product_name', this will crash
return f"Processed order for {api_response['item']}"
def test_consumer_honors_contract():
# 1. Get standard data from the Bank
mock_data = create_order_fixture(quantity=5)
# 2. In a real test, you would mock 'requests.get' to return this data
# Here we simulate processing that data
result = process_order_response(mock_data)
assert "Widget" in result
# 3. Optional: Validate the mocked data strictly (Defensive Mocking)
# This fails the test if the fixture bank produces bad data
validated = OrderModel(**mock_data)
assert validated.quantity == 5
4. Provider Service Test (Validation)
The Provider (the API itself) uses the bank to ensure it is actually outputting what it promised.
services/provider_service/test_api.py
from fastapi.testclient import TestClient
# Assuming main.py has the FastAPI app
from main import app
from fixtures_bank.schemas import OrderModel, ErrorModel
client = TestClient(app)
def test_api_get_order_returns_valid_contract():
# Call the actual API
response = client.get("/orders/1")
assert response.status_code == 200
# THE CONTRACT TEST:
# Parse the raw JSON response through the Central Bank Schema.
# If the API adds a field that breaks the type, this raises ValidationError.
validated_data = OrderModel(**response.json())
assert validated_data.id == 1
def test_api_error_format():
response = client.get("/orders/9999") # Non-existent
assert response.status_code == 404
# Ensure errors match the bank's standard error format
ErrorModel(**response.json())
5. Negative Testing (Breaking the Contract)
A good bank holds "counterfeit" money for testing fraud detection. We should test that our system rejects invalid contracts.
fixtures_bank/factories.py (Addition)
def create_invalid_order_fixture():
"""Generates data that violates the schema (e.g., negative quantity)."""
return {
"id": 1,
"item": "Bad Widget",
"quantity": -5, # Invalid
"status": "pending"
}
services/provider_service/test_validation.py
import pytest
from fixtures_bank.factories import create_invalid_order_fixture
from fixtures_bank.schemas import OrderModel
from pydantic import ValidationError
def test_system_rejects_invalid_contract():
invalid_data = create_invalid_order_fixture()
# We expect Pydantic to raise an error because quantity is < 1
with pytest.raises(ValidationError):
OrderModel(**invalid_data)
Summary of Benefits
- Single Source of Truth: If the API changes, you update
schemas.py in the bank. CI/CD immediately fails for the Consumer if they rely on the old structure.
- Decoupled Development: Frontend teams can use
factories.py to build mocks before the Backend team has finished the API.
- Living Documentation: The Pydantic models in the bank describe the API more accurately than a static wiki page.