Overview / Developer tools

testing

Dependency-free test framework. Header-only assertions and registration (C++17), plus a ready-made runner and <code>main</code>. It uses no exceptions or RTTI, and assertions do not allocate.

Always compiled: part of the core build.Include #include <ethereal/cpp/testing/testing.hpp>

testing.hpp

#include <ethereal/cpp/testing/testing.hpp>

Ethereal test framework: one include to write a test.

Usage:

#include <ethereal/cpp/testing/testing.hpp>

ETL_TEST( TimeSuite, MonotonicNeverGoesBackwards ) { ETL_EXPECT_LE( a, b ); }

The executable links 'Ethereal::Testing' and 'Ethereal::TestingMain' and runs with no arguments.

This header brings the core, the assertions and the instrumentation (no allocation, no locks, test allocators). The rest is included on demand, so files that do not use it do not pay for it at compile time:

testing_property.hpp ETL_PROPERTY, ETL_DIFFERENTIAL, the generators testing_tools.hpp ETL_FUZZ_TARGET, ETL_EXPECT_SNAPSHOT testing_concurrency.hpp CBarrier, SpinUntil, RunInterleaved testing_fakes.hpp CManualClock, CMemoryTransport, CFailingTransport, ...

testing_assert.hpp

#include <ethereal/cpp/testing/testing_assert.hpp>

The assertions of the test framework.

The quality of the failure message is the feature. Each failure writes the text of the expression as in the source, the two evaluated values, the file and the line. For spans it writes the first differing offset with a hex window around it. A framework that only says "assertion failed" costs more time than it saves.

The expansion is shallow on purpose. Each macro is one function call with the operands and the text, with no expression templates decomposing 'a == b'. That keeps a file with 500 assertions under the 2 s of compile time the spec asks for, which is where Catch2 lost. The price: ETL_EXPECT( a == b ) shows the text and not the values. To see the values, use ETL_EXPECT_EQ( a, b ).

ETL_EXPECT_* records and continues. ETL_ASSERT_* records and leaves the test with 'return', so it only works in the test body or in a 'void' function.

testing_concurrency.hpp

#include <ethereal/cpp/testing/testing_concurrency.hpp>

Concurrency helpers of the test framework.

A barrier, a wait with a deadline, and a runner that repeats a concurrent scenario N times with the thread start order shuffled.

This is not a model checker. It is enough to give TSan work: a race that only shows in one start order out of a hundred shows in a hundred shuffled repetitions, and TSan catches it when it does.

Kept out of 'testing.hpp' on purpose: '<thread>', '<mutex>' and '<condition_variable>' are heavy to compile, and most test files do not use them.

class

CBarrier

Ethereal::Testing#

A reusable barrier for N participants.

class CBarrier
constructor

CBarrier

#
explicit CBarrier( const std::size_t uParticipants ) noexcept : m_uTotal( uParticipants )

Builds a barrier for uParticipants threads.

function

ArriveAndWait

#
void ArriveAndWait()

Waits until the N participants arrive. The same barrier serves many rounds.

function

SpinUntil

Ethereal::Testing#
template < typename TPred > bool SpinUntil( TPred && Pred, const int iTimeoutMs )

Waits until Pred is true or until iTimeoutMs passes.

Never sleeps a fixed time. A test that sleeps "to give it time" is a flaky test.

Pred
The condition.
iTimeoutMs
Deadline in milliseconds.
true when the condition became true in time.
function

RunInterleaved

Ethereal::Testing#
template < typename TFn > void RunInterleaved( const int iRepeats, const int iThreads, TFn && Fn )

Runs Fn( iThread ) on iThreads threads, iRepeats times, with the creation order shuffled and a pseudo random delay before each start.

The seed is the one of the run ('--seed'), so an interleaving that failed can be asked for again.

iRepeats
Number of repetitions.
iThreads
Threads per repetition.
Fn
Body of each thread. Receives the thread index.

testing_core.hpp

#include <ethereal/cpp/testing/testing_core.hpp>

Core of the test framework.

The registry, the context of the running test and the macros that declare tests (ETL_TEST, ETL_TEST_F, ETL_TEST_P, ETL_TEST_T).

No external dependencies. GoogleTest and Catch2 are external dependencies, and a library sold as dependency free whose own suite pulled one in would lose credibility the first time a customer opened the repository. This depends only on the standard library and on Meta (headers only).

No exceptions, no RTTI and no allocation on the assertion path. The registry is an intrusive list built during static initialization, and a failure is formatted in a stack buffer. ETL_ASSERT_T leaves the test with a 'return', so it works with '-fno-exceptions'. It can only be used in the test body or in a 'void' function, like the ASSERT of GoogleTest.

struct

STestInfo

Ethereal::Testing#
C++
struct   STestInfo
{
    /// @brief  Suite name.
    const char *    sSuite = "";

    /// @brief  Test name.
    const char *    sName = "";

    /// @brief  Comma separated tags ("slow,io"). Empty means no tags.
    const char *    sTags = "";

    /// @brief  Source file of the declaration.
    const char *    sFile = "";

    /// @brief  Source line of the declaration.
    int                iLine = 0;

    /// @brief  The body. Receives the parameter index, or -1.
    void            ( *pRun )( int iParam ) = nullptr;

    /// @brief  Position of the instance in a parameterized or typed test.
    int                iParam = -1;

    /// @brief  Label of the instance (the value or the type).
    std::string_view    sParamLabel;

    /// @brief  Time limit in milliseconds. 0 uses the runner default.
    int                iTimeoutMs = 0;

    /// @brief  The test is expected to fail. If it passes, it fails.
    bool            bExpectFail = false;

    /// @brief  Next test in the registry.
    STestInfo *        pNext = nullptr;
};

A registered test. Static and intrusive, so the registry never allocates.

struct

STestOptions

Ethereal::Testing#
C++
struct   STestOptions
{
    /// @brief  Comma separated tags.
    const char *    sTags = "";

    /// @brief  Time limit in milliseconds. 0 uses the runner default.
    int                iTimeoutMs = 0;

    /// @brief  The test is expected to fail.
    bool            bExpectFail = false;
};

Options a test declares about itself.

function

RegisterTest

Ethereal::Testing#
void RegisterTest( STestInfo * pInfo ) noexcept;

Appends a test to the registry. Called during static initialization.

pInfo
The test to register.
function

FirstTest

Ethereal::Testing#
STestInfo * FirstTest() noexcept;

Head of the registered list, for the runner and for tools.

function

ReportFailure

Ethereal::Testing#
void ReportFailure( const char * sKind, const char * sExpr, const char * sDetail, const char * sFile, int iLine ) noexcept;

Records a failure in the running test. Thread safe.

sKind
Form of the assertion ("ETL_EXPECT_EQ").
sExpr
Text of the expression, as written in the source.
sDetail
Extra lines (values, hex window), already formatted. May be empty.
sFile
Source file of the assertion.
iLine
Source line of the assertion.
function

ReportSkip

Ethereal::Testing#
void ReportSkip( const char * sReason, const char * sFile, int iLine ) noexcept;

Marks the running test as skipped.

sReason
Why the test was skipped.
sFile
Source file of the skip.
iLine
Source line of the skip.
function

CurrentFailureCount

Ethereal::Testing#
int CurrentFailureCount() noexcept;

Number of failures the running test already has.

function

CurrentTest

Ethereal::Testing#
const STestInfo * CurrentTest() noexcept;

The running test, or null outside a test.

function

RunSeed

Ethereal::Testing#
std::uint64_t RunSeed() noexcept;

Seed of this run (--seed, or the random one that gets printed).

function

RunAllTests

Ethereal::Testing#
int RunAllTests( int argc, char ** argv );

Runs the registered tests with the given command line.

The main of 'Ethereal::TestingMain' calls this. A program with its own main calls it directly.

argc
Argument count.
argv
Arguments.
0 when everything passed, 1 with failures, 2 with an invalid command line.
class

CFixture

Ethereal::Testing#
class CFixture
destructor

~CFixture

#
virtual ~CFixture() = default;

Virtual destructor.

function

SetUp

#
virtual void SetUp()

Runs before the test body.

function

TearDown

#
virtual void TearDown()

Runs after the test body, even when it was aborted.

testing_fakes.hpp

#include <ethereal/cpp/testing/testing_fakes.hpp>

Test doubles that every module needs.

Kept here so they do not live copied in twenty folders.

No mocking framework, on purpose. The SDK is built on small, explicit seams (a clock, a transport, a verifier). Testing means writing a fake implementation of a small interface, which is clearer and faster than generating mocks.

These do not derive from the seams of the modules, because each module declares its own (the 'ITransport' of the Updater is not the one of the CrashReport) and Testing cannot depend on any of them. They are the core. Binding one to a seam is a five line adapter in the test:

struct CClockAdapter : Updater::IClock { Testing::CManualClock & Clk; ETL_INT64 NowUnix() noexcept override { return Clk.NowUnixSeconds(); } };

class

CManualClock

Ethereal::Testing#

A clock that only moves when the test tells it to.

class CManualClock

A test that sleeps to test a deadline is a flaky test. With this, "an hour passed" is one call, and the result is the same on any machine.

constructor

CManualClock

#
explicit CManualClock( const std::int64_t iStartNs = 0 ) noexcept : m_iNs( iStartNs )

Builds the clock at the given instant, in nanoseconds.

function

NowNs

#
std::int64_t NowNs() const noexcept

Current instant in nanoseconds.

function

NowMs

#
std::int64_t NowMs() const noexcept

Current instant in milliseconds.

function

NowUnixSeconds

#
std::int64_t NowUnixSeconds() const noexcept

Current instant in seconds.

function

AdvanceNs

#
void AdvanceNs( const std::int64_t iNs ) noexcept

Moves the clock forward by iNs nanoseconds.

function

AdvanceMs

#
void AdvanceMs( const std::int64_t iMs ) noexcept

Moves the clock forward by iMs milliseconds.

function

AdvanceSeconds

#
void AdvanceSeconds( const std::int64_t iS ) noexcept

Moves the clock forward by iS seconds.

function

SetNs

#
void SetNs( const std::int64_t iNs ) noexcept

Jumps to an instant. Backwards too, to test a clock that goes back.

class

CMemoryTransport

Ethereal::Testing#

A transport in memory: what is sent goes to a queue and is read on the other side.

class CMemoryTransport
function

Send

#
bool Send( const void * pData, const std::size_t uSize )

Queues a copy of the message.

pData
The bytes.
uSize
Number of bytes.
Always true.
function

Receive

#
bool Receive( std::vector< std::uint8_t > & Out )

Takes the oldest message. false when the queue is empty.

function

Pending

#
std::size_t Pending() const noexcept

Messages waiting in the queue.

function

BytesSent

#
std::size_t BytesSent() const noexcept

Bytes sent in total.

class

CFailingTransport

Ethereal::Testing#

A transport that fails: from the Nth operation on, or always.

class CFailingTransport
constructor

CFailingTransport

#
explicit CFailingTransport( const std::size_t uFailFrom = 1u ) noexcept : m_uFailFrom( uFailFrom )

Builds the transport.

uFailFrom
First operation that fails (counting from 1). 1 fails always.
function

Send

#
bool Send( const void *, std::size_t ) noexcept

true until the operation that fails is reached.

function

Receive

#
bool Receive( std::vector< std::uint8_t > & ) noexcept

true until the operation that fails is reached.

function

Operations

#
std::size_t Operations() const noexcept

Number of operations so far.

class

CRecordingSink

Ethereal::Testing#

A sink that keeps everything it receives, for the test to check later.

class CRecordingSink
function

Record

#
void Record( const std::string_view s )

Keeps a copy of the line.

function

Count

#
std::size_t Count() const noexcept

Number of lines received.

function

At

#
const std::string & At( const std::size_t i ) const

The line at index i.

function

Contains

#
bool Contains( const std::string_view sNeedle ) const noexcept

Does any line contain sNeedle?

function

Clear

#
void Clear() noexcept

Forgets every line.

class

CNullSerializer

Ethereal::Testing#

A serializer that accepts everything and throws it away, counting bytes. Measures the cost of the caller without measuring the write.

class CNullSerializer
function

Write

#
bool Write( const void *, const std::size_t uSize ) noexcept

Counts the bytes and the call. Always true.

function

Bytes

#
std::size_t Bytes() const noexcept

Bytes written in total.

function

Writes

#
std::size_t Writes() const noexcept

Number of writes.

testing_instrument.hpp

#include <ethereal/cpp/testing/testing_instrument.hpp>

Instrumentation: no allocation scopes, no lock scopes and the test allocators.

Almost every acceptance table of the specs asks for these: "zero allocations, checked by a test allocator that fails" and "no lock during capture". They live here once instead of being reimplemented in each module.

ETL_EXPECT_NO_ALLOC counts in the global 'operator new', which the 'Ethereal::TestingMain' target replaces. So it catches an allocation three calls down, inside a function the test does not even see. If the executable does not have TestingMain (and so the hook), the scope fails with a message saying so. It never passes silently because it was not measuring anything.

