Hegel 0.17.5
Property-based testing for C++
Loading...
Searching...
No Matches
hegel::generators Namespace Reference

Hegel generators. More...

Classes

class  AnyGenerator
 A generator: a handle to an IGenerator. More...
class  Generator
 A printable generator: TestCase::draw() accepts it. More...
class  Mapped
 The generator that map() returns. More...
class  IGenerator
 The interface of a generator that draws without printing. More...
class  IPrintableGenerator
 The interface of a printable generator: one that can print what it draws, as it draws it. More...
struct  Field
 Helper for named field initialization in builds_agg(). More...
struct  VectorsParams
 Parameters for vectors() generator. More...
struct  SetsParams
 Parameters for sets() generator. More...
struct  MapsParams
 Parameters for maps() generator. More...
struct  SubsequencesParams
 Parameters for subsequences(). More...
struct  SamplesParams
 Parameters for samples(). More...
class  DeferredGeneratorDefinition
 A forward reference to a generator whose definition is provided later. More...
struct  RecursiveParams
 Parameters for recursive() generator. More...
class  DerivedGenerator
 A Generator produced by default_generator<T>(). More...
struct  DomainsParams
 Parameters for domains() generator. More...
struct  IpAddressesParams
 Parameters for ip_addresses() generator. More...
struct  UuidsParams
 Parameters for uuids() generator. More...
struct  IntegersParams
 Parameters for integers() generator. More...
struct  FloatsParams
 Parameters for floats() generator. More...
struct  RandomsParams
 Parameters for randoms() generator. More...
class  HegelRandom
 A random engine whose values Hegel generates. More...
struct  TextParams
 Parameters for text() generator. More...
struct  CharactersParams
 Parameters for characters() generator. More...
struct  BinaryParams
 Parameters for binary() generator. More...
struct  LarkParams
 Parameters for from_lark() generator. More...
struct  RegexParams
 Parameters for the from_regex() overload with an alphabet. More...

Functions

template<typename Impl, typename... Args>
auto make_generator (Args &&... args)
 Wrap a generator implementation in a handle.
uint64_t label_from_name (std::string_view name)
 The label of a generator with no component generators.
uint64_t combine_labels (const std::vector< uint64_t > &labels)
 The label of a generator built from other generators.
template<typename F>
auto compose (F &&fn)
 Build a generator from imperative code that draws from a TestCase.
template<typename T>
DeferredGeneratorDefinition< T, true > deferred ()
 Create a deferred generator definition for forward references.
template<typename T>
DeferredGeneratorDefinition< T, false > deferred_silent ()
 Create a deferred generator definition that is not printable.
template<typename T, typename F>
auto recursive (Generator< T > leaf, F branch, RecursiveParams params={})
 Generate recursively defined values, such as trees.
template<typename T, typename F>
AnyGenerator< T > recursive (AnyGenerator< T > leaf, F branch, RecursiveParams params={})
 Generate recursively defined values from a leaf generator that is not printable.
Combinators
template<typename T, typename... Gens>
auto builds (Gens... gens)
 Construct objects using positional constructor arguments.
template<auto MemberPtr, typename Gen>
Field< MemberPtr, Gen > field (Gen gen)
 Create a field specification for builds_agg().
template<typename T, typename... Fields>
auto builds_agg (Fields... fields)
 Construct aggregates using named field initialization.
template<typename T>
Generator< T > one_of (std::vector< Generator< T > > gens)
 Choose from multiple generators of the same type.
template<typename T>
AnyGenerator< T > one_of (std::vector< AnyGenerator< T > > gens)
 Choose from generators that are not all printable.
template<typename T>
Generator< T > one_of (std::initializer_list< Generator< T > > gens)
 Choose from a list of printable generators (initializer list).
template<typename... Ts>
Generator< std::variant< Ts... > > variant (Generator< Ts >... gens)
 Generate std::variant from heterogeneous generators.
template<typename... Ts>
AnyGenerator< std::variant< Ts... > > variant (AnyGenerator< Ts >... gens)
 Generate std::variant from generators that are not all printable.
template<typename T>
Generator< std::optional< T > > optional (Generator< T > gen)
 Generate optional values (present or absent).
template<typename T>
AnyGenerator< std::optional< T > > optional (AnyGenerator< T > gen)
 Generate optional values from a generator that is not printable.
Collections
template<typename T>
Generator< std::vector< T > > vectors (Generator< T > elements, VectorsParams params={})
 Generate vectors with elements from another generator.
template<typename T>
AnyGenerator< std::vector< T > > vectors (AnyGenerator< T > elements, VectorsParams params={})
 Generate vectors with elements from a generator that is not printable.
template<typename T, typename F, typename = std::enable_if_t<std::is_invocable_v<F, const T&>>>
Generator< std::vector< T > > vectors (Generator< T > elements, VectorsParams params, F unique_by)
 Generate vectors whose elements have distinct keys.
template<typename T, typename F, typename = std::enable_if_t<std::is_invocable_v<F, const T&>>>
AnyGenerator< std::vector< T > > vectors (AnyGenerator< T > elements, VectorsParams params, F unique_by)
 Generate vectors whose elements have distinct keys, from a generator that is not printable.
template<typename T>
Generator< std::set< T > > sets (Generator< T > elements, SetsParams params={})
 Generate sets with elements from another generator.
template<typename T>
AnyGenerator< std::set< T > > sets (AnyGenerator< T > elements, SetsParams params={})
 Generate sets with elements from a generator that is not printable.
template<typename K, typename V>
Generator< std::map< K, V > > maps (Generator< K > keys, Generator< V > values, MapsParams params={})
 Generate maps with configurable key and value types.
template<typename K, typename V>
AnyGenerator< std::map< K, V > > maps (AnyGenerator< K > keys, AnyGenerator< V > values, MapsParams params={})
 Generate maps from generators that are not both printable.
template<typename... Ts>
Generator< std::tuple< Ts... > > tuples (Generator< Ts >... gens)
 Generate tuples from multiple generators.
template<typename... Ts>
AnyGenerator< std::tuple< Ts... > > tuples (AnyGenerator< Ts >... gens)
 Generate tuples from generators that are not all printable.
template<typename T, size_t N>
Generator< std::array< T, N > > arrays (Generator< T > element)
 Generate fixed-size arrays.
template<typename T, size_t N>
AnyGenerator< std::array< T, N > > arrays (AnyGenerator< T > element)
 Generate fixed-size arrays from a generator that is not printable.
template<typename T>
auto permutations (std::vector< T > values)
 Generate permutations of a fixed list of values.
template<typename T>
auto permutations (std::initializer_list< T > values)
 Generate permutations of a fixed list of values (initializer list).
template<typename T>
auto subsequences (std::vector< T > values, SubsequencesParams params={})
 Generate subsequences of a fixed list of values.
template<typename T>
auto subsequences (std::initializer_list< T > values, SubsequencesParams params={})
 Generate subsequences of a fixed list of values (initializer list).
template<typename T>
auto samples (std::vector< T > values, SamplesParams params={})
 Generate samples of a fixed list of values.
template<typename T>
auto samples (std::initializer_list< T > values, SamplesParams params={})
 Generate samples of a fixed list of values (initializer list).
Misc
template<typename T>
auto sampled_from (const std::vector< T > &elements)
 Sample from a fixed set of values.
template<typename T>
auto sampled_from (std::initializer_list< T > elements)
 Sample from a fixed set of values (initializer list).
Generator< std::string > sampled_from (std::initializer_list< const char * > elements)
 Sample from a fixed set of C-string literals.
Generator< std::string > ip_addresses (IpAddressesParams params={})
 Generate IP addresses.
Generator< std::string > uuids (UuidsParams params={})
 Generate UUIDs in canonical hyphenated form.
Typing
template<typename T>
DerivedGenerator< T > default_generator ()
 Create a default generator for type T.
Strings
Generator< std::string > emails ()
 Generate valid email addresses.
Generator< std::string > domains (DomainsParams params={})
 Generate valid domain names.
Generator< std::string > urls ()
 Generate valid URLs.
Generator< std::string > text (const TextParams &params={})
 Generate random text strings.
Generator< std::string > characters (const CharactersParams &params={})
 Generate single-character UTF-8 strings.
Generator< std::vector< uint8_t > > binary (BinaryParams params={})
 Generate random binary data (byte sequences).
Generator< std::string > from_regex (const std::string &pattern, bool fullmatch=true)
 Generate strings matching a regular expression.
Generator< std::string > from_regex (const std::string &pattern, const RegexParams &params)
 Generate strings matching a regular expression, restricted to an alphabet.
Generator< std::string > from_lark (const std::string &grammar, const LarkParams &params={})
 Generate strings of a grammar written in the syntax of the Lark parsing library.
Datetime
Generator< std::string > dates ()
 Generate calendar dates.
Generator< std::string > times ()
 Generate times of day.
Generator< std::string > datetimes ()
 Generate datetimes.
Numeric
template<typename T = int64_t>
Generator< T > integers (IntegersParams< T > params={})
 Generate random integers. For a given integral type T, produces values in the range [std::numeric_limits<T>::min(), std::numeric_limits<T>::max()] by default.
template<typename T = double>
Generator< T > floats (FloatsParams< T > params={})
 Generate random floating point numbers.
Primitives
Generator< bool > booleans ()
 Generate random boolean values.
Generator< bool > weighted_booleans (double p)
 Generate boolean values that are true with probability p.
template<typename T>
auto just (T value)
 Generate a constant value.
Generator< std::string > just (const char *value)
 Overload for just so that just("a string literal") has type Generator<std::string> rather than Generator<const char*>.
Generator< std::monostate > none ()
 Generate the unit value, std::monostate{}.
Random
Generator< HegelRandom > randoms (RandomsParams params={})
 Generate random number generators.

Detailed Description

Hegel generators.

Function Documentation

◆ arrays() [1/2]

template<typename T, size_t N>
AnyGenerator< std::array< T, N > > hegel::generators::arrays ( AnyGenerator< T > element)

Generate fixed-size arrays from a generator that is not printable.

Template Parameters
TElement type
NNumber of elements
Parameters
elementGenerator for each element
Returns
AnyGenerator producing std::array<T, N>

◆ arrays() [2/2]

template<typename T, size_t N>
Generator< std::array< T, N > > hegel::generators::arrays ( Generator< T > element)

Generate fixed-size arrays.

Draws exactly N elements from element, producing a std::array<T, N>. Unlike vectors(), the length is fixed at compile time. N cannot be deduced, so specify it explicitly. The array is printable when element is.

