/protean:generate-test-scaffoldfrom protean
Generates pytest test stubs from Protean domain definitions, focusing on user-written business logic like aggregate behavior, state transitions, invariants, and event handling. Skips framework-guaranteed tests.
Ships in protean. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Generate comprehensive pytest tests for existing Protean domain definitions, focusing on user-written business logic.
Domain unit tests are the majority of your test suite. They test the most important code (business rules) with the least overhead (no infrastructure).
raise_()@invariant.pre and @invariant.post enforcementraise_() carry the right field valuesMoney.add(), not VO construction/equalitydomain.process() creates/updates the right aggregate state@domain.value_objectrequired, max_length, min_value, choices): Protean Layer 1domain.registry: guaranteed if decorator is usedmeta_.part_of associations, meta_.stream_category: framework wiring.payload dict access: framework featureProtean's in-memory infrastructure (repositories, and event and command processing in "sync" mode) makes mocks unnecessary in almost all cases. Construct real aggregates, value objects, entities, commands, and events directly in tests. Use domain.process() and domain.repository_for() for integration tests. Mocks should only be used when testing interactions with truly external systems (e.g., third-party HTTP APIs) that cannot be replaced by Protean's built-in test infrastructure.
Before generating tests, identify:
raise_()@invariant.pre, @invariant.post)Read the domain code and fill in the checklist above.
For each aggregate method, generate tests for:
from decimal import Decimal as D
class TestOrderBehavior:
def test_place_sets_status_to_placed(self):
"""place() transitions status from draft to placed."""
order = Order.create(customer_id="cust-1")
order.add_item(product_id="p-1", quantity=2, unit_price=D("10.00"))
order.place()
assert order.status == "placed"
def test_place_raises_order_placed_event(self):
"""place() raises OrderPlaced with correct data."""
order = Order.create(customer_id="cust-1")
order.add_item(product_id="p-1", quantity=2, unit_price=D("10.00"))
order.place()
assert len(order._events) == 1
event = order._events[0]
assert isinstance(event, OrderPlaced)
assert event.order_id == order.id
def test_place_fails_for_non_draft_order(self):
"""place() rejects orders not in draft status."""
order = Order.create(customer_id="cust-1")
order.add_item(product_id="p-1", quantity=1, unit_price=D("5.00"))
order.place()
# place() raises ValueError for an order that is not a draft.
with pytest.raises(ValueError, match="Cannot place order"):
order.place()
Pattern: pytest.raises names the exception the tested method raises. Read the method to find it: here place() raises ValueError, and an invariant raises ValidationError. Add match= so the test fails when a different check raises the same type.
Pattern: Use _events.clear() to isolate event assertions when testing a method after a factory that also raises events.
class TestOrderInvariants:
def test_cannot_place_empty_order(self):
"""Invariant: placed orders must have items."""
order = Order.create(customer_id="cust-1")
with pytest.raises(ValidationError):
order.place() # No items added
The root conftest.py from Step 7 sets command_processing = "sync", so domain.process() runs the handler before it returns and returns the handler's result.
class TestHandlerProcessing:
def test_register_user_creates_and_persists(self):
"""domain.process(RegisterUser) creates a registered User."""
result = domain.process(RegisterUser(email="[email protected]", name="Alice"))
user = domain.repository_for(User).get(result)
assert user.status == "registered"
assert user.email == "[email protected]"
The root conftest.py sets event_processing = "sync", so the event handler runs when the source aggregate is persisted. Without it the handler never runs in the test and the assertions fail.
class TestCrossAggregateFlow:
def test_order_placed_reserves_inventory(self):
"""OrderPlaced event triggers stock reservation."""
inventory = Inventory(product_id="p-1", available=100, reserved=0)
domain.repository_for(Inventory).add(inventory)
order = Order.place(customer_id="c-1", product_id="p-1", quantity=5)
domain.repository_for(Order).add(order)
updated = domain.repository_for(Inventory).get(inventory.id)
assert updated.available == 95
assert updated.reserved == 5
Test full sequences: create → modify → verify final state + side effects.
Use the pytest integration in protean.integrations.pytest. Do not build a test domain by hand. A project made by protean new already has this setup in tests/<package>/conftest.py, so keep that file and skip this step. Otherwise, put one conftest.py at the root of the test suite:
# fragment
# tests/conftest.py
import pytest
from protean.integrations.pytest import DomainFixture
from myapp import domain
@pytest.fixture(scope="session")
def app_fixture():
domain.config["event_processing"] = "sync"
domain.config["command_processing"] = "sync"
fixture = DomainFixture(domain)
fixture.setup()
yield fixture
fixture.teardown()
@pytest.fixture(autouse=True)
def _ctx(app_fixture):
with app_fixture.domain_context():
yield
DomainFixture.setup() calls domain.init() and creates the database schema. teardown() drops it.domain_context() activates the domain for one test, then resets every provider, broker, and event store, so each test starts with empty repositories."sync" before setup(). A bare Domain() processes events and commands asynchronously, so a handler side effect would not happen inside the test. A project made by protean new already sets both to "sync" in domain.toml. Setting them in the conftest as well makes a copied test pass either way.Test files then import the elements they test and need no setup of their own:
# fragment
import pytest
from protean.exceptions import ValidationError
from myapp.ordering import Order, OrderPlaced
| Test class name | What it covers |
|---|---|
Test{Aggregate}Behavior | Factory methods, state transitions, entity management |
Test{Aggregate}BusinessRules | Invariants, rejected operations, error cases |
Test{Aggregate}Events | Events raised with correct data |
TestHandlerProcessing | domain.process() flows, persistence verification |
TestCrossAggregateFlow | Event handler side effects across aggregates |
TestLifecycle | Full end-to-end sequences |
Each asset is a pytest module: the domain first, then its tests below the # --- Tests --- line. Each asset defines its own domain = Domain(), so do not copy a whole asset into a project's test suite. The Step 7 conftest sets up the project's domain, not the asset's, and the asset's tests would fail.
To use an asset in a project, copy only the part below # --- Tests --- into tests/test_<name>.py. Import the elements it uses from the project, for example from myapp import domain, Order, OrderPlaced. The Step 7 conftest then sets up the domain.
domain, so do not use this conftest as a project's root conftest. Use the Step 7 conftest there.fastapi and httpx)check and resolve what it reportsassets/conftest.py (opens in a new tab)assets/scaffold_aggregate_unit.py (opens in a new tab)assets/scaffold_command_flow.py (opens in a new tab)assets/scaffold_event_driven_flow.py (opens in a new tab)references/aggregate-tests.md (opens in a new tab)references/handler-tests.md (opens in a new tab)references/integration-tests.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
test-generation, pytest, domain-driven-design, protean, test-scaffolding
npx claudepluginhub proteanhq/protean --plugin protean39 skills in this plugin
/add-commandAdd a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the command, command-handler, and api-endpoint element skills./add-domain-service-flowBuild a domain service flow in Protean for business logic that spans two or more aggregates. Domain services are stateless, encapsulate cross-aggregate business rules, and run pre/post invariants for validation. They are used when business logic doesn't naturally belong to a single aggregate. Wire them into command handlers or application services for persistence. Use when the user asks to "add a domain service", "implement cross-aggregate logic", "coordinate multiple aggregates", "add a business operation spanning aggregates", "validate across aggregates", or when they describe scenarios like "placing an order checks inventory and reserves stock", "transferring funds between accounts", "scheduling involves both resource and calendar"./add-eventAdd a complete event flow to an existing aggregate. It creates a domain event, adds or updates an aggregate method that raises the event via self.raise_(), and wires an event handler that processes the event and performs specified side effects (such as syncing state across aggregates, sending notifications, or triggering downstream processes). This is the primary workflow for adding reactive, event-driven behavior to a Protean domain. Use when the user wants to "add an event", "add a domain event", "add a reaction to a state change", "add a side effect", "create an event flow", "wire an event handler", "add event-driven behavior", "react to a state change", "sync aggregates on event", or describes something that happened or should happen (like "when an order is placed, reduce inventory", "after payment is confirmed, send a notification", "when a user registers, create a welcome email", "notify the warehouse when an order ships"). This workflow composes the event, aggregate, and event-handler element skills./add-fieldAdd fields to Protean domain elements (aggregates, entities, value objects). Guides you through selecting the right field type, configuring validations, and placing fields correctly. Use when the user asks to "add a field", "add an attribute", "add a property", "I need to store [data]", "add a new field to [aggregate/entity]", or describes data that needs to be tracked. Covers simple fields, association fields (HasOne, HasMany, ValueObject), field validation, custom validators, and choosing between field types for different use cases./add-read-modelBuild a complete read model in Protean, a projection populated by a projector that reacts to domain events. Covers single-aggregate projections (flattened view of one aggregate), cross-aggregate projections (combining data from multiple aggregates), and choosing between database-backed and cache-backed storage. Use when the user asks to "add a read model", "create a projection with projector", "build a query view", "add a CQRS read side", "create a denormalized view", "build a reporting view", "add a dashboard query model", or when they need to combine data from multiple aggregates into one queryable structure./add-saga-flowBuild a complete saga in Protean using a process manager that coordinates a multi-step flow across several aggregates. The saga reacts to domain events, issues commands to drive each aggregate forward, tracks its own state, and closes on a terminal handler with a compensating path for failures. Use when the user asks to "add a saga", "coordinate a multi-step process", "orchestrate a workflow across aggregates", "manage order fulfillment", "add a process manager flow", "compensate on failure", "roll back a distributed transaction", or when they describe a flow like "reserve stock, take payment, then ship, and undo the reservation if payment fails".Other plugins' skills for the same job