Hypothesis
repository·master·Indexed 27 days ago
https://github.com/hypothesisworks/hypothesisA property-based testing library for Python that automatically generates diverse test inputs and edge cases to find bugs, providing the simplest possible failing case through a process called shrinking.
What's inside hypothesis
- Hypothesis Build Tooling is a specialized software suite designed for managing build tasks and releases specifically for the Hypothesis project.
Overview of Hypothesis property-based testing
masterHypothesis is a property-based testing library for Python. Instead of writing individual test cases with specific inputs, you define the properties of your code and the range of inputs it should accept using 'strategies'. Hypothesis then automatically generates a wide variety of inputs, including edge cases, to attempt to falsify your properties. When a failure is found, Hypothesis performs 'shrinking' to report the simplest possible input that triggers the bug.Introduction to Hypothesis property-based testing
masterHypothesis is a property-based testing library for Python. Instead of writing individual test cases with specific inputs, you define the properties your code should satisfy and the range of inputs it should accept. Hypothesis then automatically generates a wide variety of inputs, including edge cases, to attempt to falsify your properties.
To use Hypothesis, you typically use the
@givendecorator combined withstrategies(often imported asst) to describe the data types and structures your test function expects.from hypothesis import given, strategies as st @given(st.lists(st.integers() | st.floats())) def test_sort_correctness_using_properties(lst): result = my_sort(lst) assert set(lst) == set(result) assert all(a <= b for a, b in zip(result, result[1:]))Introduction to HypoFuzz
masterHypoFuzz is a service designed to extend Hypothesis testing workflows by providing coverage-guided fuzzing. While standard Hypothesis is used for interactive development and catching regressions (often using
@example()decorators or thephases=setting), HypoFuzz is optimized for finding deep bugs by dedicating server resources to searching for interesting inputs and covering under-tested code paths.Key features include:
- Coverage-guided fuzzing: Uses code coverage to generate new inputs or variations of existing ones to trigger rare behaviors.
- Dynamic search optimization: Automatically allocates more search time to tests that haven't yet 'saturated' their coverage.
- Observability: Provides a dashboard to inspect input distributions and individual test cases.
- Scalability: Can be run on laptops, dedicated servers, or cloud instance pools.
Navigate the Hypothesis API Reference
masterThe Hypothesis technical API reference is organized into four distinct sections depending on your use case:
- API Reference: Contains non-strategy Hypothesis objects, classes, and functions (e.g., the
@givendecorator). - Strategies Reference: Documentation for Hypothesis strategies, including specialized extras.
- Integrations Reference: Details on features that provide a defined interface without a direct code API.
- Hypothesis internals: Documentation for internal APIs intended for developers building tools, libraries, or conducting research on top of Hypothesis.
- API Reference: Contains non-strategy Hypothesis objects, classes, and functions (e.g., the
Understand the /hypothesis command workflow
masterThe
/hypothesiscommand follows a structured four-step process to ensure high-quality property-based tests:- Explore: The model examines the provided code to identify candidate properties.
- Contextualize: The model explores how the codebase calls that code in practice (e.g., checking usage patterns or type hints).
- Write: The model writes Hypothesis tests grounded in the gathered context.
- Verify: The model runs the new tests and reflects on failures to determine if they are genuine bugs or unsound tests, refactoring the test if necessary.
Understand Conjecture Engine Concepts
masterThe core engine of Hypothesis is called Conjecture. It represents randomized test cases as a choice sequence—a sequence of typed primitives (integer, float, boolean, string, or bytestring) drawn via
draw_*methods onConjectureData.Key concepts:
- Choice Sequence: The sequence of choices made during test execution. This acts as the single source of truth for test inputs.
- Shortlex Minimality: The goal of shrinking is to find a choice sequence that is the shortest possible length, and among those of minimal length, the smallest when comparing choices one at a time from the left (using
sort_keyinshrinker.py). - Shrinking: Conjecture approximates the shortlex minimal sequence by applying various transformations to the choice sequence to reduce the input while satisfying test predicates.
Discover Hypothesis extensions and external strategies
masterHypothesis can be extended by various third-party libraries that provide specialized strategies or integrations. You can find these on PyPI by searching for the
hypothesiskeyword or theFramework :: Hypothesisclassifier.Common types of extensions include:
- Direct Strategies: Packages like
hypothesis-fspaths(filesystem paths),hypothesis-geojson(GeoJSON),hypothesis-sqlalchemy(SQLAlchemy objects), andhypothesis-torch(PyTorch structures). - Schema Inference: Packages that generate strategies from existing schemas, such as
hypothesis-jsonschema(JSON Schema),hypothesis-graphql(GraphQL), andhypothesis-pb(Protocol Buffers). - Framework Integrations: Deep integrations like
Pydantic(automatic registration of constrained types),deal(design-by-contract), andTrio(async support viahypothesis-trio).
- Direct Strategies: Packages like
Understand Property-Based Testing with Hypothesis
masterHypothesis is a library for property-based testing. Unlike traditional example-based testing where you manually provide specific inputs, property-based testing allows you to describe the properties or ranges of data your system should handle. Hypothesis then automatically explores a wide range of scenarios and edge cases to find inputs that break your code.Summary of complex data generation strategies
masterHypothesis provides several mechanisms for generating complex data depending on the required level of control:
st.from_type: Automatically infers strategies from type hints. Best when most random inputs are valid and you only need to handle rare edge cases.assumeandfilter: Simple tools to rule out invalid inputs when using inferred types.builds: Used to generate data that must satisfy complex invariants.composite: Provides high control by allowing you to relate multiple draws to each other, ideal for interdependent data.data: Allows interactive value picking directly within the test body for conditional generation.register_type_strategy: Used to associate custom strategies with specific types.
Understand test cases and minimal failing test cases
masterHypothesis uses several terms to describe test inputs:
- Test case: A single Hypothesis-generated input passed to a test function.
- Failing test case: A test case that causes the test to fail (e.g., by raising an exception).
- Minimal failing test case: The specific failing test case that has been fully shrunk (minimized) by Hypothesis. Hypothesis reports only this minimal case to the user at the end of the test run.
Understand Hypothesis Strategies
masterStrategies describe the values that
@givenwill generate for testing. You can pass a strategy to@given, nest strategies within each other, combine them using combinators, or modify them using.filter(),.map(), or.flatmap().Example:
st.lists(st.integers(), min_size=1)tells Hypothesis to generate lists of integers with at least one element.