auto rgb = arrays<int, 3>(integers<int>({.min_value = 0, .max_value =
255}));
// Draws std::array<int, 3>
Generator< T > integers(IntegersParams< T > params={})
Generate random integers. For a given integral type T, produces values in the range [std::numeric_lim...
Definition numeric.h:301
Generator< std::array< T, N > > arrays(Generator< T > element)
Generate fixed-size arrays.
Definition collections.h:618
Template Parameters
TElement type
NNumber of elements
Parameters
elementGenerator for each element
Returns
Generator producing std::array<T, N>

◆ binary()

Generator< std::vector< uint8_t > > hegel::generators::binary ( BinaryParams params = {})

Generate random binary data (byte sequences).

Parameters
paramsSize constraints
Returns
Generator producing byte vectors

◆ booleans()

Generator< bool > hegel::generators::booleans ( )

Generate random boolean values.

Returns
Generator producing true or false.

◆ builds()

template<typename T, typename... Gens>
auto hegel::generators::builds ( Gens... gens)

Construct objects using positional constructor arguments.

Generates constructor arguments from the provided generators and calls T's constructor. The value prints as a constructor call, T(<arg>, ...), with each argument as its generator prints it, so the result is printable when every argument generator is.

struct Point {
Point(double x, double y) : x(x), y(y) {}
double x, y;
};
auto point = builds<Point>(
floats<double>({.min_value = 0, .max_value = 100}),
floats<double>({.min_value = 0, .max_value = 100})
);
Generator< T > floats(FloatsParams< T > params={})
Generate random floating point numbers.
Definition numeric.h:337
auto builds(Gens... gens)
Construct objects using positional constructor arguments.
Definition builds.h:83
Template Parameters
TType to construct
GensGenerator types for constructor arguments
Parameters
gensGenerators providing constructor arguments
Returns
Generator producing T instances

◆ builds_agg()

template<typename T, typename... Fields>
auto hegel::generators::builds_agg ( Fields... fields)

Construct aggregates using named field initialization.

Useful for structs where you want to specify fields by name rather than position. Each field() specifies a member pointer and generator. The field draws do not print: the result prints the value it built, by its C++ representation, so it is printable when hegel::is_representable_v is true for T.

struct Rectangle {
int width;
int height;
};
integers<int>({.min_value = 1, .max_value = 100})),
integers<int>({.min_value = 1, .max_value = 100}))
);
Field< MemberPtr, Gen > field(Gen gen)
Create a field specification for builds_agg().
Definition builds.h:119
auto builds_agg(Fields... fields)
Construct aggregates using named field initialization.
Definition builds.h:151
Template Parameters
TAggregate type to construct
FieldsField specification types
Parameters
fieldsField specifications from field()
Returns
Generator producing T instances

◆ characters()

Generator< std::string > hegel::generators::characters ( const CharactersParams & params = {})

Generate single-character UTF-8 strings.

Parameters
paramsCharacter filtering constraints
Returns
Generator producing single-character strings

◆ combine_labels()

uint64_t hegel::generators::combine_labels ( const std::vector< uint64_t > & labels)
inline

The label of a generator built from other generators.

Parameters
labelsIts own label, then the labels of its components.
Returns
The combined label.

◆ compose()

template<typename F>
auto hegel::generators::compose ( F && fn)

Build a generator from imperative code that draws from a TestCase.

The element type is deduced from fn's return type. To force a specific type, give the lambda an explicit trailing return type.

The draws fn makes form one span, so the engine shrinks them as a unit, as it does for map(), flat_map() and filter(). They do not print: the result prints the value fn returns, by its C++ representation, so it is a printable Generator<T> when hegel::is_representable_v is true for T, and an AnyGenerator<T> otherwise.

auto generate_person() {
return gs::compose([](const hegel::TestCase& tc) {
int age = tc.draw(gs::integers<int>());
std::string name = tc.draw(gs::text());
return Person{age, name};
});
}
Handle to the currently-executing test case.
Definition test_case.h:46
T draw(const generators::Generator< T > &gen) const
Draw a random value from a printable generator.
Definition core.h:991
Template Parameters
FA callable taking const TestCase&
Parameters
fnFunction that draws from the TestCase and returns a value
Returns
A generator whose element type is the return type of fn

◆ dates()

Generator< std::string > hegel::generators::dates ( )

Generate calendar dates.

Generates a date between January 01, 0001 through December 31, 9999 in the proleptic Gregorian calendar) and returns the ISO 8601 serialization (YYYY-MM-DD). Values shrink towards January 1st, 2000.

Returns
Generator producing ISO 8601 date strings.

◆ datetimes()

Generator< std::string > hegel::generators::datetimes ( )

Generate datetimes.

Generates datetimes between January 01, 0001 at 00:00:00 and December 31, 9999 at 23:59:59.999999 and returns the ISO 8601 serialization (YYYY-MM-DDTHH:MM:SS[.ffffff]). No timezone is requested; generated values are naive. Examples from this strategy shrink towards midnight on January 1st 2000.

Returns
Generator producing ISO 8601 datetime strings.

◆ default_generator()

template<typename T>
DerivedGenerator< T > hegel::generators::default_generator ( )

Create a default generator for type T.

Dispatches to the appropriate built-in generator based on the type:

  • Primitive types: bool, integers, floats, std::string
  • Containers: vector, set, map, optional, tuple, variant
  • Reflected structs: any struct with public fields (via reflect-cpp)

For structs, each field is generated using default_generator for its type. Call .override(...) on the returned generator to customize individual fields:

struct Person { std::string name; int age; };
integers<int>({.min_value = 0, .max_value = 120})));
DerivedGenerator< T > default_generator()
Create a default generator for type T.
Definition default.h:455
Template Parameters
TThe type to generate
Returns
A DerivedGenerator<T> (usable anywhere a Generator<T> is)

◆ deferred()

template<typename T>
DeferredGeneratorDefinition< T, true > hegel::generators::deferred ( )

Create a deferred generator definition for forward references.

The generator is printable: set() takes a Generator<T>. For a definition that is not printable, use deferred_silent().

Template Parameters
TValue type produced by the eventual generator.
Returns
A DeferredGeneratorDefinition whose generator() handles can be used before set() supplies the implementation.
struct Tree { int leaf; std::vector<Tree> children; };
auto tree = gs::deferred<Tree>();
auto leaf = gs::integers<int>().map([](int v) { return Tree{v, {}}; });
auto branch = gs::compose([tree](const hegel::TestCase& tc) {
return Tree{0, {tc.draw(tree.generator()),
tc.draw(tree.generator())}};
});
tree.set(gs::one_of<Tree>({leaf, branch}));

