Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

pytest-mocking-strategypytest 模拟策略

Agent Skill

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

总安装

188

周安装

8

GitHub Stars

1

下载量

66
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:pytest-mocking-strategy(pytest 模拟策略)
来源仓库:https://github.com/dawiddutoit/custom-claude
仓库路径:skills/pytest-mocking-strategy
安装命令:
npx skills add https://github.com/dawiddutoit/custom-claude --skill pytest-mocking-strategy
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dawiddutoit/custom-claude --skill pytest-mocking-strategy

简介

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流,适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令或分析数据处理逻辑。

  • 适用于前端设计相关项目,支持测试模拟策略与依赖隔离。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装,需确认项目虚拟环境、依赖版本和测试入口。
  • 涉及执行脚本、读写文件或访问数据库时,应先明确运行目录和输入输出范围,避免误改生产数据。
  • 可结合原始 README 进一步核验具体用法和功能边界。

SKILL.md

Pytest Mocking Strategy

Purpose

Mocking is essential for unit testing, but over-mocking creates brittle tests that fail on refactoring. This skill provides a comprehensive framework for deciding what to mock, how to mock it safely, and when to use real objects instead.

When to Use This Skill

Use when deciding what to mock in tests with "create mock", "mock external service", "AsyncMock pattern", or "what should I mock".

Do NOT use for domain testing (never mock domain objects), pytest configuration (use pytest-configuration), or test factories (use pytest-test-data-factories).

Quick Start

The golden rule: Mock external boundaries, test the unit in isolation.

from unittest.mock import AsyncMock, create_autospec
import pytest

# ✅ GOOD: Mock external dependency
@pytest.fixture
def mock_shopify_gateway() -> AsyncMock:
    mock = create_autospec(ShopifyGateway, instance=True)
    mock.fetch_orders.return_value = [create_test_order()]
    return mock

# Test uses mocked dependency
async def test_use_case(mock_shopify_gateway: AsyncMock) -> None:
    use_case = ExtractOrdersUseCase(gateway=mock_shopify_gateway)
    result = await use_case.execute()
    assert result.orders_count == 1

Instructions

Step 1: Decide What "The Unit" Is

For function-based code: A single function For class-based code: A single method or the entire class For use cases: The use case orchestration logic (not its dependencies)

Key principle: The unit is what you're testing, everything else should be mocked.

Step 2: Always Use autospec=True (or create_autospec())

autospec prevents typos and ensures you're only mocking real methods:

# ❌ BAD: Without autospec, allows invalid calls
def test_bad():
    mock = Mock()
    mock.typo_method_name()  # No error! Dangerous!

# ✅ GOOD: With autospec, enforces interface
def test_good():
    mock = create_autospec(ShopifyGateway, instance=True)
    # mock.typo_method_name() raises AttributeError
    mock.fetch_orders.return_value = []  # Only real methods work

Step 3: Use AsyncMock for Async Methods

from unittest.mock import AsyncMock

@pytest.fixture
def mock_async_gateway() -> AsyncMock:
    mock = AsyncMock()
    mock.fetch_orders.return_value = [order1, order2]
    return mock

# For async generators:
@pytest.fixture
def mock_async_generator() -> AsyncMock:
    mock = AsyncMock()

    async def fake_generator():
        yield order1
        yield order2

    mock.fetch_orders.return_value = fake_generator()
    return mock

Step 4: Apply the Mocking Decision Matrix

What?Mock?Reasoning
Shopify API calls✅ YESExternal HTTP service
Kafka producers/consumers✅ YESMessage queue boundary
ClickHouse queries✅ YESDatabase boundary
Order domain entity❌ NOPure business logic, no deps
ProductTitle value object❌ NOSimple immutable value
Use case orchestration❌ NOThe unit under test
DTOs❌ NOSimple data containers
Third-party library functions❌ NOTest your code, not Kafka

Step 5: Create Reusable Mock Factories

Store mock factories in conftest.py for reuse across tests:

# tests/unit/conftest.py

from unittest.mock import AsyncMock, create_autospec

