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

Handle to the currently-executing test case. More...

#include <test_case.h>

Public Member Functions

 TestCase (const TestCase &)=delete
TestCase & operator= (const TestCase &)=delete
 TestCase (TestCase &&) noexcept
 Move-constructs, transferring ownership of the underlying handle.
TestCase & operator= (TestCase &&) noexcept
 Move-assigns, transferring ownership of the underlying handle.
template<typename T>
T draw (const generators::Generator< T > &gen) const
 Draw a random value from a printable generator.
template<typename T>
T draw (std::string_view name, const generators::Generator< T > &gen) const
 Draw a random value from a printable generator, printed under name.
template<typename T>
T draw_silent (const generators::AnyGenerator< T > &gen) const
 Draw a random value from any generator, without printing it.
template<typename T>
T draw_and_print (const generators::Generator< T > &gen, Printer &printer) const
 Draw a value from a printable generator and print it to printer.
void assume (bool condition) const
 Reject the current test case if condition is false.
void reject () const
 Reject the current test case unconditionally.
void target (double score, std::string_view label="") const
 Record a score for the engine's targeted-search phase to maximize.
void event (std::string_view label) const
 Record an event for the end-of-run statistics report.
void event_value (std::string_view label, double value) const
 Record a numeric observation for the end-of-run statistics report.
void repeat (const std::function< void()> &body) const
 Run body over and over until the engine ends the test case. It never returns.
void note (std::string_view message) const
 Record a message that will be printed on the final replay of a failing test case.
TestCase clone () const
 Creates a clone of this test case with an independent choice sequence forked from this test case.
void set_worker (std::size_t worker_index)
 Attribute what this test case prints from now on to a worker.
template<typename F>
auto spawn (F fn) const
 Run fn on a clone of this test case in a new thread.

Detailed Description

Handle to the currently-executing test case.

A TestCase is passed as the sole argument to the callback given to hegel::test(). It is the main way a test definition interacts with Hegel.

TestCase owns its underlying libhegel handle and is move-only (not copyable). The callback receives it by reference; a clone() returns a fresh owning TestCase. It must not outlive the test-case callback.

HEGEL_TEST(example)(hegel::TestCase& tc) {
namespace gs = hegel::generators;
auto x = tc.draw("x", gs::integers<int>({.min_value = 0}));
tc.assume(x != 0);
tc.note("x = " + std::to_string(x));
}
Handle to the currently-executing test case.
Definition test_case.h:46
#define HEGEL_TEST(name,...)
Define a Hegel property test.
Definition hegel.h:667
Hegel generators.
Definition core.h:25

Member Function Documentation

◆ assume()

void hegel::TestCase::assume ( bool condition) const

Reject the current test case if condition is false.

auto age = tc.draw(gs::integers<int>());
tc.assume(age >= 18);
Parameters
conditionValue that must be true for the test case to continue. If false, the current test case is rejected.

◆ clone()

TestCase hegel::TestCase::clone ( ) const

Creates a clone of this test case with an independent choice sequence forked from this test case.

The returned TestCase draws from its own choice sequence but shares this case's outcome and budget. A single test case must not be drawn from concurrently, so give each thread its own clone.

What the clone prints (its notes and drawn values) appears in the output at the point where the clone was made, however the threads are scheduled.

In an explicit test case, the clone draws the same values and names its draws in the same sequence as this test case.

Returns
A TestCase.
auto worker = tc.clone();
auto a = worker.draw(gs::integers<int>());
auto b = tc.draw(gs::integers<int>());

◆ draw() [1/2]

template<typename T>
T hegel::TestCase::draw ( const generators::Generator< T > & gen) const

Draw a random value from a printable generator.

Each draw is printed as a C++ declaration, auto <name> = <value>;, on the final replay of a failing test case and on every case at Verbosity::Verbose and above. The generator prints the value as it draws it (see generators::IPrintableGenerator). A value too wide for one line is broken across lines. Draws made through this overload print as draw_1, draw_2, ... in draw order. Use the named overload to print under a variable name.

Only a printable generator (generators::Generator) can be drawn with draw(). Draw any other generator with draw_silent().

Template Parameters
TThe value type produced by gen
Parameters
genThe generator to draw from
Returns
A generated value of type T

◆ draw() [2/2]

template<typename T>
T hegel::TestCase::draw ( std::string_view name,
const generators::Generator< T > & gen ) const

Draw a random value from a printable generator, printed under name.

Each use of name prints with a 1-based suffix (x_1, x_2, ...), so a draw that runs in a loop, or a helper called more than once, numbers its values in order.

Template Parameters
TThe value type produced by gen
Parameters
nameVariable name for the printed declaration.
genThe generator to draw from
Returns
A freshly generated value of type T

◆ draw_and_print()

template<typename T>
T hegel::TestCase::draw_and_print ( const generators::Generator< T > & gen,
Printer & printer ) const

Draw a value from a printable generator and print it to printer.

For use in generators::IPrintableGenerator::do_draw_and_print(), to draw a component and print it where the component goes. Draws made by gen itself do not print.

Template Parameters
TThe value type produced by gen
Parameters
genThe generator to draw from
printerThe printer to print the value to
Returns
A generated value of type T
Exceptions
std::invalid_argumentin an explicit test case.

◆ draw_silent()

