Progmasoft Git

catch3

Progmasoft Catch3: an independently maintained C++17 test framework with a parallel runner, property checks, snapshots and structured results.

Clonegit clone https://git.progmasoft.com/catch3

feat: add VirtualClock, a clock whose time the test moves

First part of roadmap step 9 (test environment): time-dependent code is
tested without waiting for real time.

- src/Progmasoft/Catch3/VirtualClock.hpp (header-only, C++17): meets the
  Clock requirements of <chrono> (steady, nanoseconds), so code taking its
  clock as a template parameter runs against it unchanged. Advance and
  AdvanceTo move it forward and refuse to move it back; SleepFor stands in
  for std::this_thread::sleep_for. After(delay, action) sets timers that run
  when an advance passes them, in time order and in setting order at equal
  times, each seeing now() at its own time; timers may set timers, which run
  within the same advance. Cancel, Pending, RunUntilIdle(limit) (an error
  past the limit, for timers that keep setting each other), Reset, and a
  Scope that resets on entry and exit so tests do not share time or timers.
  One process-wide state behind a mutex, never destroyed so that a timer may
  read it during static destruction; timers run outside the lock.
- Included from <Progmasoft/Catch3.hpp>; installed by Meson. Tests are in
  tests/Progmasoft/VirtualClock.tests.cpp, wired into CMake, Meson, Bazel
  and xmake (not the deprecated Premake build, which gets no new APIs).
- docs/progmasoft-catch3.md documents it; the roadmap marks step 9 in
  progress with the clock done.
Commit
b3ab01db5b12ab8207ec144830a719c116e25c18
Author
Leitwolf11 ·
Parents
280f56330e9b

Files · Download .tar.gz

Changes

 docs/progmasoft-catch3.md               |  39 ++++++
 docs/progmasoft-roadmap.md              |   2 +-
 src/Progmasoft/Catch3.hpp               |   1 +
 src/Progmasoft/Catch3/VirtualClock.hpp  | 231 ++++++++++++++++++++++++++++++++
 src/Progmasoft/meson.build              |   1 +
 tests/CMakeLists.txt                    |   1 +
 tests/Progmasoft/BUILD.bazel            |   1 +
 tests/Progmasoft/VirtualClock.tests.cpp | 165 +++++++++++++++++++++++
 tests/meson.build                       |   1 +
 xmake.lua                               |   1 +
 10 files changed, 442 insertions(+), 1 deletion(-)

diff --git a/docs/progmasoft-catch3.md b/docs/progmasoft-catch3.md
index d7c50363..cbba4bd1 100644
--- a/docs/progmasoft-catch3.md
+++ b/docs/progmasoft-catch3.md
@@ -148,6 +148,45 @@ const Progmasoft::Catch3::SnapshotOptions options{
 CATCH3_CHECK_SNAPSHOT("rendered-report", RenderReport(), options);
 ```
 
+## Virtual clock
+
+`<Progmasoft/Catch3/VirtualClock.hpp>` provides `VirtualClock`, a clock whose
+time moves only when the test moves it. It meets the Clock requirements of
+`<chrono>` (steady, nanoseconds), so code that takes its clock as a template
+parameter, or as a function returning `now()`, runs against it unchanged, and
+a test of a timeout or an expiry takes no real time.
+
+```cpp
+using Progmasoft::Catch3::VirtualClock;
+using namespace std::chrono_literals;
+
+VirtualClock::Scope time;                 // the clock at zero, no timers
+Cache<VirtualClock> cache(30s);
+cache.Put("key", 1);
+VirtualClock::Advance(31s);
+CHECK_FALSE(cache.Get("key"));
+```
+
+* `Advance(step)` and `AdvanceTo(time)` move the clock forward and refuse to
+  move it back. `SleepFor(step)` is `Advance` under the name code under test
+  would use in place of `std::this_thread::sleep_for`.
+* `After(delay, action)` sets a timer and returns its id for `Cancel(id)`.
+  Timers run when an advance passes their time, in time order and, at the same
+  time, in the order they were set; each sees `now()` at its own time. A timer
+  may set others, which run in the same advance when they fall within it. A
+  zero delay runs at the next advance, even `Advance(0s)`.
+* `RunUntilIdle(limit)` advances from timer to timer until none is left and
+  returns how many ran; more than `limit` (100000 by default) is an error,
+  since timers that keep setting each other would never end.
+* `Pending()` counts the timers that wait; `Reset()` sets the clock to zero and
+  drops them. A `VirtualClock::Scope` resets when it is made and when it is
+  destroyed, so a test neither sees nor leaves time or timers of another.
+
+The clock is one per process. One thread advances it, and timers run on that
+thread; any thread may read `now()`. Tests that use it in parallel worker
+processes of the Catch3 runner are independent, but two tests of one process
+must not use it at the same time (`--in-process` runs them one after another).
+
 ## Structured results and XML
 
 `<Progmasoft/Catch3/Results.hpp>` defines the model the runner's reports are
diff --git a/docs/progmasoft-roadmap.md b/docs/progmasoft-roadmap.md
index 3561803e..0f0c4225 100644
--- a/docs/progmasoft-roadmap.md
+++ b/docs/progmasoft-roadmap.md
@@ -27,7 +27,7 @@ The steps are ordered by what each one builds on.
 | 6 | Mutation testing | planned |
 | 7 | Coverage-, mutation- and history-guided test generation | planned |
 | 8 | Micro-benchmarking | planned, after steps 4 to 7 |
-| 9 | [Test environment](#9-test-environment) | planned, next after step 4 |
+| 9 | [Test environment](#9-test-environment) | in progress: the virtual clock is done, see [Virtual clock](progmasoft-catch3.md#virtual-clock); fixture lifecycle and isolated filesystems are next |
 | 10 | [Output comparison](#10-output-comparison) | planned, after step 9 |
 | 11 | [Asynchrony and concurrency](#11-asynchrony-and-concurrency) | planned |
 | 12 | [Faults and networks](#12-faults-and-networks) | planned |
diff --git a/src/Progmasoft/Catch3.hpp b/src/Progmasoft/Catch3.hpp
index 6117107b..d68eb5a6 100644
--- a/src/Progmasoft/Catch3.hpp
+++ b/src/Progmasoft/Catch3.hpp
@@ -27,4 +27,5 @@
 #include <Progmasoft/Catch3/Strategy/Context.hpp>
 #include <Progmasoft/Catch3/Strategy/Numeric.hpp>
 #include <Progmasoft/Catch3/Strategy/Strategy.hpp>
+#include <Progmasoft/Catch3/VirtualClock.hpp>
 #include <Progmasoft/Catch3/XmlWriter.hpp>
diff --git a/src/Progmasoft/Catch3/VirtualClock.hpp b/src/Progmasoft/Catch3/VirtualClock.hpp
new file mode 100644
index 00000000..92199146
--- /dev/null
+++ b/src/Progmasoft/Catch3/VirtualClock.hpp
@@ -0,0 +1,231 @@
+// Copyright (c) 2026 Progmasoft.
+// SPDX-License-Identifier: LGPL-3.0-or-later
+#pragma once
+
+#include <chrono>
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <map>
+#include <mutex>
+#include <stdexcept>
+#include <string>
+#include <utility>
+
+// A clock whose time moves only when the test moves it. Code under test takes
+// the clock as a template parameter, or a std::function returning its now(),
+// and the test advances it instead of waiting:
+//
+//     VirtualClock::Scope time;               // starts at zero, clears timers
+//     Cache<VirtualClock> cache(std::chrono::seconds(30));
+//     cache.Put("key", 1);
+//     VirtualClock::Advance(std::chrono::seconds(31));
+//     CHECK_FALSE(cache.Get("key"));
+//
+// VirtualClock meets the Clock requirements of <chrono>, with a steady
+// nanosecond time. Timers set with After() run when an Advance passes their
+// time, in time order, each seeing now() at its own time; a timer may set
+// others, which run in the same Advance if they fall within it. One thread
+// advances the clock; any thread may read it.
+
+namespace Progmasoft::Catch3
+{
+
+    class VirtualClock
+    {
+    public:
+        using rep = std::int64_t;
+        using period = std::nano;
+        using duration = std::chrono::duration<rep, period>;
+        using time_point = std::chrono::time_point<VirtualClock>;
+        static constexpr bool is_steady = true;
+
+        /// Names a timer, for Cancel().
+        using TimerId = std::uint64_t;
+
+        /// The current virtual time.
+        [[nodiscard]] static time_point now() noexcept
+        {
+            std::scoped_lock<std::mutex> lock(State().Mutex);
+            return State().Now;
+        }
+
+        /// Moves the clock forward by `step`, running the timers it passes.
+        /// A negative step is refused: the clock is steady.
+        static void Advance(duration step)
+        {
+            if (step < duration::zero())
+            {
+                throw std::invalid_argument("VirtualClock::Advance: the clock does not go back");
+            }
+
+            AdvanceTo(now() + step);
+        }
+
+        /// Moves the clock forward to `target`, running the timers due by
+        /// then. A target in the past is refused.
+        static void AdvanceTo(time_point target)
+        {
+            for (;;)
+            {
+                std::function<void()> due;
+                {
+                    std::scoped_lock<std::mutex> lock(State().Mutex);
+                    auto &state = State();
+                    if (target < state.Now)
+                    {
+                        throw std::invalid_argument("VirtualClock::AdvanceTo: the target is in the past");
+                    }
+
+                    const auto first = state.Timers.begin();
+                    if (first == state.Timers.end() || first->first.first > target)
+                    {
+                        state.Now = target;
+                        return;
+                    }
+
+                    state.Now = first->first.first;
+                    due = std::move(first->second);
+                    state.Timers.erase(first);
+                }
+
+                // Outside the lock: the timer may read the clock or set timers.
+                due();
+            }
+        }
+
+        /// Runs `action` once the clock has advanced by `delay` from now; a
+        /// zero delay runs it at the next Advance, even Advance(0).
+        static TimerId After(duration delay, std::function<void()> action)
+        {
+            if (delay < duration::zero())
+            {
+                throw std::invalid_argument("VirtualClock::After: the delay is negative");
+            }
+
+            std::scoped_lock<std::mutex> lock(State().Mutex);
+            auto &state = State();
+            const auto id = ++state.LastId;
+            state.Timers.emplace(std::make_pair(state.Now + delay, id), std::move(action));
+            return id;
+        }
+
+        /// Cancels a timer that has not run; false when it has run, was
+        /// cancelled or never existed.
+        static bool Cancel(TimerId id)
+        {
+            std::scoped_lock<std::mutex> lock(State().Mutex);
+            auto &timers = State().Timers;
+            for (auto timer = timers.begin(); timer != timers.end(); ++timer)
+            {
+                if (timer->first.second == id)
+                {
+                    timers.erase(timer);
+                    return true;
+                }
+            }
+
+            return false;
+        }
+
+        /// How many timers wait to run.
+        [[nodiscard]] static std::size_t Pending()
+        {
+            std::scoped_lock<std::mutex> lock(State().Mutex);
+            return State().Timers.size();
+        }
+
+        /// Advances from timer to timer until none is left, and returns how
+        /// many ran. Timers that keep setting new ones would never end, so
+        /// more than `limit` of them is an error.
+        static std::size_t RunUntilIdle(std::size_t limit = 100000)
+        {
+            std::size_t ran = 0;
+            for (;;)
+            {
+                time_point next;
+                {
+                    std::scoped_lock<std::mutex> lock(State().Mutex);
+                    const auto &timers = State().Timers;
+                    if (timers.empty())
+                    {
+                        return ran;
+                    }
+
+                    next = timers.begin()->first.first;
+                }
+
+                if (++ran > limit)
+                {
+                    throw std::runtime_error("VirtualClock::RunUntilIdle: more than " +
+                                             std::to_string(limit) + " timers ran; one keeps setting another");
+                }
+
+                AdvanceToOne(next);
+            }
+        }
+
+        /// A stand-in for std::this_thread::sleep_for in code under test: it
+        /// advances the clock instead of waiting.
+        static void SleepFor(duration span) { Advance(span); }
+
+        /// Sets the clock back to zero and drops every timer.
+        static void Reset()
+        {
+            std::scoped_lock<std::mutex> lock(State().Mutex);
+            State().Now = time_point{};
+            State().Timers.clear();
+        }
+
+        /// Resets the clock when it is made and when it is destroyed, so that a
+        /// test neither sees nor leaves time or timers of another.
+        class Scope
+        {
+        public:
+            Scope() { Reset(); }
+            ~Scope() { Reset(); }
+            Scope(const Scope &) = delete;
+            Scope &operator=(const Scope &) = delete;
+        };
+
+    private:
+        struct Shared
+        {
+            std::mutex Mutex;
+            time_point Now;
+            TimerId LastId = 0;
+            // Ordered by time, then by the order they were set.
+            std::map<std::pair<time_point, TimerId>, std::function<void()>> Timers;
+        };
+
+        // Never destroyed: a timer may still read the clock while static
+        // objects of the program are destroyed.
+        static Shared &State()
+        {
+            static Shared *const state = new Shared();
+            return *state;
+        }
+
+        // Runs the first timer, due at `next`, and nothing after it.
+        static void AdvanceToOne(time_point next)
+        {
+            std::function<void()> due;
+            {
+                std::scoped_lock<std::mutex> lock(State().Mutex);
+                auto &state = State();
+                const auto first = state.Timers.begin();
+                if (first == state.Timers.end())
+                {
+                    return;
+                }
+
+                state.Now = next;
+                due = std::move(first->second);
+                state.Timers.erase(first);
+            }
+
+            due();
+        }
+    };
+
+} // namespace Progmasoft::Catch3
diff --git a/src/Progmasoft/meson.build b/src/Progmasoft/meson.build
index 29ec4c56..424cc2bf 100644
--- a/src/Progmasoft/meson.build
+++ b/src/Progmasoft/meson.build
@@ -19,6 +19,7 @@ if get_option('install')
   install_headers('Catch3/Snapshot.hpp', subdir: 'Progmasoft/Catch3')
   install_headers('Catch3/Death.hpp', subdir: 'Progmasoft/Catch3')
   install_headers('Catch3/XmlWriter.hpp', subdir: 'Progmasoft/Catch3')
+  install_headers('Catch3/VirtualClock.hpp', subdir: 'Progmasoft/Catch3')
   install_headers('Catch3/ForAll.hpp', subdir: 'Progmasoft/Catch3')
   install_headers('Catch3/Relations.hpp', subdir: 'Progmasoft/Catch3')
   install_headers('Catch3/Stateful.hpp', subdir: 'Progmasoft/Catch3')
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 6ee65a34..15c47dac 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -170,6 +170,7 @@ add_executable(ProgmasoftSelfTest
   Progmasoft/RunnerCoverage.tests.cpp
   Progmasoft/RunnerOutput.tests.cpp
   Progmasoft/Snapshot.tests.cpp
+  Progmasoft/VirtualClock.tests.cpp
   Progmasoft/Death.tests.cpp
   Progmasoft/Stateful.tests.cpp
   Progmasoft/Strategy.tests.cpp
diff --git a/tests/Progmasoft/BUILD.bazel b/tests/Progmasoft/BUILD.bazel
index b2cede38..608d9a5b 100644
--- a/tests/Progmasoft/BUILD.bazel
+++ b/tests/Progmasoft/BUILD.bazel
@@ -24,6 +24,7 @@ cc_test(
         "RunnerCoverage.tests.cpp",
         "RunnerOutput.tests.cpp",
         "Snapshot.tests.cpp",
+        "VirtualClock.tests.cpp",
         "Death.tests.cpp",
         "Stateful.tests.cpp",
         "Strategy.tests.cpp",
diff --git a/tests/Progmasoft/VirtualClock.tests.cpp b/tests/Progmasoft/VirtualClock.tests.cpp
new file mode 100644
index 00000000..9955ab08
--- /dev/null
+++ b/tests/Progmasoft/VirtualClock.tests.cpp
@@ -0,0 +1,165 @@
+// Copyright (c) 2026 Progmasoft.
+// SPDX-License-Identifier: LGPL-3.0-or-later
+#include <Progmasoft/Catch3.hpp>
+
+#include <chrono>
+#include <stdexcept>
+#include <string>
+#include <thread>
+#include <type_traits>
+#include <vector>
+
+using Progmasoft::Catch3::VirtualClock;
+using namespace std::chrono_literals;
+
+namespace {
+
+    // Code under test that takes its clock as a parameter: an entry expires
+    // `ttl` after it was put.
+    template <typename Clock> class ExpiringValue {
+    public:
+        explicit ExpiringValue( typename Clock::duration ttl ): m_ttl( ttl ) {}
+
+        void Put( int value ) {
+            m_value = value;
+            m_expires = Clock::now() + m_ttl;
+        }
+
+        [[nodiscard]] bool Has() const { return Clock::now() < m_expires; }
+
+    private:
+        typename Clock::duration m_ttl;
+        typename Clock::time_point m_expires{};
+        int m_value = 0;
+    };
+
+} // namespace
+
+TEST_CASE( "The virtual clock meets the Clock requirements of chrono",
+           "[progmasoft][virtual-clock]" ) {
+    STATIC_REQUIRE( VirtualClock::is_steady );
+    STATIC_REQUIRE( std::is_same_v<VirtualClock::duration,
+                                   std::chrono::nanoseconds> );
+    STATIC_REQUIRE(
+        std::is_same_v<decltype( VirtualClock::now() ),
+                       VirtualClock::time_point> );
+    VirtualClock::Scope time;
+    CHECK( VirtualClock::now().time_since_epoch() == 0ns );
+}
+
+TEST_CASE( "Time moves only when the test advances it",
+           "[progmasoft][virtual-clock]" ) {
+    VirtualClock::Scope time;
+    ExpiringValue<VirtualClock> value( 30s );
+    value.Put( 1 );
+    std::this_thread::sleep_for( 5ms );
+    CHECK( value.Has() );
+    VirtualClock::Advance( 29s );
+    CHECK( value.Has() );
+    VirtualClock::SleepFor( 1s );
+    CHECK_FALSE( value.Has() );
+    CHECK( VirtualClock::now().time_since_epoch() == 30s );
+}
+
+TEST_CASE( "The clock does not go back", "[progmasoft][virtual-clock]" ) {
+    VirtualClock::Scope time;
+    VirtualClock::Advance( 10s );
+    CHECK_THROWS_AS( VirtualClock::Advance( -1s ), std::invalid_argument );
+    CHECK_THROWS_AS( VirtualClock::AdvanceTo( VirtualClock::time_point{ 5s } ),
+                     std::invalid_argument );
+    CHECK_THROWS_AS( VirtualClock::After( -1ns, [] {} ),
+                     std::invalid_argument );
+    CHECK( VirtualClock::now().time_since_epoch() == 10s );
+}
+
+TEST_CASE( "Timers run in time order, each at its own time",
+           "[progmasoft][virtual-clock]" ) {
+    VirtualClock::Scope time;
+    std::vector<std::string> ran;
+    auto at = [&]( const char* name ) {
+        return [&ran, name] {
+            ran.push_back(
+                std::string( name ) + "@" +
+                std::to_string( std::chrono::duration_cast<std::chrono::seconds>(
+                                    VirtualClock::now().time_since_epoch() )
+                                    .count() ) );
+        };
+    };
+    VirtualClock::After( 3s, at( "c" ) );
+    VirtualClock::After( 1s, at( "a" ) );
+    VirtualClock::After( 1s, at( "b" ) ); // same time: in the order set
+    VirtualClock::After( 9s, at( "late" ) );
+    CHECK( VirtualClock::Pending() == 4 );
+
+    VirtualClock::Advance( 5s );
+    CHECK( ran == std::vector<std::string>{ "a@1", "b@1", "c@3" } );
+    CHECK( VirtualClock::now().time_since_epoch() == 5s );
+    CHECK( VirtualClock::Pending() == 1 );
+}
+
+TEST_CASE( "A timer may set another, which runs if it falls within the step",
+           "[progmasoft][virtual-clock]" ) {
+    VirtualClock::Scope time;
+    int ticks = 0;
+    std::function<void()> tick = [&] {
+        ++ticks;
+        VirtualClock::After( 1s, tick );
+    };
+    VirtualClock::After( 1s, tick );
+    VirtualClock::Advance( 10s );
+    CHECK( ticks == 10 );
+    CHECK( VirtualClock::Pending() == 1 );
+    CHECK_THROWS_WITH( VirtualClock::RunUntilIdle( 50 ),
+                       Catch::Matchers::ContainsSubstring( "keeps setting" ) );
+}
+
+TEST_CASE( "A zero delay runs at the next advance, even a zero one",
+           "[progmasoft][virtual-clock]" ) {
+    VirtualClock::Scope time;
+    bool ran = false;
+    VirtualClock::After( 0s, [&] { ran = true; } );
+    CHECK_FALSE( ran );
+    VirtualClock::Advance( 0s );
+    CHECK( ran );
+}
+
+TEST_CASE( "A cancelled timer does not run", "[progmasoft][virtual-clock]" ) {
+    VirtualClock::Scope time;
+    bool ran = false;
+    const auto id = VirtualClock::After( 2s, [&] { ran = true; } );
+    CHECK( VirtualClock::Cancel( id ) );
+    CHECK_FALSE( VirtualClock::Cancel( id ) );
+    VirtualClock::Advance( 3s );
+    CHECK_FALSE( ran );
+}
+
+TEST_CASE( "RunUntilIdle advances from timer to timer",
+           "[progmasoft][virtual-clock]" ) {
+    VirtualClock::Scope time;
+    std::vector<long long> seen;
+    for ( auto delay : { 7s, 2s, 4s } ) {
+        VirtualClock::After( delay, [&] {
+            seen.push_back(
+                std::chrono::duration_cast<std::chrono::seconds>(
+                    VirtualClock::now().time_since_epoch() )
+                    .count() );
+        } );
+    }
+    CHECK( VirtualClock::RunUntilIdle() == 3 );
+    CHECK( seen == std::vector<long long>{ 2, 4, 7 } );
+    CHECK( VirtualClock::now().time_since_epoch() == 7s );
+    CHECK( VirtualClock::RunUntilIdle() == 0 );
+}
+
+TEST_CASE( "A scope leaves neither time nor timers to the next test",
+           "[progmasoft][virtual-clock]" ) {
+    {
+        VirtualClock::Scope time;
+        VirtualClock::Advance( 1h );
+        VirtualClock::After( 1s, [] { FAIL( "a timer of another scope ran" ); } );
+    }
+    VirtualClock::Scope time;
+    CHECK( VirtualClock::now().time_since_epoch() == 0ns );
+    CHECK( VirtualClock::Pending() == 0 );
+    VirtualClock::Advance( 2s );
+}
diff --git a/tests/meson.build b/tests/meson.build
index 7caf74ea..467f5951 100644
--- a/tests/meson.build
+++ b/tests/meson.build
@@ -88,6 +88,7 @@ progmasoft_property_tests = executable(
     'Progmasoft/RunnerCoverage.tests.cpp',
     'Progmasoft/RunnerOutput.tests.cpp',
     'Progmasoft/Snapshot.tests.cpp',
+    'Progmasoft/VirtualClock.tests.cpp',
     'Progmasoft/Death.tests.cpp',
     'Progmasoft/Stateful.tests.cpp',
     'Progmasoft/Strategy.tests.cpp',
diff --git a/xmake.lua b/xmake.lua
index 096a2baa..b26d222f 100644
--- a/xmake.lua
+++ b/xmake.lua
@@ -71,6 +71,7 @@ target("ProgmasoftPropertyTests")
         "tests/Progmasoft/RunnerCoverage.tests.cpp",
         "tests/Progmasoft/RunnerOutput.tests.cpp",
         "tests/Progmasoft/Snapshot.tests.cpp",
+        "tests/Progmasoft/VirtualClock.tests.cpp",
         "tests/Progmasoft/Death.tests.cpp",
         "tests/Progmasoft/Stateful.tests.cpp",
         "tests/Progmasoft/Strategy.tests.cpp",