@pytest.fixture
def mock_shopify_gateway() -> AsyncMock:
    """Reusable mock for ShopifyGateway."""
    mock = create_autospec(ShopifyGateway, 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_kafka_publisher() -> AsyncMock:
    """Reusable mock for Kafka publisher."""
    mock = create_autospec(PublisherPort, instance=True)
    mock.publish_order.return_value = None
    mock.close.return_value = None
    return mock

Step 6: Mock Complex Side Effects Carefully

Use side_effect for error scenarios, but keep it simple:

# ✅ GOOD: Simple side effect for retry testing
mock_gateway.fetch_orders.side_effect = [
    ShopifyApiException("Temporary error"),
    [order1, order2],  # Succeeds on second call
]

# ❌ BAD: Over-complex side effect (use parametrization instead)
def complex_side_effect(*args, **kwargs):
    if args[0] == "123":
        return order1
    elif args[0] == "456":
        return order2
    else:
        raise ValueError()

mock_gateway.get_order.side_effect = complex_side_effect

Step 7: Know What NOT to Mock

Never mock:

  • Domain entities (Order, ProductRanking)
  • Value objects (ProductTitle, Money, OrderId)
  • Domain validation logic and business rules
  • Simple data structures and DTOs
  • The unit under test itself

Instead:

  • Create real instances
  • Test their behavior directly
  • Use factories for sensible defaults
# ❌ DON'T mock domain objects
def test_bad(mocker):
    mock_order = mocker.Mock()  # Wrong!
    assert mock_order.is_valid()  # Testing the mock, not domain logic

# ✅ DO create real domain objects
def test_good():
    order = Order(
        order_id=OrderId("123"),
        customer_name="John",
        line_items=[create_test_line_item()],
        total_price=Money.from_float(99.99),
    )
    order.validate()  # Testing real business logic
    assert order.is_valid()

Step 8: Verify Mock Interactions Properly

Use mock assertion methods to verify the unit called its dependencies correctly:

async def test_use_case_interactions(mock_gateway: AsyncMock) -> None:
    """Verify use case calls dependencies as expected."""
    use_case = ExtractOrdersUseCase(gateway=mock_gateway)

    await use_case.execute()

    # Verify the gateway was called
    mock_gateway.fetch_orders.assert_awaited_once()  # For async

    # Verify it was called with specific arguments
    mock_gateway.fetch_orders.assert_called_once_with(
        start_date=expected_date,
        end_date=expected_date
    )

    # Verify call count for loops
    assert mock_gateway.publish.call_count == 3

Examples

Example 1: Mock External HTTP API

from unittest.mock import AsyncMock, create_autospec
import pytest
from app.extraction.application.use_cases import ExtractOrdersUseCase
from app.extraction.adapters.shopify import ShopifyGateway

@pytest.fixture
def mock_shopify_gateway() -> AsyncMock:
    """Mock Shopify API calls."""
    mock = create_autospec(ShopifyGateway, instance=True)

    async def fake_orders():
        yield {"id": "1", "total": 100.0}
        yield {"id": "2", "total": 200.0}

    mock.fetch_orders.return_value = fake_orders()
    return mock

@pytest.mark.asyncio
async def test_extract_orders_success(mock_shopify_gateway: AsyncMock) -> None:
    """Test order extraction with mocked API."""
    use_case = ExtractOrdersUseCase(gateway=mock_shopify_gateway)

    result = await use_case.execute()

    assert result.orders_count == 2
    mock_shopify_gateway.fetch_orders.assert_awaited_once()

Example 2: Mock with Error Scenarios

from unittest.mock import AsyncMock
import pytest

@pytest.mark.asyncio
async def test_extract_orders_with_retry(
    mock_shopify_gateway: AsyncMock
) -> None:
    """Test retry logic on temporary failure."""
    # First call fails, second succeeds
    mock_shopify_gateway.fetch_orders.side_effect = [
        RuntimeError("Temporary error"),
        [{"id": "1", "total": 100.0}],
    ]

    use_case = ExtractOrdersUseCase(
        gateway=mock_shopify_gateway,
        max_retries=3
    )

    result = await use_case.execute()

    assert result.orders_count == 1
    assert mock_shopify_gateway.fetch_orders.call_count == 2

Example 3: Builder Pattern for Complex Mocks

from unittest.mock import AsyncMock, create_autospec

class MockGatewayBuilder:
    """Builder for creating configured mocks with sensible defaults."""

    def __init__(self):
        self.mock = create_autospec(ShopifyGateway, instance=True)
        self.orders = []

    def with_orders(self, orders: list) -> "MockGatewayBuilder":
        """Configure mock to return specific orders."""
        async def fake_fetch():
            for order in orders:
                yield order

        self.mock.fetch_orders.return_value = fake_fetch()
        return self

    def with_error(self, error: Exception) -> "MockGatewayBuilder":
        """Configure mock to raise error."""
        self.mock.fetch_orders.side_effect = error
        return self

    def build(self) -> AsyncMock:
        """Return configured mock."""
        return self.mock

# Usage
@pytest.mark.asyncio
async def test_with_builder():
    mock = MockGatewayBuilder()\
        .with_orders([order1, order2])\
        .build()

    use_case = ExtractOrdersUseCase(gateway=mock)
    result = await use_case.execute()
    assert result.orders_count == 2

Example 4: Type-Safe Mocking with Protocols

from typing import Protocol
from unittest.mock import AsyncMock, create_autospec

class OrderRepository(Protocol):
    """Protocol defining repository interface."""

    async def create(self, order_data: dict) -> Order:
        """Create order in storage."""
        ...

@pytest.fixture
def mock_repository() -> AsyncMock:
    """Create type-safe mock repository."""
    mock = create_autospec(OrderRepository, instance=True)
    mock.create = AsyncMock(return_value=Order(id="123"))
    return mock

Requirements

  • Python 3.11+
  • pytest >= 7.0
  • unittest.mock (standard library)
  • Optional: pytest-mock for mocker fixture
  • pytest-asyncio for async test support

See Also

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.33%
按下载量换算24

Claude

29.65%
按下载量换算20

Cursor

20.8%
按下载量换算14

Gemini CLI

11.07%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills