"""
Change Data Testing Harness
===========================
A Python-based testing harness for Change Data Capture (CDC) pipelines.
Supports:
- **Contracts**: Schema validation (using Pydantic) on change events and state.
- **Invariants**: Custom check functions that must hold after every change.
- **Replays**: Replay sequences of changes from JSON files or lists, validating contracts/invariants at each step.
- **State Simulation**: In-memory dict-based state (key -> row) to simulate source/sink.
- **Generation**: Helpers to generate random change sequences for fuzzing/property-based testing.
- **Integration**: Pytest fixtures for easy testing.
Example Usage:
```python
from pydantic import BaseModel, EmailStr
from harness import TestingHarness, ChangeEventDict, generate_events
class User(BaseModel):
id: str
name: str
email: EmailStr
def unique_emails(state: dict[str, dict]) -> bool:
emails = {row["email"] for row in state.values()}
return len(emails) == len(state)
harness = TestingHarness(
row_model=User,
invariants=[unique_emails]
)
events = generate_events(100, row_model=User) # Fuzz 100 events
harness.replay(events) # Raises AssertionError on failure
# Replay from file
harness.replay_from_file("test_changes.json")
Requirements: pip install pydantic pytest hypothesis
"""
from future import annotations
from typing import Any, Callable, Dict, List, Optional, Sequence
from dataclasses import dataclass
from pathlib import Path
import json
import random
from enum import Enum
from pydantic import BaseModel, ValidationError
import pytest
from hypothesis import given, strategies as st
class Op(str, Enum):
INSERT = "i"
UPDATE = "u"
DELETE = "d"
@dataclass
class ChangeEvent:
"""Immutable CDC event."""
op: Op
key: str # Primary key (e.g., 'id')
before: Dict[str, Any]
after: Dict[str, Any]
ts: float # Timestamp
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> ChangeEvent:
return cls(
op=Op(data["op"]),
key=data["key"],
before=data["before"],
after=data["after"],
ts=data["ts"]
)
def as_dict(self) -> Dict[str, Any]:
return {
"op": self.op.value,
"key": self.key,
"before": self.before,
"after": self.after,
"ts": self.ts
}
ChangeEventDict = Dict[str, Any] # Alias for JSON-serializable events
class TestingHarness:
def init(
self,
row_model: Optional[type[BaseModel]] = None,
invariants: List[Callable[[Dict[str, Dict[str, Any]]], bool]] = None,
strict_mode: bool = True # Fail on missing key, schema errors, etc.
):
self.row_model = row_model
self.invariants = invariants or []
self.strict_mode = strict_mode
def _validate_contract(self, data: Dict[str, Any]) -> None:
"""Validate row against Pydantic model (contract)."""
if self.row_model:
try:
self.row_model(**data)
except ValidationError as e:
raise AssertionError(f"Contract violation: {e}") from e
def _apply(self, event: ChangeEvent, state: Dict[str, Dict[str, Any]]) -> None:
"""Apply change to state, enforcing pre-conditions in strict mode."""
key = event.key
if self.strict_mode:
if event.op == Op.INSERT:
assert key not in state, f"Key {key} already exists on INSERT"
elif event.op == Op.UPDATE:
assert key in state, f"Key {key} missing on UPDATE"
elif event.op == Op.DELETE:
assert key in state, f"Key {key} missing on DELETE"
if event.op == Op.INSERT:
self._validate_contract(event.after)
state[key] = event.after
elif event.op == Op.UPDATE:
self._validate_contract(event.after)
# Optionally validate before if needed
state[key] = event.after
elif event.op == Op.DELETE:
del state[key]
def _check_invariants(self, state: Dict[str, Dict[str, Any]]) -> None:
"""Run all invariants on current state."""
for invariant in self.invariants:
if not invariant(state):
raise AssertionError(f"Invariant failed: {invariant.__name__}")
def replay(
self,
events: Sequence[ChangeEvent | ChangeEventDict],
initial_state: Optional[Dict[str, Dict[str, Any]]] = None
) -> Dict[str, Dict[str, Any]]:
"""
Replay events, checking contracts/invariants after each.
Returns final state.
"""
state = initial_state.copy() if initial_state else {}
parsed_events = [e.as_dict() if isinstance(e, ChangeEvent) else e for e in events]
for event_data in parsed_events:
event = ChangeEvent.from_dict(event_data)
self._apply(event, state)
self._check_invariants(state)
return state
def replay_from_file(self, path: str | Path, **kwargs: Any) -> Dict[str, Dict[str, Any]]:
"""Replay events from JSON file."""
path = Path(path)
with open(path) as f:
events = json.load(f)
return self.replay(events, **kwargs)
def save_events(self, events: List[ChangeEvent | ChangeEventDict], path: str | Path) -> None:
"""Save events to JSON for later replay."""
path = Path(path)
event_dicts = [e.as_dict() if isinstance(e, ChangeEvent) else e for e in events]
with open(path, "w") as f:
json.dump(event_dicts, f, indent=2)
def generate_events(
count: int,
row_model: type[BaseModel],
keys: List[str] = None,
seed: int = 42
) -> List[ChangeEvent]:
"""
Generate random CDC events that satisfy the row model (for fuzzing).
Uses Hypothesis-like strategies internally.
"""
random.seed(seed)
if keys is None:
keys = list(range(count // 2)) # Some fixed keys for updates/deletes
def sample_row() -> Dict[str, Any]:
# Simple faker: extract fields from model, generate plausible data
fields = {f.name for f in row_model.__fields__.values()}
row = {}
for field in fields:
if field == "id":
row[field] = str(random.randint(1, 10000))
elif "email" in field:
row[field] = f"user{random.randint(1,1000)}@example.com"
else:
row[field] = f"val{random.randint(1,100)}"
row_model(**row) # Validate
return row
events = []
ts = 0.0
for _ in range(count):
key = random.choice(keys) if keys else str(random.randint(1, 100))
op = random.choice([Op.INSERT, Op.UPDATE, Op.DELETE])
before = sample_row() if random.random() > 0.5 else {}
after = sample_row() if op != Op.DELETE else {}
# Make before/after consistent for updates
if op == Op.UPDATE:
before["id"] = key
after["id"] = key
events.append(ChangeEvent(op=op, key=key, before=before, after=after, ts=ts))
ts += random.uniform(0.1, 1.0)
return events
Pytest Integration
def pytest_configure(config):
"""Auto-register fixtures."""
@pytest.fixture
def cdc_harness(request):
"""Fixture: harness with model/invariants from test params or defaults."""
model = getattr(request, 'param', {}).get('model')
invariants = getattr(request, 'param', {}).get('invariants', [])
return TestingHarness(row_model=model, invariants=invariants)
@pytest.fixture
def random_events(request, cdc_harness):
"""Fixture: generate N random events."""
count = getattr(request, 'param', {}).get('count', 10)
return generate_events(count, cdc_harness.row_model)
@pytest.mark.parametrize("cdc_harness, random_events", [
({'model': None}, {'count': 5}),
], indirect=True)
def test_replay_valid(cdc_harness, random_events):
"""Example: Replay succeeds on valid events."""
final_state = cdc_harness.replay(random_events)
assert final_state # Non-empty
Example with contracts/invariants
class ExampleUser(BaseModel):
id: str
name: str
email: str # No EmailStr for simplicity
def no_null_names(state: dict[str, dict]):
return all(row.get("name") for row in state.values())
harness = TestingHarness(row_model=ExampleUser, invariants=[no_null_names])
Usage in tests/docs
if name == "main":
events = generate_events(20, ExampleUser)
harness.save_events(events, "test_events.json")
final = harness.replay_from_file("test_events.json")
print("Replay successful. Final state:", final)
## Key Features Explained
### 1. **Contracts**
- **Pydantic Models**: Pass `row_model` to validate `after` (and optionally `before`) on every INSERT/UPDATE.
- **Strict Pre-conditions**: In `strict_mode`, enforces no duplicate INSERTs, existing keys for UPDATE/DELETE.
- **Extensible**: Add custom contract checks in `_validate_contract`.
### 2. **Invariants**
- **Stateful Checks**: Functions take `state: Dict[key, row]` and return `bool`.
- **Checked After Every Event**: Fail-fast on violation.
- **Examples**: Unique emails, no nulls, referential integrity.
### 3. **Replays**
- **In-Memory State**: Simulates source/sink DB.
- **JSON Persistence**: Save/load sequences for regression testing.
- **Batch Replay**: Handles lists or files.
### 4. **Fuzzing & Testing**
- **Event Generation**: `generate_events` creates valid sequences respecting contracts.
- **Pytest Fixtures**: `cdc_harness`, `random_events` for property-based tests.
- **Hypothesis-Compatible**: Integrate `@given` for advanced fuzzing.
### 5. **Extending**
- **Custom State**: Pass `initial_state` to replays.
- **Multi-Table**: Use `state: Dict[table_name, Dict[key, row]]`.
- **Real DB**: Replace `_apply` with SQLAlchemy/Debezium hooks.
- **Streams**: Adapt for Kafka: yield events from consumer.
Run `python harness.py` for a demo. Use in CI for CDC pipeline validation! 🚀