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

Hegel generators. More...

Classes

struct  BasicGenerator
class  CompositeGenerator
class  MappedGenerator
struct  IGenerator
 *‍/ More...
class  Generator
 The base class of all generators. 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...
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  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 that integrates with Hypothesis via Hegel. More...
struct  TextParams
 Parameters for text() generator. More...
struct  CharactersParams
 Parameters for characters() generator. More...
struct  BinaryParams
 Parameters for binary() generator. More...

Functions

template<typename F>
auto compose (F &&fn)
 *‍/
Combinators
template<typename T, typename... Gens>
Generator< T > 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>
Generator< T > 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>
Generator< T > one_of (std::initializer_list< Generator< T > > gens)
 Choose from a list of generators (initializer list).
template<typename... Ts>
Generator< std::variant< Ts... > > variant (Generator< Ts >... gens)
 Generate std::variant from heterogeneous generators.
template<typename T>
Generator< std::optional< T > > optional (Generator< T > gen)
 Generate optional values (present or absent).
Collections
template<typename T>
Generator< std::vector< T > > vectors (Generator< T > elements, VectorsParams params={})
 Generate vectors with elements from another generator.
template<typename T>
Generator< std::set< T > > sets (Generator< T > elements, SetsParams params={})
 Generate sets with elements from another generator.
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... Ts>
Generator< std::tuple< Ts... > > tuples (Generator< Ts >... gens)
 Generate tuples from multiple generators.
Misc
template<typename T>
Generator< T > sampled_from (const std::vector< T > &elements)
 Sample from a fixed set of values.
template<typename T>
Generator< T > 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.
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 (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=false)
 Generate strings matching a regular expression.
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>
requires std::is_integral_v<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>
requires std::is_floating_point_v<T>
Generator< T > floats (FloatsParams< T > params={})
 Generate random floating point numbers.
Primitives
Generator< bool > booleans ()
 Generate random boolean values.
template<typename T>
Generator< T > 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*>.
Random
Generator< HegelRandomrandoms (RandomsParams params={})
 Generate random number generators.

Detailed Description

Hegel generators.

Function Documentation

◆ 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>
Generator< T > hegel::generators::builds ( Gens... gens)

Construct objects using positional constructor arguments.

Generates constructor arguments from the provided generators and calls T's constructor.

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 > builds(Gens... gens)
Construct objects using positional constructor arguments.
Definition builds.h:35
Generator< T > floats(FloatsParams< T > params={})
Generate random floating point numbers.
Definition numeric.h:168
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>
Generator< T > 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.

struct Rectangle {
int width;
int height;
};
integers<int>({.min_value = 1, .max_value = 100})),
integers<int>({.min_value = 1, .max_value = 100}))
);
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:146
Field< MemberPtr, Gen > field(Gen gen)
Create a field specification for builds_agg().
Definition builds.h:73
Generator< T > builds_agg(Fields... fields)
Construct aggregates using named field initialization.
Definition builds.h:102
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

◆ 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.

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:34
T draw(const generators::Generator< T > &gen) const
Draw a random value from a generator.
Definition core.h:371
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:283
Template Parameters
TThe type to generate
Returns
A DerivedGenerator<T> (usable anywhere a Generator<T> is)

◆ 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>
requires std::is_floating_point_v<T>
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 = 0.0, .max_value = 1.0,
.exclude_min = true, .exclude_max = true
});
Template Parameters
TFloating point type (default: double)
Parameters
paramsBounds and exclusion constraints
Returns
Generator producing floats in the specified range

◆ from_regex()

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

Generate strings matching a regular expression.

The pattern is interpreted server-side using Python's re syntax which differs from C++ std::regex — notably it supports \d, \w, \s, non-greedy quantifiers, and Unicode character classes.

// Default: 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}");
// e.g. "xx QX-8271 yy"
// fullmatch = true: the entire generated string matches the pattern,
// as if anchored with ^...$.
auto strict = from_regex("[A-Z]{2}-[0-9]{4}", true);
// e.g. "QX-8271"
Generator< std::string > from_regex(const std::string &pattern, bool fullmatch=false)
Generate strings matching a regular expression.
Parameters
patternRegex pattern (Python re syntax).
fullmatchIf true, the entire generated string must match the pattern (equivalent to anchoring with ^ and $). If false (default), 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.

◆ integers()

template<typename T = int64_t>
requires std::is_integral_v<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});
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>
Generator< T > hegel::generators::just ( T value)

Generate a constant value.

auto answer = just(42);
auto greeting = just("hello");
Generator< T > just(T value)
Generate a constant value.
Definition primitives.h:52
Template Parameters
TThe value type
Parameters
valueThe constant value to generate
Returns
Generator that always produces value

◆ maps()

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.

// 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(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:304
Template Parameters
KKey type
VValue type
Parameters
keysGenerator for map keys
valuesGenerator for map values
paramsSize constraints
Returns
Generator producing maps

◆ one_of() [1/2]

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

Choose from a list of 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/2]

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.

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:172
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()

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.

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:382
Template Parameters
TValue type
Parameters
genGenerator for the value when present
Returns
Generator producing optional 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(gs::randoms());
std::lognormal_distribution<double> dist(0.0, 1.0);
double value = dist(rng);
Hegel generators.
Definition core.h:16
Parameters
paramsConfiguration (use_true_random to switch modes)
Returns
Generator producing HegelRandom instances

◆ sampled_from() [1/3]

template<typename T>
Generator< T > 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});
Generator< T > sampled_from(const std::vector< T > &elements)
Sample from a fixed set of values.
Definition combinators.h:121
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>
Generator< T > 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

◆ sets()

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

Generate sets with elements from another generator.

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:276
Template Parameters
TElement type (must be comparable)
Parameters
elementsGenerator for set elements
paramsSize constraints
Returns
Generator producing sets

◆ text()

Generator< std::string > hegel::generators::text ( 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()

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.

auto pair = tuples(integers<int>(), text());
Generator< std::tuple< Ts... > > tuples(Generator< Ts >... gens)
Generate tuples from multiple generators.
Definition collections.h:397
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.

◆ variant()

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.

auto value = variant(integers<int>(), text(), booleans());
// Returns std::variant<int, std::string, bool>
Generator< std::variant< Ts... > > variant(Generator< Ts >... gens)
Generate std::variant from heterogeneous generators.
Definition combinators.h:361
Template Parameters
TsVariant alternative types
Parameters
gensGenerators for each alternative
Returns
Generator producing variant

◆ vectors()

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

Generate vectors with elements from another generator.

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});
Generator< std::vector< T > > vectors(Generator< T > elements, VectorsParams params={})
Generate vectors with elements from another generator.
Definition collections.h:256
Template Parameters
TElement type
Parameters
elementsGenerator for vector elements
paramsSize and uniqueness constraints
Returns
Generator producing vectors