Build schema coverage targets by template with validation.
- User
Build schema coverage targets by template with validation.
Assistant
Build schema coverage targets by template with validation.
The user wants me to "Build schema coverage targets by template with validation."
1. Deconstruct the Request:
2. Identify the Context/Technology Stack: The prompt is abstract. It doesn't specify a language (Python, Java, Go?) or a schema format (JSON, XML, SQL?).
pydantic is great for validation. hypothesis or custom generators are good for data generation.pydantic for the schema and validation, and standard data classes for the templates/targets. This is the most practical and demonstrable approach.3. Define the Core Concepts:
User with ID, Email, Role).4. Architecture Design:
5. Drafting the Solution (Mental Sandbox):
User(id: int, role: Enum[Admin, User])id=1, role=Admin.id=2, role=User.role=Admin as covered.role=User as covered.6. Refining "By Template": The prompt asks for targets by template. This might mean:
Let's implement a system where:
7. Coding the Solution (Python):
pydantic (for schema/val), typing.CoverageTarget: Defines a specific path (e.g., user.role) and a value or constraint (e.g., Admin).DataTemplate: A generator or fixed payload builder. It has a name and a method to produce data.CoverageEngine:
{ TemplateName: [TargetIDs] }.8. Adding "Validation" Nuance: If the data generated doesn't match the schema, it shouldn't count towards coverage. Pydantic will raise an error. We need to catch that and report a failure.
9. Structure of the Output:
10. Self-Correction/Refinement during drafting:
user.role is brittle.11. Finalizing the Code Plan:
Order model (id, amount, status, items).status='shipped', status='refunded', high value amounts, etc.StandardOrderTemplate: Basic order.RefundTemplate: Covers the refund logic.Let's write the code. I will use pydantic for the validation part as it's the industry standard for this in Python.
Steps in the code:
Order model.CoverageTarget class.Template class.CoverageManager class.
add_target(template_name, target)process(template_name, data)report()Refinement on "Validation": The prompt says "with validation". This implies the system must verify the data fits the schema before crediting the coverage.
Let's build the response.
models.py (The Schema)targets.py (The definitions)engine.py (The logic)This looks solid. It covers all aspects: Schema, Coverage, Targets, Templates, Validation.
Self-Correction on the "Template" aspect: In software testing, a "Template" often refers to a file (like Jinja2) that generates code or data. Here, I will interpret "Template" as a "Test Data Profile" or "Factory" that produces specific scenarios. This is the most logical interpretation in a QA/Data context.
Let's write the prompt response based on this thought process.
This solution implements a Schema Coverage System in Python. It defines a way to map specific data "Templates" (test scenarios) to "Coverage Targets" (specific fields or constraints within a schema) and validates the data against a strict schema (using pydantic) before awarding coverage credit.
status must be set to archived at least once").You will need pydantic installed (pip install pydantic).
import json
from typing import Dict, List, Set, Type, Any, Callable, Optional
from pydantic import BaseModel, ValidationError, Field, constr
from enum import Enum
# ==========================================
# 1. The Schema (The Contract)
# ==========================================
class UserType(str, Enum):
ADMIN = "admin"
GUEST = "guest"
REGULAR = "regular"
class UserSchema(BaseModel):
"""
The definitive schema for our data.
Coverage Target: We want to ensure we test valid data for all these fields.
"""
id: int
username: constr(min_length=3)
role: UserType
is_active: bool = True
login_count: int = Field(ge=0)
# ==========================================
# 2. Coverage Definitions
# ==========================================
class CoverageTarget:
"""
Represents a specific requirement or area of the schema to cover.
"""
def __init__(self, name: str, description: str):
self.name = name
self.description = description
def check(self, data: Dict) -> bool:
"""Logic to determine if this specific target is hit by the data."""
raise NotImplementedError
class FieldPresenceTarget(CoverageTarget):
"""Checks if a specific field exists and is not None."""
def __init__(self, field_name: str):
super().__init__(
name=f"field_present_{field_name}",
description=f"Ensure field '{field_name}' is present in valid data"
)
self.field_name = field_name
def check(self, data: Dict) -> bool:
return self.field_name in data and data[self.field_name] is not None
class EnumValueTarget(CoverageTarget):
"""Checks if a specific enum value is used."""
def __init__(self, field_name: str, enum_value: Any):
super().__init__(
name=f"enum_{field_name}_{enum_value}",
description=f"Test '{field_name}' with value '{enum_value}'"
)
self.field_name = field_name
self.target_value = enum_value
def check(self, data: Dict) -> bool:
return data.get(self.field_name) == self.target_value
# ==========================================
# 3. Template System
# ==========================================
class DataTemplate:
"""
A template generates data and declares which coverage targets
it intends to satisfy.
"""
def __init__(self, name: str, generator: Callable[[], Dict], targets: List[CoverageTarget]):
self.name = name
self.generator = generator
self.targets = targets
def generate(self) -> Dict:
return self.generator()
# ==========================================
# 4. The Engine (Validation & Tracking)
# ==========================================
class CoverageValidator:
def __init__(self, schema_model: Type[BaseModel]):
self.schema_model = schema_model
self.covered_targets: Set[str] = set()
self.validation_errors: List[Dict] = []
self.all_targets: Dict[str, CoverageTarget] = {}
def register_targets(self, targets: List[CoverageTarget]):
for t in targets:
self.all_targets[t.name] = t
def run_template(self, template: DataTemplate):
print(f"\n▶ Running Template: {template.name}")
# 1. Generate Data
try:
raw_data = template.generate()
print(f" Generated Payload: {json.dumps(raw_data, indent=2)}")
except Exception as e:
print(f" ❌ Generator Error: {e}")
return
# 2. Validate against Schema (The "With Validation" requirement)
try:
# validate() converts dict -> Model Instance -> dict (ensuring types are cast correctly)
validated_instance = self.schema_model(**raw_data)
validated_data = validated_instance.model_dump()
print(" ✅ Schema Validation Passed")
except ValidationError as e:
print(f" ❌ Schema Validation Failed:\n {e}")
self.validation_errors.append({"template": template.name, "errors": e.errors()})
return
# 3. Check Coverage Targets
hits = 0
for target in template.targets:
# Check logic specific to the target
if target.check(validated_data):
self.covered_targets.add(target.name)
hits += 1
print(f" 🎯 Targets Hit: {hits}/{len(template.targets)}")
def report(self):
total = len(self.all_targets)
covered = len(self.covered_targets)
percent = (covered / total) * 100 if total > 0 else 0
print("\n" + "="*40)
print(" COVERAGE REPORT")
print("="*40)
print(f"Schema: {self.schema_model.__name__}")
print(f"Total Targets: {total}")
print(f"Covered Targets: {covered}")
print(f"Coverage %: {percent:.2f}%")
missing = set(self.all_targets.keys()) - self.covered_targets
if missing:
print("\n🚨 Missing Coverage:")
for m in missing:
print(f" - {self.all_targets[m].description}")
if self.validation_errors:
print("\n⚠️ Validation Errors Occurred:")
for err in self.validation_errors:
print(f" - Template '{err['template']}' failed validation.")
# ==========================================
# 5. Execution / Usage
# ==========================================
if __name__ == "__main__":
# A. Setup the Engine
engine = CoverageValidator(UserSchema)
# B. Define Global Targets (What constitutes 'full coverage'?)
targets = [
FieldPresenceTarget("id"),
FieldPresenceTarget("username"),
FieldPresenceTarget("role"),
EnumValueTarget("role", UserType.ADMIN),
EnumValueTarget("role", UserType.GUEST),
EnumValueTarget("role", UserType.REGULAR),
FieldPresenceTarget("login_count")
]
engine.register_targets(targets)
# C. Define Templates (Builders that map to targets)
# Template 1: Basic Admin User
def gen_admin():
return {
"id": 1,
"username": "admin_user",
"role": "admin", # Covers EnumValueTarget(ADMIN)
"login_count": 5
}
t1 = DataTemplate(
name="AdminFixture",
generator=gen_admin,
targets=[
targets[0], targets[1], targets[2], # Presence checks
targets[3], # Admin Enum check
targets[6] # Login count
]
)
# Template 2: Guest User (Intentionally Invalid for Demo)
def gen_bad_guest():
return {
"id": 2,
"username": "gu", # Too short! Should fail validation
"role": "guest",
"login_count": -5 # Negative! Should fail validation
}
t2 = DataTemplate(
name="InvalidGuestFixture",
generator=gen_bad_guest,
targets=[
targets[4] # Intended to cover Guest Enum
]
)
# Template 3: Regular User
def gen_regular():
return {
"id": 3,
"username": "john_doe",
"role": "regular",
"login_count": 0
}
t3 = DataTemplate(
name="RegularFixture",
generator=gen_regular,
targets=[
targets[5] # Regular Enum
]
)
# D. Run
engine.run_template(t1)
engine.run_template(t2) # This will fail validation, targets NOT counted
engine.run_template(t3)
engine.report()
CoverageTarget class is abstract. You can create complex logic (e.g., "Ensure login_count is > 100") inside the check method.run_template, we wrap the data generation in a try/except ValidationError block.
UserSchema (e.g., username is too short), the process stops.DataTemplate, we pass in the list of CoverageTarget objects that this specific template is responsible for. This creates the "By Template" mapping.