Architect a domain service test harness employing contract tests, property-based…
- User
Architect a domain service test harness employing contract tests, property-based generators, and fixtures.
Assistant
Architect a domain service test harness employing contract tests, property-based generators, and fixtures.
The user wants a comprehensive guide and code example for architecting a "domain service test harness." This harness needs to incorporate three specific testing methodologies:
Scope and Technology Stack:
pytest and hypothesis) or TypeScript/Java/C# are good candidates. Python is often the most readable for architectural patterns, but TypeScript is very popular for modern web services. Let's stick to Python for its clarity and strong testing libraries (pytest for fixtures/structure, hypothesis for property-based testing, and pact or similar for contracts, though contract testing in a unit context is often about interface adherence).Architectural Components:
Detailed Plan:
User or Order) and a Repository/Service interface.Drafting the Code Structure (Mental or Scratchpad):
Language: Python 3.10+.
Framework: pytest.
PBT: hypothesis.
Domain: A Task Management service.
Contract Test Strategy: I'll use unittest.TestCase or an abstract pytest class. The "Harness" will be a mixin or a factory that accepts a provider (the SUT - System Under Test).
Property Strategy: Define st.builds(Task).
Refining the "Harness" Concept:
A "Test Harness" in this context isn't just a script; it's an architectural pattern for the test suite itself.
It should look like:
ServiceTestHarness(ABC) -> specific implementations like InMemoryTestHarness or PostgresTestHarness.
Structure of the response:
Code specifics:
dataclasses for entities.Protocol for the interface.hypothesis for generating complex data.Constraint Checklist & Confidence Score:
Confidence Score: 5/5
Mental Sandbox Simulation:
UserRepository.test_save_then_find.test_idempotency (saving twice doesn't change state).InMemoryUserRepository.I will structure the solution using Python and pytest as it is the industry standard for this specific combination of requirements (especially hypothesis integration).
Key distinctions to make:
SqlRepo behaves exactly like MockRepo. I will focus on the Domain Level for a "Domain Service", as that's where the value lies in unit/integration testing. I will briefly mention PACT for integration but focus the code on domain contracts.Let's write the solution. Designing a test harness for a domain service requires shifting focus from simple unit tests (return values) to behavioral verification. In a Domain-Driven Design (DDD) context, we need to ensure that our concrete implementations (adapters) strictly adhere to the domain logic (ports) and can handle a wide variety of inputs without leaking infrastructure concerns.
Here is an architectural blueprint for a robust test harness using Python, pytest (fixtures/structure), and hypothesis (property-based testing).
We will define a generic Test Harness (or Template) that accepts a specific implementation (e.g., SQL Repo, In-Memory Repo) and runs a suite of standard compliance tests against it.
First, define the interface and the domain logic errors.
# src/domain/model.py
from dataclasses import dataclass
from uuid import UUID, uuid4
@dataclass(frozen=True)
class User:
id: UUID
email: str
credits: int
class InsufficientFundsError(Exception):
pass
class UserNotFoundError(Exception):
pass
# src/domain/service.py
from abc import ABC, abstractmethod
from .model import User
class IUserRepository(ABC):
@abstractmethod
async def get(self, user_id: str) -> User:
pass
@abstractmethod
async def save(self, user: User) -> None:
pass
class DomainService:
def __init__(self, repo: IUserRepository):
self.repo = repo
async def transfer_credits(self, sender_id: str, recipient_id: str, amount: int):
if amount <= 0:
raise ValueError("Amount must be positive")
sender = await self.repo.get(sender_id)
recipient = await self.repo.get(recipient_id)
if sender.credits < amount:
raise InsufficientFundsError("Sender has insufficient funds")
# Domain Logic: Create new states
updated_sender = User(sender.id, sender.email, sender.credits - amount)
updated_recipient = User(recipient.id, recipient.email, recipient.credits + amount)
# Persistence
await self.repo.save(updated_sender)
await self.repo.save(updated_recipient)
This is the core of your request. We build an abstract test class. This class does not know about SQL or Memory; it only knows the Contract and Properties of the domain.
We use hypothesis to generate valid domain objects. This ensures our tests cover edge cases (like empty strings, max integers, unicode) that we might forget to write manually.
# tests/strategies.py
from hypothesis import strategies as st
from src.domain.model import User
from uuid import uuid4
# Strategy for generating valid User objects
user_strategy = st.builds(
User,
id=st.uuids(),
email=st.emails(),
credits=st.integers(min_value=0, max_value=1_000_000)
)
This is the "Harness." Any implementation (SQL, Mongo, In-Memory) must inherit from this class to prove it works.
# tests/harness.py
import pytest
from abc import ABC, abstractmethod
from src.domain.service import IUserRepository, DomainService, InsufficientFundsError
from src.domain.model import User
from tests.strategies import user_strategy
from hypothesis import given, settings
class RepositoryContractTest(ABC):
"""
Generic Test Harness.
This class defines WHAT a repository must do, but not HOW.
"""
@abstractmethod
def create_repository(self) -> IUserRepository:
"""Fixture: Subclasses must implement this to provide the concrete repo."""
pass
@pytest.fixture
def service(self):
# Wire up the service with the concrete implementation
return DomainService(self.create_repository())
# --- 1. CONTRACT TESTS (Behavior Verification) ---
@pytest.mark.asyncio
async def test_contract_save_and_retrieve(self):
"""Contract: Data persisted must be retrievable exactly as stored."""
repo = self.create_repository()
original_user = User(id="1", email="test@example.com", credits=100)
await repo.save(original_user)
retrieved_user = await repo.get("1")
assert retrieved_user == original_user
@pytest.mark.asyncio
async def test_contract_update_overwrites(self):
"""Contract: Saving an existing ID overwrites the data."""
repo = self.create_repository()
user_v1 = User(id="1", email="v1@example.com", credits=10)
user_v2 = User(id="1", email="v2@example.com", credits=20)
await repo.save(user_v1)
await repo.save(user_v2) # Update
assert (await repo.get("1")).credits == 20
# --- 2. PROPERTY-BASED TESTS (Logic Stress Testing) ---
@pytest.mark.asyncio
@given(sender=user_strategy, recipient=user_strategy, amount=st.integers(min_value=1))
@settings(max_examples=50)
async def test_property_transfer_conserves_mass(self, service, sender, recipient, amount):
"""
Property: Credits are neither created nor destroyed during a transfer,
provided the sender has enough money.
"""
# We assume distinct IDs for simplicity in this example
if sender.id == recipient.id: return
# Setup: Force state into repo
await service.repo.save(sender)
await service.repo.save(recipient)
# Assume: We only run the logic if the sender can afford it
# (Hypothesis handles filtering, but assume is cleaner for explanation)
if sender.credits < amount:
return
# Act
await service.transfer_credits(str(sender.id), str(recipient.id), amount)
# Assert: Conservation of Credits
s_final = await service.repo.get(str(sender.id))
r_final = await service.repo.get(str(recipient.id))
total_before = sender.credits + recipient.credits
total_after = s_final.credits + r_final.credits
assert total_after == total_before
# --- 3. FIXTURE STATE TESTS ---
@pytest.fixture
def user_with_zero_credits(self):
"""Fixture: A specific state of the world."""
u = User(id="99", email="broke@example.com", credits=0)
return u
@pytest.mark.asyncio
async def test_domain_logic_insufficient_funds(self, service, user_with_zero_credits):
"""Test domain rules using a pre-canned fixture state."""
# Arrange
rich_user = User(id="100", email="rich@example.com", credits=1000)
await service.repo.save(user_with_zero_credits)
await service.repo.save(rich_user)
# Act & Assert
with pytest.raises(InsufficientFundsError):
await service.transfer_credits(
str(user_with_zero_credits.id),
str(rich_user.id),
10
)
Now, we create concrete test files. We simply inherit the Harness and implement the abstract factory method. This allows us to test an In-Memory version (fast) and a SQL version (integration) using the exact same logic.
# tests/test_inmemory_repo.py
from src.infra.inmemory_repo import InMemoryUserRepository
from tests.harness import RepositoryContractTest
class TestInMemoryRepository(RepositoryContractTest):
def create_repository(self):
return InMemoryUserRepository()
# tests/test_sql_repo.py
import pytest
from src.infra.sql_repo import SqlUserRepository
from tests.harness import RepositoryContractTest
# Assuming you use something like docker-py or testcontainers
@pytest.fixture(scope="module")
def db_session():
# Setup DB connection logic here...
yield session
# Teardown...
class TestSqlRepository(RepositoryContractTest):
def create_repository(self):
# This harness test now runs against a real DB!
return SqlUserRepository(db_session)
IUserRepository): The architectural contract. The harness enforces that any implementation adheres to the method signatures and expected side effects (saving implies retrieving).RepositoryContractTest): The harness architecture. It contains the logic that must be true regardless of technology.hypothesis): Instead of writing user_credits_100, we define a strategy that generates user_credits_X. This allows us to test mathematical invariants (like Conservation of Credits) across hundreds of random scenarios.user_with_zero_credits): These define specific "States of the World" used to verify specific domain rules (like throwing an error) that property-based testing might skip (due to filtering conditions).