Hypothesis : Tests basés sur les propriétés

VérifiéSûr

Utilisez Hypothesis pour automatiser la génération de cas de test, trouver des cas limites et écrire des tests robustes avec réduction d'exemples.

Spar Skills Guide Bot
TestingIntermédiaire
23/07/2026
Claude CodeCursorWindsurfCopilotCodex
#property-based-testing#python#pytest#test-generation#stateful-testing

Recommandé pour

Synthèse automatique

Guide l'utilisation de Hypothesis pour les tests basés sur les propriétés en Python, avec stratégies, réglages, aides et tests avec état.

Points forts

  • Couvre l'API des stratégies, les combinateurs et les stratégies composites avec des exemples concis.
  • Montre la configuration par profils pour le développement et la CI, ainsi que les aides assume, note, example et seed.
  • Présente un modèle de test avec état pour les machines à états basées sur des règles.
  • Renvoie à la documentation officielle pour approfondir.

Limites

  • Suppose une certaine familiarité avec pytest et les tests Python ; ce n'est pas un tutoriel complet sur la conception de tests.
  • Les tests basés sur les propriétés exigent de formuler de bons invariants, ce que le skill n'enseigne pas entièrement.
  • L'intégration Polars n'est que brièvement mentionnée dans le contenu visible.
Quand l'utiliser

À utiliser lorsqu'on écrit ou améliore des tests Python devant vérifier des invariants sur un large éventail d'entrées, notamment avec pytest.

Quand l'éviter

À éviter pour de simples tests unitaires par exemples, ou lorsque le comportement attendu ne peut pas être exprimé par des propriétés ou invariants clairs.

Analyse de sécurité

Sûr
Score qualité85/100

The skill is a documentation/reference guide for Hypothesis property-based testing. It contains only Python examples and links to official documentation, with no destructive commands, exfiltration, obfuscation, or safety-disabling instructions.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Integer property test
Write a pytest test using Hypothesis that checks a sorting function returns a list with the same elements as the input and in non-decreasing order.
CI profile setup
Add a Hypothesis settings profile named ci with max_examples=1000 and deadline=None, and explain how to activate it with the HYPOTHESIS_PROFILE environment variable.
Stateful list test
Create a Hypothesis RuleBasedStateMachine test for a simple list-like class with add and clear rules and an invariant that the size is never negative.

name: hypothesis description: Use Hypothesis for property-based testing to automatically generate comprehensive test cases, find edge cases, and write more robust tests with minimal example shrinking. Includes Polars parametric testing integration.

Hypothesis - Property-Based Testing

Property-based testing framework that generates test cases automatically, finds minimal failing examples through shrinking, and verifies invariants.

Official Docs: https://hypothesis.readthedocs.io/en/latest/

Key Features:

  • Automatic test data generation from strategies
  • Minimal failing example shrinking
  • Stateful testing with rule-based state machines
  • pytest integration
  • Deterministic reproducibility

Quick Start

from hypothesis import given
from hypothesis import strategies as st


@given(st.integers())
def test_property(x):
    """Test properties that should always hold"""
    assert abs(x) >= 0


@given(st.lists(st.integers()))
def test_list_property(lst):
    sorted_lst = sorted(lst)
    assert len(sorted_lst) == len(lst)
    # Check monotonic property
    for i in range(len(sorted_lst) - 1):
        assert sorted_lst[i] <= sorted_lst[i + 1]

Strategies

Full reference: https://hypothesis.readthedocs.io/en/latest/data.html

Common strategies:

  • Primitives: st.integers(), st.floats(), st.text(), st.booleans()
  • Collections: st.lists(), st.dictionaries(), st.tuples(), st.sets()
  • Dates/Times: st.dates(), st.datetimes(), st.timedeltas()
  • Combinators: st.one_of(), st.sampled_from(), st.recursive()
  • Type-based: st.from_type(MyClass)

Composite Strategies

from hypothesis import strategies as st
from hypothesis.strategies import composite


@composite
def user_strategy(draw):
    age = draw(st.integers(min_value=18, max_value=100))
    name = draw(st.text(min_size=1))
    return {"name": name, "age": age, "is_adult": age >= 18}


@given(user_strategy())
def test_user(user):
    assert user["is_adult"] == (user["age"] >= 18)

Strategy Combinators

st.integers().filter(lambda x: x % 2 == 0)  # Filter
st.integers().map(str)  # Transform
st.one_of(st.integers(), st.text())  # Choose between strategies
st.sampled_from([1, 2, 3, 4, 5])  # Pick from collection
st.from_type(MyClass)  # Infer from type hints
st.builds(MyClass, arg1=st.integers())  # Build instances

Settings

from hypothesis import given, settings
from hypothesis import strategies as st


