Stratégie de mock avec pytest

VérifiéSûr

Maîtrisez la stratégie de mock avec pytest : autospec, AsyncMock, factories et quand utiliser de vrais objets.

Spar Skills Guide Bot
TestingIntermédiaire
18/08/2026
Claude CodeCursorCopilotCodex
#pytest#mocking#unit-testing#asyncmock#test-isolation

Recommandé pour

Synthèse automatique

Cette skill propose un cadre de décision pour choisir quoi mocker dans des tests pytest, avec autospec, AsyncMock et des fabriques de mocks réutilisables.

Points forts

  • Matrice de décision explicite qui distingue frontières externes à mocker et objets métier à laisser réels
  • Impose autospec/create_autospec pour éviter les mocks permissifs et les fautes de frappe sur les méthodes
  • Couvre les motifs AsyncMock, y compris le retour d'un générateur asynchrone factice
  • Recommande de centraliser les fabriques de mocks dans conftest.py pour la réutilisation

Limites

  • Les exemples sont fortement liés à un domaine e-commerce (Shopify, Kafka, ClickHouse) et doivent être transposés
  • Ne traite ni la configuration pytest ni les factories de données, renvoyées vers des skills distinctes
  • L'extrait de conftest.py fourni est tronqué et doit être complété par l'utilisateur
Quand l'utiliser

À utiliser quand il faut décider ce qui doit être mocké dans un test unitaire ou mettre en place des dépendances mockées typées et isolées.

Quand l'éviter

À éviter pour tester la logique métier du domaine elle-même, configurer pytest ou générer des jeux de données de test.

Analyse de sécurité

Sûr
Score qualité95/100

The skill provides guidance on writing unit tests with mocks in Python, including code examples and best practices. It does not contain any destructive commands, data exfiltration, or obfuscated payloads. The allowed tools (Read, Bash, Write) are standard for code generation and testing, and the content is purely educational.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Autospec fixture for a gateway
Write a pytest fixture that uses create_autospec on my ShopifyGateway with instance=True, makes fetch_orders return two test orders, and then show a test of ExtractOrdersUseCase using that fixture.
Mock or real object?
I'm unit testing my use case. Should I mock the Kafka producer and the ClickHouse repository, or use real objects? Run through the mocking decision matrix and justify each choice.
AsyncMock for async code
My gateway method returns an async generator of orders. Show me the AsyncMock pattern to fake it, including how to assert the awaited calls were made.

name: pytest-mocking-strategy description: | Master mocking strategy for pytest: when to use autospec=True vs manual mocks, AsyncMock patterns for async code, mock builders and factories, and what should NEVER be mocked. Includes type-safe mock creation patterns and decision matrix for mocking vs real objects.

Use when: Creating unit tests with mocked dependencies, deciding whether to mock or use real objects, setting up test isolation, testing use cases with external service boundaries, or building reusable mock factories. allowed-tools: Read, Bash, Write

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 | ✅ YES | External HTTP service | | Kafka producers/consumers | ✅ YES | Message queue boundary | | ClickHouse queries | ✅ YES | Database boundary | | Order domain entity | ❌ NO | Pure business logic, no deps | | ProductTitle value object | ❌ NO | Simple immutable value | | Use case orchestration | ❌ NO | The unit under test | | DTOs | ❌ NO | Simple data containers | | Third-party library functions | ❌ NO | Test 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

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/pytest-mocking-strategy-msy76azv' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/pytest-mocking-strategy-msy76azv/download' --output '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md.part' && mv '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md.part' '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Bash, Write

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

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md' && test -s '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/pytest-mocking-strategy' && cp -R '.skill-downloads/pytest-mocking-strategy-msy76azv' '.claude/skills/pytest-mocking-strategy'

Cursor
test -f '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md' && test -s '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/pytest-mocking-strategy' && cp -R '.skill-downloads/pytest-mocking-strategy-msy76azv' '.cursor/skills/pytest-mocking-strategy'

Codex
test -f '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md' && test -s '.skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/pytest-mocking-strategy' && cp -R '.skill-downloads/pytest-mocking-strategy-msy76azv' '.agents/skills/pytest-mocking-strategy'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/pytest-mocking-strategy-msy76azv'

openskills read 'pytest-mocking-strategy-msy76azv'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/pytest-mocking-strategy-msy76azv/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires