pytest-application-layer-testing
Testing use cases and application services: use case testing with mocked gateways, DTO testing, application exception testing, orchestration testing, mocking at adapter boundaries. Coverage target: 85-90%. Use when: Testing use cases, testing application services, testing DTOs and data transformation, testing error handling in use cases, mocking external dependencies at layer boundaries.
What this skill does
# Pytest Application Layer Testing
## Purpose
The application layer orchestrates domain logic with external dependencies. Tests verify that use cases correctly coordinate business logic and integration boundaries.
## When to Use This Skill
Use when testing use cases and application services with "test use case", "mock gateways", "test orchestration", or "test DTOs".
Do NOT use for domain testing (use `pytest-domain-model-testing`), adapter testing (use `pytest-adapter-integration-testing`), or pytest configuration (use `pytest-configuration`).
## Quick Start
Test use cases with mocked gateways:
```python
from unittest.mock import AsyncMock
import pytest
@pytest.mark.asyncio
async def test_extract_orders_use_case(
mock_shopify_gateway: AsyncMock,
mock_event_publisher: AsyncMock,
) -> None:
"""Test use case orchestration."""
use_case = ExtractOrdersUseCase(
gateway=mock_shopify_gateway,
publisher=mock_event_publisher,
)
# Mock external dependencies
async def fake_orders():
yield create_test_order(order_id="1")
yield create_test_order(order_id="2")
mock_shopify_gateway.fetch_orders.return_value = fake_orders()
# Execute
result = await use_case.execute()
# Verify behavior
assert result.orders_count == 2
mock_shopify_gateway.fetch_orders.assert_awaited_once()
assert mock_event_publisher.publish_order.call_count == 2
```
## Instructions
### Step 1: Structure Use Case Tests with Mocked Dependencies
```python
from __future__ import annotations
from typing import Any
from unittest.mock import AsyncMock, create_autospec
import pytest
from app.extraction.application.use_cases import ExtractOrdersUseCase
from app.extraction.application.ports import ShopifyPort, PublisherPort
from app.extraction.application.dtos import ExtractOrdersRequest, ExtractOrdersResponse
# Fixtures for mocked dependencies
@pytest.fixture
def mock_shopify_gateway() -> AsyncMock:
"""Mock Shopify gateway."""
mock = create_autospec(ShopifyPort, instance=True)
async def fake_orders():
yield create_test_order(order_id="1")
yield create_test_order(order_id="2")
mock.fetch_orders.return_value = fake_orders()
return mock
@pytest.fixture
def mock_event_publisher() -> AsyncMock:
"""Mock Kafka publisher."""
mock = create_autospec(PublisherPort, instance=True)
mock.publish_order.return_value = None
mock.close.return_value = None
return mock
class TestExtractOrdersUseCase:
"""Test extraction use case."""
@pytest.mark.asyncio
async def test_execute_success(
self,
mock_shopify_gateway: AsyncMock,
mock_event_publisher: AsyncMock,
) -> None:
"""Test successful extraction."""
# Arrange
use_case = ExtractOrdersUseCase(
gateway=mock_shopify_gateway,
publisher=mock_event_publisher,
)
# Act
result = await use_case.execute()
# Assert
assert result.total_extracted == 2
assert result.total_published == 2
assert result.total_errors == 0
mock_shopify_gateway.fetch_orders.assert_awaited_once()
assert mock_event_publisher.publish_order.call_count == 2
mock_event_publisher.close.assert_called_once()
```
### Step 2: Test Error Handling and Recovery
```python
@pytest.mark.asyncio
async def test_use_case_with_error_recovery(
mock_shopify_gateway: AsyncMock,
mock_event_publisher: AsyncMock,
) -> None:
"""Test use case handles and recovers from errors."""
# Arrange
async def fake_orders_with_errors():
yield create_test_order(order_id="1")
raise RuntimeError("Temporary API error")
mock_shopify_gateway.fetch_orders.return_value = fake_orders_with_errors()
use_case = ExtractOrdersUseCase(
gateway=mock_shopify_gateway,
publisher=mock_event_publisher,
max_errors=5,
)
# Act
result = await use_case.execute()
# Assert: Extracted some, had 1 error
assert result.total_extracted == 1
assert result.total_published == 1
assert result.total_errors == 1
@pytest.mark.asyncio
async def test_use_case_aborts_after_max_errors(
mock_shopify_gateway: AsyncMock,
mock_event_publisher: AsyncMock,
) -> None:
"""Test use case aborts when errors exceed threshold."""
from app.extraction.application.exceptions import ExtractionException
# Arrange
mock_event_publisher.publish_order.side_effect = RuntimeError("Kafka down")
async def fake_orders():
for i in range(20):
yield create_test_order(order_id=str(i))
mock_shopify_gateway.fetch_orders.return_value = fake_orders()
use_case = ExtractOrdersUseCase(
gateway=mock_shopify_gateway,
publisher=mock_event_publisher,
max_errors=10,
)
# Act & Assert
with pytest.raises(ExtractionException, match="Too many errors"):
await use_case.execute()
# Verify cleanup
mock_event_publisher.close.assert_called()
```
### Step 3: Test DTO Creation and Validation
```python
from __future__ import annotations
from pydantic import ValidationError
import pytest
from app.extraction.application.dtos import ExtractOrdersRequest
from app.reporting.adapters.api.dtos import ProductRankingDTO
class TestExtractOrdersRequestDTO:
"""Test DTO for use case input."""
def test_valid_creation(self) -> None:
"""Test DTO creation with valid data."""
from datetime import datetime
request = ExtractOrdersRequest(
start_date=datetime(2024, 1, 1),
end_date=datetime(2024, 12, 31),
)
assert request.start_date.year == 2024
assert request.end_date.month == 12
def test_validation_end_before_start_fails(self) -> None:
"""Test DTO validation fails when dates are invalid."""
from datetime import datetime
with pytest.raises(ValidationError, match="end_date must be after start_date"):
ExtractOrdersRequest(
start_date=datetime(2024, 12, 31),
end_date=datetime(2024, 1, 1), # Before start!
)
def test_serialization_to_dict(self) -> None:
"""Test DTO serializes to dict correctly."""
from datetime import datetime
request = ExtractOrdersRequest(
start_date=datetime(2024, 1, 1),
end_date=datetime(2024, 12, 31),
)
data = request.model_dump()
assert "start_date" in data
assert "end_date" in data
class TestProductRankingDTO:
"""Test DTO for API response."""
def test_valid_creation(self) -> None:
"""Test DTO with valid data."""
dto = ProductRankingDTO(
title="Laptop",
cnt_bought=100,
)
assert dto.title == "Laptop"
assert dto.cnt_bought == 100
def test_validation_negative_count_fails(self) -> None:
"""Test DTO validates cnt_bought is non-negative."""
with pytest.raises(ValidationError):
ProductRankingDTO(
title="Laptop",
cnt_bought=-5, # Invalid!
)
def test_serialization_to_json(self) -> None:
"""Test DTO serializes to JSON."""
dto = ProductRankingDTO(title="Laptop", cnt_bought=100)
json_data = dto.model_dump_json()
assert "Laptop" in json_data
assert "100" in json_data
```
### Step 4: Test Use Case Interactions with Multiple Dependencies
```python
@pytest.mark.asyncio
async def test_use_case_coordinates_multiple_services(
mock_gateway: AsyncMock,
mock_publisher: AsyncMock,
mock_logger: AsyncMock,
) -> None:
"""Test use case coordinates multiple dependencies correctly."""
use_case = ExtractOrdersUseCase(
gateway=mock_gateway,
publisher=mock_publisher,
logger=mock_logger,
)
result = await use_case.execute()
# Verify coRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.