◆ deferred_silent()

template<typename T>
DeferredGeneratorDefinition< T, false > hegel::generators::deferred_silent ( )

Create a deferred generator definition that is not printable.

As deferred(), but generator() returns an AnyGenerator<T> and set() takes one.

Template Parameters
TValue type produced by the eventual generator.
Returns
A DeferredGeneratorDefinition whose generator() handles can be used before set() supplies the implementation.

◆ domains()

Generator< std::string > hegel::generators::domains ( DomainsParams params = {})

Generate valid domain names.

Generates RFC 1035-compliant fully qualified domain names.

Parameters
paramsLength constraints. max_length (default 255) must be in the range [4, 255];
Returns
Generator producing domain-name strings.

◆ emails()

Generator< std::string > hegel::generators::emails ( )

Generate valid email addresses.

Generates addresses in the format specified by RFC 5322 Section 3.4.1 (i.e. local-part@domain). Values shrink towards shorter local-parts and host domains.

Returns
Generator producing email-address strings.

◆ field()

template<auto MemberPtr, typename Gen>
Field< MemberPtr, Gen > hegel::generators::field ( Gen gen)

Create a field specification for builds_agg().

integers<int>({.min_value = 1, .max_value = 100})),
integers<int>({.min_value = 1, .max_value = 100}))
);
Template Parameters
MemberPtrPointer-to-member specifying which field
GenGenerator type
Parameters
genGenerator for the field value
Returns
A Field specification for use with builds_agg()

◆ floats()

template<typename T = double>
Generator< T > hegel::generators::floats ( FloatsParams< T > params = {})

Generate random floating point numbers.

auto any_float = floats<double>();
auto unit = floats<double>({.min_value = 0.0, .max_value = 1.0});
auto open = floats<double>({
.min_value_exclusive = 0.0, .max_value_exclusive = 1.0
});
auto flush_to_zero_safe = floats<double>({.allow_subnormal = false});

A bound is inclusive (min_value, max_value) or exclusive (min_value_exclusive, max_value_exclusive); giving both forms of one bound is an error. Subnormal values are drawn whenever the bounds admit any, unless allow_subnormal is false; asking for them with bounds that exclude them all, or excluding them from a range that holds nothing else, is an error.

A float is drawn as a 32-bit value, so it shrinks and hits edge cases as a float. Every other type is drawn as a double. Where long double is wider than double, a bound that is not a double is moved inward to the nearest double, so every value is still within the bounds. Bounds with no double between them are an error.

Template Parameters
TFloating point type (default: double)
Parameters
paramsBounds, exclusion and special-value constraints
Returns
Generator producing floats in the specified range

◆ from_lark()

Generator< std::string > hegel::generators::from_lark ( const std::string & grammar,
const LarkParams & params = {} )

Generate strings of a grammar written in the syntax of the Lark parsing library.

The whole grammar language is supported: rules, terminals with string and regex patterns and priorities, import (including Lark's bundled common, python, unicode and lark grammars), ignore, declare, override, extend and templates. The generated strings are ones Lark's Earley parser accepts for the grammar, with ignored terminals such as whitespace and comments inserted where a lexer would skip them. A string that Lark's basic lexer would read differently is avoided where the grammar allows it. A draw that cannot make such a string after several attempts rejects the test case, as a failed TestCase::assume() does.

The value of an explicit terminal (LarkParams::explicit_terminals) is drawn from its generator for each place the terminal occurs. The lexing checks do not apply to these values: the generator must make values that read as the terminal where they land (a value inside a quoted string must not contain a quote, for example). The values count toward LarkParams::max_size. When they make a string too long, Hegel draws the string again with less space for the grammar's own text, and after several attempts it rejects the test case.

import a.b.X reads a/b.lark from LarkParams::import_path, and Lark's bundled grammar of that name is used when the directory has no such file. A relative import (import .lib.X) in a/b.lark reads a/lib.lark, and in the grammar text itself reads lib.lark.

const char* expressions = R"lark(
?start: sum
?sum: product | sum "+" product
?product: atom | product "*" atom
?atom: NUMBER | "(" sum ")"
%import common.NUMBER
%import common.WS
%ignore WS
)lark";
auto expression = tc.draw(from_lark(expressions));
Generator< std::string > from_lark(const std::string &grammar, const LarkParams &params={})
Generate strings of a grammar written in the syntax of the Lark parsing library.
Parameters
grammarThe grammar, in Lark's syntax
paramsThe start rule, explicit terminals, alphabet, size limits and import directory
Returns
Generator producing strings of the grammar
Exceptions
std::invalid_argumentfor a grammar Lark would reject, an undefined start rule, a max_size below the smallest string the grammar can produce, a terminal given more than one generator or that the grammar does not have, or an imported file that exists but cannot be read

◆ from_regex() [1/2]

Generator< std::string > hegel::generators::from_regex ( const std::string & pattern,
bool fullmatch = true )

Generate strings matching a regular expression.

// Default: the entire generated string matches the pattern,
// as if anchored with ^...$.
auto strict = from_regex("[A-Z]{2}-[0-9]{4}");
// e.g. "QX-8271"
// fullmatch = false: generated string only needs to *contain* a match,
// so arbitrary prefix/suffix characters may surround it.
auto loose = from_regex("[A-Z]{2}-[0-9]{4}", false);
// e.g. "xx QX-8271 yy"
Generator< std::string > from_regex(const std::string &pattern, bool fullmatch=true)
Generate strings matching a regular expression.
Parameters
patternRegex pattern
fullmatchIf true (default), the entire generated string must match the pattern (equivalent to anchoring with ^ and $). If false, the generated string need only contain a substring that matches; arbitrary characters may appear before or after the match.
Returns
Generator producing strings that satisfy pattern under the selected match mode.