What the scope does not see: allocations made by other threads during the scope (the counter is per thread), and memory that does not go through 'operator new' (direct malloc, VirtualAlloc, mmap). For those, use CTestAllocator explicitly.

ETL_EXPECT_NO_LOCK, on glibc, sees every POSIX lock of the thread: TestingMain interposes 'pthread_mutex_*', 'pthread_rwlock_*' and 'pthread_spin_*', and with them every 'std::mutex' and 'std::shared_mutex'. On other platforms (Windows, macOS) there is no interposition. It only counts the primitives that call NoteLockAcquired(), and writes a note to the output saying so.

function

NoteLockAcquired

Ethereal::Testing#
void NoteLockAcquired() noexcept;
class

CTestAllocator

Ethereal::Testing#

Counts everything: how many, how many bytes, the peak and what is left to free.

class CTestAllocator : public Memory::IAllocator

With FailAt, the Nth allocation fails (returns null). This covers the out of memory paths that no normal test exercises.

It is a Memory::IAllocator, so it can be passed to any module that takes one.

constructor

CTestAllocator

#
CTestAllocator() noexcept = default;

Default constructor.

function

Allocate

#
void * Allocate( const std::size_t uBytes, const std::size_t uAlign = alignof( std::max_align_t ) ) noexcept override

Allocates a block.

uBytes
Size in bytes.
uAlign
Alignment.
The block, or null when this is the allocation marked to fail.
function

Deallocate

#
void Deallocate( void * p, const std::size_t uBytes ) noexcept override

Frees a block. A size that does not match the allocation counts as a usage error.

p
The block. Null is ignored.
uBytes
Size the caller believes the block has.
function

FailAt

#
void FailAt( const std::size_t uNth ) noexcept

The uNth allocation (counting from 1) fails. Zero disables it.

function

Count

#
std::size_t Count() const noexcept

Number of allocation attempts.

function

LiveCount

#
std::size_t LiveCount() const noexcept

Blocks not freed yet.

function

LiveBytes

#
std::size_t LiveBytes() const noexcept

Bytes not freed yet.

function

PeakBytes

#
std::size_t PeakBytes() const noexcept

Highest number of live bytes.

function

TotalBytes

#
std::size_t TotalBytes() const noexcept

Bytes allocated in total.

function

Failures

#
std::size_t Failures() const noexcept

Allocations that failed on purpose.

function

SizeMismatches

#
std::size_t SizeMismatches() const noexcept

Deallocations with the wrong size.

function

Clean

#
bool Clean() const noexcept

Nothing left to free and no wrong size.

class

CFailingAllocator

Ethereal::Testing#

A CTestAllocator that fails the Nth allocation from the start.

class CFailingAllocator : public CTestAllocator
constructor

CFailingAllocator

#
explicit CFailingAllocator( const std::size_t uNth ) noexcept

Marks allocation uNth to fail.

struct

TStdAllocator

Ethereal::Testing#
C++
template < typename T >
struct   TStdAllocator
{
    /// @brief  Allocated type.
    using value_type = T;

    /// @brief  The allocator that does the work.
    CTestAllocator *    pAlloc;


    /// @brief  Wraps the given allocator.
    ///
    explicit TStdAllocator( CTestAllocator & a ) noexcept : pAlloc( &a ) {}


    /// @brief  Rebind constructor.
    ///
    template < typename U >
    TStdAllocator( const TStdAllocator< U > & o ) noexcept : pAlloc( o.pAlloc ) {}


    /// @brief  Allocates n objects. Throws or aborts on failure.
    ///
    T * allocate( const std::size_t n )
    {
        void * p = pAlloc->Allocate( n * sizeof( T ), alignof( T ) );

        if( p == nullptr )
        {
        #if defined( __cpp_exceptions ) || defined( _CPPUNWIND )
            throw std::bad_alloc();
        #else /// No exceptions: aborts.
            std::abort();
        #endif
        }

        return static_cast< T * >( p );
    }


    /// @brief  Frees n objects.
    ///
    void deallocate( T * p, const std::size_t n ) noexcept { pAlloc->Deallocate( p, n * sizeof( T ) ); }


    /// @brief  Equal when both use the same allocator.
    ///
    template < typename U > bool operator==( const TStdAllocator< U > & o ) const noexcept { return pAlloc == o.pAlloc; }

    /// @brief  Different when they use different allocators.
    ///
    template < typename U > bool operator!=( const TStdAllocator< U > & o ) const noexcept { return pAlloc != o.pAlloc; }
};

