Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

hypothesis

БесплатноБез исполняемых скриптовНе проверен

Hypothesis is a Python library for property-based testing: a test states a rule that must hold for all inputs, and Hypothesis generates hundreds of inputs…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Hypothesis — Property-based testing for Python

Overview

An ordinary test checks a few hand-picked inputs. A Hypothesis test describes the inputs with a strategy and asserts something that must be true for every one of them. Hypothesis runs the test 100 times by default with generated values, remembers failures, and shrinks a failing input to a minimal one. It fits pure functions, parsers, serializers, money and date arithmetic, and any code with an invariant that can be written down.

Instructions

Installation

pip install hypothesis pytest
pip install "hypothesis[cli]"      # adds the `hypothesis` command, including `hypothesis write`

Integrations come as extras with their own dependencies, among them numpy, pandas, django, dateutil, pytz, lark, redis and codemods: for example pip install "hypothesis[numpy]".

Write a property test

from hypothesis import given, strategies as st

from billing.installments import split_installments


@given(
    total_cents=st.integers(min_value=0, max_value=5_000_000),
    count=st.integers(min_value=1, max_value=36),
)
def test_installments_add_up_to_the_total(total_cents, count):
    parts = split_installments(total_cents, count)
    assert len(parts) == count
    assert sum(parts) == total_cents
pytest tests/test_installments.py

The test is a normal function; pytest and unittest collect it as usual. @given fills arguments from the right, so a pytest fixture goes first in the signature, or all strategies are passed by keyword as above.

Properties that work well: a round trip returns the original (decode(encode(x)) == x), an invariant holds (sum, length, ordering), two implementations agree, an operation applied twice equals applying it once, valid input never raises.

Choose strategies

Strategy Generates
st.integers(min_value=0, max_value=120) integers in a range
st.floats(min_value=0, max_value=1e6, allow_nan=False) floats; without bounds also nan and inf
st.decimals(min_value="0.00", max_value="9999.99", places=2) Decimal values for money
st.text(min_size=1, max_size=40) Unicode strings
st.from_regex(r"[A-Z]{3}-[0-9]{4}", fullmatch=True) strings that match a pattern
st.lists(st.integers(), min_size=1, unique=True) lists; also st.sets, st.tuples, st.dictionaries
st.fixed_dictionaries({"sku": st.text(), "qty": st.integers(1, 20)}) dictionaries with fixed keys
st.sampled_from(["EUR", "USD", "GBP"]) one of the given values, or an Enum member
st.dates(), st.datetimes(), st.timedeltas() date and time values
st.booleans(), st.none(), st.uuids(), st.emails() the named types
st.one_of(st.none(), st.integers()) a value from any of the strategies
st.builds(Order, sku=st.text(), qty=st.integers(1, 20)) instances of a class or results of a callable
st.from_type(Order) a strategy derived from type annotations

Shape and combine inputs

from hypothesis import assume, given, strategies as st

even_numbers = st.integers().map(lambda n: n * 2)
nonzero = st.integers().filter(lambda n: n != 0)


@st.composite
def date_ranges(draw):
    start = draw(st.dates())
    end = draw(st.dates(min_value=start))
    return (start, end)


@given(date_ranges())
def test_range_is_ordered(date_range):
    start, end = date_range
    assert start <= end


@given(st.integers(), st.integers())
def test_remainder_is_smaller_than_divisor(a, b):
    assume(b != 0)
    assert abs(a % b) < abs(b)

.map transforms values, .filter rejects values of one strategy, and assume rejects a whole test case. @st.composite builds inputs that depend on each other. When values must be drawn in the middle of a test, take st.data() as an argument and call data.draw(strategy).

Keep failures reproducible

from hypothesis import example, given, strategies as st

from billing.installments import split_installments


@example(total_cents=1, count=2)
@given(total_cents=st.integers(0, 5_000_000), count=st.integers(1, 36))
def test_installments_add_up_to_the_total(total_cents, count):
    assert sum(split_installments(total_cents, count)) == total_cents

@example runs that exact input on every run, before the generated ones. Failures are also stored in the .hypothesis/ directory and replayed first on the next run. To replay a CI failure locally, copy the @reproduce_failure(...) line from the CI output onto the test for the duration of the debugging session, or run pytest --hypothesis-seed=20260914 with the seed you want.

Settings and profiles

import os

from hypothesis import Verbosity, settings

settings.register_profile("dev", max_examples=25)
settings.register_profile("ci", settings.get_profile("ci"), max_examples=500)
settings.register_profile("debug", max_examples=10, verbosity=Verbosity.verbose)
settings.load_profile(os.getenv("H
Полный SKILL.md на GitHub

Установить hypothesis в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл hypothesis?

Hypothesis is a Python library for property-based testing: a test states a rule that must hold for all inputs, and Hypothesis generates hundreds of inputs, including edge cases, then reports the simplest one that breaks the rule. Use when a user asks to write property-based tests, fuzz a Python function, find edge cases, test a round trip such as encode and decode, write stateful tests, reproduce a failing Hypothesis example, or tune Hypothesis settings and profiles for pytest and CI.

Как установить скилл hypothesis?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл hypothesis запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить hypothesis с