◆ from_regex() [2/2]

Generator< std::string > hegel::generators::from_regex ( const std::string & pattern,
const RegexParams & params )

Generate strings matching a regular expression, restricted to an alphabet.

auto ascii = from_regex(
"a.c", {.alphabet = CharactersParams{.codec = "ascii"}});
// e.g. "a!c": the wildcard draws only ASCII characters
Parameters for characters() generator.
Definition strings.h:44
Parameters
patternRegex pattern
paramsMatch mode and alphabet
Returns
Generator producing strings that satisfy pattern, every character of which the alphabet can generate.

◆ integers()

template<typename T = int64_t>
Generator< T > hegel::generators::integers ( IntegersParams< T > params = {})

Generate random integers. For a given integral type T, produces values in the range [std::numeric_limits<T>::min(), std::numeric_limits<T>::max()] by default.

auto any_int = integers<int>();
auto bounded = integers<int>({.min_value = 0, .max_value = 100});
auto positive = integers<int>({.min_value = 1});

Integer types wider than 64 bits, such as __int128 where the compiler provides it, are supported.

Template Parameters
TInteger type (default: int64_t)
Parameters
paramsBounds constraints
Returns
Generator producing integers in the specified range

◆ ip_addresses()

Generator< std::string > hegel::generators::ip_addresses ( IpAddressesParams params = {})

Generate IP addresses.

Generates IP addresses serialized to text:

  • IPv4: dotted-quad form (e.g. 192.0.2.5).
  • IPv6: colon-hex form (e.g. 2001:db8::1).

Any address in the selected version's space may be produced.

Parameters
paramsVersion constraint: v = 4 for IPv4 only, v = 6 for IPv6 only, or std::nullopt (default) for a mix of both.
Returns
Generator producing IP-address strings.

◆ just() [1/2]

Generator< std::string > hegel::generators::just ( const char * value)
inline

Overload for just so that just("a string literal") has type Generator<std::string> rather than Generator<const char*>.

Parameters
valueThe constant value to generator
Returns
Generator that always produces value

◆ just() [2/2]

template<typename T>
auto hegel::generators::just ( T value)

Generate a constant value.

auto answer = just(42);
auto greeting = just("hello");
auto just(T value)
Generate a constant value.
Definition primitives.h:70

The result prints the value by its C++ representation, so it is a printable Generator<T> when hegel::is_representable_v is true for T, and an AnyGenerator<T> otherwise.

Template Parameters
TThe value type
Parameters
valueThe constant value to generate
Returns
Generator that always produces value

◆ label_from_name()

uint64_t hegel::generators::label_from_name ( std::string_view name)

The label of a generator with no component generators.

Two generators with the same label are the same kind of generator, for the engine. Derive the label from a name that no other generator uses.

Parameters
nameThe generator's name.
Returns
The label.

◆ make_generator()

template<typename Impl, typename... Args>
auto hegel::generators::make_generator ( Args &&... args)

Wrap a generator implementation in a handle.

Returns a Generator<T> when Impl implements IPrintableGenerator<T>, else an AnyGenerator<T>.

auto points = gs::make_generator<PointGenerator>();
Template Parameters
ImplThe implementation, an IGenerator<T>
ArgsThe types of its constructor arguments
Parameters
argsThe arguments to construct Impl with.
Returns
A handle to a new Impl

◆ maps() [1/2]

template<typename K, typename V>
AnyGenerator< std::map< K, V > > hegel::generators::maps ( AnyGenerator< K > keys,
AnyGenerator< V > values,
MapsParams params = {} )

Generate maps from generators that are not both printable.

Template Parameters
KKey type
VValue type
Parameters
keysGenerator for map keys
valuesGenerator for map values
paramsSize constraints
Returns
AnyGenerator producing maps

◆ maps() [2/2]

template<typename K, typename V>
Generator< std::map< K, V > > hegel::generators::maps ( Generator< K > keys,
Generator< V > values,
MapsParams params = {} )

Generate maps with configurable key and value types.

The map prints its entries in the order they were drawn, each key and value as its generator prints it, so it is printable when both generators are.

// String keys
auto strMap = maps(text(), integers<int>());
// Integer keys
auto intMap = maps(integers<int>(), text());
// With size bounds
auto bounded = maps(text(), integers<int>(), {.min_size = 1,
.max_size = 3});
Generator< std::string > text(const TextParams &params={})
Generate random text strings.
Generator< std::map< K, V > > maps(Generator< K > keys, Generator< V > values, MapsParams params={})
Generate maps with configurable key and value types.
Definition collections.h:436
Template Parameters
KKey type
VValue type
Parameters
keysGenerator for map keys
valuesGenerator for map values
paramsSize constraints
Returns
Generator producing maps

◆ none()

Generator< std::monostate > hegel::generators::none ( )
inline

Generate the unit value, std::monostate{}.

Draws nothing. Useful where a generator is required but carries no information, for example as an alternative of variant().

auto maybe = variant(none(), integers<int>());
// Generator<std::variant<std::monostate, int>>
Generator< std::monostate > none()
Generate the unit value, std::monostate{}.
Definition primitives.h:98
Generator< std::variant< Ts... > > variant(Generator< Ts >... gens)
Generate std::variant from heterogeneous generators.
Definition combinators.h:306
Returns
Generator that always produces std::monostate{}

◆ one_of() [1/3]

template<typename T>
Generator< T > hegel::generators::one_of ( std::initializer_list< Generator< T > > gens)

Choose from a list of printable generators (initializer list).

Template Parameters
TValue type produced by each generator
Parameters
gensGenerators to choose from (must not be empty)
Returns
Generator that picks from gens and forwards do_draw

◆ one_of() [2/3]

template<typename T>
AnyGenerator< T > hegel::generators::one_of ( std::vector< AnyGenerator< T > > gens)

Choose from generators that are not all printable.

A braced list of generators that are not all printable, such as one_of<int>({printable, silent}), converts to this overload.

Template Parameters
TValue type (all generators must produce this type)
Parameters
gensVector of generators to choose from (must not be empty)
Returns
AnyGenerator that delegates to a randomly chosen generator

◆ one_of() [3/3]

template<typename T>
Generator< T > hegel::generators::one_of ( std::vector< Generator< T > > gens)

Choose from multiple generators of the same type.

Randomly selects one generator and uses it to produce a value. The value prints as the chosen generator prints it, so the result is printable when every generator is.

auto range = one_of({
integers<int>({.min_value = 0, .max_value = 10}),
integers<int>({.min_value = 100, .max_value = 110})
});
Generator< T > one_of(std::vector< Generator< T > > gens)
Choose from multiple generators of the same type.
Definition combinators.h:158
Template Parameters
TValue type (all generators must produce this type)
Parameters
gensVector of generators to choose from (must not be empty)
Returns
Generator that delegates to a randomly chosen generator

◆ optional() [1/2]

template<typename T>
AnyGenerator< std::optional< T > > hegel::generators::optional ( AnyGenerator< T > gen)

Generate optional values from a generator that is not printable.

Template Parameters
TValue type
Parameters
genGenerator for the value when present
Returns
AnyGenerator producing optional values

◆ optional() [2/2]

template<typename T>
Generator< std::optional< T > > hegel::generators::optional ( Generator< T > gen)

Generate optional values (present or absent).

Randomly produces either a value from the given generator or std::nullopt. It is printable when gen is.

auto maybe_int = optional(integers<int>());
// Returns std::optional<int>, may be nullopt
Generator< std::optional< T > > optional(Generator< T > gen)
Generate optional values (present or absent).
Definition combinators.h:341
Template Parameters
TValue type
Parameters
genGenerator for the value when present
Returns
Generator producing optional values

◆ permutations() [1/2]

template<typename T>
auto hegel::generators::permutations ( std::initializer_list< T > values)

Generate permutations of a fixed list of values (initializer list).

Template Parameters
TElement type
Parameters
valuesThe values to reorder
Returns
Generator producing reorderings of values

◆ permutations() [2/2]

template<typename T>
auto hegel::generators::permutations ( std::vector< T > values)

Generate permutations of a fixed list of values.

Each generated vector holds all of values in some order. It shrinks toward the original order.

auto order = permutations(std::vector<int>{1, 2, 3, 4, 5});
auto permutations(std::vector< T > values)
Generate permutations of a fixed list of values.
Definition collections.h:718

The result prints the reordered vector by its C++ representation, so it is printable when hegel::is_representable_v is true for T.

Template Parameters
TElement type
Parameters
valuesThe values to reorder
Returns
Generator producing reorderings of values

◆ randoms()

Generator< HegelRandom > hegel::generators::randoms ( RandomsParams params = {})

Generate random number generators.

Returns a Generator that produces HegelRandom instances satisfying UniformRandomBitGenerator, enabling use with any <random> distribution. If use_true_random is set to true then values will be drawn from their usual distribution, seeded by Hegel. Otherwise they will actually be Hegel generated values (and will be shrunk accordingly for any failing test case). Setting use_true_random=false will tend to expose bugs that would occur with very low probability when it is set to true, and this flag should only be set to true when your code relies on the distribution of values for correctness.

Note
Some distributions from <random> do not interact well with Hegel controlling their randomness, and will behave in unpredictable ways, such as causing the program to hang. We recommend using true randoms on RNG instances that you expect to be passed to distributions from <random>.
namespace gs = hegel::generators;
auto rng = tc.draw("rng", gs::randoms());
std::lognormal_distribution<double> dist(0.0, 1.0);
double value = dist(rng);
Hegel generators.
Definition core.h:25
Parameters
paramsConfiguration (use_true_random to switch modes)
Returns
Generator producing HegelRandom instances

◆ recursive() [1/2]

template<typename T, typename F>
AnyGenerator< T > hegel::generators::recursive ( AnyGenerator< T > leaf,
F branch,
RecursiveParams params = {} )

Generate recursively defined values from a leaf generator that is not printable.

As recursive(), but branch receives an AnyGenerator<T>.

Template Parameters
TValue type
FCallable taking an AnyGenerator<T> of sub-values and returning a generator of T
Parameters
leafGenerator for the values that do not recurse
branchFunction that builds a branch from a generator of sub-values
paramsLimits on the depth and the number of leaves
Returns
AnyGenerator producing recursive values

◆ recursive() [2/2]

template<typename T, typename F>
auto hegel::generators::recursive ( Generator< T > leaf,
F branch,
RecursiveParams params = {} )

Generate recursively defined values, such as trees.

leaf generates the values that do not recurse. branch builds one level of recursive structure: it receives a generator of sub-values of the same type, and returns a generator that combines some number of them into one value. Hegel calls it again for each branch it generates.

The engine decides where a value branches, so values range in size from one leaf up to the limits in params, and recursive values are distributed the same way in every Hegel library. Where the structure is not a tree of one type, for example for mutually recursive types, use deferred().

The value prints as leaf and the generators branch returns print it, so the result is printable when leaf is printable and branch returns a Generator<T>.

struct Tree {
int value;
std::vector<Tree> children;
};
auto trees = gs::recursive(
gs::integers<int>().map([](int v) { return Tree{v, {}}; }),
[](gs::Generator<Tree> subtrees) {
return gs::vectors(subtrees, {.max_size = 3})
.map([](std::vector<Tree> children) {
return Tree{0, std::move(children)};
});
});
Template Parameters
TValue type
FCallable taking a Generator<T> of sub-values and returning a generator of T
Parameters
leafGenerator for the values that do not recurse
branchFunction that builds a branch from a generator of sub-values
paramsLimits on the depth and the number of leaves
Returns
Generator producing recursive values