Adapter of CTestAllocator for the standard containers.

A container cannot handle a null: when the CTestAllocator fails, this aborts (in a build with exceptions it throws std::bad_alloc). To test the out of memory paths of your own code, call the CTestAllocator directly.

testing_print.hpp

#include <ethereal/cpp/testing/testing_print.hpp>

Value printing for the failure messages.

Values are printed into a stack buffer, with no allocation.

A struct described with ETL_META_DESCRIBE prints field by field, with no work from the test author. This is why Meta came first: the same descriptor that binds the Config and serializes the message makes a failure say '{ port = 80, host = "x" }' instead of "the objects differ". A described enum prints its name.

A type that cannot be printed prints its bytes and never breaks the build. Any type in an assertion still compiles, and the message shows '<24 bytes: 01 00 ...>'.

struct

SText

Ethereal::Testing#
C++
struct   SText
{
    /// @brief  Buffer capacity in bytes.
    static constexpr std::size_t kCap = 2048u;

    /// @brief  The text, always terminated.
    char            aData[ kCap ] = {};

    /// @brief  Length of the text.
    std::size_t        uLen = 0u;

    /// @brief  The buffer filled up and the text was truncated.
    bool            bFull = false;

    /// @brief  Maximum number of text characters. The last 4 bytes hold the ellipsis
    ///             and the terminator. The indices are written against constants so the
    ///             bound is evident (GCC warned about an overflow the previous version
    ///             did not have, but could not prove).
    static constexpr std::size_t kMax = kCap - 4u;


    /// @brief  Appends one character.
    ///
    void Put( const char c ) noexcept
    {
        /// Room left: stores the character and keeps the terminator.
        if( uLen < kMax )
        {
            aData[ uLen++ ] = c;
            aData[ uLen ] = '\0';
        }
        else if( !bFull ) /// First overflow: closes the text with the ellipsis.
        {
            bFull = true;
            aData[ kMax + 0u ] = '.';
            aData[ kMax + 1u ] = '.';
            aData[ kMax + 2u ] = '.';
            aData[ kMax + 3u ] = '\0';
            uLen = kMax + 3u;
        }
    }


    /// @brief  Appends a string.
    ///
    void Put( const std::string_view s ) noexcept
    {
        for( const char c : s )
            Put( c );
    }


    ///
    /// Fmt
    ///
    /// @brief  Formats into a 256 byte stack buffer and appends. No allocation.
    ///
    /// @param sFormat    printf style format, followed by its arguments.
    ///
    void Fmt( const char * sFormat, ... ) noexcept
    {
        char aTmp[ 256 ];

        /// Formats into the temporary buffer.
        va_list Args;
        va_start( Args, sFormat );
        const int n = std::vsnprintf( aTmp, sizeof( aTmp ), sFormat, Args );
        va_end( Args );

        /// Appends what fits (vsnprintf returns the full length, even when truncated).
        if( n > 0 )
            Put( std::string_view( aTmp, ( static_cast< std::size_t >( n ) < sizeof( aTmp ) ) ? static_cast< std::size_t >( n ) : sizeof( aTmp ) - 1u ) );
    }


    /// @brief  The text as a C string.
    ///
    const char * CStr() const noexcept    { return aData; }


    /// @brief  The text as a view.
    ///
    std::string_view View() const noexcept    { return std::string_view( aData, uLen ); }
};

A text buffer on the stack. Truncates silently when full, ending with '...'.

function

PrintValue

Ethereal::Testing#
template < typename T > void PrintValue( SText & Out, const T & Value, int iDepth = 0 ) noexcept;
function

PrintValue

Ethereal::Testing#
template < typename T > void PrintValue( SText & Out, const T & Value, const int iDepth ) noexcept

testing_property.hpp

#include <ethereal/cpp/testing/testing_property.hpp>

Property and differential tests, with shrinking.

Usage:

ETL_PROPERTY( EncodingSuite, Base64RoundTrips, const std::vector< std::uint8_t > & Input ) { ETL_EXPECT_SPAN_EQ( Decode( Encode( Input ) ), Input ); }

Shrinking is the whole value. A failure on a random 4 KB input is almost useless, while the same failure reduced to 3 bytes is a bug report. When the property fails, the engine shrinks the input while it keeps failing, and only then runs the property one last time in the open, with the minimal input printed and the seed to repeat it.

The seed is fixed, printed on failure and repeatable: '--property-seed <n>' redoes exactly the same sequence. Without it, the seed derives from the run seed and from the test name, so each test has its own and a new test does not change the seeds of the others.