@given(st.integers())
@settings(
    max_examples=1000,  # Default: 100
    deadline=None,  # Remove time limit
    derandomize=True,  # Deterministic ordering
)
def test_example(x):
    pass


# Profiles for different environments
settings.register_profile("dev", max_examples=10)
settings.register_profile("ci", max_examples=1000, deadline=None)
# Activate: HYPOTHESIS_PROFILE=ci pytest

Full settings reference: https://hypothesis.readthedocs.io/en/latest/settings.html

Helpers

from hypothesis import given, assume, note, example, seed


@given(st.integers(), st.integers())
def test_division(x, y):
    assume(y != 0)  # Skip invalid cases (prefer .filter() instead)
    note(f"Testing {x} / {y}")  # Add debug info
    assert (x / y) * y == x


@given(st.integers())
@example(0)  # Always test specific cases
@seed(12345)  # Reproducible run
def test_something(x):
    pass

Stateful Testing

For testing complex stateful systems with rule-based state machines.

from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
from hypothesis import strategies as st


class MyStateMachine(RuleBasedStateMachine):
    def __init__(self):
        super().__init__()
        self.data = []

    @rule(value=st.integers())
    def add(self, value):
        self.data.append(value)

    @invariant()
    def check_invariant(self):
        assert isinstance(self.data, list)


TestMachine = MyStateMachine.TestCase

Full stateful testing guide: https://hypothesis.readthedocs.io/en/latest/stateful.html

Polars Integration

Polars provides built-in parametric testing strategies for generating DataFrames.

Official docs: https://docs.pola.rs/api/python/stable/reference/api/polars.testing.parametric.dataframes.html

from hypothesis import given
import polars as pl
from polars.testing.parametric import dataframes, column


# Generate DataFrames with specific column schemas
@given(
    dataframes(
        cols=[
            column("id", dtype=pl.Int64),
            column("name", dtype=pl.String),
            column("value", dtype=pl.Float64),
        ],
        min_size=1,
        max_size=100,
    )
)
def test_dataframe_property(df: pl.DataFrame):
    """Test properties of DataFrame operations"""
    assert df.shape[0] >= 1
    assert set(df.columns) == {"id", "name", "value"}
    assert df["id"].dtype == pl.Int64


# With Narwhals wrapper
import narwhals as nw


@given(dataframes(cols=[column("a", dtype=pl.Int64)]))
def test_narwhals_operation(df: pl.DataFrame):
    nw_df = nw.from_native(df)
    result = nw_df.select(nw.col("a") * 2)
    assert result.shape[0] == nw_df.shape[0]

Key functions:

  • dataframes(): Generate DataFrames with specified columns
  • column(name, dtype, ...): Define column schemas with constraints
  • series(): Generate standalone Series

Column constraints:

  • null_probability: Control null value frequency
  • min_size/max_size: Control row count
  • allow_null: Enable/disable nulls
  • unique: Generate unique values
  • strategy: Custom strategy for column values

Best Practices

  • Use constraints over filters: st.integers(min_value=0) not st.integers().filter(lambda x: x >= 0)
  • Test properties, not examples: Focus on invariants that always hold
  • Combine with @example(): Test specific edge cases explicitly
  • Avoid assume() overuse: Makes tests slow; use filtered strategies
  • Document properties: Clear docstrings explain what invariant is tested
  • Set size limits: Always bound collection sizes to prevent memory issues
  • Use .hypothesis/ in .gitignore: Stores example database locally

Troubleshooting

Common issues and solutions:

  • HealthCheck failures: Too many rejected examples → use constrained strategies or suppress_health_check
  • Flaky tests: Non-deterministic code → use @seed() or @settings(derandomize=True)
  • Slow tests: Too many examples → reduce max_examples or use profiles
  • Deadline exceeded: Complex operations → increase deadline or set to None

Resources

  • Main docs: https://hypothesis.readthedocs.io/
  • Strategies: https://hypothesis.readthedocs.io/en/latest/data.html
  • Stateful testing: https://hypothesis.readthedocs.io/en/latest/stateful.html
  • Ghost writer (auto-generate tests): hypothesis write mymodule.myfunction

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/hypothesis-property-based-testing-mrx3xzpd/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/hypothesis-property-based-testing-mrx3xzpd' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/hypothesis-property-based-testing-mrx3xzpd/download' --output '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md.part' && mv '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md.part' '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/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.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

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/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && test -s '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/hypothesis' && cp -R '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd' '.claude/skills/hypothesis'

Cursor
test -f '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && test -s '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/hypothesis' && cp -R '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd' '.cursor/skills/hypothesis'

Codex
test -f '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && test -s '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/hypothesis' && cp -R '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd' '.agents/skills/hypothesis'

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/hypothesis-property-based-testing-mrx3xzpd'

openskills read 'hypothesis-property-based-testing-mrx3xzpd'

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/hypothesis-property-based-testing-mrx3xzpd/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