Hegel for Python compared with Hypothesis¶
This page records how Hegel for Python differs from Hypothesis 6.168, as a
reference for porting tests. Hegel’s API is modelled on Hypothesis’s, but
matching Hypothesis is not a goal: the differences below are not a to-do list.
tests/hypothesis_port
is Hypothesis’s own test suite ported to the Hegel API, asserting what Hegel
does, with a note per file of what was dropped.
Same job, different shape¶
Hypothesis |
Hegel |
Notes |
|---|---|---|
|
|
Draws happen in the body; names come from the assignment. |
|
|
|
|
|
The body draws with |
|
|
The test case is explicit rather than thread-local. |
|
the test case itself |
Interactive draws are the normal way to draw. |
|
|
Positional values feed draws in order; keywords match draw names. |
|
|
The blob is Hegel’s, printed when |
|
|
|
|
|
Rules take the test case and draw their own arguments; a precondition is |
|
none; write a test |
A test whose failure is finding the value gets it shrunk. |
|
|
|
|
|
Hegel defaults to |
|
|
Takes the grammar’s text, not a |
|
|
|
|
the same names in |
|
|
|
Only under |
|
|
An |
|
|
A |
|
|
Hegel has, Hypothesis lacks¶
Concurrent stateful testing:
max_concurrency > 1runs rules from several threads in engine-scheduled rounds, with per-worker output attribution.tc.repeat(body): engine-sized repetition of a block of a test.Drawing from several threads in one test case:
tc.clone()gives each thread aTestCaseof its own, drawing from an independent choice stream that still shrinks and replays, andset_worker(i)attributes its output to a numbered worker. See Draw from several threads.Nondeterministic-run handling: when a test’s behaviour changes under replay (a concurrent machine, say), the engine confirms each failure by repeated replay and reports it with a caveat describing how reliably it reproduced.
nondeterminism_strictnessmakes that silent (the default), a one-line notice, or aFlakyerror, which is Hypothesis’s behaviour.An engine shared with the Rust, Go, TypeScript and other bindings, so the example database and reproduce blobs behave the same everywhere.
Hypothesis has, Hegel for Python does not¶
deadline: Hegel has no per-test-case time limit.HealthCheck.too_slowonly fails a run whose first ten valid test cases take more than 30 seconds in all.The health checks
function_scoped_fixture,nested_given(a Hegel test called from inside another is anInvalidArgumentinstead) anddiffering_executors.find(),.example(),@seed(setseedin the settings instead),register_randomand the per-test-case seeding of the globalrandom.The strategies
shared,runner,slices,functions,randoms,random_module,decimals,fractions,complex_numbers,timezone_keys, andfloats(width=16).@precondition,@initialize,consumes,multipleandBundlesemantics for state machines,stateful_step_countand a minimum step count, andMachineClass.TestCase. A pool shrinks toward the first value added, where a bundle prefers the most recent.The key/value example database API (
save/fetch/move,.paretoand secondary keys,ReadOnlyDatabase,InMemoryExampleDatabase): Hegel’s database is an opaque directory,database=""disables it, andPhase.reusereplays it.Phase.explain(the explain phase’s comments on which parts of an input matter),settings.backendproviders other than Hegel’s own (crosshair, …),fuzz_one_input, observability callbacks and theHYPOTHESIS_EXPERIMENTAL_OBSERVABILITYoutput.The
hypothesis.extrapackages (numpy, pandas, django, pytz, dateutil, redis, …) other than lark, whichgs.from_larkcovers, the ghostwriter, the CLI andhypothesis.statistics.from_typeof most of what Hypothesis’s type lookup covers beyond value types, generics, enums, dataclasses, TypedDicts, protocols’ registered implementations and annotated constructors: builtins without annotations (exceptions,range,slice, …), typing special forms such asCallable[...]andFinal, and forward references found in caller frames. Recursive types are resolved eagerly rather than deferred, and aProtocolwith no resolvable subclass isResolutionFailedwhen the generator is built rather than aTypeErrorwhen drawn.characters(codec=...)beyond ascii, latin-1 and utf-8.Lambda source in reprs: a filtered or mapped generator reprs with the function’s
__name__, so<lambda>rather than the lambda’s text.Strategy objects cached by argument: two calls of
gs.integers()are two objects.Empty-strategy detection (
is_empty):nothing()only rejects when it is drawn, solists(nothing())can reject test cases rather than always giving[],lists(nothing(), min_size=1)is not an error when built, and an empty registration forfrom_typeis not detected.The pytest plugin’s
--hypothesis-*options and statistics in the terminal summary; Hegel’s plugin has--hegel-profile,--hegel-setting,--hegel-seed,--hegel-verbosity,--hegel-derandomizeand--hegel-database.
Different because the engine behaves differently¶
The failing example is printed as
name = valuelines rather than a call, verbose output saysRunning test caserather thanTrying example, and the drawn values andnote()lines form one document that the binding renders after the final replay, in draw order, so they do not interleave with anything the test itself prints to stdout. See “Output format” below.Reproduce blobs are opaque engine blobs, printed as
@hegel.reproduce_failure("..."). No@seed(...)hint is printed, and noHighest target scoreline.target()steers generation, but the engine begins targeting only after a warm-up (a short one in runs of a thousand cases or more), so a target-driven failure can take more test cases to find than in Hypothesis.By default a failure that does not reproduce on replay is confirmed by repeated replay and reported with a caveat, rather than aborting the run as
Flaky; non-deterministic data generation is reported as a run error. A failure that reproduces only once is dropped once another failure is confirmed.A finite search space is not detected as exhausted early; the engine runs up to
test_casesand does not suppress duplicate inputs. There is no shrinking time limit.Shrinking differs in places: Hegel does not rewrite a
sampled_frombranch of aone_ofinto the wide branch (Hypothesis’s widening pass, which Hegel will not adopt).A skipped test ends the run before anything is saved to the database.
Generator arguments are validated when the generator is built, not when the test runs.
datetimes()andtimes()never setfold, and there is no targeting of DST folds, gaps or leap seconds.from_regexdepends on the engine’s regex generator rather than Python’sre. A pattern that can match nothing over its alphabet is rejected when the generator is built, as in Hypothesis, but with Hegel’s wording.A
deferreddefinition that only refers back to itself abandons the test case as too large once its draws nest close to Python’s recursion limit (so a test drawing nothing else fails a health check), where Hypothesis detects the empty strategy up front.A test whose every input is rejected fails the
filter_too_muchhealth check, where Hypothesis raisesUnsatisfiableonce it detects that a finite space is exhausted; with that check suppressed, Hegel raisesUnsatisfiabletoo.Pool.values_consumed()removes a value from the pool as soon as it is drawn, so a rule rejected bytc.assumeafter drawing one loses it, where a Hypothesisconsumes(bundle)would keep it. A.filteron the consumed values consumes only the value it yields.
Output format¶
Hegel prints a failing input as the draws it made, one per line, and attaches the same text to the exception as a note:
xs = [0, 0]
Hypothesis prints the test call, test_f(xs=[0, 0]).