Generators¶
All generators live in hegel.generators, conventionally imported as gs:
from hegel import generators as gs
A generator is an immutable description of how to produce values. Building one
validates its arguments, so a bad argument raises
InvalidArgument where the generator is defined, and the same
generator can be drawn from any number of times, in any number of tests.
Numbers and booleans¶
- hegel.generators.integers(min_value: int | None = None, max_value: int | None = None) Generator[int]¶
Generate integers in
[min_value, max_value], inclusive.Either bound may be omitted. Python integers are unbounded, but the values drawn are not: a missing bound is taken to be
2**127values beyond the other bound, or beyond zero when that is further. Values shrink toward zero, or toward the bound nearest zero when zero is out of range.A bound that is not an integer (a
floatwith an integral value is accepted) ormin_value > max_valueis anInvalidArgument.n = tc.draw(gs.integers(min_value=0, max_value=100))
- hegel.generators.floats(min_value: float | None = None, max_value: float | None = None, *, allow_nan: bool | None = None, allow_infinity: bool | None = None, allow_subnormal: bool | None = None, width: int = 64, min_value_exclusive: float | None = None, max_value_exclusive: float | None = None) Generator[float]¶
Generate floating-point numbers in
[min_value, max_value].Either bound may be omitted.
min_value_exclusiveandmax_value_exclusiveset a bound that is itself excluded, in place of the inclusivemin_valueandmax_value; giving both forms of one bound is anInvalidArgument. Values shrink toward0.0, and toward simple values with few significant digits: integers before fractions.allow_nan,allow_infinityandallow_subnormaldefault to whatever the bounds permit. Without bounds, NaN and the infinities are allowed. Setting a bound disables NaN, and asking for it with a bound is anInvalidArgument. Setting both bounds disables infinity; with one bound, the infinity on the unbounded side is allowed unlessallow_infinity=False. Subnormals are allowed when the range contains any.widthis 64 (the default) or 32, in which case every value is exactly representable as a 32-bit float and the bounds must be too.Bounds that are NaN or not real numbers,
min_value > max_value, and any combination that leaves no values (allow_infinity=Falsewithmin_value=math.inf, ormin_value_exclusive=1.0withmax_value=1.0, say) are each anInvalidArgument.probability = tc.draw(gs.floats(min_value=0.0, max_value=1.0)) positive = tc.draw(gs.floats(min_value_exclusive=0.0)) finite = tc.draw(gs.floats(allow_nan=False, allow_infinity=False))
Text and bytes¶
- hegel.generators.text(alphabet: Any = None, *, min_size: int = 0, max_size: int | None = None, codec: str | None = None, min_codepoint: int | None = None, max_codepoint: int | None = None, categories: Iterable[str] | None = None, exclude_categories: Iterable[str] | None = None, include_characters: Iterable[str] | None = None, exclude_characters: Iterable[str] | None = None) Generator[str]¶
Generate Unicode strings of between
min_sizeandmax_sizecharacters, shrinking toward shorter strings of simpler characters ("", then"0").Without
max_sizethe engine applies its default maximum for text: 100 characters, ormin_size + 100whenmin_sizeis larger than that, whatever the alphabet. A negative size ormax_size < min_sizeis anInvalidArgument.alphabetrestricts the characters: a string or sequence of characters, or acharacters()generator. Any other generator is anInvalidArgument; to build text from an arbitrary generator of characters, draw a list of them and join it:gs.lists(chars).map("".join). An empty alphabet gives only"". The keyword filters (codec, codepoint bounds, Unicode categories, included and excluded characters) are shorthand for acharacters()alphabet, with the same meanings, and cannot be combined withalphabet. Surrogate code points are never generated unless asked for by category.Unicode categories follow the Unicode version of the running Python’s
unicodedata, sostr.isalphaand friends agree with them.name = tc.draw(gs.text(min_size=1)) word = tc.draw(gs.text(alphabet="abc", max_size=5)) ascii_text = tc.draw(gs.text(codec="ascii"))
- hegel.generators.characters(*, codec: str | None = None, min_codepoint: int | None = None, max_codepoint: int | None = None, categories: Iterable[str] | None = None, exclude_categories: Iterable[str] | None = None, include_characters: Iterable[str] | None = None, exclude_characters: Iterable[str] | None = None) Generator[str]¶
Generate single characters (strings of length one), shrinking toward
"0".Each argument narrows the characters generated:
codec: only characters that the codec can encode. One of"ascii","latin-1"(or"iso-8859-1") and"utf-8".min_codepoint,max_codepoint: an inclusive range of code points, within0to0x10FFFF.categories: only these Unicode general categories, by two-letter name ("Lu") or by major class ("L"for every letter).exclude_categories: every category but these. Surrogates ("Cs") are always excluded unlesscategoriesnames them.include_characters: characters to allow whatever the other filters say.exclude_characters: characters never to generate.
categoriesandexclude_categoriescannot both be given. An unknown codec or category, an out-of-range code point, ormax_codepoint < min_codepointis anInvalidArgument. Categories follow the Unicode version of the running Python’sunicodedata.upper = tc.draw(gs.characters(categories=["Lu"])) printable_ascii = tc.draw(gs.characters(min_codepoint=32, max_codepoint=126))
- hegel.generators.from_regex(regex: Any, *, fullmatch: bool = True, alphabet: Any = None) Generator[str]¶
Generate strings matching
regex, a pattern string or a compiledre.Pattern(whose flags are honoured).By default the whole string matches, as
re.fullmatch()checks; withfullmatch=Falsethe string merely contains a match, asre.search()would find, and may have arbitrary text around it. (Hypothesis’sfrom_regexdefaults tofullmatch=False.)alphabetrestricts the characters the pattern’s character classes and.may produce, as a string of characters or acharacters()generator; it cannot be empty, and cannot be used with a bytes pattern. A bytes pattern generatesbytes, matching with the semantics ofrefor bytes (\wand friends are ASCII-only).The pattern is parsed and the strings generated by Hegel’s engine, not by
re. A pattern the engine cannot parse, or one that can match nothing over its alphabet, is anInvalidArgumentwhen the generator is built.identifier = tc.draw(gs.from_regex(r"[a-z_][a-z0-9_]*"))
- hegel.generators.from_lark(grammar: str, *, start: str | None = None, explicit: Mapping[str, Generator[str]] | None = None, alphabet: Any = None, max_size: int | None = None, max_depth: int | None = None, import_path: str | PathLike[str] | None = None) Generator[str]¶
Generate strings matching
grammar, a grammar written in the syntax of the Lark parsing library, starting from itsstartrule (or the rule named bystart).The whole grammar language is supported: rules, terminals with string and regex patterns and priorities,
%import(including Lark’s bundledcommon,python,unicodeandlarkgrammars),%ignore,%declare,%override,%extendand templates. Generated strings are ones Lark’s Earley parser accepts for the grammar, with%ignored terminals such as whitespace and comments inserted wherever a lexer would skip them; a string Lark’s basic lexer would read differently is avoided where the grammar allows it. A draw that cannot produce such a string after several attempts rejects the test case, as a failedassume()does. The grammar is parsed and the strings generated by Hegel’s engine: Lark itself need not be installed.explicitmaps terminal names to generators of strings, which supply those terminals’ values instead of their patterns. A terminal the grammar%declares without defining needs one; any other may be overridden. The values are beyond the lexing checks made on the rest of the string: it is the generator’s part to draw values that read as the terminal where they land (a value under a quoted-string terminal should contain no quote, say). A value that is not a string is anInvalidArgumentwhen drawn.alphabetrestricts the characters the terminals’ patterns may produce, as forfrom_regex(): a string of characters or acharacters()generator.max_sizecaps the length of a string in characters, explicit terminals’ values included (default 8192, at most 1048576); a string whose values push it over is drawn again with less room for the grammar’s own text.max_depthcaps how deeply rules nest (default 200, at most 500).import_pathis the directory%imported grammars are read from:%import a.b.Xreadsa/b.larkfrom it, and Lark’s bundled grammars stand in when it has no such file. A relative import (%import .lib.X) ina/b.larkreadsa/lib.lark, and ingrammaritselflib.lark.A grammar Lark would reject, an undefined start rule, a cap below the smallest string the grammar can produce, or an
explicitgenerator for a terminal the grammar does not have is anInvalidArgumentwhen the generator is built.EXPRESSIONS = r''' ?start: sum ?sum: product | sum "+" product ?product: atom | product "*" atom ?atom: NUMBER | "(" sum ")" %import common.NUMBER %import common.WS %ignore WS ''' expression = tc.draw(gs.from_lark(EXPRESSIONS))
- hegel.generators.binary(*, min_size: int = 0, max_size: int | None = None) Generator[bytes]¶
Generate byte strings of between
min_sizeandmax_sizebytes, shrinking toward shorter strings of zero bytes.Without
max_sizethe engine applies its default maximum: 100 bytes, ormin_size + 100whenmin_sizeis larger than that. A negative size ormax_size < min_sizeis anInvalidArgument.
Collections¶
- hegel.generators.lists(elements: Generator[T], *, min_size: int = 0, max_size: int | None = None, unique: bool = False, unique_by: Any = None) Generator[list[T]]¶
Generate lists of values from
elements, with betweenmin_sizeandmax_sizeelements.max_sizedefaults to no fixed limit: the engine decides when to stop, and keeps lists reasonably short. Lists shrink toward fewer elements, and each element shrinks aselementsdoes.unique=Truerequires the elements to be distinct (and hashable).unique_byis a key function, or a tuple of them, each of whose results must be distinct across the list; it cannot be combined withunique. A duplicate element is discarded and another drawn in its place. When the elements are asampled_from()(under anymap()andfilter()), unique lists draw its elements without replacement, so a unique list needing most of them is still found quickly.A negative size,
max_size < min_size, or amin_sizelarger than the number of distinct valueselementsis known to have, is anInvalidArgument.xs = tc.draw(gs.lists(gs.integers(), min_size=1, max_size=10)) ids = tc.draw(gs.lists(gs.integers(), unique=True)) pairs = tc.draw(gs.lists(gs.tuples(gs.text(), gs.integers()), unique_by=lambda p: p[0]))
- hegel.generators.sets(elements: Generator[T], *, min_size: int = 0, max_size: int | None = None) Generator[set[T]]¶
Generate sets of values from
elements, with betweenmin_sizeandmax_sizemembers; the elements must be hashable. Sizes are as forlists(), and a drawn duplicate is discarded and another element drawn in its place.
- hegel.generators.frozensets(elements: Generator[T], *, min_size: int = 0, max_size: int | None = None) Generator[frozenset[T]]¶
Generate frozensets of values from
elements, assets()does.
- hegel.generators.dicts(keys: Generator[Any], values: Generator[Any], *, min_size: int = 0, max_size: int | None = None) Generator[dict[Any, Any]]¶
Generate dicts with keys drawn from
keysand values fromvalues, with betweenmin_sizeandmax_sizeentries.Sizes are as for
lists(). A drawn duplicate key is discarded and another drawn in its place. For dicts with a fixed set of keys, usefixed_dicts().scores = tc.draw(gs.dicts(gs.text(), gs.integers(0, 100)))
- hegel.generators.fixed_dicts(mapping: dict[Any, Generator[Any]], *, optional: dict[Any, Generator[Any]] | None = None) Generator[dict[Any, Any]]¶
Generate dicts with the keys of
mapping, each value drawn from the generator thatmappinggives for its key.Each key of
optional(a dict of the same shape) is present or absent independently, shrinking toward absent. A key in both, or a value that is not a generator, is anInvalidArgument. The keys appear in the order given, required keys first.user = tc.draw(gs.fixed_dicts( {"name": gs.text(), "age": gs.integers(0, 120)}, optional={"email": gs.emails()}, ))
- hegel.generators.tuples(*generators: Generator[Any]) Generator[tuple[Any, ...]]¶
Generate tuples with one element from each generator, in order:
tuples(gs.integers(), gs.text())generates pairs like(0, ""). With no generators it generates only().
- hegel.generators.iterables(elements: Generator[T], *, min_size: int = 0, max_size: int | None = None, unique: bool = False, unique_by: Any = None) Generator[Iterable[T]]¶
Generate one-shot iterables of values from
elements: an iterator over a list thatlists()would generate, with the same arguments. Iterating once exhausts it, which tests code that must not iterate its input twice. The failure report prints the values it started with.
Choosing from values¶
- hegel.generators.sampled_from(elements: Any) Generator[Any]¶
Pick one of
elements, shrinking toward the first.elementsis a sequence (copied if mutable, so later changes to it do not affect the generator), any other iterable (read once), or anEnumclass, whose members are sampled in definition order. AFlagclass also yields the empty flag and combinations of its members. An empty collection, an enum with no members, or aset(which has no stable order to shrink in) is anInvalidArgument.colour = tc.draw(gs.sampled_from(["red", "green", "blue"]))
.filteron the result narrows the elements rather than retrying draws, so even a predicate that accepts one element in thousands finds it.
- hegel.generators.just(value: T) Generator[T]¶
Always generate
value.The same object is returned by every draw, so mutating it in one test case is visible in the next. It is useful as an argument to
one_of()orbuilds(), or as the result of aflat_map().
- hegel.generators.nothing() Generator[Any]¶
A generator with no values: every draw rejects the test case, as
TestCase.rejectdoes.one_of()drops it, soone_of(gs.nothing(), g)isg.
- hegel.generators.permutations(elements: Iterable[T]) Generator[list[T]]¶
Generate reorderings of
elements(any iterable, read once), as lists, shrinking toward the original order.
- hegel.generators.samples(elements: Iterable[T], *, min_size: int = 0, max_size: int | None = None, replacement: bool = True) Generator[list[T]]¶
Generate lists sampled from
elements, with betweenmin_sizeandmax_sizeitems.With
replacement=True(the default) each item is chosen independently, so an element may appear more than once. Withreplacement=Falseeach element is used at most once, in the order drawn, so the size is capped atlen(elements). Amin_sizethat cannot be met is anInvalidArgumentwhen drawn.
- hegel.generators.subsequences(elements: Iterable[T], *, min_size: int = 0, max_size: int | None = None) Generator[list[T]]¶
Generate subsequences of
elements: lists of some of its elements, each used at most once, in their original order. Sizes are as forlists(), capped atlen(elements); amin_sizelarger than that is anInvalidArgumentwhen drawn.
Combining generators¶
- hegel.generators.one_of(*generators: Any) Generator[Any]¶
Draw from one of
generators, shrinking toward the earlier ones.The generators are passed as separate arguments or as one iterable;
a | bisone_of(a, b). Nestedone_ofcalls are flattened,nothing()arguments are dropped, and a single generator is returned as it is.one_of()with no arguments, or an argument that is not a generator, is anInvalidArgument.key = tc.draw(gs.one_of(gs.integers(), gs.text())) key = tc.draw(gs.integers() | gs.text())
- hegel.generators.optional(inner: Generator[T]) Generator[T | None]¶
Generate either
Noneor a value frominner, shrinking towardNone. Passing something other than a generator is anInvalidArgument.
- hegel.generators.composite(function: Callable[[...], T]) Callable[[...], Generator[T]]¶
Define a generator as a function taking a
TestCasefirst.Calling the decorated function with the remaining arguments returns a generator; each draw runs the function body with the test case and those arguments, and the generated value is what the body returns. The body draws with
tc.drawlike a test does, so later draws can depend on earlier ones. Its own draws are not printed separately: the failure report prints the composite’s value.@hegel.composite def sorted_pairs(tc, limit): a = tc.draw(gs.integers(0, limit)) b = tc.draw(gs.integers(a, limit)) return (a, b) @hegel.test def test_pairs(tc): a, b = tc.draw(sorted_pairs(100)) assert a <= b
Decorating a class, or a function without a positional first parameter for the test case, is an
InvalidArgument.hegel.compositeandhegel.generators.compositeare the same function.
- hegel.generators.builds(target: Callable[[...], T], /, *args: Any, **kwargs: Any) Generator[T]¶
Generate values by calling
targetwith arguments drawn from the given generators:builds(f, gs.integers(), name=gs.text())drawsf(n, name=s).Required parameters of
targetthat are not given, and that have a type annotation, are filled in fromfrom_type()of the annotation; parameters with defaults are left to their defaults. The value is printed as the call,f(0, name=''). Atargetthat is not callable, or an argument that is not a generator, is anInvalidArgument.@dataclass class Point: x: int y: int point = tc.draw(gs.builds(Point)) origin_row = tc.draw(gs.builds(Point, y=gs.just(0)))
- hegel.generators.recursive(leaf: Generator[T], branch: Callable[[Generator[T]], Generator[T]], *, max_depth: int = DEFAULT_MAX_DEPTH, max_leaves: int = DEFAULT_MAX_LEAVES) Generator[T]¶
Generate recursively structured data: trees whose leaves come from
leaf.branchreceives a generator of sub-values (each a leaf or a further branch) and returns a generator combining some of them into a compound value. Values are bounded bymax_depth(nesting, default 32) andmax_leaves(default 100; an attempt drawing more leaves is discarded and retried). Values shrink toward a single leaf.json = gs.recursive( gs.none() | gs.booleans() | gs.floats() | gs.text(), lambda children: gs.lists(children) | gs.dicts(gs.text(), children), )
A negative
max_depth, ormax_leavesbelow 1, is anInvalidArgument. For mutually recursive definitions, usedeferred().
- hegel.generators.deferred(definition: Callable[[], Generator[T]]) Generator[T]¶
A generator whose definition is evaluated on first use, enabling recursive and mutually recursive definitions.
definitionis a function of no arguments returning a generator. It is called once, the first time the generator is drawn from (or its label is needed), so it can refer to generators defined after it, including the deferred generator itself:tree = gs.deferred(lambda: gs.none() | gs.tuples(tree, tree))
Draws nested so deeply that Python’s recursion limit is in sight abandon the test case as too large, so a definition that always refers back to itself cannot recurse forever: a test drawing from one fails with
FailedHealthCheck. A definition that resolves only to itself is anInvalidArgument.
Inferring generators from types¶
- hegel.generators.from_type(type_: Any) Generator[Any]¶
A generator of instances of
type_, inferred from the type.type_may be:a type registered with
register_type_generator();a builtin or standard-library value type (
int,str,bytes,float,datetime.date,uuid.UUID,decimal.Decimal,ipaddresstypes, …);a parameterised collection or
typingconstruct (list[int],dict[str, float],tuple[int, ...],int | None,Literal[...],Optional,Annotated,NewType, aTypeVarby its bound or constraints, and type aliases);an
Enum, sampled withsampled_from();a dataclass or
TypedDict, built from its field annotations;an abstract class or protocol, by its resolvable subclasses;
any other class whose constructor’s required parameters are all annotated, built with
builds()(annotated optional parameters are either left to their defaults or generated).
A type that cannot be resolved (a required constructor parameter without an annotation, an abstract class or protocol with no resolvable subclass, an unresolved string annotation) is a
ResolutionFailed, raised when the generator is built.pairs = tc.draw(gs.from_type(list[tuple[int, str]]))
- hegel.generators.register_type_generator(type_: Any, generator: Generator[Any] | Callable[[Any], Generator[Any]]) None¶
Make
from_type()oftype_(and sobuilds()inference of a parameter annotated with it) usegenerator.generatoris a generator, or a callable that takes the type asked for (a parameterisation such asMyBox[int], for a generic) and returns one.from_typeof a class with no registration of its own but with registered subclasses draws from those subclasses’ generators. Registering again replaces the earlier registration. A string in place of a type is anInvalidArgument.gs.register_type_generator(Money, gs.integers(0, 10**6).map(Money))
Dates and times¶
- hegel.generators.dates(min_value: date = dt.date.min, max_value: date = dt.date.max) Generator[date]¶
Generate
datetime.dateobjects in[min_value, max_value], inclusive, shrinking toward 2000-01-01 (or the bound nearest it).The bounds default to the whole range
datetimesupports. Bounds that are not dates (adatetimeis not accepted), ormin_value > max_value, are anInvalidArgument.
- hegel.generators.times(min_value: time = dt.time.min, max_value: time = dt.time.max, *, timezones: Generator[Any] | None = None) Generator[time]¶
Generate
datetime.timeobjects in[min_value, max_value], inclusive, shrinking toward midnight.The bounds must be naive. The times are naive too, unless
timezonesis given: a generator ofdatetime.tzinfoobjects (such astimezones()), one of which is attached to each time.
- hegel.generators.datetimes(min_value: datetime = dt.datetime.min, max_value: datetime = dt.datetime.max, *, timezones: Generator[Any] | None = None, allow_imaginary: bool = True) Generator[datetime]¶
Generate
datetime.datetimeobjects in[min_value, max_value], inclusive, shrinking toward 2000-01-01 00:00 (or the bound nearest it).The bounds must be naive, and the datetimes are naive unless
timezonesis given: a generator ofdatetime.tzinfoobjects (orNone), such astimezones(). The drawn timezone is attached to the drawn wall-clock time, so the bounds limit the local time, not the instant. Withallow_imaginary=False, a local time that does not exist in its timezone (one skipped by a daylight-saving transition) rejects the test case.foldis never set.aware = tc.draw(gs.datetimes(timezones=gs.timezones()))
Bounds that are not naive datetimes,
min_value > max_value, or a timezone generator producing something other thantzinfoobjects are anInvalidArgument.
- hegel.generators.timedeltas(min_value: timedelta = dt.timedelta.min, max_value: timedelta = dt.timedelta.max) Generator[timedelta]¶
Generate
datetime.timedeltaobjects in[min_value, max_value], inclusive, shrinking toward zero: whole days first, then seconds, then microseconds. The bounds default to the whole rangedatetimesupports.
- hegel.generators.timezones(*, no_cache: bool = False) Generator[tzinfo]¶
Generate IANA timezones, as
zoneinfo.ZoneInfoobjects, shrinking toward UTC.The timezones are those
zoneinfo.available_timezones()lists; on a system without a timezone database (Windows, say) install thetzdatapackage. Withno_cache=Trueeach is built withzoneinfo.ZoneInfo.no_cache(), so it is not the same object asZoneInfo(key).
Identifiers and network values¶
- hegel.generators.uuids(*, version: int | None = None, allow_nil: bool = False) Generator[UUID]¶
Generate
uuid.UUIDobjects.With
version(1 to 5) every UUID is an RFC 4122 UUID of that version. Without it, the UUIDs are arbitrary 128-bit values, most of which have no RFC 4122 version. The nil UUID (all zeros) is generated only withallow_nil=True, which cannot be combined withversion. Invalid arguments are anInvalidArgument.
- hegel.generators.ip_addresses(*, v: int | None = None, network: Any = None) Generator[Any]¶
Generate IP addresses, as
ipaddress.IPv4Addressoripaddress.IPv6Addressobjects.v=4orv=6picks one version; by default either may be generated.network(a string such as"10.0.0.0/8", or anipaddress.IPv4Networkoripaddress.IPv6Network) restricts the addresses to that network, including its network and broadcast addresses. Addresses shrink toward the lowest one:0.0.0.0,::, or the network address. Avother than 4 or 6, or one that disagrees withnetwork, is anInvalidArgument.
- hegel.generators.emails() Generator[str]¶
Generate email addresses, as strings.
Each is a local part of RFC 5322
atextcharacters and dots,@, and a domain asdomains()generates. The addresses are well formed, not real.
- hegel.generators.domains(*, max_length: int = 255) Generator[str]¶
Generate fully qualified domain names of at most
max_lengthcharacters, as strings, ending in a top-level domain from the IANA list.max_lengthmust be between 4 and 255 (the default), or it is anInvalidArgument.
The generator class¶
Every generator is an instance of Generator, which provides the
methods for transforming one generator into another. Subclassing it directly is
rarely necessary: composite() covers almost every case. A subclass that
should be drawn with TestCase.draw implements
do_draw_and_print, which prints the value as it draws it; see
Printing values.
- class hegel.generators.Generator¶
A recipe for drawing values of some type from a
TestCase.Generators are built by the functions in
hegel.generatorsand drawn from withTestCase.draw. They are immutable descriptions of how to make a value: the same generator can be drawn from any number of times, in any number of tests. Every generator has the combinatorsmap(),filter()andflat_map(), anda | bisone_of()of the two:evens = gs.integers().map(lambda n: n * 2) small = gs.integers().filter(lambda n: abs(n) < 100) numbers = gs.integers() | gs.floats()
Most custom generators are best written with
composite(). Subclassing is for generators that need to control how their values are printed or how they are labelled.Printing is the generator’s job.
TestCase.drawreports the drawn value, so it needs a printable generator: one that implementsdo_draw_and_print(), drawing its components withtc.draw_and_print(component, printer)and writing its own syntax to the printer as it goes. Such a subclass getsdo_draw()for free:class Coords(gs.Generator[tuple[int, int]]): def do_draw_and_print(self, tc, printer): with printer.group("Coord(", ")"): x = tc.draw_and_print(gs.integers(0, 9), printer) printer.separator() y = tc.draw_and_print(gs.integers(0, 9), printer) return (x, y)
A subclass that implements only
do_draw()draws silently: it can be drawn withTestCase.draw_silentor used as the source ofmap(), andprint_as_repr()orprint_with()make it printable. Drawing it withtc.drawraisesNotPrintable.labelidentifies the generator to the engine’s shrinker: generators drawing the same shape of value share one. A subclass that sets nolabelof its own is labelled by its qualified class name, so two generator classes shrink apart.- do_draw(tc: TestCase) T¶
Produce a value without printing it. Draw component generators with
tc.draw_silent(ortc.draw_and_print), never by calling theirdo_drawdirectly, so each gets a span of its own.The default runs
do_draw_and_print()with a no-op printer, so a printable generator writes its drawing logic once.
- do_draw_and_print(tc: TestCase, printer: PrettyPrinter) T¶
Produce a value, printing its representation to
printeras it is drawn. Must draw exactly the same choices asdo_draw().There is no default: a generator that does not implement it cannot print what it draws, and drawing it with
tc.drawraisesNotPrintable.
- map(f: Callable[[T], U]) Generator[U]¶
A generator of
f(value)for eachvaluethis one generates.The mapped value is what the failure report prints.
fruns every time a value is drawn, and shrinking happens on the underlying value, so a mapped generator shrinks towardfof the source’s simplest value:evens = gs.integers().map(lambda n: n * 2)
- flat_map(f: Callable[[T], Generator[U]]) Generator[U]¶
Generate a value, then draw from the generator
fbuilds from it.fmust return aGenerator; anything else is anInvalidArgument. Only the final value is printed. Use this when the shape of one value depends on another:lists_and_index = gs.integers(1, 10).flat_map( lambda n: gs.tuples( gs.lists(gs.integers(), min_size=n, max_size=n), gs.integers(0, n - 1), ) )
A
composite()generator expresses the same dependency more readably, and is usually the better choice.
- filter(predicate: Callable[[T], bool]) Generator[T]¶
Keep only values satisfying
predicate.Each draw tries the source as many times as the engine’s
HEGEL_FILTER_ATTEMPTS, which every Hegel library’s filter shares; if no attempt satisfiespredicate, the test case is rejected as if byTestCase.assume. A filter that rejects most values therefore rejects many test cases, and may fail thefilter_too_muchhealth check: prefer generating the values you want directly (gs.integers(min_value=0)rather thangs.integers().filter(lambda n: n >= 0)). Chained filters combine into one, and filteringsampled_from()narrows its elements instead of retrying, so even a rare element is found.
- print_with(print: Callable[[T, PrettyPrinter], None]) Generator[T]¶
A generator of the same values that prints each one with
print, in place of however this generator prints.printis called asprint(value, printer)with aPrettyPrinterto write the value’s representation into the failure report; it is only called when the output will be shown. It works on any generator, printable or not, and is the way to print a custom representation or mask a secret:tokens = gs.text().print_with(lambda value, printer: printer.text("<token>"))
- print_as_repr() Generator[T]¶
A generator of the same values that prints each one as its
repr(throughPrettyPrinter.repr), in place of however this generator prints. This makes a subclass that implements onlydo_draw()printable.
- print_as_call(function: str) Generator[T]¶
For a mapped generator: print
function(input)around the source generator’s own output instead of the mapped value.This makes a value whose
repris unhelpful print as the call that built it:points = gs.tuples(gs.integers(), gs.integers()).map( lambda t: Point(*t) ).print_as_call("Point")
prints a drawn point as
Point((0, 0)). Calling it on a generator that is not the result ofmap(), or with an empty name, is anInvalidArgument.