◆ sampled_from() [1/3]

template<typename T>
auto hegel::generators::sampled_from ( const std::vector< T > & elements)

Sample from a fixed set of values.

auto color = sampled_from({"red", "green", "blue"});
auto digit = sampled_from({1, 2, 3, 4, 5});
auto sampled_from(const std::vector< T > &elements)
Sample from a fixed set of values.
Definition combinators.h:105

The result prints the chosen value by its C++ representation, so it is printable when hegel::is_representable_v is true for T.

Template Parameters
TElement type
Parameters
elementsVector of values to sample from (must not be empty)
Returns
Generator that picks from elements

◆ sampled_from() [2/3]

Generator< std::string > hegel::generators::sampled_from ( std::initializer_list< const char * > elements)
inline

Sample from a fixed set of C-string literals.

Parameters
elementsString literals to sample from (must not be empty)
Returns
Generator of std::string picking from elements

◆ sampled_from() [3/3]

template<typename T>
auto hegel::generators::sampled_from ( std::initializer_list< T > elements)

Sample from a fixed set of values (initializer list).

Template Parameters
TElement type
Parameters
elementsValues to sample from (must not be empty)
Returns
Generator that picks from elements

◆ samples() [1/2]

template<typename T>
auto hegel::generators::samples ( std::initializer_list< T > values,
SamplesParams params = {} )

Generate samples of a fixed list of values (initializer list).

Template Parameters
TElement type
Parameters
valuesThe values to choose from
paramsLength constraints and whether to sample with replacement
Returns
Generator producing samples of values

◆ samples() [2/2]

template<typename T>
auto hegel::generators::samples ( std::vector< T > values,
SamplesParams params = {} )

Generate samples of a fixed list of values.

With replacement (the default) each element of the generated vector is chosen independently from the whole of values, so a value can appear any number of times. With replacement = false each of values is used at most once, so the result is a reordered subset of them. Either way it shrinks toward fewer elements, taken from earlier in the list.

auto rolls = samples(std::vector<int>{1, 2, 3, 4, 5, 6},
{.min_size = 2, .max_size = 2});
// e.g. {4, 4}
auto picks = samples(std::vector<int>{1, 2, 3, 4, 5, 6},
{.max_size = 3, .replacement = false});
// e.g. {5, 1, 3}
auto samples(std::vector< T > values, SamplesParams params={})
Generate samples of a fixed list of values.
Definition collections.h:933

The result prints the vector by its C++ representation, so it is printable when hegel::is_representable_v is true for T.

Template Parameters
TElement type
Parameters
valuesThe values to choose from
paramsLength constraints and whether to sample with replacement
Returns
Generator producing samples of values
Exceptions
std::invalid_argumentif the size bounds are inconsistent, min_size is positive and values is empty, or, without replacement, min_size exceeds the number of values

◆ sets() [1/2]

template<typename T>
AnyGenerator< std::set< T > > hegel::generators::sets ( AnyGenerator< T > elements,
SetsParams params = {} )

Generate sets with elements from a generator that is not printable.

Template Parameters
TElement type (must be comparable)
Parameters
elementsGenerator for set elements
paramsSize constraints
Returns
AnyGenerator producing sets

◆ sets() [2/2]

template<typename T>
Generator< std::set< T > > hegel::generators::sets ( Generator< T > elements,
SetsParams params = {} )

Generate sets with elements from another generator.

The set prints its elements in the order they were drawn, each as elements prints it, so it is printable when elements is.

auto int_set = sets(integers<int>());
auto bounded = sets(integers<int>(), {.min_size = 1, .max_size = 5});
Generator< std::set< T > > sets(Generator< T > elements, SetsParams params={})
Generate sets with elements from another generator.
Definition collections.h:388
Template Parameters
TElement type (must be comparable)
Parameters
elementsGenerator for set elements
paramsSize constraints
Returns
Generator producing sets

◆ subsequences() [1/2]

template<typename T>
auto hegel::generators::subsequences ( std::initializer_list< T > values,
SubsequencesParams params = {} )

Generate subsequences of a fixed list of values (initializer list).

Template Parameters
TElement type
Parameters
valuesThe values to choose from
paramsLength constraints
Returns
Generator producing subsequences of values

◆ subsequences() [2/2]

template<typename T>
auto hegel::generators::subsequences ( std::vector< T > values,
SubsequencesParams params = {} )

Generate subsequences of a fixed list of values.

Each generated vector holds some of values, in their original order. It shrinks toward fewer values, taken from earlier in the list.

auto some = subsequences(std::vector<int>{1, 2, 3, 4, 5},
{.min_size = 1});
// e.g. {2, 5}
auto subsequences(std::vector< T > values, SubsequencesParams params={})
Generate subsequences of a fixed list of values.
Definition collections.h:880

The result prints the vector by its C++ representation, so it is printable when hegel::is_representable_v is true for T.

Template Parameters
TElement type
Parameters
valuesThe values to choose from
paramsLength constraints
Returns
Generator producing subsequences of values
Exceptions
std::invalid_argumentif the size bounds are inconsistent or min_size exceeds the number of values

◆ text()

Generator< std::string > hegel::generators::text ( const TextParams & params = {})

Generate random text strings.

Parameters
paramsLength and character filtering constraints
Returns
Generator producing random strings

◆ times()

Generator< std::string > hegel::generators::times ( )

Generate times of day.

Generates a time between 00:00:00 and 23:59:59.999999 and returns the ISO 8601 serialization (HH:MM:SS[.ffffff]). Values shrink towards midnight. No timezone component is requested; generated values are naive.