Generators: integers (with the boundary values), reals (with NaN, infinities, denormals and signed zero), bool, 'std::string' (with hostile Unicode), 'std::vector<T>', 'std::pair', and any struct described with Meta, field by field. A type of your own gets a generator by specializing 'Ethereal::Testing::SGen<T>'.

class

CRandom

Ethereal::Testing#

A small, reproducible pseudo random generator (xoshiro256**).

class CRandom
constructor

CRandom

#
explicit CRandom( std::uint64_t uSeed ) noexcept

Seeds the generator.

function

Next

#
std::uint64_t Next() noexcept

Next 64 bit value.

function

Below

#
std::uint64_t Below( const std::uint64_t n ) noexcept

Uniform in [0, n). Zero returns zero.

function

OneIn

#
bool OneIn( const std::uint64_t n ) noexcept

true with probability 1/n.

struct

SGen

Ethereal::Testing#
C++
template < typename T, typename = void >
struct   SGen
{
    static_assert( sizeof( T ) == 0,
        "Testing: no generator for this type. Describe it with ETL_META_DESCRIBE or specialize Ethereal::Testing::SGen." );
};

The generator of a type. Specialize it for your own types.

Two static functions:

  • 'T Generate( CRandom &, std::size_t uSize )'. 'uSize' grows along the run, so the first inputs are small.
  • 'template < typename F > void Shrink( const T &, F && Try )'. Proposes simpler candidates to 'Try', and stops when 'Try' returns true.
struct

SGen

Ethereal::Testing#
C++
template < typename T >
struct   SGen< T, std::enable_if_t< std::is_integral_v< T > && !std::is_same_v< T, bool > > >
{
    /// @brief  A boundary value one time in eight, otherwise a value that grows with uSize.
    ///
    static T Generate( CRandom & Rng, const std::size_t uSize ) noexcept
    {
        /// One time in eight it is a boundary value, which is where the bugs live.
        if( Rng.OneIn( 8u ) )
        {
            const T aBoundary[] = { T( 0 ), T( 1 ), static_cast< T >( T( 0 ) - T( 1 ) ),
                                     std::numeric_limits< T >::min(), std::numeric_limits< T >::max(),
                                     static_cast< T >( std::numeric_limits< T >::max() / 2 ) };

            return aBoundary[ Rng.Below( sizeof( aBoundary ) / sizeof( aBoundary[ 0 ] ) ) ];
        }

        /// The rest: small at the start, growing with the size, up to the full range.
        const std::uint64_t uRaw = Rng.Next();

        if( uSize < 64u && Rng.OneIn( 2u ) )
        {
            const auto uLim = static_cast< std::uint64_t >( uSize * uSize + 2u );
            const auto v = static_cast< long long >( uRaw % uLim );
            if constexpr( std::is_signed_v< T > )
                return static_cast< T >( Rng.OneIn( 2u ) ? -v : v );
            else
                return static_cast< T >( v );
        }

        /// Full range: the raw bits.
        T v{};
        std::memcpy( &v, &uRaw, sizeof( T ) );
        return v;
    }


    /// @brief  Proposes 0, then -v, v / 2 and one step towards zero.
    ///
    template < typename F >
    static void Shrink( const T & v, F && Try )
    {
        if( v == T( 0 ) )
            return;

        if( Try( T( 0 ) ) ) return;

        /// The minimum of a signed type has no positive counterpart.
        if constexpr( std::is_signed_v< T > )
            if( v < 0 && v != std::numeric_limits< T >::min() && Try( static_cast< T >( -v ) ) ) return;

        if( Try( static_cast< T >( v / 2 ) ) ) return;

        if constexpr( std::is_signed_v< T > )
        {
            if( Try( static_cast< T >( v > 0 ? v - 1 : v + 1 ) ) ) return;
        }
        else
        {
            if( Try( static_cast< T >( v - 1u ) ) ) return;
        }
    }
};

Generator of the integers other than bool.

struct

SGen

Ethereal::Testing#
C++
template <>
struct   SGen< bool >
{
    /// @brief  true or false with equal chance.
    ///
    static bool Generate( CRandom & Rng, std::size_t ) noexcept    { return Rng.OneIn( 2u ); }

    /// @brief  true shrinks to false.
    ///
    template < typename F >
    static void Shrink( const bool & v, F && Try )                { if( v ) Try( false ); }
};

Generator of bool.

struct

SGen

Ethereal::Testing#
C++
template < typename T >
struct   SGen< T, std::enable_if_t< std::is_floating_point_v< T > > >
{
    /// @brief  A special value one time in six, otherwise a value whose scale grows with uSize.
    ///
    static T Generate( CRandom & Rng, const std::size_t uSize ) noexcept
    {
        using L = std::numeric_limits< T >;

        /// Special values: signed zero, infinities, NaN, denormals and the limits.
        if( Rng.OneIn( 6u ) )
        {
            const T aSpecial[] = { T( 0 ), -T( 0 ), T( 1 ), -T( 1 ), L::infinity(), -L::infinity(),
                                     L::quiet_NaN(), L::denorm_min(), L::min(), L::max(), L::lowest(), L::epsilon() };

            return aSpecial[ Rng.Below( sizeof( aSpecial ) / sizeof( aSpecial[ 0 ] ) ) ];
        }

        /// Uniform in [-1, 1) times a power of ten that grows with the size.
        const double dUnit = static_cast< double >( Rng.Next() >> 11 ) * ( 1.0 / 9007199254740992.0 );
        const double dScale  = std::pow( 10.0, static_cast< double >( Rng.Below( uSize / 4u + 2u ) ) );
        const double d     = ( dUnit * 2.0 - 1.0 ) * dScale;

        return static_cast< T >( d );
    }


    /// @brief  Proposes +0, then the integer part and the half.
    ///
    template < typename F >
    static void Shrink( const T & v, F && Try )
    {
        if( v == T( 0 ) && !std::signbit( v ) )
            return;

        if( Try( T( 0 ) ) ) return;

        if( std::isfinite( v ) )
        {
            if( Try( std::trunc( v ) ) ) return;
            if( Try( v / T( 2 ) ) ) return;
        }
    }
};

Generator of the floating point types.

struct

SGen

Ethereal::Testing#
C++
template < typename T >
struct   SGen< std::vector< T > >
{
    /// @brief  Up to uSize elements, each from the generator of T.
    ///
    static std::vector< T > Generate( CRandom & Rng, const std::size_t uSize )
    {
        std::vector< T > v( static_cast< std::size_t >( Rng.Below( uSize + 1u ) ) );

        for( T & e : v )
            e = SGen< T >::Generate( Rng, uSize );

        return v;
    }

    /// @brief  Shrinks the length and then each element.
    ///
    template < typename F >
    static void Shrink( const std::vector< T > & v, F && Try )
    {
        Detail::ShrinkSequence( v, []( const T & e, auto && TryElem ) { SGen< T >::Shrink( e, TryElem ); }, Try );
    }
};
struct

SGen

Ethereal::Testing#
C++
template <>
struct   SGen< std::string >
{
    /// @brief  Printable ASCII, control bytes and hostile UTF-8 pieces.
    ///
    static std::string Generate( CRandom & Rng, const std::size_t uSize )
    {
        /// Pieces that break text code. None of them is rare in real life.
        static const char * const kHostile[] = {
            "\xC0\x80",                /// overlong NUL
            "\xE0\x80\xAF",            /// overlong '/' (the classic path traversal)
            "\xED\xA0\x80",            /// high surrogate encoded in UTF-8 (forbidden)
            "\xF4\x90\x80\x80",        /// above U+10FFFF
            "\x80",                    /// stray continuation byte
            "\xFF",                    /// byte that never appears in UTF-8
            "\xEF\xBB\xBF",            /// BOM
            "\xE2\x80\xAE",            /// U+202E, right to left override
            "\xE2\x80\x8D",            /// ZWJ
            "e\xCC\x81",            /// 'e' + combining accent
            "\xF0\x9F\x91\xA8\xE2\x80\x8D\xF0\x9F\x91\xA9",    /// emoji ZWJ sequence
            "\xF4\x8F\xBF\xBF",        /// U+10FFFF, the last code point
        };

        std::string s;
        const std::size_t n = static_cast< std::size_t >( Rng.Below( uSize + 1u ) );

        /// Loop : 60% printable ASCII, 10% control bytes, 30% hostile pieces.
        while( s.size() < n )
        {
            const std::uint64_t r = Rng.Below( 10u );

            if( r < 6u )
                s.push_back( static_cast< char >( 0x20 + Rng.Below( 0x5F ) ) );        /// printable ASCII
            else if( r < 7u )
                s.push_back( static_cast< char >( Rng.Below( 0x20 ) ) );            /// control byte, NUL included
            else
                s += kHostile[ Rng.Below( sizeof( kHostile ) / sizeof( kHostile[ 0 ] ) ) ];
        }

        return s;
    }

    /// @brief  Shrinks the length and then turns each byte into 'a'.
    ///
    template < typename F >
    static void Shrink( const std::string & v, F && Try )
    {
        Detail::ShrinkSequence( v, []( const char c, auto && TryElem )
        {
            if( c != 'a' ) TryElem( 'a' );
        }, Try );
    }
};

Generator of std::string.

struct

SGen

Ethereal::Testing#
C++
template < typename A, typename B >
struct   SGen< std::pair< A, B > >
{
    /// @brief  Each side from its own generator.
    ///
    static std::pair< A, B > Generate( CRandom & Rng, const std::size_t uSize )
    {
        A a = SGen< A >::Generate( Rng, uSize );
        B b = SGen< B >::Generate( Rng, uSize );
        return { std::move( a ), std::move( b ) };
    }

    /// @brief  Shrinks the first side, then the second.
    ///
    template < typename F >
    static void Shrink( const std::pair< A, B > & v, F && Try )
    {
        bool bStopped = false;
        SGen< A >::Shrink( v.first, [ & ]( const A & a ) { bStopped = Try( std::pair< A, B >( a, v.second ) ); return bStopped; } );
        if( bStopped ) return;
        SGen< B >::Shrink( v.second, [ & ]( const B & b ) { return Try( std::pair< A, B >( v.first, b ) ); } );
    }
};

Generator of std::pair.

struct

SGen

Ethereal::Testing#
C++
template < typename T >
struct   SGen< T, std::enable_if_t< ::Ethereal::Meta::IsDescribed< T > > >
{
    /// @brief  Each field from the generator of its type.
    ///
    static T Generate( CRandom & Rng, const std::size_t uSize )
    {
        T Obj{};

        ::Ethereal::Meta::ForEachField( Obj, [ & ]( std::string_view, auto & FieldRef, const auto & )
        {
            using C = std::decay_t< decltype( FieldRef ) >;
            FieldRef = SGen< C >::Generate( Rng, uSize );
        } );

        return Obj;
    }

    /// @brief  Shrinks one field at a time, keeping the others.
    ///
    template < typename F >
    static void Shrink( const T & v, F && Try )
    {
        bool bStopped = false;

        ::Ethereal::Meta::ForEachField< T >( [ & ]( std::string_view, const auto & Field )
        {
            if( bStopped )
                return;

            using C = typename std::decay_t< decltype( Field ) >::MemberType;
            const auto pM = Field.pMember;

            /// Each candidate is a copy of the object with this field replaced.
            SGen< C >::Shrink( v.*pM, [ & ]( const C & c ) -> bool
            {
                T Candidate = v;
                Candidate.*pM = c;
                bStopped = Try( Candidate );
                return bStopped;
            } );
        } );
    }
};

Generator of the structs described with Meta, field by field.

testing_tools.hpp

#include <ethereal/cpp/testing/testing_tools.hpp>

Fuzz adapter and snapshot tests.

Fuzz: one function, three ways to run it.

ETL_FUZZ_TARGET( ConfigParser, pData, uSize ) { Parse( pData, uSize ); }

  • In the normal runner it is a test ("Fuzz.ConfigParser") that replays the committed corpus ('<corpus>/ConfigParser/*') plus a few hundred random inputs from a fixed seed.
  • With -DETL_FUZZ_LIBFUZZER, ETL_FUZZ_ENTRY( ConfigParser ) defines 'LLVMFuzzerTestOneInput', and the same source is a libFuzzer target.
  • With -DETL_FUZZ_STDIN, ETL_FUZZ_ENTRY defines a 'main' that reads stdin, which is the AFL form.

A fuzzer finding in a CI becomes a permanent regression test by copying the file that reproduces it into the corpus folder. One copy, nothing else.

Snapshot: compares a text with a committed golden file.

ETL_EXPECT_SNAPSHOT( "render_table", sOutput );

The file is '<folder>/<Suite>.<Test>.<name>.snap'. Different fails with the first line that differs. Missing fails too, unless '--update-snapshots' is given, which writes the current text. The update is always explicit, and the diff is reviewed in the commit.

alias

void

Ethereal::Testing#
using FFuzzTarget = void ( * )( const std::uint8_t * pData, std::size_t uSize );

Signature of a fuzz target.