We are going to design an integration test virtualization lab that supports:
- Contract Mocks: Simulating external services based on their contracts (e.g., OpenAPI, GraphQL schema, etc.)
- Dependency Replay: Capturing and replaying interactions with dependencies (like HTTP, databases, etc.) to make tests deterministic and fast.
- Fixtures: Predefined data and states for setting up test environments.
We'll design a modular system that can be used in integration tests.
Components:
- Virtualization Lab: A central coordinator that sets up and tears down the virtual environment.
- Contract Mock Server: A server that mocks external services based on their contracts. We can use a tool like WireMock, MockServer, or a custom one.
- Dependency Replayer: A component that records and replays interactions (like HTTP requests/responses, database queries) for dependencies.
- Fixture Manager: Manages the loading and application of fixtures (e.g., database seeds, configuration files).
Steps for an integration test:
- Start the Virtualization Lab.
- Configure and start the Contract Mock Server with the necessary contracts.
- The system under test (SUT) is started (if it's an application) or we are about to call it.
- The Dependency Replayer might be set to "record" mode for the first run to capture interactions, then "replay" mode for subsequent runs.
Alternatively, we might have pre-recorded interactions (replay files) that we load.
- Apply fixtures (e.g., load test data into the database).
- Run the test (exercise the SUT).
- Verify interactions (if in replay mode, we check that the SUT made the same requests as in the recording).
- Tear down: stop the SUT, stop the mock server, clean up fixtures, etc.
We'll design an abstract base class for the VirtualizationLab that can be extended for specific technologies.
Let's assume we are testing a web application that depends on:
- A payment gateway (external HTTP API)
- A user database (PostgreSQL)
- An internal inventory service (HTTP)
We'll use:
- WireMock for HTTP contract mocks.
- For database dependency replay, we might use a tool that records SQL queries and responses, or we can mock at the driver level.
Alternatively, we can use a database fixture (snapshot) and then check that the same queries are made (but that's hard because queries might have parameters).
Another approach: use a proxy for the database that records and replays. But for simplicity, we might just use fixtures for the database and verify state changes.
However, note: dependency replay for databases is tricky because of state. We might record the sequence of queries and their results, but the state of the database might change.
Alternative for database: we can use a fixture (initial state) and then after the test, we verify the state (by querying). But that's not exactly replaying the dependency interaction, it's more about setting up the environment.
Let's clarify:
- Contract Mocks: For external HTTP services, we define the contract (request/response) and the mock server returns the predefined responses.
- Dependency Replay: For dependencies that are stateful (like databases) we might not be able to replay in the same way. Instead, we can use a fixture to set the state and then verify that the expected queries were made (by intercepting the driver) and that the state changed as expected.
We might decide to split:
a) For stateless HTTP services: use contract mocks (WireMock) with predefined stubs.
b) For stateful dependencies (like databases): use fixtures to set up the state, and then after the test, verify the state (or the queries made).
However, if we want to record and replay the exact database interactions (including the results of each query), we can use a proxy that sits between the application and the database and records the queries and their results. Then in replay mode, it returns the recorded results without going to the database.
But note: the database might be updated (INSERT/UPDATE/DELETE). In that case, we cannot simply replay because the state changes. So we might need to record the entire session and then replay exactly the same sequence, but that would require the database to be in the same state as at the beginning of the recording.
This is complex. Alternatively, we can:
-
For tests that only read from the database: we can record the queries and their results (from a known initial state) and then replay without a real database.
-
For tests that write: we can record the writes and then in replay mode we don't actually write? But then the application might rely on the write for subsequent operations.
Given the complexity, maybe we limit dependency replay to stateless dependencies (like HTTP) and use fixtures for stateful ones.
Let's adjust:
We'll focus on:
- Contract Mocks: for external HTTP/HTTPS services (using WireMock).
- Dependency Replay: for internal HTTP services (that we control) we can record and replay? But note: if we are testing the integration of multiple services, we might want to record the entire interaction and then replay without starting the other services.
Actually, the term "dependency replay" might be broader. We can think of it as:
- Recording the interactions with a dependency (including the request and the response) and then in replay mode, we return the recorded response for a matching request.
This can be done at the HTTP level (with a proxy) or at the database level (with a proxy that records and replays results).
But for the database, if we are going to change the state, we cannot replay the same responses for queries that expect the updated state.
So perhaps we design two modes for stateful dependencies:
- Record: run the test against the real dependency and record the interactions (requests and responses). Then, for replay, we use the recorded responses and do not touch the real dependency.
This requires that the test is deterministic in the sense that the same initial state and the same sequence of operations produce the same sequence of interactions (with the same requests and responses). But if the dependency is stateful and the test changes the state, then the responses in the recording are for that state. In replay, we are not changing the state, so if the test expects to see the updated state in subsequent queries, it will fail.
Therefore, for stateful dependencies, we might not be able to use replay in the same way. Instead, we use fixtures to set up the state and then let the test run against the real dependency (or a mock that is aware of the state?).
Alternatively, we can record the entire state of the dependency (like a database dump) and then for replay, we restore that state and then run the test, but then we are not replaying the interactions, we are resetting the state.
Given the complexity, let's define:
-
Contract Mocks: for stateless HTTP services (or stateful but we only care about the contract, not the state). We can use WireMock with stubs that return fixed responses.
-
Dependency Replay: for dependencies that we want to record and replay exactly (like HTTP calls) and that are not stateful in a way that would break replay. For example, if we have an internal service that we want to isolate, we can record its responses and then replay without starting it.
-
Fixtures: for setting up the state of stateful dependencies (like databases) and for providing test data.
We might not use dependency replay for databases, but we can use a database fixture (a known state) and then after the test, we verify the state.
So, in the lab:
- We'll have a ContractMockServer (using WireMock) for HTTP services.
- We'll have a DependencyReplayer that can record and replay HTTP interactions (maybe using a proxy that the SUT uses). But note: if we are already using a contract mock server for some dependencies, we don't need to replay those. The dependency replayer might be for dependencies that we don't have a contract for, or for internal services that we want to capture without writing contracts.
Alternatively, we can use the same WireMock for both contract mocks and dependency replay? WireMock can record and replay.
WireMock has a feature called "recording" where you can point it at a real service and it will record the interactions and then you can replay them.
So we can use WireMock for both:
-
For known contracts: we write the stubs (or generate from contract) and load them.
-
For unknown contracts or for internal services: we start WireMock in recording mode, run the test against the real service, then stop recording and then we have a set of recorded interactions that we can replay.
But note: the contract mocks are usually predefined (from a contract file) and the dependency replay is recorded from a real run.
We can design:
-
The VirtualizationLab will manage WireMock instances (maybe multiple for different services).
-
We can have a configuration for each dependency:
type: "contract_mock" -> we load stubs from a contract file (or directory of stubs)
type: "replay" -> we have a recorded mapping file (from a previous recording)
-
For fixtures, we'll have a FixtureManager that can load data into the database (using SQL scripts, or using an ORM, etc.)
Steps:
- Start the VirtualizationLab.
- For each dependency that is a contract mock: start a WireMock instance (or use a shared one) and load the stubs from the contract.
- For each dependency that is a replay: start a WireMock instance and load the recorded mappings (and set it to replay mode, i.e., not record).
- Apply fixtures to the database (and possibly other stateful systems).
- Start the SUT (if it's an application) or prepare the function to be tested.
- Run the test.
- Optionally, if we are in record mode for some dependencies, we save the recordings.
- Tear down.
But note: we might want to run the same test in both record and replay mode? Usually, we record once and then replay many times.
We can design the lab to have a mode:
-
"record": for dependencies that are set to replay, we actually record (if we haven't recorded before) and then save the recording for future replay.
-
"replay": use the existing recordings.
Alternatively, we can have two different configurations: one for recording and one for replaying.
Implementation:
We'll create a class VirtualizationLab that:
- Takes a configuration (list of dependencies with their types and sources).
- Has a method
start() that sets up the mocks and applies fixtures.
- Has a method
stop() that tears down.
We'll have a Dependency abstract class and two subclasses: ContractMockDependency and ReplayDependency.
For WireMock, we can run one instance per dependency (if they are on different ports) or we can use one instance and use different mappings (but then we need to map by host). Since each dependency might have its own base URL, we can run separate WireMock instances.
Alternatively, we can run one WireMock instance and use the scope feature? But that's for matching by host. We can set up the SUT to use the WireMock instance's base URL for each dependency.
We'll assume we are running one WireMock per dependency for simplicity.
Steps for setting up a dependency:
-
For contract mock: we start WireMock on a port, then load the stubs from the contract (which might be a JSON file or a directory of JSON files). We also might need to set up the base URL for the dependency (so the SUT uses the WireMock URL).
-
For replay: we start WireMock on a port, then load the recorded mappings (from a file). We also set WireMock to not record (so it uses the mappings).
We might also want to verify that in replay mode, the SUT makes exactly the same requests as in the recording? We can use WireMock's verification features.
But note: in replay mode, WireMock will only respond to requests that have a mapping. If the SUT makes a request that is not in the recording, it will fail (get a 404). That might be what we want.
For fixtures, we'll have a FixtureManager that can load fixtures into the database. The fixture might be a SQL script, or a set of JSON files that we insert.
We'll design the VirtualizationLab to be used in a test framework (like pytest, JUnit, etc.). We can create a context manager (in Python) or a rule (in JUnit) to automatically start and stop.
Example in Python (using pytest):
We create a fixture that sets up the lab:
import pytest
from virtualization_lab import VirtualizationLab, DependencyConfig, ContractMockConfig, ReplayConfig
@pytest.fixture(scope="module")
def virtualization_lab():
config = [
DependencyConfig(
name="payment_gateway",
type="contract_mock",
config=ContractMockConfig(contract_file="contracts/payment_gateway.json")
),
DependencyConfig(
name="inventory_service",
type="replay",
config=ReplayConfig(recording_file="recordings/inventory_service.json")
)
]
lab = VirtualizationLab(config)
lab.start()
yield lab
lab.stop()
Then in a test:
def test_order_creation(virtualization_lab):
# The SUT (order service) is configured to use the virtualization_lab.get_url("payment_gateway") for payment gateway
# and virtualization_lab.get_url("inventory_service") for inventory.
# Apply fixtures to the database? Maybe the lab does that on start.
# Run the test: create an order.
order = create_order(...)
# Verify that the order was created and that the payment was processed (via the mock) and inventory was updated (via replay).
# Optionally, verify interactions with the mocks:
virtualization_lab.verify("payment_gateway", times=1) # that payment gateway was called once
Implementation of VirtualizationLab:
We'll use wiremock Python package? Or we can run the WireMock standalone server and control it via its admin API.
We'll assume we are using the standalone WireMock server and we start it as a subprocess for each dependency? That might be heavy. Alternatively, we can run one WireMock and use multiple ports? But then we have to manage multiple mappings.
Actually, WireMock can run multiple instances on different ports, but we have to start each one separately.
Alternatively, we can run one WireMock and use the scope feature to match by host. But then we need to configure the SUT to use different hostnames (and we have to map those hostnames to the same WireMock instance). That's possible by setting up the SUT's configuration to use different base URLs that point to the same WireMock server but with different host headers? Actually, WireMock can match on the host header.
We can set up:
- For dependency A: base URL = http://localhost:8080 (and set the Host header to 'dependency-a.example.com')
- For dependency B: base URL = http://localhost:8080 (and set the Host header to 'dependency-b.example.com')
But then we have to configure the SUT to use the same base URL for both but with different host headers? That might not be feasible if the SUT uses the base URL as the host.
Alternatively, we can run multiple WireMock instances on different ports.
Let's run multiple WireMock instances.
Steps for starting a WireMock for a dependency:
- Find an available port (or use a fixed one for each dependency in a test environment).
- Start WireMock as a subprocess (or use the Java API? but we are in Python). We can use the
wiremock standalone JAR.
We'll assume we have the WireMock JAR and Java installed.
We'll create a WireMockInstance class that:
- Starts the server on a given port.
- Stops the server.
- Loads stubs from a file or directory.
- Can switch between record and replay mode? Actually, for contract mocks we just load stubs and it's in mock mode. For replay, we load the recorded mappings and set the server to not record.
We'll use the WireMock admin API to load mappings and to configure recording.
But note: for replay, we are just loading the mappings and then the server will return the recorded responses.
For recording, we would configure the server to record to a file and then run the test against the real service (by setting up the SUT to use the WireMock as a proxy? Actually, WireMock can record by acting as a proxy to the real service).
However, in our design, we are not necessarily using WireMock as a proxy. For contract mocks, we are stubbing. For replay, we are using recorded mappings.
But what if we want to record? Then we need to point the SUT to WireMock and then WireMock will forward the requests to the real service and record the responses. But then we are not mocking, we are proxying.
We can have a mode for a dependency: "record" (which means we start WireMock as a proxy to the real service and record the interactions) and then after the test, we save the mappings.
Then, for the same dependency, we can change the type to "replay" and load the saved mappings and then the SUT will use the recorded responses.
So we can have:
-
ContractMock: we provide stubs (from contract) and WireMock returns them without going to the real service.
-
Record: we start WireMock as a proxy to the real service (we need to know the real URL) and record the mappings. Then we save the mappings.
-
Replay: we load the mappings and WireMock returns them (without going to the real service).
But note: in record mode, we are actually calling the real service. That might be slow and non-deterministic. We only do it once to create the recording.
So we can design:
DependencyConfig:
name: string
type: "contract_mock" | "record" | "replay"
config:
for contract_mock: contract_file (or directory)
for record: real_url (the real service URL), recording_file (where to save)
for replay: recording_file (to load)
Steps for the lab:
For each dependency:
if type is contract_mock:
start WireMock on a port (if not already started for this dependency? we start one per dependency)
load stubs from contract_file (or directory)
if type is record:
start WireMock on a port
configure it as a proxy to real_url and set recording to recording_file
then, during the test, the SUT will use this WireMock, which will forward to the real service and record.
after the test, we stop the recording and save the mappings? Actually, WireMock records continuously to a file? We can configure it to record to a file and then we have the file.
But note: we might want to record only for this test and then use the recording for future tests. So we run the test in record mode once, then change the config to replay for future tests.
if type is replay:
start WireMock on a port
load the mappings from recording_file (which was saved during a record run)
However, note that in record mode, we are using the real service, so the test might be flaky if the real service is down. We only do it when we want to update the recordings.
So we can have two sets of configs: one for recording (temporary) and one for replay (stable).
We'll design the VirtualizationLab to be agnostic of the mode? Actually, the mode is per dependency.
We'll create a Dependency base class and then:
ContractMockDependency loads stubs.
RecordDependency sets up WireMock as a proxy and starts recording.
ReplayDependency loads recorded mappings.
But note: the RecordDependency might need to know the real URL and the recording file.
We'll design:
class DependencyConfig:
name: str
type: str
config: dict
class VirtualizationLab:
def __init__(self, dependencies_config: List[DependencyConfig]):
self.dependencies = []
for config in dependencies_config:
if config.type == "contract_mock":
dep = ContractMockDependency(config)
elif config.type == "record":
dep = RecordDependency(config)
elif config.type == "replay":
dep = ReplayDependency(config)
else:
raise ValueError(f"Unknown dependency type: {config.type}")
self.dependencies.append(dep)
def start(self):
for dep in self.dependencies:
dep.start()
def stop(self):
for dep in self.dependencies:
dep.stop()
def get_url(self, name: str) -> str:
for dep in self.dependencies:
if dep.name == name:
return dep.base_url
raise KeyError(f"Dependency {name} not found")
def verify(self, name: str, **kwargs):
dep = self.get_dependency(name)
dep.verify(**kwargs)
Each Dependency subclass will have:
__init__(self, config)
start(): start the underlying mock server (WireMock) and configure it.
stop(): stop the server.
base_url: the URL that the SUT should use for this dependency.
verify(**kwargs): verify that the expected interactions happened (using WireMock's verification).
For ContractMockDependency and ReplayDependency, we are just loading mappings and then we can verify that the SUT made requests that match those mappings (or that were recorded). But note: in replay mode, the mappings are fixed and we can verify that the SUT made the same requests as in the recording? Actually, WireMock will only respond if the request matches a mapping. So if the SUT makes a request that doesn't match, it will get a 404. That's one form of verification.
But we might want to verify the number of times a particular endpoint was called. We can use WireMock's verification.
For RecordDependency, we are recording and we might want to verify that the SUT made the same requests as in the recording? Actually, in record mode, we are not verifying against a recording, we are just recording for the first time. We might skip verification in record mode? Or we can verify that the SUT made at least one request to each endpoint we expect? That's up to the test.
We can have:
-
In record mode: we don't have a recording to verify against, but we can verify that the SUT made some requests (using WireMock's verification that at least one request was made).
-
In replay mode: we can verify that the SUT made exactly the same requests as in the recording (by checking the count and maybe the order?).
WireMock's verification can check the count and also the request details (method, URL, body, headers). So we can do:
dep.verify(method="POST", url="/pay", times=1)
But in replay mode, we might have multiple requests in the recording. We might want to verify the entire sequence? That's more complex.
Alternatively, we can rely on the fact that in replay mode, if the SUT makes a request that doesn't match any mapping, it will fail. And if it makes the same requests as in the recording, then the test will pass. But we might want to verify the exact number of calls for each endpoint.
We can design the verify method to take the same parameters as WireMock's verification.
Now, for the database fixtures:
We'll have a separate FixtureManager that is not part of the dependency. It might be configured separately.
We can extend the VirtualizationLab to also manage fixtures:
class VirtualizationLab:
def __init__(self, dependencies_config, fixture_manager=None):
...
self.fixture_manager = fixture_manager
def start(self):
for dep in self.dependencies:
dep.start()
if self.fixture_manager:
self.fixture_manager.apply()
def stop(self):
if self.fixture_manager:
self.fixture_manager.cleanup()
for dep in self.dependencies:
dep.stop()
The FixtureManager might have:
apply(): load fixtures (e.g., run SQL scripts, insert JSON data, etc.)
cleanup(): remove the fixtures (or truncate tables, etc.)
But note: the fixtures might be for the database only, or for other stateful systems. We can make it generic.
Alternatively, we can have the lab start the database and then apply fixtures? But the database might be an external dependency too? In integration testing, the database might be a real one or a container.
We might already have a database running (maybe in a container) and then we just need to load the fixtures.
We'll assume that the database is already running (or started by the test setup) and the fixture manager knows how to connect and load/cleanup.
Example:
class SqlFixtureManager:
def __init__(self, db_url, fixture_files):
self.db_url = db_url
self.fixture_files = fixture_files
def apply(self):
for file in self.fixture_files:
run_sql_script(self.db_url, file)
def cleanup(self):
# run cleanup scripts or truncate tables
pass
Now, let's think about the SUT. The SUT must be configured to use the URLs provided by the lab for its dependencies.
We can have the lab return the base URL for each dependency, and then the test must configure the SUT to use these URLs.
Alternatively, we can have the lab set environment variables or update configuration files for the SUT.
We'll leave that to the test.
Now, let's write some pseudo-code for the ContractMockDependency:
class ContractMockDependency(Dependency):
def __init__(self, config):
self.name = config.name
self.contract_file = config.config.contract_file
self.port = self._find_free_port()
self.base_url = f"http://localhost:{self.port}"
self.wiremock_process = None
def start(self):
# Start WireMock server on self.port
self.wiremock_process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port)
])
# Wait for server to start
time.sleep(5) # better to use a health check
# Load stubs from contract_file
# The contract_file might be a directory of JSON files or a single file.
# We use the WireMock admin API to import the mappings.
# Alternatively, we can start WireMock with the `--root-dir` option pointing to a directory that contains the mappings.
# But we want to load specific contracts.
# Let's assume we have a directory of mappings for this dependency.
# We can copy the contract_file (which is a directory) to a temporary directory and then start WireMock with that as the root?
# Or we can use the admin API to create mappings.
# We'll use the admin API:
for mapping_file in Path(self.contract_file).glob("*.json"):
with open(mapping_file) as f:
mapping = json.load(f)
# POST to http://localhost:port/__admin/mappings
response = requests.post(
f"{self.base_url}/__admin/mappings",
json=mapping
)
response.raise_for_status()
def stop(self):
if self.wiremock_process:
self.wiremock_process.terminate()
self.wiremock_process.wait()
def verify(self, **kwargs):
# Use WireMock's verification API.
# We'll construct a verification request.
# Example: verify that a POST to /pay was called exactly once.
# We can pass: method, url, body, headers, times
# We'll build a verification JSON and send to /__admin/requests/count
# But note: WireMock's verification is done by querying the requests log.
# We can do:
# GET /__admin/requests?method=POST&url=/pay
# and then check the count.
# Alternatively, we can use the `verify` endpoint (POST /__admin/requests/count) but that's for verifying that a request was made exactly N times? Actually, the admin API doesn't have a direct verify endpoint.
# We'll just check the requests log.
# Build query parameters for the requests log.
params = {}
if 'method' in kwargs:
params['method'] = kwargs['method']
if 'url' in kwargs:
params['url'] = kwargs['url']
if 'body' in kwargs:
params['body'] = kwargs['body']
# ... and so on for headers? But note: the requests log in WireMock doesn't store headers by default? Actually, it does.
# We'll get the request log and filter by the given criteria and then check the count.
response = requests.get(f"{self.base_url}/__admin/requests", params=params)
response.raise_for_status()
requests_log = response.json()['requests']
count = len(requests_log)
expected_times = kwargs.get('times', 1)
if count != expected_times:
raise AssertionError(f"Expected {expected_times} requests matching {kwargs}, but got {count}")
This is a simplified version. We might want to match more precisely (like body patterns, headers, etc.)
For ReplayDependency and RecordDependency, the start method will be different.
For ReplayDependency:
- We start WireMock on a port.
- We load the recorded mappings (from a JSON file that contains an array of mapping objects). We can use the same admin API to create mappings.
For RecordDependency:
- We start WireMock on a port.
- We configure it as a proxy to the real URL (from config) and set the recording file.
- We might not need to load any initial mappings.
But note: when recording, WireMock will record the requests and responses and save them to a file. We can then use that file for replay.
Steps for RecordDependency.start():
class RecordDependency(Dependency):
def __init__(self, config):
self.name = config.name
self.real_url = config.config.real_url
self.recording_file = config.config.recording_file
self.port = self._find_free_port()
self.base_url = f"http://localhost:{self.port}"
self.wiremock_process = None
def start(self):
# Start WireMock with proxy settings and recording.
# We can use the --proxy-all option to forward all requests to the real_url.
# And we can use the --record-mappings option to save the mappings to a file.
# But note: the --record-mappings option is for recording to a file? Actually, WireMock can record mappings to a file.
# We'll start WireMock with:
# --port <port>
# --proxy-all <real_url>
# --record-mappings <recording_file>
self.wiremock_process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port),
"--proxy-all", self.real_url,
"--record-mappings", self.recording_file
])
time.sleep(5)
Then, after the test, we have a recording file that we can use for replay.
However, note: the recording file will contain mappings for all the requests that were made. But it might contain requests that we don't want to mock? We might want to filter.
Also, the recorded mappings might have dynamic parts (like timestamps) that we need to handle? WireMock records the exact request and response, so if the response has a dynamic field, we might need to adjust the mapping to use matching patterns.
We might need to edit the recorded mappings to make them more robust? That's a separate problem.
Given the complexity, we might just record and then use the recorded mappings as is, and hope that the SUT makes the same requests (with the same exact bodies, etc.) in replay.
But note: the SUT might generate dynamic data (like timestamps, UUIDs). Then the recorded mappings will have those specific values and the replay will fail.
So we might need to adjust the recorded mappings to use patterns (like "\\d+" for numbers) or use WireMock's matching features.
This is a common problem with record and replay. We might need to post-process the recorded mappings to replace dynamic values with patterns.
We can leave that as an exercise for the user.
Alternatively, we can use contract mocks for everything and avoid record and replay? But then we have to write the contracts (stubs) manually.
The idea of record and replay is to avoid writing stubs manually.
So we'll provide the record and replay feature, but note the limitations.
Now, for the ReplayDependency, we just load the recorded mappings:
class ReplayDependency(Dependency):
def __init__(self, config):
self.name = config.name
self.recording_file = config.config.recording_file
self.port = self._find_free_port()
self.base_url = f"http://localhost:{self.port}"
self.wiremock_process = None
def start(self):
# Start WireMock on the port without any special options.
self.wiremock_process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port)
])
time.sleep(5)
# Load the recorded mappings.
# The recording_file is a JSON file that contains an array of mapping objects.
with open(self.recording_file) as f:
mappings = json.load(f)
for mapping in mappings:
# Each mapping is a WireMock mapping object.
response = requests.post(
f"{self.base_url}/__admin/mappings",
json=mapping
)
response.raise_for_status()
This is a simplified version. The recorded mappings might have been saved by WireMock in a specific format? Actually, when you record with WireMock, it saves the mappings in a file that is an array of mapping objects, and also saves the response bodies in separate files? Wait, the --record-mappings option saves the mappings and the response bodies in a directory? Let me check.
According to WireMock documentation, when you run with --record-mappings, it saves the mappings (as JSON) and the response bodies (as files) in the specified directory.
So the recording_file might be a directory? Actually, the option --record-mappings takes a directory? Let me check:
From the WireMock docs:
--record-mappings <directory>
Record all mappings to the specified directory.
So we need to pass a directory. Then, in the mappings, the response body is stored in a file and the mapping has a "bodyFileName" instead of "body".
Therefore, when we load the mappings, we need to also copy the response body files? Actually, WireMock expects the response body files to be in a specific location relative to the mappings.
We can start WireMock with the --root-dir set to the recording directory? Then it will find the mappings and the response body files.
Alternatively, we can start WireMock and then use the admin API to create mappings that have body (if the response body is small and recorded inline) or bodyFileName (if it's in a file). And then we need to make sure the file is in the right place.
This is getting complex.
Let's change our approach:
We'll use one WireMock instance per dependency and we'll manage the recordings in a directory per dependency.
For RecordDependency:
-
We create a temporary directory for the recordings (or use a provided one).
-
We start WireMock with:
--port
--proxy-all <real_url>
--record-mappings <recording_dir>
-
Then, after the test, we stop WireMock and the recording_dir will contain the mappings and the response bodies.
For ReplayDependency:
- We start WireMock with:
--port
--root-dir <recording_dir>
This way, WireMock will load all the mappings from that directory (and the response bodies from the same directory).
So we don't need to use the admin API to load mappings. We just start WireMock with the root directory set to the recording directory.
Then, for ContractMockDependency, we can also use the root directory? We can have a directory of contract mappings and start WireMock with that as the root.
So we can unify:
-
For contract mock: we have a directory of mapping files (and possibly response body files). We start WireMock with --root-dir set to that directory.
-
For record: we start WireMock with --proxy-all and --record-mappings to a directory.
-
For replay: we start WireMock with --root-dir set to the recording directory.
Then, we don't need the admin API to load mappings. We just start WireMock with the appropriate options.
But note: for contract mock, we might have multiple dependencies? We are starting one WireMock per dependency, so each dependency gets its own root directory.
So we change:
ContractMockDependency:
config.root_dir (directory containing the contract mappings)
RecordDependency:
config.real_url
config.recording_dir (where to record)
ReplayDependency:
config.recording_dir (to load from)
And then in start():
def start(self):
if self.type == "contract_mock":
self.wiremock_process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port),
"--root-dir", self.root_dir
])
elif self.type == "record":
self.wiremock_process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port),
"--proxy-all", self.real_url,
"--record-mappings", self.recording_dir
])
elif self.type == "replay":
self.wiremock_process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port),
"--root-dir", self.recording_dir
])
This is much simpler.
Now, for verification, we still need to use the admin API to check the requests log.
We can do:
def verify(self, **kwargs):
# Build query string for the requests log.
params = {}
if 'method' in kwargs:
params['method'] = kwargs['method']
if 'url' in kwargs:
params['url'] = kwargs['url']
# ... etc.
response = requests.get(f"{self.base_url}/__admin/requests", params=params)
response.raise_for_status()
requests_log = response.json()['requests']
count = len(requests_log)
expected_times = kwargs.get('times', 1)
if count != expected_times:
raise AssertionError(f"Expected {expected_times} requests matching {kwargs}, but got {count}")
But note: the requests log might include requests for the admin API itself? We are querying the admin API, but that's from the test, not from the SUT. So we are safe.
Now, for the fixture manager, we'll leave it as a separate component.
We might also want to have a way to reset the state of the mocks between tests? For example, clear the requests log in WireMock.
We can add a reset() method in the Dependency that clears the requests log and (for record mode) maybe we want to start a new recording? But for record mode, we usually record once and then replay.
We can add:
def reset(self):
# Clear the requests log and reset the state? For contract mock and replay, we don't have state, just the log.
requests.delete(f"{self.base_url}/__admin/requests")
# For record mode, we might want to clear the recording file and start fresh? But then we are recording again.
# We can leave it to the user to decide when to record.
We might call reset() at the beginning of each test (if we want to isolate tests). But note: for replay mode, the mappings are fixed and we don't want to change them. We just want to clear the requests log.
So we can have:
- In
VirtualizationLab.start() we start the dependencies.
- In
VirtualizationLab.reset() we reset the requests log for each dependency.
And then in a test, we can call lab.reset() to clear the log.
But note: for record mode, if we reset, we might lose the recording? Actually, the recording is saved to a file and we are still recording to that file? We might want to start a new recording for each test? But then we would have multiple recordings in the same file? That might not be what we want.
So for record mode, we might not reset the recording. We just use the same recording file for the entire test suite? But then the requests from previous tests would be in the log and might affect verification.
We can design:
-
For contract mock and replay: we can reset the requests log between tests.
-
For record: we don't reset the recording file, but we can reset the requests log (so that verification in the same test doesn't count previous tests). But note: the recording file is being written continuously. We might want to record per test? That would require a new recording file per test.
Given the complexity, we might say that record mode is only for one-time recording (like when we are creating the stubs) and then we switch to replay. So we don't use record mode in the actual test suite.
Alternatively, we can have:
- Record mode: we record to a file and then we stop recording (and switch to replay) for the rest of the tests.
So we can have a separate mode for creating the recordings.
We'll leave it as:
- The test suite should use either contract mock or replay. Record is only for creating the recordings.
So in the test suite, we don't use record mode. We use replay.
Therefore, in the VirtualizationLab we don't need to reset for record mode because we won't use it in the test suite.
We can have:
reset() only for contract mock and replay (clear the requests log).
Now, let's write the code structure:
We assume the following directory structure for the project:
tests/
integration/
test_order.py
fixtures/
sql/
initial_data.sql
contracts/
payment_gateway/
mappings/
payment.json
inventory_service/
mappings/ (empty because we use replay)
recordings/
inventory_service/ (created when we record)
mappings/
... (recorded mappings)
__files/ (response bodies)
We'll create:
virtualization_lab.py
Let's code:
Note: We are using Python, but the same idea can be implemented in other languages.
We'll use subprocess to start WireMock and requests to talk to the admin API.
We need to handle:
- Finding an available port.
- Starting and stopping the process.
- Waiting for the server to be ready.
We'll create a helper for the port.
Let's code:
(We'll skip the exact implementation of _find_free_port and assume we have a function.)
We'll also assume that the WireMock JAR is in the PATH or we provide the path.
Let's code the Dependency base class:
import subprocess
import time
import requests
from abc import ABC, abstractmethod
class Dependency(ABC):
def __init__(self, config):
self.config = config
self.name = config.name
self.port = self._find_free_port()
self.base_url = f"http://localhost:{self.port}"
self.process = None
@abstractmethod
def start(self):
pass
def stop(self):
if self.process:
self.process.terminate()
self.process.wait()
def reset(self):
# Clear the requests log.
requests.delete(f"{self.base_url}/__admin/requests")
def verify(self, **kwargs):
# Build query parameters for the requests log.
params = {}
if 'method' in kwargs:
params['method'] = kwargs['method']
if 'url' in kwargs:
params['url'] = kwargs['url']
# Note: the WireMock requests log endpoint supports query parameters for method, url, bodyPattern, etc.
# But we are only going to support a few for simplicity.
# We can extend as needed.
response = requests.get(f"{self.base_url}/__admin/requests", params=params)
response.raise_for_status()
requests_log = response.json()['requests']
count = len(requests_log)
expected_times = kwargs.get('times', 1)
if count != expected_times:
raise AssertionError(f"Expected {expected_times} requests matching {kwargs}, but got {count}")
def _find_free_port(self):
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('', 0))
return s.getsockname()[1]
Then:
class ContractMockDependency(Dependency):
def __init__(self, config):
super().__init__(config)
self.root_dir = config.config.root_dir
def start(self):
self.process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port),
"--root-dir", self.root_dir
])
self._wait_until_ready()
def _wait_until_ready(self):
for _ in range(30):
try:
response = requests.get(f"{self.base_url}/__admin")
if response.status_code == 200:
return
except requests.exceptions.ConnectionError:
time.sleep(1)
raise RuntimeError(f"WireMock did not start on port {self.port}")
Similarly, for RecordDependency and ReplayDependency:
class RecordDependency(Dependency):
def __init__(self, config):
super().__init__(config)
self.real_url = config.config.real_url
self.recording_dir = config.config.recording_dir
def start(self):
self.process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port),
"--proxy-all", self.real_url,
"--record-mappings", self.recording_dir
])
self._wait_until_ready()
class ReplayDependency(Dependency):
def __init__(self, config):
super().__init__(config)
self.recording_dir = config.config.recording_dir
def start(self):
self.process = subprocess.Popen([
"java", "-jar", "wiremock-standalone.jar",
"--port", str(self.port),
"--root-dir", self.recording_dir
])
self._wait_until_ready()
Now, the VirtualizationLab:
class VirtualizationLab:
def __init__(self, dependencies_config, fixture_manager=None):
self.dependencies = []
for config in dependencies_config:
if config.type == "contract_mock":
dep = ContractMockDependency(config)
elif config.type == "record":
dep = RecordDependency(config)
elif config.type == "replay":
dep = ReplayDependency(config)
else:
raise ValueError(f"Unknown dependency type: {config.type}")
self.dependencies.append(dep)
self.fixture_manager = fixture_manager
def start(self):
for dep in self.dependencies:
dep.start()
if self.fixture_manager:
self.fixture_manager.apply()
def stop(self):
if self.fixture_manager:
self.fixture_manager.cleanup()
for dep in self.dependencies:
dep.stop()
def get_url(self, name):
for dep in self.dependencies:
if dep.name == name:
return dep.base_url
raise KeyError(f"Dependency {name} not found")
def get_dependency(self, name):
for dep in self.dependencies:
if dep.name == name:
return dep
raise KeyError(f"Dependency {name} not found")
def reset(self):
for dep in self.dependencies:
dep.reset()
Now, the FixtureManager:
class FixtureManager(ABC):
@abstractmethod
def apply(self):
pass
@abstractmethod
def cleanup(self):
pass
class SqlFixtureManager(FixtureManager):
def __init__(self, db_url, fixture_files):
self.db_url = db_url
self.fixture_files = fixture_files
def apply(self):
for file in self.fixture_files:
self._run_sql_script(file)
def cleanup(self):
# In a real scenario, we might run a cleanup script or truncate tables.
# We assume that the test database is reset by other means (like transactions that are rolled back) or we have a cleanup script.
pass
def _run_sql_script(self, file):
# Use a database connector to run the SQL file.
# This is database-specific.
# We can use sqlalchemy or psycopg2 for PostgreSQL, etc.
pass
This is a very high-level design.
We have:
- VirtualizationLab: manages dependencies (WireMock instances) and fixtures.
- Dependency: base class for WireMock-based mocks.
- ContractMockDependency, RecordDependency, ReplayDependency: specific types.
- FixtureManager: for database fixtures.
This design should work for integration tests that need to:
- Mock external HTTP services via contracts.
- Record and replay HTTP interactions.
- Set up database state via fixtures.
We can extend the Dependency class to support other types of mocks (like gRPC, etc.) by having different implementations.
We can also extend the FixtureManager to support other stateful systems (like message queues, etc.)
This is a starting point.
Note: We assume that the SUT is configured to use the base URLs from the lab for its dependencies. That configuration is outside the scope of the lab.
We also assume that the WireMock JAR and Java are available.
We might want to improve:
- Error handling and logging.
- More flexible configuration (like custom WireMock options).
- Support for dynamic ports (we are assigning a free port for each dependency, but we might want to fix the port for replay to avoid changing the SUT config? Actually, the SUT config should be set by the test to use the lab's URLs, so dynamic ports are okay as long as the test gets the URL from the lab.)
We can also consider:
- Using Docker containers for WireMock? But then we have to manage containers.
We'll leave it as a subprocess for simplicity.
This is a complex system and we've only scratched the surface, but it should give a good starting point.
I'll design a comprehensive integration test virtualization lab that supports contract mocks, dependency replay, and fixtures. Here's a production-ready solution:
Integration Test Virtualization Lab Architecture
"""
test_virtualization_lab/
├── virtualization_lab/
│ ├── __init__.py
│ ├── core/
│ │ ├── lab.py # Main lab coordinator
│ │ ├── fixtures.py # Fixture management
│ │ ├── contracts.py # Contract mock engine
│ │ ├── recorder.py # Dependency recorder/replayer
│ │ └── verifier.py # Interaction verification
│ ├── providers/
│ │ ├── http/
│ │ │ ├── mock_server.py # WireMock/Pact integration
│ │ │ └── http_recorder.py
│ │ ├── database/
│ │ │ ├── db_fixtures.py # Database fixture loader
│ │ │ └── db_recorder.py # Query recorder
│ │ └── message_queue/
│ │ ├── mq_fixtures.py
│ │ └── mq_recorder.py
│ ├── matchers/
│ │ ├── request_matcher.py # Request matching logic
│ │ └── response_stub.py # Response generation
│ ├── config/
│ │ ├── lab_config.py # Lab configuration
│ │ └── contracts/ # Contract definitions (OpenAPI, GraphQL, etc.)
│ ├── storage/
│ │ ├── recording_store.py # Recording persistence
│ │ └── fixture_store.py # Fixture storage
│ └── utils/
│ ├── diff.py # Comparison utilities
│ └── validators.py # Validation helpers
├── tests/
│ ├── integration/
│ │ ├── test_order_service.py
│ │ ├── test_payment_flow.py
│ │ └── conftest.py # Lab fixture for pytest
│ └── contracts/ # Contract test definitions
├── recordings/ # Stored dependency recordings
├── fixtures/ # Test fixtures (SQL, JSON, etc.)
├── docker-compose.yml # Optional: containerized dependencies
├── requirements.txt
└── README.md
Core Components Implementation
1. Main Lab Coordinator (virtulization_lab/core/lab.py)
from typing import Dict, List, Optional, Any
from contextlib import asynccontextmanager
from dataclasses import dataclass
import logging
from .contracts import ContractMockEngine
from .recorder import DependencyRecorder
from .fixtures import FixtureManager
from .verifier import InteractionVerifier
logger = logging.getLogger(__name__)
@dataclass
class DependencyConfig:
name: str
type: str # 'http', 'database', 'message_queue', etc.
contract_path: Optional[str] = None
recording_path: Optional[str] = None
fixture_path: Optional[str] = None
mode: str = 'mock' # 'mock', 'replay', 'hybrid'
timeout: int = 30
class VirtualizationLab:
"""
Main coordinator for integration test virtualization.
Manages contract mocks, dependency replay, and fixtures.
"""
def __init__(self, config: List[DependencyConfig]):
self.config = config
self._engines: Dict[str, Any] = {}
self._recorders: Dict[str, DependencyRecorder] = {}
self._fixture_managers: Dict[str, FixtureManager] = {}
self._verifier = InteractionVerifier()
self._active = False
async def __aenter__(self):
await self.start()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.stop()
async def start(self):
"""Initialize all configured dependencies"""
logger.info("Starting virtualization lab...")
for dep_config in self.config:
await self._start_dependency(dep_config)
self._active = True
logger.info("Virtualization lab started successfully")
async def stop(self):
"""Teardown all dependencies"""
logger.info("Stopping virtualization lab...")
# Stop in reverse order (LIFO)
for dep_name in reversed(list(self._engines.keys())):
await self._stop_dependency(dep_name)
self._active = False
logger.info("Virtualization lab stopped")
async def _start_dependency(self, config: DependencyConfig):
"""Start a single dependency based on its type"""
logger.info(f"Starting dependency: {config.name} ({config.type})")
if config.type == 'http':
from .providers.http.mock_server import HttpMockEngine
engine = HttpMockEngine(config)
await engine.start()
self._engines[config.name] = engine
elif config.type == 'database':
from .providers.dataset.db_fixtures import DatabaseFixtureManager
fixture_mgr = DatabaseFixtureManager(config)
await fixture_mgr.load_fixtures()
self._fixture_managers[config.name] = fixture_mgr
# Initialize recorder if needed
if config.mode in ('replay', 'hybrid'):
from .recorder import DependencyRecorder
recorder = DependencyRecorder(config)
await recorder.start()
self._recorders[config.name] = recorder
# Load contract if provided
if config.contract_path:
await self._load_contract(config.name, config.contract_path)
async def _stop_dependency(self, name: str):
"""Stop a specific dependency"""
logger.info(f"Stopping dependency: {name}")
if name in self._recorders:
await self._recorders[name].stop()
if name in self._engines:
await self._engines[name].stop()
if name in self._fixture_managers:
await self._fixture_managers[name].cleanup()
async def _load_contract(self, dep_name: str, contract_path: str):
"""Load contract definition for a dependency"""
if dep_name not in self._engines:
raise ValueError(f"Dependency {dep_name} not started")
engine = self._engines[dep_name]
if hasattr(engine, 'load_contract'):
await engine.load_contract(contract_path)
def get_endpoint(self, dep_name: str) -> str:
"""Get the virtualized endpoint URL for a dependency"""
if dep_name not in self._engines:
raise ValueError(f"Dependency {dep_name} not configured")
return self._engines[dep_name].endpoint
async def verify_interaction(self,
dep_name: str,
matcher: Dict[str, Any],
times: int = 1,
at_least: bool = False):
"""
Verify that expected interactions occurred with a dependency.
Args:
dep_name: Name of dependency
matcher: Request matcher dictionary
times: Expected number of occurrences
at_least: If True, verify at least N occurrences
"""
return await self._verifier.verify(
dep_name=dep_name,
matcher=matcher,
times=times,
at_least=at_least,
recorder=self._recorders.get(dep_name)
)
async def replay_recording(self, dep_name: str, recording_path: str):
"""Load and activate a recorded interaction sequence"""
if dep_name in self._recorders:
await self._recorders[dep_name].load_recording(recording_path)
@property
def is_active(self) -> bool:
return self._active
2. Contract Mock Engine (virtulization_lab/core/contracts.py)
from abc import ABC, abstractmethod
from typing import Dict, Any, List, Optional
import json
from pathlib import Path
class ContractDefinition(ABC):
"""Base class for contract definitions"""
@abstractmethod
def validate(self) -> bool:
"""Validate the contract definition"""
pass
@abstractmethod
def generate_stubs(self) -> List[Dict[str, Any]]:
"""Generate WireMock/Pact stubs from contract"""
pass
class OpenAPIContract(ContractDefinition):
"""OpenAPI/Swagger contract implementation"""
def __init__(self, spec_path: str):
self.spec_path = Path(spec_path)
self.spec = self._load_spec()
def _load_spec(self) -> Dict[str, Any]:
with open(self.spec_path) as f:
return json.load(f)
def validate(self) -> bool:
"""Basic OpenAPI validation"""
required = ['openapi', 'info', 'paths']
return all(key in self.spec for key in required)
def generate_stubs(self) -> List[Dict[str, Any]]:
"""Convert OpenAPI paths to WireMock stubs"""
stubs = []
for path, methods in self.spec['paths'].items():
for method, details in methods.items():
stub = {
"request": {
"method": method.upper(),
"url": path
},
"response": {
"status": details.get('responses', {}).get('200', {}).get('schema', {}).get('default', 200)
}
}
# Add response examples if available
if 'examples' in details.get('responses', {}).get('200', {}):
stub['response']['body'] = list(
details['responses']['200']['examples'].values()
)[0]
stubs.append(stub)
return stubs
class ContractMockEngine:
"""Manages contract-based mocking for dependencies"""
def __init__(self, config):
self.config = config
self.contract: Optional[ContractDefinition] = None
self.stubs: List[Dict[str, Any]] = []
async def start(self):
"""Initialize the mock server"""
# Implementation depends on provider (WireMock, MockServer, etc.)
pass
async def load_contract(self, contract_path: str):
"""Load and parse contract file"""
if contract_path.endswith('.yaml') or contract_path.endswith('.yml'):
# Assume OpenAPI
self.contract = OpenAPIContract(contract_path)
# Add other contract types (GraphQL, gRPC, etc.)
if self.contract.validate():
self.stubs = self.contract.generate_stubs()
await self._apply_stubs()
async def _apply_stubs(self):
"""Apply generated stubs to the mock server"""
# Implementation depends on provider
pass
def get_stub_for_request(self,
method: str,
path: str,
body: Optional[Any] = None) -> Optional[Dict[str, Any]]:
"""Find matching stub for a request"""
for stub in self.stubs:
if (stub['request']['method'] == method.upper() and
self._match_path(stub['request']['url'], path)):
if self._match_body(stub, body):
return stub['response']
return None
def _match_path(self, stub_path: str, request_path: str) -> bool:
"""Path pattern matching (simplified)"""
# Handle path parameters like /users/{id}
stub_parts = stub_path.strip('/').split('/')
req_parts = request_path.strip('/').split('/')
if len(stub_parts) != len(req_parts):
return False
for stub_part, req_part in zip(stub_parts, req_parts):
if stub_part.startswith('{') and stub_part.endswith('}'):
continue # Path parameter matches anything
if stub_part != req_part:
return False
return True
def _match_body(self, stub: Dict[str, Any], body: Any) -> bool:
"""Simple body matching - extend as needed"""
if 'bodyPatterns' in stub['request']:
# Use WireMock-style patterns
return self._match_body_patterns(stub['request']['bodyPatterns'], body)
return True # No body pattern specified
def _match_body_patterns(self, patterns: List[Dict], body: Any) -> bool:
"""Match body against patterns"""
body_str = json.dumps(body) if body else ""
for pattern in patterns:
if 'matches' in pattern:
import re
if not re.search(pattern['matches'], body_str):
return False
elif 'contains' in pattern:
if pattern['contains'] not in body_str:
return False
return True
3. Dependency Recorder (virtulization_lab/core/recorder.py)
from typing import Dict, Any, List, Optional
from datetime import datetime
import json
from pathlib import Path
class RecordingSession:
"""Represents a single recording session"""
def __init__(self, dependency: str):
self.dependency = dependency
self.start_time = datetime.utcnow()
self.interactions: List[Dict[str, Any]] = []
self.metadata: Dict[str, Any] = {
'dependency': dependency,
'recorded_at': self.start_time.isoformat(),
'version': '1.0'
}
def record_interaction(self,
request: Dict[str, Any],
response: Dict[str, Any],
latency_ms: float):
"""Record a single request-response interaction"""
interaction = {
'timestamp': datetime.utcnow().isoformat(),
'request': request,
'response': response,
'latency_ms': latency_ms,
'sequence': len(self.interactions) + 1
}
self.interactions.append(interaction)
def save(self, filepath: Path):
"""Save recording to file"""
data = {
'metadata': self.metadata,
'interactions': self.interactions
}
with open(filepath, 'w') as f:
json.dump(data, f, indent=2)
@classmethod
def load(cls, filepath: Path) -> 'RecordingSession':
"""Load recording from file"""
with open(filepath) as f:
data = json.load(f)
session = cls(data['metadata']['dependency'])
session.metadata = data['metadata']
session.interactions = data['interactions']
session.start_time = datetime.fromisoformat(data['metadata']['recorded_at'])
return session
class DependencyRecorder:
"""Records and replays dependency interactions"""
def __init__(self, config):
self.config = config
self.session: Optional[RecordingSession] = None
self.recording_mode = False
self.replay_mode = False
self.replay_index = 0
async def start(self):
"""Initialize recorder"""
self._setup_proxy()
async def stop(self):
"""Cleanup recorder"""
if self.recording_mode and self.session:
self._save_recording()
def start_recording(self):
"""Begin recording interactions"""
self.recording_mode = True
self.replay_mode = False
self.session = RecordingSession(self.config.name)
self._enable_proxy()
def stop_recording(self):
"""Stop recording and save"""
self.recording_mode = False
self._disable_proxy()
def start_replay(self, recording_path: str):
"""Begin replaying from saved recording"""
self.replay_mode = True
self.recording_mode = False
self.session = RecordingSession.load(Path(recording_path))
self.replay_index = 0
self._enable_proxy()
def stop_replay(self):
"""Stop replay mode"""
self.replay_mode = False
self._disable_proxy()
async def handle_request(self,
request: Dict[str, Any]) -> Dict[str, Any]:
"""
Intercept and handle dependency request.
Returns:
Response dictionary
"""
if self.replay_mode:
return self._replay_next_response(request)
elif self.recording_mode:
return await self._record_and_forward(request)
else:
# Pass-through mode (no recording/replay)
return await self._forward_request(request)
def _replay_next_response(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Get next response from recording that matches request"""
if self.replay_index >= len(self.session.interactions):
raise RuntimeError("Replay exhausted - no more recorded interactions")
interaction = self.session.interactions[self.replay_index]
# Simple matching - in reality, we'd need more sophisticated matching
if self._requests_match(request, interaction['request']):
self.replay_index += 1
return interaction['response']
else:
# Try to find matching interaction later in sequence
for i in range(self.replay_index, len(self.session.interactions)):
if self._requests_match(request, self.session.interactions[i]['request']):
self.replay_index = i + 1
return self.session.interactions[i]['response']
raise ValueError(f"No matching recorded response for request: {request}")
def _requests_match(self, req1: Dict, req2: Dict) -> bool:
"""Compare two requests for matching (simplified)"""
return (req1.get('method') == req2.get('method') and
req1.get('path') == req2.get('path'))
async def _record_and_forward(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Record request, forward to real dependency, record response"""
import time
start = time.time()
response = await self._forward_request(request)
latency = (time.time() - start) * 1000
self.session.record_interaction(request, response, latency)
return response
def _save_recording(self):
"""Save current recording session"""
if self.session:
recordings_dir = Path(self.config.recording_path or 'recordings')
recordings_dir.mkdir(exist_ok=True)
filename = f"{self.config.name}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
self.session.save(recordings_dir / filename)
def _setup_proxy(self):
"""Setup proxy interception (implementation depends on type)"""
# HTTP: Use mitmproxy, WireMock proxy, etc.
# Database: Use JDBC proxy, etc.
pass
def _enable_proxy(self):
"""Enable proxy interception"""
pass
def _disable_proxy(self):
"""Disable proxy interception"""
pass
async def _forward_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Forward request to actual dependency"""
# Implementation depends on dependency type
raise NotImplementedError()
4. Fixture Manager (virtulization_lab/core/fixtures.py)
from abc import ABC, abstractmethod
from typing import Dict, Any, List
from pathlib import Path
import json
import yaml
class FixtureSet:
"""Represents a set of fixtures for a dependency"""
def __init__(self, name: str, data: Dict[str, Any]):
self.name = name
self.data = data
self._original_state = None
def get(self, key: str, default=None) -> Any:
"""Get fixture value by key (supports dot notation)"""
keys = key.split('.')
value = self.data
for k in keys:
value = value.get(k, {})
if value is None:
return default
return value if value != {} else default
def save_original_state(self, state: Any):
"""Save original state for cleanup"""
self._original_state = state
def restore_original_state(self) -> Any:
"""Restore original state"""
return self._original_state
class FixtureManager(ABC):
"""Base fixture manager"""
def __init__(self, config):
self.config = config
self.fixtures: Dict[str, FixtureSet] = {}
@abstractmethod
async def load_fixtures(self):
"""Load fixtures from configured source"""
pass
@abstractmethod
async def cleanup(self):
"""Cleanup fixtures after test"""
pass
@abstractmethod
async def reset_to_fixture(self, fixture_name: str):
"""Reset dependency to specific fixture state"""
pass
class JsonFileFixtureManager(FixtureManager):
"""Load fixtures from JSON/YAML files"""
async def load_fixtures(self):
fixture_path = Path(self.config.fixture_path or 'fixtures')
for filepath in fixture_path.glob('*.json'):
with open(filepath) as f:
data = json.load(f)
name = filepath.stem
self.fixtures[name] = FixtureSet(name, data)
for filepath in fixture_path.glob('*.yaml'):
with open(filepath) as f:
data = yaml.safe_load(f)
name = filepath.stem
self.fixtures[name] = FixtureSet(name, data)
async def cleanup(self):
"""Cleanup all fixtures"""
# Implementation depends on dependency type
pass
async def reset_to_fixture(self, fixture_name: str):
"""Reset to specific fixture"""
if fixture_name not in self.fixtures:
raise ValueError(f"Fixture '{fixture_name}' not found")
fixture = self.fixtures[fixture_name]
# Apply fixture data to dependency
await self._apply_fixture_data(fixture.data)
@abstractmethod
async def _apply_fixture_data(self, data: Dict[str, Any]):
"""Apply fixture data to actual dependency"""
pass
class DatabaseFixtureManager(JsonFileFixtureManager):
"""Database-specific fixture manager"""
def __init__(self, config):
super().__init__(config)
self.connection = None
async def _apply_fixture_data(self, data: Dict[str, Any]):
"""Apply SQL fixtures to database"""
if not self.connection:
await self._connect()
# Execute SQL scripts in order
for table, rows in data.get('tables', {}).items():
# Clear table
await self.connection.execute(f"TRUNCATE TABLE {table} RESTART IDENTITY CASCADE")
# Insert rows
for row in rows:
columns = ', '.join(row.keys())
placeholders = ', '.join([f'${i+1}' for i in range(len(row))])
values = list(row.values())
await self.connection.execute(
f"INSERT INTO {table} ({columns}) VALUES ({placeholders})",
values
)
async def _connect(self):
"""Connect to database (implementation specific)"""
# Use asyncpg, aiomysql, etc.
pass
5. Interaction Verifier (virtulization_lab/core/verifier.py)
from typing import Dict, Any, List, Optional
from datetime import datetime
from .recorder import RecordingSession
class Expectation:
"""Represents an expected interaction"""
def __init__(self,
matcher: Dict[str, Any],
times: int = 1,
at_least: bool = False,
sequence: Optional[int] = None):
self.matcher = matcher
self.times = times
self.at_least = at_least
self.sequence = sequence
self.actual_count = 0
def matches(self, interaction: Dict[str, Any]) -> bool:
"""Check if interaction matches expectation"""
return self._match_request(interaction['request'], self.matcher)
def _match_request(self, request: Dict[str, Any], matcher: Dict[str, Any]) -> bool:
"""Match request against matcher criteria"""
for key, expected in matcher.items():
actual = request.get(key)
if actual != expected:
return False
return True
class InteractionVerifier:
"""Verifies interactions with dependencies"""
def __init__(self):
self.expectations: List[Expectation] = []
self.recorded_interactions: List[Dict[str, Any]] = []
def add_expectation(self, expectation: Expectation):
"""Add an expectation to verify against"""
self.expectations.append(expectation)
async def verify(self,
dep_name: str,
matcher: Dict[str, Any],
times: int = 1,
at_least: bool = False,
recorder=None) -> bool:
"""
Verify interactions occurred.
Args:
dep_name: Dependency name
matcher: Request matching criteria
times: Expected number of occurrences
at_least: Minimum occurrences required
recorder: DependencyRecorder to get interactions from
Returns:
True if verification passes
"""
interactions = self._get_interactions(dep_name, recorder)
expectation = Expectation(matcher, times, at_least)
matching = [i for i in interactions if expectation.matches(i)]
expectation.actual_count = len(matching)
if at_least:
success = len(matching) >= times
else:
success = len(matching) == times
if not success:
self._raise_verification_error(expectation, len(interactions))
return success
def _get_interactions(self,
dep_name: str,
recorder) -> List[Dict[str, Any]]:
"""Get interactions for dependency"""
if recorder and recorder.session:
return recorder.session.interactions
return []
def _raise_verification_error(self,
expectation: Expectation,
total_interactions: int):
"""Raise detailed verification error"""
msg = (f"Expected {expectation.times} interaction(s) matching "
f"{expectation.matcher}, but got {expectation.actual_count}")
if expectation.at_least:
msg = f"Expected at least {expectation.times}, got {expectation.actual_count}"
raise AssertionError(
f"{msg}\n"
f"Total interactions recorded: {total_interactions}"
)
def verify_sequence(self,
dep_name: str,
matchers: List[Dict[str, Any]],
recorder=None) -> bool:
"""Verify interactions occurred in specific sequence"""
interactions = self._get_interactions(dep_name, recorder)
if len(interactions) < len(matchers):
raise AssertionError(
f"Expected sequence of {len(matchers)} interactions, "
f"but only {len(interactions)} occurred"
)
for i, matcher in enumerate(matchers):
expectation = Expectation(matcher, sequence=i)
if not expectation.matches(interactions[i]):
raise AssertionError(
f"Interaction at position {i} does not match expected pattern.\n"
f"Expected: {matcher}\n"
f"Actual: {interactions[i]['request']}"
)
return True
6. HTTP Provider Example (virtulization_lab/providers/http/mock_server.py)
import asyncio
from aiohttp import web
from typing import Dict, Any
import aiohttp
from ..contracts import ContractMockEngine
class WireMockAdapter:
"""Adapter for WireMock server"""
def __init__(self, port: int, root_dir: Optional[str] = None):
self.port = port
self.root_dir = root_dir
self.app = web.Application()
self.runner = None
self.site = None
async def start(self):
"""Start WireMock-like server"""
self.app.router.add_route('*', '/{path:.*}', self._handle_request)
self.runner = web.AppRunner(self.app)
await self.runner.setup()
self.site = web.TCPSite(self.runner, 'localhost', self.port)
await self.site.start()
async def stop(self):
"""Stop server"""
if self.site:
await self.site.stop()
if self.runner:
await self.runner.cleanup()
async def _handle_request(self, request: web.Request) -> web.Response:
"""Handle incoming HTTP request"""
# Read request body
body = await request.read()
try:
body_json = json.loads(body) if body else None
except:
body_json = None
request_data = {
'method': request.method,
'path': request.path,
'query': dict(request.query),
'headers': dict(request.headers),
'body': body_json
}
# Try to find matching stub
response_data = self.contract_engine.get_stub_for_request(
method=request.method,
path=request.path,
body=body_json
)
if response_data:
return web.Response(
status=response_data.get('status', 200),
text=response_data.get('body', ''),
headers=response_data.get('headers', {})
)
else:
return web.Response(status=404, text='No matching stub')
def load_stubs(self, stubs: List[Dict[str, Any]]):
"""Load response stubs"""
self.contract_engine.stubs = stubs
class HttpMockEngine:
"""HTTP dependency mock engine"""
def __init__(self, config):
self.config = config
self.port = config.port
self.adapter = WireMockAdapter(self.port)
self.contract_engine = ContractMockEngine(config)
@property
def endpoint(self) -> str:
return f"http://localhost:{self.port}"
async def start(self):
"""Start HTTP mock server"""
await self.adapter.start()
self.adapter.contract_engine = self.contract_engine
async def stop(self):
"""Stop HTTP mock server"""
await self.adapter.stop()
async def load_contract(self, contract_path: str):
"""Load OpenAPI contract"""
await self.contract_engine.load_contract(contract_path)
def add_stub(self, stub: Dict[str, Any]):
"""Add individual stub"""
self.contract_engine.stubs.append(stub)
7. Pytest Integration (tests/integration/conftest.py)
import pytest
import asyncio
from virtualization_lab.core.lab import VirtualizationLab, DependencyConfig
@pytest.fixture(scope="module")
def event_loop():
"""Create event loop for async tests"""
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
@pytest.fixture(scope="module")
async def virtualization_lab():
"""Main lab fixture for integration tests"""
config = [
DependencyConfig(
name="payment_gateway",
type="http",
contract_path="contracts/payment_gateway.yaml",
mode="mock"
),
DependencyConfig(
name="user_service",
type="http",
recording_path="recordings/user_service.json",
mode="replay"
),
DependencyConfig(
name="database",
type="database",
fixture_path="fixtures/database",
mode="mock"
)
]
lab = VirtualizationLab(config)
await lab.start()
yield lab
await lab.stop()
@pytest.fixture
async def payment_gateway_url(virtualization_lab):
"""Convenience fixture for payment gateway URL"""
return virtualization_lab.get_endpoint("payment_gateway")
@pytest.fixture
async def clean_database(virtualization_lab):
"""Reset database to known state"""
db_manager = virtualization_lab._fixture_managers.get("database")
if db_manager:
await db_manager.reset_to_fixture("baseline")
8. Example Test Usage (tests/integration/test_order_service.py)
import pytest
from datetime import datetime
class TestOrderService:
@pytest.mark.asyncio
async def test_create_order_success(self, virtualization_lab, payment_gateway_url):
"""Test successful order creation with payment"""
# Arrange
order_data = {
"user_id": "123",
"items": [
{"product_id": "P1", "quantity": 2, "price": 10.00}
],
"total": 20.00
}
# Act
async with aiohttp.ClientSession() as session:
async with session.post(
f"{payment_gateway_url}/payments",
json=order_data
) as response:
payment_result = await response.json()
# Assert - Verify payment was called correctly
await virtualization_lab.verify_interaction(
dep_name="payment_gateway",
matcher={
"method": "POST",
"path": "/payments",
"body": {"amount": 20.00}
},
times=1
)
assert payment_result["status"] == "approved"
@pytest.mark.asyncio
async def test_order_flow_with_replay(self, virtualization_lab):
"""Test using recorded interactions"""
# Load a pre-recorded user service interaction
await virtualization_lab.replay_recording(
dep_name="user_service",
recording_path="recordings/user_service_valid.json"
)
# Test that uses the recorded responses
# ...
@pytest.mark.asyncio
async def test_multiple_dependencies(self, virtualization_lab):
"""Test with multiple virtualized dependencies"""
# Verify sequence of interactions
await virtualization_lab.verifier.verify_sequence(
dep_name="payment_gateway",
matchers=[
{"method": "POST", "path": "/validate"},
{"method": "POST", "path": "/charge"},
{"method": "POST", "path": "/receipt"}
]
)
9. Configuration Example (virtulization_lab/config/lab_config.py)
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class LabConfig:
"""Global lab configuration"""
recording_storage: str = "recordings/"
fixture_storage: str = "fixtures/"
contract_storage: str = "contracts/"
default_timeout: int = 30
enable_verification: bool = True
verbose_logging: bool = False
@dataclass
class ContractConfig:
"""Contract-specific configuration"""
type: str # 'openapi', 'graphql', 'grpc', 'custom'
path: str
stub_generation: bool = True
validate_requests: bool = True
@dataclass
class DependencyOverride:
"""Test-specific dependency override"""
test_name: str
dependency: str
mode: Optional[str] = None # Override default mode
fixture: Optional[str] = None # Use specific fixture
recording: Optional[str] = None # Use specific recording
10. Docker Compose for Optional Container Dependencies
# docker-compose.yml
version: '3.8'
services:
postgres:
image: postgres:15
environment:
POSTGRES_DB: testdb
POSTGRES_USER: testuser
POSTGRES_PASSWORD: testpass
ports:
- "5432:5432"
volumes:
- ./fixtures/init.sql:/docker-entrypoint-initdb.d/init.sql
redis:
image: redis:7-alpine
ports:
- "6379:6379"
rabbitmq:
image: rabbitmq:3-management
ports:
- "5672:5672"
- "15672:15672"
Key Features & Usage Patterns
1. Contract-First Mocking
# contracts/payment_gateway.yaml (OpenAPI 3.0)
openapi: 3.0.0
paths:
/payments:
post:
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
amount:
type: number
currency:
type: string
default: "USD"
responses:
'200':
description: Payment processed
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: "approved"
transaction_id:
type: string
2. Recording & Replay Workflow
# Record first run (manual or CI job)
async with VirtualizationLab([RecordConfig("user_service", real_url="https://api.example.com")]) as lab:
# Run test against real service
await test_something()
# Recording auto-saved
# Subsequent runs use replay
async with VirtualizationLab([ReplayConfig("user_service")]) as lab:
# Test uses recorded responses
await test_something()
3. Fixture Management
# fixtures/database/users.json
{
"tables": {
"users": [
{"id": 1, "email": "test@example.com", "verified": true},
{"id": 2, "email": "pending@example.com", "verified": false}
],
"orders": []
}
}
4. Dynamic Matching & Stubbing
# Programmatic stub configuration
lab = VirtualizationLab([])
await lab.start()
# Add dynamic stub that responds with request data
lab.engines['payment_gateway'].add_stub({
"request": {
"method": "POST",
"urlPattern": "/payments/.*"
},
"response": {
"status": 200,
"json": {
"status": "approved",
"transaction_id": "{{request.path.[1]}}", # Extract from URL
"amount_received": "{{request.body.amount}}"
}
}
})
Setup & Installation
# requirements.txt
aiohttp>=3.8.0
pytest>=7.0.0
pytest-asyncio>=0.20.0
pyyaml>=6.0
jsonschema>=4.0.0
asyncpg>=0.27.0 # For PostgreSQL
aiomysql>=0.2.0 # For MySQL
# Install dependencies
pip install -r requirements.txt
# Optional: Install WireMock for advanced HTTP mocking
# Download from: https://wiremock.org/downloads.html
Best Practices
-
Contract Management:
- Store contracts in version control alongside service code
- Generate contracts from source services when possible
- Validate contracts against real implementations
-
Recording Strategy:
- Record once per dependency version
- Store recordings in artifact repository
- Use recordings for regression testing
- Regenerate recordings when contracts change
-
Fixture Design:
- Keep fixtures minimal and focused
- Use baseline fixtures for common states
- Create test-specific fixture variants
Version fixtures alongside schema changes
-
Verification:
- Verify critical interactions explicitly
- Use sequence verification for workflows
- Check request/response payloads thoroughly
- Set reasonable timeouts for async operations
-
Performance:
- Reuse lab instances across related tests
- Clean up recordings regularly
- Use in-memory databases where possible
- Parallelize independent tests
This virtualization lab provides a comprehensive solution for integration testing with:
- ✅ Contract-based mocking (OpenAPI, GraphQL, etc.)
- ✅ Dependency recording & replay for deterministic tests
- ✅ Flexible fixture management for data setup
- ✅ Detailed interaction verification
- ✅ Async/await support for modern Python
- ✅ Provider extensibility (HTTP, DB, MQ, etc.)
- ✅ Pytest integration out of the box
The architecture is designed to be extensible, allowing you to add new dependency types (gRPC, SOAP, etc.) by implementing provider-specific adapters while sharing common recording, verification, and fixture infrastructure.