template<typename T>
T hegel::TestCase::draw_silent ( const generators::AnyGenerator< T > & gen) const

Draw a random value from any generator, without printing it.

Draws made by gen itself (for example with draw() inside a generators::compose() function) do not print either.

auto handle = tc.draw_silent(gs::compose(open_file));
Template Parameters
TThe value type produced by gen
Parameters
genThe generator to draw from
Returns
A generated value of type T
Exceptions
std::invalid_argumentin an explicit test case.

◆ event()

void hegel::TestCase::event ( std::string_view label) const

Record an event for the end-of-run statistics report.

With Settings::show_statistics on, the end of the run reports, for each label, the fraction of generated test cases that recorded it at least once. Without it, events report nothing.

Parameters
labelThe event to record.
auto xs = tc.draw(gs::vectors(gs::integers<int>()));
if (xs.empty()) {
tc.event("empty");
}

◆ event_value()

void hegel::TestCase::event_value ( std::string_view label,
double value ) const

Record a numeric observation for the end-of-run statistics report.

With Settings::show_statistics on, the end of the run reports, for each label, a summary of the observed values (count, min, median, mean, p90, max) over the generated test cases. Unlike target(), a label can be observed any number of times per test case, and the observations do not steer generation.

Parameters
labelNames the observed quantity.
valueThe observation. Must be finite.
auto xs = tc.draw(gs::vectors(gs::integers<int>()));
tc.event_value("size", static_cast<double>(xs.size()));

◆ note()

void hegel::TestCase::note ( std::string_view message) const

Record a message that will be printed on the final replay of a failing test case.

The message prints in order with the drawn values, and on every test case at Verbosity::Verbose and above. Each line of a multi-line message prints as its own line.

Parameters
messageThe message to record.

◆ operator=()

TestCase & hegel::TestCase::operator= ( TestCase && )
noexcept

Move-assigns, transferring ownership of the underlying handle.

Returns
Reference to this test case.

◆ reject()

void hegel::TestCase::reject ( ) const

Reject the current test case unconditionally.

Equivalent to assume(false), but marked [[noreturn]] so code after the call is statically known to be unreachable.

auto n = tc.draw(gs::integers<int>());
unsigned u = n >= 0 ? static_cast<unsigned>(n) : tc.reject();
void reject() const
Reject the current test case unconditionally.

◆ repeat()

void hegel::TestCase::repeat ( const std::function< void()> & body) const

Run body over and over until the engine ends the test case. It never returns.

The loop is logically infinite: the engine decides how many repetitions run, so a failing loop shrinks to the fewest, and when the engine ends the loop the test case ends as passing. Code after the call never runs. Use it for workload-style tests that drive a system with a stream of random operations. Each repetition's draws and notes print indented under a // Repetition #N note. A repetition rejected with assume() or reject() is skipped and the loop goes on; any other exception fails the test case.

In an explicit test case the body runs once, and the test case ends.

Parameters
bodyCallable invoked once per repetition.
int total = 0;
tc.repeat([&] {
total += tc.draw(gs::integers<int>({.min_value = 0}));
if (total < 0) throw std::runtime_error("overflow");
});

◆ set_worker()

void hegel::TestCase::set_worker ( std::size_t worker_index)

Attribute what this test case prints from now on to a worker.

When several threads each draw from their own clone, give each clone a worker index so the output says which thread printed what. Every line this test case prints after the call, and every line of the blocks and clones made from it after the call, is prefixed with [worker N +X.XXXms]: the worker index and the time since the test case started. In an explicit test case, which has no output to attribute, this does nothing.

Parameters
worker_indexThe worker to attribute the output to.
std::vector<std::thread> threads;
for (std::size_t i = 0; i < 2; i++) {
threads.emplace_back([worker = tc.clone(), i]() mutable {
worker.set_worker(i);
auto n = worker.draw(gs::integers<int>());
});
}
for (auto& thread : threads) {
thread.join();
}

◆ spawn()

template<typename F>
auto hegel::TestCase::spawn ( F fn) const

Run fn on a clone of this test case in a new thread.

Clones this test case on the calling thread, then invokes fn with the clone (as a TestCase&) on a std::thread. The returned Worker awaits it. Worker::join() returns fn's result and re-raises any exception it threw. Join every worker before the test body returns.

Template Parameters
FCallable invocable as fn(TestCase&).
Parameters
fnThe work to run on the cloned stream.
Returns
A Worker handle to the running thread.
auto w = tc.spawn([](hegel::TestCase& c) {
return c.draw(gs::integers<int>());
});
auto mine = tc.draw(gs::integers<int>());
auto theirs = w.join();
T draw(const generators::Generator< T > &gen) const
Draw a random value from a printable generator.
Definition core.h:991

◆ target()

void hegel::TestCase::target ( double score,
std::string_view label = "" ) const

Record a score for the engine's targeted-search phase to maximize.

Higher scores are treated as "more interesting." The engine biases later test cases toward inputs that produced higher scores under the same label. Has no effect unless the Target phase is enabled.

Parameters
scoreThe observation to maximize. Must be finite.
labelDistinguishes independent targeting goals. Each label may be recorded at most once per test case.
auto n = tc.draw(gs::integers<int>({.min_value = 0}));
tc.target(static_cast<double>(n));

The documentation for this class was generated from the following files: