The user wants an integration test virtualization lab that supports three specific things:
Contract Mocks: The ability to simulate external services or dependencies based on predefined contracts (like OpenAPI/Swagger or gRPC definitions) to ensure interaction compliance.
Dependency Replay: The ability to record interactions with real dependencies and replay them during testing to ensure determinism and isolation without actually hitting external systems.
Fixtures: The management of test data and state setups.
The output should be a "composition" of such a lab. This implies code, architecture, or a detailed plan. Given the complexity, a conceptual framework implemented in code (likely Python or TypeScript/Node.js are popular for this, but Python has pytest which is great for fixtures, and libraries like responses or pretenders are common) is best. I will choose Python because pytest provides a world-class fixture system out of the box, and libraries like WireMock (via docker) or schemathesis fit well.
However, to make it a "Lab" (a runnable example), I need to structure it as a project.
Key Components:
The System Under Test (SUT): A simple microservice.
The Virtualization Layer:
Mocking: Using something like WireMock or a lightweight Python mock server.
Replay: Interceptors (e.g., VCR.py or a custom middleware).
Fixtures: Pytest fixtures.
The Contracts: OpenAPI specs.
Plan:
Architecture Diagram/Description: Briefly explain how the pieces fit.
Project Structure: File tree.
Contracts (The Source of Truth): An OpenAPI YAML.
The SUT (Service under test): A FastAPI or Flask app.
The Test Lab (Implementation):
Fixture Manager: Loading data.
Virtualization Service: A class that handles spinning up mocks or loading tapes (replay).
Contract Enforcer: A wrapper around the mock that validates requests against the schema.
The Integration Test: Demonstrating the usage.
Refining the "Virtualization Lab" concept:
Instead of just writing a test file, I will design a VirtualizationLab class. This class acts as a context manager for the test environment. It will handle:
Setting up the mock server.
Injecting recorded interactions (Replay).
Validating calls against a contract (Contract Mocks).
Tools Selection:
Language: Python (Great for prototyping this logic).
Framework: Pytest.
HTTP Client/Server:httpx and fastapi.
Mocking/Virtualization:wiremock is industry standard but hard to embed in a single script. mock (standard lib) or responses is easier for a self-contained example. However, to truly capture "Replay" and "Contracts", a proxy-like structure is better.
Replay:VCR.py is the standard here. It records to cassettes (YAML/JSON).
Contracts:schemathesis is good for running tests, but for mocking based on a contract, prism (Stoplight) or wiremock are better. For this code generation, I will build a lightweight "VirtualService" wrapper that simulates this behavior to make the code portable and self-contained without needing Docker.
Drafting the Code Structure:
contracts/: Store API specs.
cassettes/: Store recorded interactions (Replay).
fixtures/: Store DB seed data or test states.
src/: The SUT.
tests/: The lab.
Feature 1: Contract Mocks
I need a mock that says: "If a request comes in matching the contract, return X."
Ideally, it also validates that the request matches the contract schema.
Feature 2: Dependency Replay
This implies: "Don't hit the real service. Load cassette.json and return what the real service returned last time."
Feature 3: Fixtures
Standard pytest fixtures. I'll create a "World" fixture that sets up the state.
Let's synthesize into a cohesive example.
I'll create a VirtualizationLab python package/module that can be used in tests.
The Lab Manager: A context manager.
The Mock: A mock object that draws from a "Replay Tape" but validates against a "Contract".
Let's build a simplified but powerful version using pytest + responses (for HTTP mocking) + jsonschema (for contract validation).
Step-by-Step Implementation Plan:
Define the Contract (OpenAPI/JSON Schema).
Implement the Virtualization Engine:
Record/Tape: A class to hold replay data.
Validator: Checks requests/responses against the Contract.
Mock: Intercepts calls.
Define Fixtures: Create reusable test data components.
The Test Case: Wire it all together.
Self-Correction/Refinement:
The prompt asks for a "Virtualization Lab." This sounds like infrastructure. I should present it as a design pattern implementation. I will provide a complete Python project skeleton.
SUT: A service that calls a "Payment Gateway".
Contract: Payment Gateway spec.
Replay: Recorded successful payment responses.
Code Logic:
The VirtualizationLab class will take a contract file.
It will expose a replay(fixture_name) method.
It will expose a verify() method to ensure all calls matched the contract.
Let's write the code.
File:conftest.py (The Lab setup)
File:contracts.py (The Schema definitions)
File:replay_tapes.py (The recorded interactions)
File:test_integration.py (The actual test)
I will write the solution as a Python-based framework named virtu_lab.
Key classes:
Contract: Parses OpenAPI/JSON Schema.
ReplayTape: Loads recorded interactions.
VirtualService: The mock that combines Contract validation + Replay data.
Let's refine the "Dependency Replay" part.
Often this means "Record mode" vs "Replay mode". I will implement "Replay mode" (reading from a fixture) for the test stability.
The "Lab" Concept:
It's a fixture itself.
python
@pytest.fixture
def lab():
with VirtualizationLab(services=[...]) as lab:
yield lab
Let's go.
This solution designs a Virtualization Lab framework in Python. It creates a structured environment for integration testing that decouples your application logic from external dependencies (APIs, Databases).
The framework implements:
Contract Mocks: Ensures the service behaves according to a schema (OpenAPI/JSON Schema) and returns mocked responses.
Dependency Replay: Intercepts calls and returns pre-recorded "cassettes" (fixtures) of real interactions.
Fixtures: Manages the stateful loading of test data.
Project Structure
text
virtualization_lab/
├── contracts/
│ └── payment_service.json # JSON Schema definition of the external dependency
├── cassettes/
│ └── success_payment.json # Recorded interaction (Replay Fixture)
├── lab.py # The Virtualization Lab Framework
├── service.py # The System Under Test (SUT)
└── test_integration.py # The Integration Test Suite
1. The Contract Definition
This file represents the "Truth" of the external API structure.
This test uses the Lab to verify the PaymentProcessor without touching the real network.
File:test_integration.py
python
import pytest
from lab import VirtualizationLab, LabSession, ContractViolationError
from service import PaymentProcessor
import json
@pytest.fixture
def lab():
# Initialize the lab and load contracts
vl = VirtualizationLab()
vl.load_contract('payment_contract', 'contracts/payment_service.json')
return vl
def test_successful_payment_replay(lab):
"""
Test Case: Dependency Replay
Scenario: We want to assert logic against a known successful interaction (Cassette).
"""
session = LabSession(lab)
processor = PaymentProcessor("http://external-bank")
# Start the virtualization session
with session.setup_replay('payment_contract', 'cassettes/success_payment.json'):
status, body = processor.charge(100.0, "USD")
assert status == 200
assert body['status'] == 'approved'
assert body['transaction_id'] == 'txn_12345'
def test_contract_violation_on_bad_input(lab):
"""
Test Case: Contract Mocking
Scenario: The SUT sends invalid data. The Lab should catch this before 'sending'.
"""
session = LabSession(lab)
processor = PaymentProcessor("http://external-bank")
# We are strictly enforcing the contract here
with session.setup_replay('payment_contract', 'cassettes/success_payment.json'):
# We expect the lab to raise an error because we are passing a string
# where the contract expects a number for 'amount'
with pytest.raises(ContractViolationError) as excinfo:
processor.charge("one-hundred", "USD") # Invalid payload
assert "Request violates contract" in str(excinfo.value)
def test_dynamic_mock_generation(lab):
"""
Test Case: Pure Mocking
Scenario: We don't have a cassette, we just want to stub the network quickly.
"""
session = LabSession(lab)
processor = PaymentProcessor("http://external-bank")
with session.setup_mock('payment_contract'):
status, body = processor.charge(500.0, "EUR")
assert status == 200
assert body['status'] == 'mocked_success'
How It Works
Isolation: The VirtualizationLab patches urllib.request.urlopen. When the PaymentProcessor tries to make a real HTTP request, it is intercepted by the side_effect method inside mock_dependency.
Contract Validation: Before returning a response, _validate_request checks the JSON payload being sent by the SUT against the JSON Schema in contracts/payment_service.json. If the SUT sends bad data, the test fails immediately.
Replay: If the validation passes, the lab looks at the cassettes/success_payment.json file and returns the static response found there, simulating the external bank server.
import json
import jsonschema
from unittest.mock import patch, MagicMock
from http.client import HTTPConnection
import urllib.request
class ContractViolationError(Exception):
pass
class VirtualizationLab:
def __init__(self):
self.active_mocks = {}
self.fixtures = {}
def load_contract(self, name, filepath):
"""Loads a contract definition."""
with open(filepath, 'r') as f:
self.fixtures[name] = json.load(f)
def load_cassette(self, filepath):
"""Loads a recorded interaction (Replay mode)."""
with open(filepath, 'r') as f:
return json.load(f)
def _validate_request(self, contract, request_body):
"""Validates outgoing request against Contract Mock."""
try:
jsonschema.validate(instance=request_body, schema=contract['request_schema'])
except jsonschema.exceptions.ValidationError as e:
raise ContractViolationError(f"Request violates contract: {e.message}")
def mock_dependency(self, contract_name, mode='replay', cassette_path=None):
"""
Activates the virtualization for a dependency.
Mode 'replay': Uses cassette files.
Mode 'mock': Generates dynamic responses based on contract.
"""
contract = self.fixtures.get(contract_name)
if not contract:
raise ValueError(f"Contract {contract_name} not found.")
def side_effect(*args, **kwargs):
# 1. Intercept the request
# Note: This example patches urllib for simplicity.
# In a real lab, you might patch 'requests' or 'httpx' client directly.
url = args[0]
# 2. Contract Enforcement
# Validate that the SUT is sending what it promised to send
if 'data' in kwargs:
self._validate_request(contract, json.loads(kwargs['data']))
# 3. Response Generation (Replay vs Mock)
if mode == 'replay':
if not cassette_path:
raise ValueError("Replay mode requires a cassette_path")
tape = self.load_cassette(cassette_path)
resp_mock = MagicMock()
resp_mock.read.return_value = json.dumps(tape['response']['body']).encode('utf-8')
resp_mock.status = tape['response']['status_code']
return resp_mock
elif mode == 'mock':
# Generate a generic 200 OK based on contract logic
resp_mock = MagicMock()
resp_mock.read.return_value = json.dumps({"status": "mocked_success"}).encode('utf-8')
resp_mock.status = 200
return resp_mock
# Patching the standard library urllib.request.urlopen as an example transport layer
return patch('urllib.request.urlopen', side_effect=side_effect)
# Context manager for easy usage
class LabSession:
def __init__(self, lab):
self.lab = lab
def setup_replay(self, contract, cassette):
return self.lab.mock_dependency(contract, mode='replay', cassette_path=cassette)
def setup_mock(self, contract):
return self.lab.mock_dependency(contract, mode='mock')