Returns
Generator producing ISO 8601 time strings.

◆ tuples() [1/2]

template<typename... Ts>
AnyGenerator< std::tuple< Ts... > > hegel::generators::tuples ( AnyGenerator< Ts >... gens)

Generate tuples from generators that are not all printable.

Template Parameters
TsElement types
Parameters
gensGenerators for each tuple element
Returns
AnyGenerator producing tuples

◆ tuples() [2/2]

template<typename... Ts>
Generator< std::tuple< Ts... > > hegel::generators::tuples ( Generator< Ts >... gens)

Generate tuples from multiple generators.

Each generator produces one element of the resulting tuple. The tuple prints each element as its generator prints it, so it is printable when every generator is.

auto pair = tuples(integers<int>(), text());
Generator< std::tuple< Ts... > > tuples(Generator< Ts >... gens)
Generate tuples from multiple generators.
Definition collections.h:530
Generator< bool > booleans()
Generate random boolean values.
Template Parameters
TsElement types
Parameters
gensGenerators for each tuple element
Returns
Generator producing tuples

◆ urls()

Generator< std::string > hegel::generators::urls ( )

Generate valid URLs.

Generates RFC 3986-compliant URLs with either the http or https scheme.

Returns
Generator producing http/https URL strings.

◆ uuids()

Generator< std::string > hegel::generators::uuids ( UuidsParams params = {})

Generate UUIDs in canonical hyphenated form.

Produces lowercase 8-4-4-4-12 hex strings (e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479). By default any version is generated; set version to restrict to a specific RFC 4122 version.

Parameters
paramsVersion constraint: version = 1..5 forces that RFC 4122 version, or std::nullopt (default) for any version.
Returns
Generator producing canonical UUID strings.

◆ variant() [1/2]

template<typename... Ts>
AnyGenerator< std::variant< Ts... > > hegel::generators::variant ( AnyGenerator< Ts >... gens)

Generate std::variant from generators that are not all printable.

Template Parameters
TsVariant alternative types
Parameters
gensGenerators for each alternative
Returns
AnyGenerator producing variant

◆ variant() [2/2]

template<typename... Ts>
Generator< std::variant< Ts... > > hegel::generators::variant ( Generator< Ts >... gens)

Generate std::variant from heterogeneous generators.

Each generator produces one possible variant alternative. The variant prints the alternative as its generator prints it, so it is printable when every generator is.

auto value = variant(integers<int>(), text(), booleans());
// Returns std::variant<int, std::string, bool>
Template Parameters
TsVariant alternative types
Parameters
gensGenerators for each alternative
Returns
Generator producing variant

◆ vectors() [1/4]

template<typename T, typename F, typename = std::enable_if_t<std::is_invocable_v<F, const T&>>>
AnyGenerator< std::vector< T > > hegel::generators::vectors ( AnyGenerator< T > elements,
VectorsParams params,
F unique_by )

Generate vectors whose elements have distinct keys, from a generator that is not printable.

Template Parameters
TElement type
FCallable taking const T& and returning the element's key
Parameters
elementsGenerator for vector elements
paramsSize constraints
unique_byFunction from an element to its key
Returns
AnyGenerator producing vectors with distinct keys

◆ vectors() [2/4]

template<typename T>
AnyGenerator< std::vector< T > > hegel::generators::vectors ( AnyGenerator< T > elements,
VectorsParams params = {} )

Generate vectors with elements from a generator that is not printable.

Template Parameters
TElement type
Parameters
elementsGenerator for vector elements
paramsSize and uniqueness constraints
Returns
AnyGenerator producing vectors

◆ vectors() [3/4]

template<typename T, typename F, typename = std::enable_if_t<std::is_invocable_v<F, const T&>>>
Generator< std::vector< T > > hegel::generators::vectors ( Generator< T > elements,
VectorsParams params,
F unique_by )

Generate vectors whose elements have distinct keys.

Like vectors(), but no two elements of a generated vector have equal keys. unique_by computes the key of an element, and the keys are compared with ==. Do not also set VectorsParams::unique.

struct User { int id; std::string name; };
auto users = vectors(
builds<User>(integers<int>(), text()), {.max_size = 10},
[](const User& user) { return user.id; });
// No two users have the same id.
Generator< std::vector< T > > vectors(Generator< T > elements, VectorsParams params={})
Generate vectors with elements from another generator.
Definition collections.h:285
Template Parameters
TElement type
FCallable taking const T& and returning the element's key
Parameters
elementsGenerator for vector elements
paramsSize constraints
unique_byFunction from an element to its key
Returns
Generator producing vectors with distinct keys

◆ vectors() [4/4]

template<typename T>
Generator< std::vector< T > > hegel::generators::vectors ( Generator< T > elements,
VectorsParams params = {} )

Generate vectors with elements from another generator.

The vector prints each element as elements prints it, so it is printable when elements is.

auto int_vec = vectors(integers<int>());
auto bounded = vectors(integers<int>(), {.min_size = 1, .max_size = 10});
auto unique_vec = vectors(integers<int>(), {.unique = true});
Template Parameters
TElement type
Parameters
elementsGenerator for vector elements
paramsSize and uniqueness constraints
Returns
Generator producing vectors

◆ weighted_booleans()

Generator< bool > hegel::generators::weighted_booleans ( double p)

Generate boolean values that are true with probability p.

Shrinks toward false. weighted_booleans(0.5) is booleans().

auto mostly_true = weighted_booleans(0.9);
Generator< bool > weighted_booleans(double p)
Generate boolean values that are true with probability p.
Parameters
pThe probability of true, between 0 and 1 inclusive.
Returns
Generator producing true or false.
Exceptions
std::invalid_argumentif p is outside [0, 1] or NaN.