Hypothesis JSONSchema
Hypothesis-jsonschema is a Python library that provides a Hypothesis strategy for generating test data that conforms to a given JSON schema. It is currently in version 0.23.1. As a 0.x release series, it may introduce backwards-incompatible changes before reaching 1.0. It supports JSONSchema drafts 04, 05, and 07, including resolving non-recursive references.
Warnings
- breaking As a 0.x series library, `hypothesis-jsonschema` adheres to semantic versioning but may introduce backwards-incompatible changes at any point before version 1.0. The primary source of such breaks often involves schemas that previously behaved ambiguously or produced incorrect values now raising explicit errors.
- gotcha The library has a known limitation in its support for *recursive* references within JSON schemas (e.g., using `$ref` for self-referential schemas), which are commonly found in complex specifications like OpenAPI. While non-recursive references are supported since v0.11, full recursive support is an ongoing challenge.
- gotcha The 0.x versions of `hypothesis-jsonschema` generally require very recent versions of all its dependencies. This is a design choice by the maintainer to avoid complex compatibility workarounds, which means older dependency versions might not work as expected.
Install
-
pip install hypothesis-jsonschema
Imports
- from_schema
from hypothesis_jsonschema import from_schema
Quickstart
from hypothesis import given, settings, HealthCheck
from hypothesis_jsonschema import from_schema
# Basic example: generate integers within a range
@given(from_schema({"type": "integer", "minimum": 1, "exclusiveMaximum": 10}))
def test_integers(value):
assert isinstance(value, int)
assert 1 <= value < 10
# Example with string formats and avoiding null characters
# (Note: custom_formats argument can be used for non-standard formats)
@given(from_schema({'type': 'string', 'format': 'uuid'}))
def test_uuid_string(value):
import re
assert isinstance(value, str)
assert re.match(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$', value)
# To demonstrate, typically you'd run these with pytest or similar test runner
# For standalone execution, you'd call the functions, but Hypothesis normally runs tests implicitly
# Example of using settings to suppress health checks if needed (not recommended for general use)
@given(from_schema({"type": "number"}))
@settings(suppress_health_check=[HealthCheck.filter_too_much])
def test_numbers(value):
assert isinstance(value, (int, float))
print("Quickstart examples defined. Run with pytest to execute.")