Reflection and filesystem

Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-05-03 18:09:46 +03:00
1 parent f0825fbd1a
commit 42268c6c35
45 files changed
+2732 -262

No files matched your search

+1
View File
@@ -18,6 +18,7 @@ if(INTERNAL_SOURCES)
if(TARGET Void::TestingMock)
target_link_libraries(VoidInternalTests PRIVATE Void::TestingMock)
endif()
add_test(NAME internal COMMAND VoidInternalTests --no-color)
endif()
# ------------------------------------------------------------------------------
+115
View File
@@ -0,0 +1,115 @@
// Cross-module integration tests for the kitchen-sink VoidInternalTests
// binary. Exercises Logging + Result + Stacktrace + FileSystem working
// together — the kind of thing the standalone per-module tests can't
// reach because they only link one module.
#include <Void/FileSystem/Path.hpp>
#include <Void/FileSystem/TempDir.hpp>
#include <Void/Logging/ConsoleLogger.hpp>
#include <Void/Logging/FileLogger.hpp>
#include <Void/Logging/Level.hpp>
#include <Void/Result/Error.hpp>
#include <Void/Result/Result.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <filesystem>
#include <sstream>
#include <string>
namespace
{
struct ConfigError {
std::string file;
int line;
std::string detail;
};
} // namespace
// Reflection-based repr (Phase 2.6) renders user-defined error structs
// inside Testing assertions without any per-type formatter.
Void::Testing::Test repr_handles_user_error_struct()
{
const auto out = Void::Testing::Detail::repr(
ConfigError{"settings.toml", 17, "missing key 'name'"});
Void::Testing::expect(out.find("ConfigError") != std::string::npos);
Void::Testing::expect(out.find("file: settings.toml") != std::string::npos);
Void::Testing::expect(out.find("line: 17") != std::string::npos);
Void::Testing::expect(out.find("detail: missing key 'name'") !=
std::string::npos);
}
// Result + Stacktrace: read_source_snippet returns Result, and a missing
// file produces an Error whose chained message is rendered correctly.
Void::Testing::Test stacktrace_snippet_returns_result_on_missing_file()
{
auto r = Void::Stacktrace::read_source_snippet(
"/this/path/does/not/exist.cpp", 10);
Void::Testing::expect(!r.has_value());
const auto chained = Void::Result::with_context(r, "loading test fixture");
const auto rendered = chained.error().format();
Void::Testing::expect(rendered.find("loading test fixture") !=
std::string::npos);
Void::Testing::expect(rendered.find("read_source_snippet") !=
std::string::npos);
Void::Testing::expect(rendered.find("caused by:") != std::string::npos);
}
// Logging + Result: FileLogger::open returns Result; chained context
// surfaces meaningfully.
Void::Testing::Test file_logger_open_failure_chains_into_context()
{
auto r = Void::Logging::FileLogger::open("/no/such/dir/test.log");
Void::Testing::expect(!r.has_value());
auto wrapped =
Void::Result::with_context(std::move(r), "starting test runner");
const auto rendered = wrapped.error().format();
Void::Testing::expect(rendered.find("starting test runner") !=
std::string::npos);
Void::Testing::expect(rendered.find("FileLogger") != std::string::npos);
}
// Logging emits scope boundaries that survive into the output stream.
Void::Testing::Test logger_scope_entries_render_through_console_sink()
{
std::ostringstream out;
{
Void::Logging::ConsoleLogger log(out);
log.set_level(Void::Logging::Level::Trace);
auto scope = log.push_scope("worker");
log.info("doing work");
}
const auto content = out.str();
Void::Testing::expect(content.find("doing work") != std::string::npos);
Void::Testing::expect(content.find("worker") != std::string::npos);
}
// Logging + Result + FileSystem: roundtrip a chained error into a
// FileLogger sink and read it back through Void::FileSystem::read_file
// (no manual std::filesystem boilerplate, no manual cleanup).
Void::Testing::Test error_chain_logged_to_file_roundtrip()
{
Void::FileSystem::TempDir tmp;
const auto path = tmp / "log.txt";
{
auto sink_r = Void::Logging::FileLogger::open(
path, Void::Logging::Mode::Buffered, 8);
Void::Testing::expect(sink_r.has_value());
auto& sink = **sink_r;
Void::Result::Error inner{"socket closed"};
auto outer = inner.with_context("api request /users");
sink.error(outer.format());
}
auto read_back = Void::FileSystem::read_file(path);
Void::Testing::expect(read_back.has_value());
const auto& content = *read_back;
Void::Testing::expect(content.find("api request /users") !=
std::string::npos);
Void::Testing::expect(content.find("socket closed") != std::string::npos);
Void::Testing::expect(content.find("caused by:") != std::string::npos);
}
+98
View File
@@ -0,0 +1,98 @@
#include <Void/FileSystem/Path.hpp>
#include <Void/FileSystem/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <fstream>
#include <string>
Void::Testing::Test read_file_returns_contents()
{
Void::FileSystem::TempDir tmp;
const auto path = tmp / "data.txt";
{
std::ofstream f{path};
f << "hello\nworld";
}
auto r = Void::FileSystem::read_file(path);
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"hello\nworld"});
}
Void::Testing::Test read_file_fails_on_missing()
{
auto r = Void::FileSystem::read_file("/this/path/does/not/exist");
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().message().find("read_file") !=
std::string::npos);
}
Void::Testing::Test write_file_creates_and_overwrites()
{
Void::FileSystem::TempDir tmp;
const auto path = tmp / "out.txt";
auto r1 = Void::FileSystem::write_file(path, "first");
Void::Testing::expect(r1.has_value());
auto r2 = Void::FileSystem::write_file(path, "second");
Void::Testing::expect(r2.has_value());
auto read_back = Void::FileSystem::read_file(path);
Void::Testing::expect(read_back.has_value());
Void::Testing::expect_eq(*read_back, std::string{"second"});
}
Void::Testing::Test atomic_write_replaces_target()
{
Void::FileSystem::TempDir tmp;
const auto path = tmp / "snapshot.json";
{
std::ofstream f{path};
f << "old contents";
}
auto r = Void::FileSystem::atomic_write(path, "new contents");
Void::Testing::expect(r.has_value());
auto read_back = Void::FileSystem::read_file(path);
Void::Testing::expect(read_back.has_value());
Void::Testing::expect_eq(*read_back, std::string{"new contents"});
// Staging file should not be left behind on success.
auto staging = path;
staging += ".tmp";
Void::Testing::expect(!std::filesystem::exists(staging));
}
Void::Testing::Test ensure_directory_creates_nested_dirs()
{
Void::FileSystem::TempDir tmp;
const auto nested = tmp / "a/b/c/d";
auto r = Void::FileSystem::ensure_directory(nested);
Void::Testing::expect(r.has_value());
Void::Testing::expect(std::filesystem::is_directory(nested));
// Idempotent — second call still succeeds.
auto r2 = Void::FileSystem::ensure_directory(nested);
Void::Testing::expect(r2.has_value());
}
Void::Testing::Test remove_path_handles_missing_and_recursive()
{
// Missing path is a no-op (success).
auto r1 = Void::FileSystem::remove_path("/nonexistent/path");
Void::Testing::expect(r1.has_value());
// Recursive removal.
Void::FileSystem::TempDir tmp;
const auto nested = tmp / "a/b";
(void)Void::FileSystem::ensure_directory(nested);
(void)Void::FileSystem::write_file(nested / "leaf.txt", "x");
auto r2 = Void::FileSystem::remove_path(tmp.path() / "a");
Void::Testing::expect(r2.has_value());
Void::Testing::expect(!std::filesystem::exists(tmp.path() / "a"));
}
+70
View File
@@ -0,0 +1,70 @@
#include <Void/FileSystem/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <filesystem>
#include <fstream>
#include <utility>
Void::Testing::Test temp_dir_creates_directory_under_temp()
{
std::filesystem::path captured;
{
Void::FileSystem::TempDir tmp;
captured = tmp.path();
Void::Testing::expect(std::filesystem::is_directory(captured));
Void::Testing::expect(captured.parent_path() ==
std::filesystem::temp_directory_path());
}
// Removed on destruction.
Void::Testing::expect(!std::filesystem::exists(captured));
}
Void::Testing::Test temp_dir_removes_recursive_contents()
{
std::filesystem::path captured;
{
Void::FileSystem::TempDir tmp;
captured = tmp.path();
std::filesystem::create_directories(tmp / "nested/deep");
std::ofstream{tmp / "nested/deep/leaf.txt"} << "data";
Void::Testing::expect(
std::filesystem::exists(tmp / "nested/deep/leaf.txt"));
}
Void::Testing::expect(!std::filesystem::exists(captured));
}
Void::Testing::Test temp_dir_move_transfers_ownership()
{
std::filesystem::path captured;
{
Void::FileSystem::TempDir a;
captured = a.path();
Void::FileSystem::TempDir b{std::move(a)};
// `a` is moved-from; `b` owns the directory.
Void::Testing::expect_eq(b.path(), captured);
Void::Testing::expect(std::filesystem::is_directory(b.path()));
}
Void::Testing::expect(!std::filesystem::exists(captured));
}
Void::Testing::Test temp_dir_open_factory_returns_result()
{
std::filesystem::path captured;
{
auto r = Void::FileSystem::TempDir::open("void_factory_test_");
Void::Testing::expect(r.has_value());
captured = r->path();
Void::Testing::expect(std::filesystem::is_directory(captured));
}
// `r` is destroyed at end of scope, which destroys the contained
// TempDir and removes the directory.
Void::Testing::expect(!std::filesystem::exists(captured));
}
Void::Testing::Test temp_dir_two_concurrent_dirs_have_distinct_paths()
{
Void::FileSystem::TempDir a;
Void::FileSystem::TempDir b;
Void::Testing::expect(a.path() != b.path());
}
@@ -0,0 +1,62 @@
#include <Void/Logging/ConsoleLogger.hpp>
#include <Void/Logging/Level.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Fixture.hpp>
#include <Void/Testing/Test.hpp>
#include <sstream>
#include <string>
class ConsoleLoggerTests : public Void::Testing::Fixture
{
public:
Void::Testing::Test writes_to_stream()
{
std::ostringstream out;
{
Void::Logging::ConsoleLogger log(out);
log.info("hello world");
}
const auto content = out.str();
Void::Testing::expect(content.find("hello world") !=
std::string::npos);
Void::Testing::expect(content.find("INFO") != std::string::npos);
}
Void::Testing::Test level_filtering()
{
std::ostringstream out;
{
Void::Logging::ConsoleLogger log(out);
log.set_level(Void::Logging::Level::Error);
log.info("filtered out");
log.error("kept");
}
const auto content = out.str();
Void::Testing::expect(content.find("filtered out") ==
std::string::npos);
Void::Testing::expect(content.find("kept") != std::string::npos);
}
Void::Testing::Test multiple_levels_emit_in_order()
{
std::ostringstream out;
{
Void::Logging::ConsoleLogger log(out);
log.set_level(Void::Logging::Level::Trace);
log.trace("first");
log.warning("second");
log.fatal("third");
}
const auto content = out.str();
const auto first = content.find("first");
const auto second = content.find("second");
const auto third = content.find("third");
Void::Testing::expect(first != std::string::npos);
Void::Testing::expect(second != std::string::npos);
Void::Testing::expect(third != std::string::npos);
Void::Testing::expect(first < second);
Void::Testing::expect(second < third);
}
};
+36 -68
View File
@@ -1,4 +1,5 @@
#include <Void/Logging/Logger.hpp>
#include <Void/Logging/FileLogger.hpp>
#include <Void/Logging/Level.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Fixture.hpp>
#include <Void/Testing/Test.hpp>
@@ -6,60 +7,8 @@
#include <filesystem>
#include <format>
#include <fstream>
#include <span>
#include <stdexcept>
#include <string>
namespace
{
class FileLogger final : public Void::Logging::Logger
{
public:
explicit FileLogger(const std::filesystem::path &path,
std::size_t capacity = 64)
: Logger(Void::Logging::Mode::Buffered, capacity),
m_file(path, std::ios::app)
{
if (!m_file.is_open())
throw std::runtime_error(
std::format("FileLogger: cannot open '{}'",
path.string()));
}
~FileLogger() noexcept override { flush(); }
FileLogger(const FileLogger &) = delete;
FileLogger &operator=(const FileLogger &) = delete;
FileLogger(FileLogger &&) = delete;
FileLogger &operator=(FileLogger &&) = delete;
protected:
void on_flush(
std::span<const Void::Logging::Entry> entries) override
{
for (const auto &e : entries)
m_file << std::format("[{}] {}\n",
Void::Logging::to_string(e.level),
e.message);
m_file.flush();
}
void write(const Void::Logging::Entry &entry) override
{
m_file << std::format("[{}] {}\n",
Void::Logging::to_string(entry.level),
entry.message);
m_file.flush();
}
private:
std::ofstream m_file;
};
} // namespace
class FileLoggerTests : public Void::Testing::Fixture
{
public:
@@ -68,8 +17,8 @@ class FileLoggerTests : public Void::Testing::Fixture
void setup() override
{
path = std::filesystem::temp_directory_path()
/ "void_filelogger_test.log";
path = std::filesystem::temp_directory_path() /
"void_filelogger_test.log";
std::filesystem::remove(path);
}
@@ -78,7 +27,7 @@ class FileLoggerTests : public Void::Testing::Fixture
Void::Testing::Test creates_file()
{
{
FileLogger log(path);
Void::Logging::FileLogger log(path);
log.info("hello");
}
Void::Testing::expect(std::filesystem::exists(path));
@@ -87,41 +36,60 @@ class FileLoggerTests : public Void::Testing::Fixture
Void::Testing::Test writes_messages()
{
{
FileLogger log(path, /*capacity=*/1);
Void::Logging::FileLogger log(
path, Void::Logging::Mode::Buffered, 1);
log.info("test message");
}
std::ifstream f(path);
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("test message")
!= std::string::npos);
Void::Testing::expect(content.find("test message") !=
std::string::npos);
}
Void::Testing::Test level_filtering()
{
{
FileLogger log(path, /*capacity=*/1);
Void::Logging::FileLogger log(
path, Void::Logging::Mode::Buffered, 1);
log.set_level(Void::Logging::Level::Warning);
log.debug("should be dropped");
log.warning("should appear");
}
std::ifstream f(path);
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("should be dropped")
== std::string::npos);
Void::Testing::expect(content.find("should appear")
!= std::string::npos);
Void::Testing::expect(content.find("should be dropped") ==
std::string::npos);
Void::Testing::expect(content.find("should appear") !=
std::string::npos);
}
Void::Testing::Test buffered_flush()
{
{
FileLogger log(path, /*capacity=*/100);
for (int i = 0; i < 5; ++i)
Void::Logging::FileLogger log(
path, Void::Logging::Mode::Buffered, 100);
for (int i = 0; i < 5; ++i) {
log.info(std::format("entry {}", i));
}
}
std::ifstream f(path);
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("entry 4")
!= std::string::npos);
Void::Testing::expect(content.find("entry 4") != std::string::npos);
}
Void::Testing::Test open_factory_returns_ok_on_valid_path()
{
auto r = Void::Logging::FileLogger::open(path);
Void::Testing::expect(r.has_value());
(*r)->info("via factory");
}
Void::Testing::Test open_factory_returns_error_on_bad_path()
{
auto r = Void::Logging::FileLogger::open(
"/this/path/does/not/exist/file.log");
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().message().find("FileLogger") !=
std::string::npos);
}
};
+44
View File
@@ -0,0 +1,44 @@
#include <Void/Result/Error.hpp>
#include <Void/Result/Result.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
namespace
{
Void::Result::Result<int> divide(int n, int d)
{
if (d == 0) {
return Void::Result::fail("division by zero");
}
return Void::Result::ok(n / d);
}
} // namespace
Void::Testing::Test ok_constructs_success()
{
auto r = divide(10, 2);
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, 5);
}
Void::Testing::Test fail_constructs_failure()
{
auto r = divide(10, 0);
Void::Testing::expect(!r.has_value());
Void::Testing::expect_eq(r.error().message(),
std::string{"division by zero"});
}
Void::Testing::Test value_or_returns_fallback_on_error()
{
auto r = divide(10, 0);
Void::Testing::expect_eq(r.value_or(-1), -1);
}
Void::Testing::Test bool_conversion()
{
Void::Testing::expect(static_cast<bool>(divide(10, 2)));
Void::Testing::expect(!static_cast<bool>(divide(10, 0)));
}
+56
View File
@@ -0,0 +1,56 @@
#include <Void/Result/Error.hpp>
#include <Void/Result/Result.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
namespace
{
Void::Result::Result<int> read_file()
{
return Void::Result::fail("disk read error");
}
Void::Result::Result<int> parse_config()
{
return Void::Result::with_context(read_file(), "parsing config.toml");
}
Void::Result::Result<int> load()
{
return Void::Result::with_context(parse_config(), "starting up");
}
} // namespace
Void::Testing::Test context_chain_preserves_root_message()
{
auto r = load();
Void::Testing::expect(!r.has_value());
const auto& e = r.error();
Void::Testing::expect_eq(e.message(), std::string{"starting up"});
Void::Testing::expect(e.cause() != nullptr);
Void::Testing::expect_eq(e.cause()->message(),
std::string{"parsing config.toml"});
Void::Testing::expect_eq(e.cause()->cause()->message(),
std::string{"disk read error"});
}
Void::Testing::Test format_renders_full_chain()
{
auto r = load();
const auto rendered = r.error().format();
Void::Testing::expect(rendered.find("starting up") != std::string::npos);
Void::Testing::expect(rendered.find("parsing config.toml") !=
std::string::npos);
Void::Testing::expect(rendered.find("disk read error") !=
std::string::npos);
Void::Testing::expect(rendered.find("caused by:") != std::string::npos);
}
Void::Testing::Test with_context_no_op_on_success()
{
auto r = Void::Result::with_context(Void::Result::ok(42), "unused context");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, 42);
}
+49
View File
@@ -0,0 +1,49 @@
#include <Void/Result/Error.hpp>
#include <Void/Result/Result.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
namespace
{
Void::Result::Result<int> parse_int(const std::string& s)
{
try {
return Void::Result::ok(std::stoi(s));
} catch (...) {
return Void::Result::fail("not a number");
}
}
Void::Result::Result<int> doubled(int n) { return Void::Result::ok(n * 2); }
} // namespace
Void::Testing::Test and_then_chains_on_success()
{
auto r = parse_int("21").and_then(doubled);
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, 42);
}
Void::Testing::Test and_then_short_circuits_on_failure()
{
auto r = parse_int("xyz").and_then(doubled);
Void::Testing::expect(!r.has_value());
Void::Testing::expect_eq(r.error().message(), std::string{"not a number"});
}
Void::Testing::Test transform_maps_value()
{
auto r = parse_int("3").transform([](int n) { return n + 100; });
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, 103);
}
Void::Testing::Test or_else_recovers_on_failure()
{
auto r = parse_int("xyz").or_else(
[](const Void::Result::Error&) { return Void::Result::ok(0); });
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, 0);
}
@@ -0,0 +1,54 @@
#include <Void/Result/Detail/Repr.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
namespace
{
struct PlainStruct {
int code;
std::string label;
};
struct DiagInfo {
std::string file;
int line;
std::string detail;
};
} // namespace
Void::Testing::Test repr_uses_std_format_when_available()
{
const auto out = Void::Result::Detail::repr(42);
Void::Testing::expect_eq(out, std::string{"42"});
}
Void::Testing::Test repr_uses_std_format_for_string()
{
const auto out = Void::Result::Detail::repr(std::string{"hello"});
Void::Testing::expect_eq(out, std::string{"hello"});
}
#ifdef VOID_RESULT_HAS_REFLECTION
// @tag reflection
Void::Testing::Test repr_walks_struct_fields_via_reflection()
{
PlainStruct s{42, "ok"};
const auto out = Void::Result::Detail::repr(s);
Void::Testing::expect(out.find("PlainStruct") != std::string::npos);
Void::Testing::expect(out.find("code: 42") != std::string::npos);
Void::Testing::expect(out.find("label: ok") != std::string::npos);
}
// @tag reflection
Void::Testing::Test repr_handles_multiple_fields()
{
DiagInfo d{"foo.cpp", 17, "bad token"};
const auto out = Void::Result::Detail::repr(d);
Void::Testing::expect(out.find("DiagInfo") != std::string::npos);
Void::Testing::expect(out.find("file: foo.cpp") != std::string::npos);
Void::Testing::expect(out.find("line: 17") != std::string::npos);
Void::Testing::expect(out.find("detail: bad token") != std::string::npos);
}
#endif
+47
View File
@@ -0,0 +1,47 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
namespace
{
struct Point {
int x;
int y;
};
bool operator==(const Point& a, const Point& b)
{
return a.x == b.x && a.y == b.y;
}
} // namespace
// Sanity: equal structs pass.
Void::Testing::Test struct_eq_passes_when_equal()
{
Void::Testing::expect_eq(Point{1, 2}, Point{1, 2});
}
// The reflection-aware repr is exercised by Void::Result::Detail::repr;
// we verify here that calling repr on a struct produces a string that
// includes the type name and field values.
Void::Testing::Test repr_renders_struct_via_reflection()
{
const auto out = Void::Testing::Detail::repr(Point{3, 4});
Void::Testing::expect(out.find("Point") != std::string::npos);
Void::Testing::expect(out.find("x: 3") != std::string::npos);
Void::Testing::expect(out.find("y: 4") != std::string::npos);
}
// repr for primitives still works.
Void::Testing::Test repr_handles_primitives()
{
Void::Testing::expect_eq(Void::Testing::Detail::repr(42),
std::string{"42"});
Void::Testing::expect_eq(Void::Testing::Detail::repr(true),
std::string{"true"});
Void::Testing::expect_eq(Void::Testing::Detail::repr(nullptr),
std::string{"nullptr"});
Void::Testing::expect_eq(Void::Testing::Detail::repr(std::string{"hi"}),
std::string{"\"hi\""});
}
@@ -0,0 +1,100 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Config.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/TestingMock/MockFunction.hpp>
#include <cstddef>
#include <string>
#include <utility>
#include <vector>
namespace
{
// Capture any failed assertions added by `fn()` and clear them from
// the current test result so this test can itself pass while still
// inspecting the captured messages.
template <typename Fn> std::vector<std::string> capture_failures(Fn&& fn)
{
auto& ctx = Void::Testing::Detail::TestContext::current();
auto& assertions = ctx.current_result->assertions;
const std::size_t saved = assertions.size();
std::forward<Fn>(fn)();
std::vector<std::string> messages;
for (std::size_t i = saved; i < assertions.size(); ++i) {
if (!assertions[i].passed) {
messages.push_back(assertions[i].message);
}
}
// Drop everything we recorded so the test result stays clean.
assertions.erase(assertions.begin() + saved, assertions.end());
ctx.current_result->state = Void::Testing::TestState::Passed;
return messages;
}
} // namespace
Void::Testing::Test failure_message_includes_actual_args()
{
using namespace Void::TestingMock;
auto messages = capture_failures([] {
MockFunction<int(int, std::string)> fn{"do_thing"};
fn.expect(Eq(1), Eq(std::string{"alpha"})).returns(0);
(void)fn(99, std::string{"beta"});
});
Void::Testing::expect(!messages.empty());
const auto& msg = messages.front();
Void::Testing::expect(msg.find("do_thing(99") != std::string::npos);
Void::Testing::expect(msg.find("\"beta\"") != std::string::npos);
}
Void::Testing::Test failure_message_lists_each_expectation()
{
using namespace Void::TestingMock;
auto messages = capture_failures([] {
MockFunction<int(int)> fn{"do_thing"};
fn.expect(Eq(1)).returns(10);
fn.expect(Range(50, 60)).returns(20);
(void)fn(99);
});
Void::Testing::expect(!messages.empty());
const auto& msg = messages.front();
Void::Testing::expect(msg.find("expectation 1") != std::string::npos);
Void::Testing::expect(msg.find("Eq(1)") != std::string::npos);
Void::Testing::expect(msg.find("expectation 2") != std::string::npos);
Void::Testing::expect(msg.find("Range(50, 60)") != std::string::npos);
Void::Testing::expect(msg.find("0/1 calls") != std::string::npos);
}
Void::Testing::Test failure_message_when_no_expectations_registered()
{
using namespace Void::TestingMock;
auto messages = capture_failures([] {
MockFunction<int(int)> fn{"do_thing"};
(void)fn(42);
});
Void::Testing::expect(!messages.empty());
Void::Testing::expect(messages.front().find("no expectations registered") !=
std::string::npos);
}
Void::Testing::Test verify_failure_message_describes_unsatisfied_expectation()
{
using namespace Void::TestingMock;
auto messages = capture_failures([] {
MockFunction<int(int)> fn{"do_thing"};
fn.expect(Gt(100)).returns(0).times(2);
// Never called — destructor fires verify(), which fails.
});
Void::Testing::expect(!messages.empty());
const auto& msg = messages.front();
Void::Testing::expect(msg.find("unsatisfied expectation") !=
std::string::npos);
Void::Testing::expect(msg.find("do_thing") != std::string::npos);
Void::Testing::expect(msg.find("Gt(100)") != std::string::npos);
Void::Testing::expect(msg.find("0/2 calls") != std::string::npos);
}
+64
View File
@@ -0,0 +1,64 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/TestingMock/MockFunction.hpp>
#include <string>
#include <string_view>
Void::Testing::Test lt_le_gt_ge_match_appropriately()
{
using namespace Void::TestingMock;
MockFunction<int(int)> fn{"f"};
fn.expect(Lt(10)).returns(1).times(1);
fn.expect(Le(20)).returns(2).times(1);
fn.expect(Gt(30)).returns(3).times(1);
fn.expect(Ge(40)).returns(4).times(1);
Void::Testing::expect_eq(fn(5), 1);
Void::Testing::expect_eq(fn(15), 2);
Void::Testing::expect_eq(fn(35), 3);
Void::Testing::expect_eq(fn(40), 4);
}
Void::Testing::Test range_matches_inclusive_bounds()
{
using namespace Void::TestingMock;
MockFunction<int(int)> fn{"in_range"};
fn.expect(Range(10, 20)).returns(99).times(3);
Void::Testing::expect_eq(fn(10), 99); // lower bound
Void::Testing::expect_eq(fn(15), 99); // middle
Void::Testing::expect_eq(fn(20), 99); // upper bound
}
Void::Testing::Test pred_matcher_invokes_user_callable()
{
using namespace Void::TestingMock;
MockFunction<int(int)> fn{"is_even"};
fn.expect(Pred<int>([](const int& v) { return v % 2 == 0; }))
.returns(1)
.times(2);
Void::Testing::expect_eq(fn(4), 1);
Void::Testing::expect_eq(fn(8), 1);
}
Void::Testing::Test starts_with_matches_string_prefix()
{
using namespace Void::TestingMock;
MockFunction<int(std::string_view)> fn{"prefix"};
fn.expect(StartsWith<std::string_view>("hello")).returns(1).times(2);
Void::Testing::expect_eq(fn("hello world"), 1);
Void::Testing::expect_eq(fn("hello"), 1);
}
Void::Testing::Test contains_matches_substring()
{
using namespace Void::TestingMock;
MockFunction<int(std::string_view)> fn{"contains"};
fn.expect(Contains<std::string_view>("foo")).returns(1).times(2);
Void::Testing::expect_eq(fn("a foo b"), 1);
Void::Testing::expect_eq(fn("foobar"), 1);
}
@@ -0,0 +1,24 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/TestingMock/MockFunction.hpp>
#include <memory>
// std::move_only_function support: a unique_ptr-capturing lambda used to
// fail to compile against std::function. With Phase 2.3.4 the action
// holder is std::move_only_function, so this works.
Void::Testing::Test invokes_accepts_unique_ptr_capturing_lambda()
{
using namespace Void::TestingMock;
MockFunction<int(int)> fn{"counter"};
auto state = std::make_unique<int>(10);
fn.expect(_<int>())
.invokes(
[s = std::move(state)](int delta) -> int { return *s + delta; })
.times(2);
Void::Testing::expect_eq(fn(1), 11);
Void::Testing::expect_eq(fn(5), 15);
}
@@ -0,0 +1,58 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/TestingMock/Mock.hpp>
#include <Void/TestingMock/MockFunction.hpp>
namespace
{
// Minimal interface to mock.
struct Service {
virtual ~Service() = default;
virtual int compute(int) = 0;
virtual void log(int) = 0;
};
class MockService : public Void::TestingMock::Mock<MockService>,
public Service
{
public:
Void::TestingMock::MockFunction<int(int)> compute_mock{*this,
"compute"};
Void::TestingMock::MockFunction<void(int)> log_mock{*this, "log"};
int compute(int n) override { return compute_mock(n); }
void log(int n) override { log_mock(n); }
};
} // namespace
// Both registered MockFunctions are exercised — verify_all() succeeds.
Void::Testing::Test verify_all_passes_when_all_expectations_met()
{
using namespace Void::TestingMock;
MockService svc;
svc.compute_mock.expect(Eq(1)).returns(42);
svc.log_mock.expect(Eq(2));
Void::Testing::expect_eq(svc.compute(1), 42);
svc.log(2);
svc.verify_all();
}
// register_function is reachable directly for users who don't want to
// use the constructor-overload registration (e.g. dynamically created
// MockFunctions).
Void::Testing::Test register_function_is_publicly_callable()
{
using namespace Void::TestingMock;
MockService svc;
// The two members already auto-registered; svc.verify_all() should
// be a no-op since the two MockFunctions in the class were never
// expected to be called.
svc.compute_mock.expect(Eq(7)).returns(0);
svc.log_mock.expect(Eq(8));
(void)svc.compute(7);
svc.log(8);
svc.verify_all();
}