Token导航 LogoToken导航

Agent Skill · 前端设计

pytest-mocking-strategy(pytest 模拟策略)

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

pytest-mocking-strategy 是前端设计类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在前端设计类的 10,216 个 Skill 里排第 9,985。

总安装 188周安装 8GitHub Stars 1下载 66核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 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

这个 Skill 是做什么的

前端设计类 Skill 关注页面结构、视觉规范和组件写法,输出通常是可运行的界面代码。

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流,适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令或分析数据处理逻辑。适用于前端设计相关项目,支持测试模拟策略与依赖隔离。

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

来源仓库内路径:skills/pytest-mocking-strategy

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/dawiddutoit/custom-claude --skill pytest-mocki…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

pytest-mocking-strategy 怎么安装?

在终端执行 npx skills add https://github.com/dawiddutoit/custom-claude --skill pytest-mocking-strateg…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

pytest-mocking-strategy 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

pytest-mocking-strategy 需要什么权限?

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

pytest-mocking-strategy 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

pytest-mocking-strategy 用的人多吗?

公开数据是累计安装 188 次,近一周安装 8 次,下载 66 次,GitHub 1 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

pytest-mocking-strategy 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理前端设计类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

前端设计类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
frontend-design

前端设计 · Codex、Claude

8,823,360126,072只读MIT通过
vercel-composition-patterns

Vercel 组合模式 · Codex、Claude

3,858,81625,893需要联网MIT通过
vercel-react-native-skills

Vercel React native skills 前端 · Codex、Claude

2,468,66425,878只读MIT通过
adapt

adapt 搜索 · Codex、Claude

2,027,04023,125操作浏览器未明确通过
bolder

bolder 分析 · Codex、Claude

2,004,28823,130只读未明确通过
pytest-mocking-strategy

pytest 模拟策略 · 本页

1881需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

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

平台分布

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