Hegel 0.7.4
Property-based testing for C++
Loading...
Searching...
No Matches
Hegel

Hegel is a property-based testing library for C++. Hegel is based on Hypothesis, using the libhegel engine.

Getting started

This guide walks you through the basics of installing Hegel and writing your first tests.

Install Hegel

Using CMake:

include(FetchContent)
FetchContent_Declare(
hegel
GIT_REPOSITORY https://github.com/hegeldev/hegel-cpp.git
GIT_TAG v0.7.4
)
FetchContent_MakeAvailable(hegel)
target_link_libraries(your_target PRIVATE hegel)

Hegel requires CMake 3.14 and, by default, a C++20 compiler. The build downloads a small prebuilt shared library (libhegel, Hegel's native engine) for your platform; no other tooling is required.

To consume Hegel from C++17, configure with -DHEGEL_REFLECTION=OFF. This drops the reflect-cpp dependency: you lose default_generator (type-directed derivation for structs), but every other generator and combinator still works. (The designated-initializer parameter API, e.g. integers<int>({.min_value = 0}), then relies on a GCC/Clang C++17 extension.)

Write your first test

You're now ready to write your first test. In a new file:

#include <hegel/hegel.h>
namespace gs = hegel::generators;
HEGEL_TEST(self_equality)(hegel::TestCase& tc) {
int n = tc.draw(gs::integers<int>());
if (n != n) { // integers should always be equal to themselves
throw std::runtime_error("self-equality failed");
}
}
int main() {
}
Handle to the currently-executing test case.
Definition test_case.h:35
#define HEGEL_TEST(name,...)
Define a Hegel property test.
Definition hegel.h:391
Hegel generators.
Definition core.h:16
int run_all_tests()
Run every test defined with HEGEL_TEST in this binary.

Now build and run the test. You should see that this test passes.

Let's look at what's happening in more detail. HEGEL_TEST defines a property test as an ordinary function, self_equality, and registers it with hegel::run_all_tests(), which runs every test defined this way in the binary. You can also invoke the function individually — from main() or from any test framework (a GoogleTest TEST body, for example). Running the test executes your test body many times (100, by default).

The body receives a TestCase, which provides a TestCase::draw() method for drawing different values. This test draws a random integer and checks that it should be equal to itself. The macro also names the test in Hegel's example database, so a failure found in one run is replayed first in the next.

Next, try a test that fails:

HEGEL_TEST(below_50)(hegel::TestCase& tc) {
int n = tc.draw(gs::integers<int>());
if (n >= 50) { // this will fail!
throw std::runtime_error("n should be below 50");
}
}

This test asserts that any integer is less than 50, which is obviously incorrect. Hegel will find a test case that makes this assertion fail, and then shrink it to find the smallest counterexample — in this case, n = 50.

To fix this test, you can constrain the integers you generate with the min_value and max_value parameters:

HEGEL_TEST(below_50)(hegel::TestCase& tc) {
int n = tc.draw(gs::integers<int>({.min_value = 0, .max_value = 49}));
if (n >= 50) {
throw std::runtime_error("n should be below 50");
}
}

Run the test again. It should now pass.

Use generators

Hegel provides a rich library of generators in the hegel::generators namespace that you can use out of the box. There are primitive generators, such as integers, floats, and text, and combinators that allow you to make generators out of other generators, such as vectors and tuples.

For example, you can use vectors to generate a vector of integers:

namespace gs = hegel::generators;
HEGEL_TEST(push_back_grows)(hegel::TestCase& tc) {
auto vector = tc.draw(gs::vectors(gs::integers<int>()));
auto initial_length = vector.size();
vector.push_back(tc.draw(gs::integers<int>()));
if (vector.size() <= initial_length) {
throw std::runtime_error("push_back should increase size");
}
}

This test checks that appending an element to a random vector of integers should always increase its length.

You can also define custom generators. For example, say you have a Person struct that we want to generate:

struct Person {
int age;
std::string name;
};
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};
});
}
T draw(const generators::Generator< T > &gen) const
Draw a random value from a generator.
Definition core.h:263

Note that you can feed the results of a draw to subsequent calls. For example, say that you extend the Person struct to include a driving_license boolean field:

struct Person {
int age;
std::string name;
bool driving_license;
};
auto generate_person() {
return gs::compose([](const hegel::TestCase& tc) {
int age = tc.draw(gs::integers<int>());
std::string name = tc.draw(gs::text());
bool driving_license =
age >= 18 ? tc.draw(gs::booleans()) : false;
return Person{age, name, driving_license};
});
}

Hegel can also derive generators automatically for reflectable structs via default_generator. This uses reflect-cpp to inspect the struct's fields and pick an appropriate generator for each:

struct Person {
std::string name;
int age;
};
HEGEL_TEST(generate_people)(hegel::TestCase& tc) {
Person p = tc.draw(gs::default_generator<Person>());
}

Call .override(...) on the returned generator to customize individual fields (see override).

Debug your failing test cases

Use TestCase::note to attach debug information:

HEGEL_TEST(addition_commutes)(hegel::TestCase& tc) {
int x = tc.draw(gs::integers<int>());
int y = tc.draw(gs::integers<int>());
tc.note("x + y = " + std::to_string(x + y) +
", y + x = " + std::to_string(y + x));
if (x + y != y + x) {
throw std::runtime_error("addition is not commutative");
}
}
void note(std::string_view message) const
Record a message that will be printed on the final replay of a failing test case.

Notes only appear when Hegel replays the minimal failing example.

Change the number of test cases

By default Hegel runs 100 test cases. To override this, write a Settings initializer after the test name:

HEGEL_TEST(self_equality, {.test_cases = 500})(hegel::TestCase& tc) {
int n = tc.draw(gs::integers<int>());
if (n != n) {
throw std::runtime_error("self-equality failed");
}
}

These settings are the test function's default argument; passing a Settings when invoking the test (self_equality({.test_cases = 5})) replaces them for that run.

Use hegel::test() directly

HEGEL_TEST is a macro around hegel::test(), which remains available when a macro doesn't fit — for example to run a lambda or another callable built at runtime:

int n = tc.draw(gs::integers<int>());
if (n != n) {
throw std::runtime_error("self-equality failed");
}
}, {.test_cases = 500});
void test(const std::function< void(TestCase &)> &test_fn, const Settings &settings={}, const std::vector< std::string > &failure_blobs={})
Run a Hegel test.

Unlike the macro, hegel::test() cannot derive a name for the test, so set Settings::database_key yourself if you want failures persisted to the example database and replayed across runs.

Learning more

  • Browse the hegel::generators namespace for the full list of available generators.
  • See Settings for more configuration settings to customise how your test runs.