1 parent
f0825fbd1a
commit
42268c6c35
45 files changed
+2732
-262
No files matched your search
@@ -0,0 +1,62 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
build-gcc16:
|
||||
name: GCC 16 / C++26 / ${{ matrix.config }}
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
config:
|
||||
- default
|
||||
- werror
|
||||
- sanitizers
|
||||
include:
|
||||
- config: default
|
||||
cmake_args: ""
|
||||
- config: werror
|
||||
cmake_args: "-DVOID_WARNINGS_AS_ERRORS=ON"
|
||||
- config: sanitizers
|
||||
cmake_args: "-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install GCC 16 + tooling
|
||||
run: |
|
||||
sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y g++-16 ninja-build cmake libboost-all-dev
|
||||
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-16 100
|
||||
|
||||
- name: Cache FetchContent dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: build/_deps
|
||||
key: ${{ runner.os }}-fetchcontent-boost-${{ hashFiles('cmake/Dependencies.cmake') }}
|
||||
|
||||
- name: Configure
|
||||
run: |
|
||||
cmake -B build -S . -G Ninja \
|
||||
-DCMAKE_CXX_COMPILER=g++-16 \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
${{ matrix.cmake_args }}
|
||||
|
||||
- name: Build
|
||||
run: cmake --build build
|
||||
|
||||
- name: Test
|
||||
run: ctest --test-dir build --output-on-failure
|
||||
|
||||
# NOTE: a Clang job is intentionally absent. The library targets C++26
|
||||
# with std::meta reflection (-freflection), which Clang does not yet
|
||||
# support. The Repr.hpp helper degrades gracefully via __has_include,
|
||||
# but CMakeLists.txt currently hard-pins CMAKE_CXX_STANDARD to 26.
|
||||
# Add a Clang job once Clang ships P2996 reflection (tracked in the
|
||||
# roadmap as Phase 2 follow-up).
|
||||
@@ -1,2 +1,3 @@
|
||||
build
|
||||
build*
|
||||
CLAUDE.md
|
||||
@@ -4,11 +4,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## Build
|
||||
|
||||
Requires CMake 4.0+ and a C++23 compiler (clang++ is the default in the configure command below).
|
||||
Requires CMake 4.0+ and a C++26 compiler. GCC 16+ is the default — it ships
|
||||
the experimental `-freflection` flag and the `<meta>` header that several
|
||||
modules use. Clang is supported but currently lacks P2996 reflection, so
|
||||
modules that use it stay reflection-free behind `__has_include(<meta>)`.
|
||||
|
||||
```bash
|
||||
# Configure (clang++, Ninja, Debug)
|
||||
cmake -B build -S . -G Ninja -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_BUILD_TYPE=Debug
|
||||
# Configure (g++, Ninja, Debug)
|
||||
cmake -B build -S . -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Debug
|
||||
|
||||
# Build
|
||||
cmake --build build
|
||||
|
||||
+5
-1
@@ -1,7 +1,11 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(Void VERSION 1.0.0 LANGUAGES CXX)
|
||||
option(VOID_ENABLE_TESTING "Build the test suite" ON)
|
||||
set(CMAKE_CXX_STANDARD 23)
|
||||
option(VOID_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF)
|
||||
option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF)
|
||||
option(VOID_ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (Clang/GCC)" OFF)
|
||||
option(VOID_ENABLE_COVERAGE "Enable code coverage instrumentation" OFF)
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# VoidLibrary
|
||||
|
||||
A modular C++26 shared library. Each module is an independently installable
|
||||
CMake target under the `Void::` namespace; the build system auto-discovers
|
||||
modules under `src/` and links them together.
|
||||
|
||||
## Build
|
||||
|
||||
Requires CMake 4.0+ and a C++26 compiler. GCC 16+ is the default — it ships
|
||||
experimental P2996 reflection (`-freflection`, `<meta>` header) that several
|
||||
modules opt into.
|
||||
|
||||
```bash
|
||||
# Configure (g++, Ninja, Debug)
|
||||
cmake -B build -S . -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Debug
|
||||
|
||||
# Build
|
||||
cmake --build build
|
||||
|
||||
# Run all tests
|
||||
ctest --test-dir build
|
||||
|
||||
# Run a single standalone test binary directly
|
||||
./build/tests/test_standalone_Logging_FileLogger
|
||||
```
|
||||
|
||||
### Optional build flags
|
||||
|
||||
| Flag | Default | Effect |
|
||||
|----------------------------|---------|------------------------------------------------------------------------|
|
||||
| `VOID_ENABLE_TESTING` | `ON` | Build the test suite under `tests/`. |
|
||||
| `VOID_WARNINGS_AS_ERRORS` | `OFF` | Adds `-Wall -Wextra -Wpedantic -Werror` (GCC/Clang) or `/W4 /WX` (MSVC). |
|
||||
| `VOID_ENABLE_ASAN` | `OFF` | Adds `-fsanitize=address` to compile and link. |
|
||||
| `VOID_ENABLE_UBSAN` | `OFF` | Adds `-fsanitize=undefined` to compile and link. |
|
||||
| `VOID_ENABLE_COVERAGE` | `OFF` | Adds `--coverage` (GCC) or `-fprofile-instr-generate -fcoverage-mapping` (Clang). After `ctest`, run `gcovr -r . build` for a report. |
|
||||
|
||||
```bash
|
||||
cmake -B build-asan -S . -G Ninja -DCMAKE_CXX_COMPILER=g++ \
|
||||
-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON \
|
||||
-DVOID_WARNINGS_AS_ERRORS=ON -DCMAKE_BUILD_TYPE=Debug
|
||||
cmake --build build-asan
|
||||
ctest --test-dir build-asan
|
||||
```
|
||||
|
||||
Format code with `clang-format -i <file>`.
|
||||
|
||||
## Modules
|
||||
|
||||
| Module | Namespace | Description |
|
||||
|---------------|-----------------------|-----------------------------------------------------------------------------|
|
||||
| `Logging` | `Void::Logging` | Thread-safe `Logger` ABC with buffering, scopes, presets; ships `FileLogger` and `ConsoleLogger` sinks. |
|
||||
| `Testing` | `Void::Testing` | Self-registering test framework with fixtures, tags, JUnit/console reporters, signal-handler crash capture. |
|
||||
| `TestingMock` | `Void::TestingMock` | Header-only mock framework: `MockFunction`, `Mock<Derived>` CRTP base, matchers (`Eq`/`_`/`Lt`/`Le`/`Gt`/`Ge`/`Range`/`Pred`/`StartsWith`/`Contains`), move-only actions. |
|
||||
| `Stacktrace` | `Void::Stacktrace` | Stack capture + source-snippet rendering via Boost.Stacktrace; ANSI color helpers. |
|
||||
| `Result` | `Void::Result` | Header-only `Result<T,E> = std::expected<T,E>` plus `Error` with cause-chain context, `with_context()` helper, reflection-based struct `repr` (C++26 `<meta>`). |
|
||||
| `FileSystem` | `Void::FileSystem` | Header-only path utilities returning `Result<T,E>`: `read_file`, `write_file`, `atomic_write`, `ensure_directory`, `remove_path`, RAII `TempDir`. |
|
||||
|
||||
## Adding a module
|
||||
|
||||
Create `src/<ModuleName>/` and populate it with sources/headers — the build
|
||||
picks it up automatically. Public headers go in
|
||||
`include/Void/<ModuleName>/*.hpp`. For special dependency wiring drop a
|
||||
`module.cmake` in the source directory; see `cmake/module.cmake.template`
|
||||
for the shape and `cmake/Module.cmake` for the full `void_add_module`
|
||||
contract (`INTERNAL_DEPS`, `EXTERNAL_DEPS`, `OPTIONAL_DEPS`,
|
||||
`DEPS_WIN32`/`DEPS_UNIX`, `OPTIONS_WIN32`/`OPTIONS_UNIX`).
|
||||
|
||||
## Using as a dependency
|
||||
|
||||
```cmake
|
||||
find_package(Void REQUIRED)
|
||||
target_link_libraries(myapp PRIVATE Void::Logging Void::Stacktrace)
|
||||
```
|
||||
|
||||
`find_package(Void)` exposes every installed module under the `Void::`
|
||||
namespace and auto-loads the test scanner so downstream projects can use
|
||||
`void_add_tests()` for free.
|
||||
|
||||
## Writing tests
|
||||
|
||||
Tests are free functions or methods on a `Void::Testing::Fixture` subclass
|
||||
returning `Void::Testing::Test` (or `Void::Testing::DisabledTest`).
|
||||
Registration is automatic — the CMake test scanner parses each `.cpp` at
|
||||
configure time and generates the registration shim. See `CLAUDE.md` for the
|
||||
comment-metadata syntax (`// @tag`, `// @skip`).
|
||||
+47
-3
@@ -20,7 +20,7 @@ function(void_add_module MODULE_NAME)
|
||||
set(LIB_TYPE "INTERFACE")
|
||||
set(SCOPE "INTERFACE")
|
||||
add_library(${TGT} INTERFACE)
|
||||
target_compile_features(${TGT} INTERFACE cxx_std_23)
|
||||
target_compile_features(${TGT} INTERFACE cxx_std_26)
|
||||
else()
|
||||
set(LIB_TYPE "SHARED")
|
||||
set(SCOPE "PUBLIC")
|
||||
@@ -30,7 +30,7 @@ function(void_add_module MODULE_NAME)
|
||||
add_library(${TGT} SHARED)
|
||||
endif()
|
||||
target_sources(${TGT} PRIVATE ${SRC})
|
||||
target_compile_features(${TGT} PUBLIC cxx_std_23)
|
||||
target_compile_features(${TGT} PUBLIC cxx_std_26)
|
||||
endif()
|
||||
add_library(${ALIAS} ALIAS ${TGT})
|
||||
|
||||
@@ -73,14 +73,58 @@ function(void_add_module MODULE_NAME)
|
||||
foreach(_opt IN LISTS ARG_OPTIONS_UNIX)
|
||||
target_compile_options(${TGT} PRIVATE "$<$<NOT:$<PLATFORM_ID:Windows>>:${_opt}>")
|
||||
endforeach()
|
||||
|
||||
if(VOID_WARNINGS_AS_ERRORS)
|
||||
target_compile_options(${TGT} PRIVATE
|
||||
"$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-Wall;-Wextra;-Wpedantic;-Werror;-Wno-missing-field-initializers>"
|
||||
"$<$<CXX_COMPILER_ID:Clang,AppleClang>:-Wno-missing-designated-field-initializers>"
|
||||
"$<$<CXX_COMPILER_ID:MSVC>:/W4;/WX>"
|
||||
)
|
||||
endif()
|
||||
|
||||
if(VOID_ENABLE_ASAN)
|
||||
target_compile_options(${TGT} PUBLIC
|
||||
"$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-fsanitize=address;-fno-omit-frame-pointer>"
|
||||
)
|
||||
target_link_options(${TGT} PUBLIC
|
||||
"$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-fsanitize=address>"
|
||||
)
|
||||
endif()
|
||||
|
||||
if(VOID_ENABLE_UBSAN)
|
||||
target_compile_options(${TGT} PUBLIC
|
||||
"$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-fsanitize=undefined>"
|
||||
)
|
||||
target_link_options(${TGT} PUBLIC
|
||||
"$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-fsanitize=undefined>"
|
||||
)
|
||||
endif()
|
||||
|
||||
if(VOID_ENABLE_COVERAGE)
|
||||
target_compile_options(${TGT} PUBLIC
|
||||
"$<$<CXX_COMPILER_ID:GNU>:--coverage;-fprofile-update=atomic>"
|
||||
"$<$<CXX_COMPILER_ID:Clang,AppleClang>:-fprofile-instr-generate;-fcoverage-mapping>"
|
||||
)
|
||||
target_link_options(${TGT} PUBLIC
|
||||
"$<$<CXX_COMPILER_ID:GNU>:--coverage>"
|
||||
"$<$<CXX_COMPILER_ID:Clang,AppleClang>:-fprofile-instr-generate>"
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set_target_properties(${TGT} PROPERTIES
|
||||
CXX_STANDARD 23
|
||||
CXX_STANDARD 26
|
||||
CXX_STANDARD_REQUIRED ON
|
||||
CXX_EXTENSIONS OFF
|
||||
EXPORT_NAME ${MODULE_NAME}
|
||||
)
|
||||
|
||||
# GCC 16+ exposes experimental C++26 reflection (P2996) via -freflection.
|
||||
# Apply it to every module unconditionally so any module is free to use
|
||||
# ^^T / std::meta::* without per-module wiring.
|
||||
if(SRC AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
|
||||
target_compile_options(${TGT} PUBLIC -freflection)
|
||||
endif()
|
||||
target_sources(${TGT} ${SCOPE} FILE_SET HEADERS BASE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/include" FILES ${HDR})
|
||||
target_include_directories(${TGT} ${SCOPE}
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Result/Error.hpp>
|
||||
#include <Void/Result/Result.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <ios>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::FileSystem
|
||||
{
|
||||
/// Read the entire contents of a file as a string.
|
||||
///
|
||||
/// Failure modes wrapped in `Result`:
|
||||
/// - File does not exist
|
||||
/// - File cannot be opened (permissions, etc.)
|
||||
/// - I/O error during read
|
||||
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
||||
read_file(const std::filesystem::path& path)
|
||||
{
|
||||
std::ifstream f{path, std::ios::binary};
|
||||
if (!f.is_open()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"FileSystem::read_file: cannot open '{}'", path.string()));
|
||||
}
|
||||
std::string content{std::istreambuf_iterator<char>(f),
|
||||
std::istreambuf_iterator<char>()};
|
||||
if (f.bad()) {
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::read_file: I/O error reading '{}'",
|
||||
path.string()));
|
||||
}
|
||||
return Void::Result::ok(std::move(content));
|
||||
}
|
||||
|
||||
/// Write `content` to `path`, overwriting any existing file.
|
||||
///
|
||||
/// This is NOT crash-safe — a process killed mid-write may leave a
|
||||
/// truncated file. Use `atomic_write` when you need durability.
|
||||
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
||||
write_file(const std::filesystem::path& path, std::string_view content)
|
||||
{
|
||||
std::ofstream f{path, std::ios::binary | std::ios::trunc};
|
||||
if (!f.is_open()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"FileSystem::write_file: cannot open '{}'", path.string()));
|
||||
}
|
||||
f.write(content.data(), static_cast<std::streamsize>(content.size()));
|
||||
f.flush();
|
||||
if (!f.good()) {
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::write_file: I/O error writing '{}'",
|
||||
path.string()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/// Crash-safe write: stage `content` in a sibling `.tmp` file, then
|
||||
/// atomically rename onto `path`. The rename is atomic on POSIX
|
||||
/// within the same filesystem; std::filesystem::rename uses the
|
||||
/// platform-appropriate primitive (`ReplaceFileW` on Windows).
|
||||
///
|
||||
/// Note: this does NOT fsync the staged file before rename. A
|
||||
/// process or kernel crash between write and rename may leave the
|
||||
/// `.tmp` file behind, but the original `path` is never corrupted.
|
||||
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
||||
atomic_write(const std::filesystem::path& path,
|
||||
std::string_view content)
|
||||
{
|
||||
auto staging = path;
|
||||
staging += ".tmp";
|
||||
if (auto r = write_file(staging, content); !r) {
|
||||
return r;
|
||||
}
|
||||
std::error_code ec;
|
||||
std::filesystem::rename(staging, path, ec);
|
||||
if (ec) {
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove(staging, ignore);
|
||||
return Void::Result::fail(std::format(
|
||||
"FileSystem::atomic_write: rename failed for '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/// Create `path` as a directory, including any missing parents.
|
||||
/// Succeeds (no-op) if `path` already exists as a directory.
|
||||
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
||||
ensure_directory(const std::filesystem::path& path)
|
||||
{
|
||||
std::error_code ec;
|
||||
if (std::filesystem::is_directory(path, ec)) {
|
||||
return {};
|
||||
}
|
||||
std::filesystem::create_directories(path, ec);
|
||||
if (ec) {
|
||||
return Void::Result::fail(std::format(
|
||||
"FileSystem::ensure_directory: cannot create '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/// Remove a file or directory (recursively for directories).
|
||||
/// Succeeds (no-op) if the path doesn't exist.
|
||||
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
||||
remove_path(const std::filesystem::path& path)
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::remove_all(path, ec);
|
||||
if (ec) {
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::remove_path: cannot remove '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace Void::FileSystem
|
||||
@@ -0,0 +1,122 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/FileSystem/Path.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::FileSystem
|
||||
{
|
||||
/// RAII scoped directory under `std::filesystem::temp_directory_path()`.
|
||||
///
|
||||
/// The directory is created with a unique name on construction and
|
||||
/// recursively removed on destruction. Useful in tests that need a
|
||||
/// scratch area without manual cleanup.
|
||||
///
|
||||
/// Construction throws `std::system_error` if the directory cannot
|
||||
/// be created. Use `TempDir::open(prefix)` for a non-throwing
|
||||
/// `Result`-returning factory.
|
||||
class TempDir
|
||||
{
|
||||
public:
|
||||
|
||||
explicit TempDir(std::string_view prefix = "void_test_")
|
||||
: m_path(make_unique_dir(prefix))
|
||||
{
|
||||
}
|
||||
|
||||
~TempDir() noexcept
|
||||
{
|
||||
if (!m_path.empty()) {
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove_all(m_path, ignore);
|
||||
}
|
||||
}
|
||||
|
||||
TempDir(const TempDir&) = delete;
|
||||
TempDir& operator=(const TempDir&) = delete;
|
||||
|
||||
TempDir(TempDir&& other) noexcept
|
||||
: m_path(std::exchange(other.m_path, {}))
|
||||
{
|
||||
}
|
||||
|
||||
TempDir& operator=(TempDir&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
if (!m_path.empty()) {
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove_all(m_path, ignore);
|
||||
}
|
||||
m_path = std::exchange(other.m_path, {});
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return m_path;
|
||||
}
|
||||
|
||||
/// Build a path inside the temp dir.
|
||||
/// Example: `auto log_path = tmp / "test.log";`
|
||||
[[nodiscard]] std::filesystem::path
|
||||
operator/(std::string_view relative) const
|
||||
{
|
||||
return m_path / relative;
|
||||
}
|
||||
|
||||
/// Non-throwing factory.
|
||||
[[nodiscard]] static Void::Result::Result<TempDir,
|
||||
Void::Result::Error>
|
||||
open(std::string_view prefix = "void_test_")
|
||||
{
|
||||
try {
|
||||
return Void::Result::ok(TempDir{prefix});
|
||||
} catch (const std::exception& e) {
|
||||
return Void::Result::fail(std::string{e.what()});
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::filesystem::path m_path;
|
||||
|
||||
static std::filesystem::path
|
||||
make_unique_dir(std::string_view prefix)
|
||||
{
|
||||
static std::atomic<std::uint64_t> counter{0};
|
||||
const auto base = std::filesystem::temp_directory_path();
|
||||
for (int attempt = 0; attempt < 16; ++attempt) {
|
||||
const auto seed =
|
||||
static_cast<std::uint64_t>(
|
||||
std::chrono::steady_clock::now()
|
||||
.time_since_epoch()
|
||||
.count()) ^
|
||||
(counter.fetch_add(1, std::memory_order_relaxed)
|
||||
<< 16) ^
|
||||
static_cast<std::uint64_t>(std::hash<std::thread::id>{}(
|
||||
std::this_thread::get_id()));
|
||||
auto candidate =
|
||||
base / std::format("{}{:016x}", prefix, seed);
|
||||
std::error_code ec;
|
||||
if (std::filesystem::create_directory(candidate, ec)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
throw std::system_error(
|
||||
std::make_error_code(std::errc::file_exists),
|
||||
"TempDir: failed to create unique directory after 16 "
|
||||
"attempts");
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::FileSystem
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Logging/Logger.hpp>
|
||||
|
||||
#include <iosfwd>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Logger sink that writes formatted entries to a std::ostream.
|
||||
///
|
||||
/// Defaults to Mode::Immediate (each entry written as soon as it is
|
||||
/// submitted) and to std::cerr if no stream is supplied.
|
||||
///
|
||||
/// When the Stacktrace module is present (VOID_HAS_STACKTRACE), each
|
||||
/// level prefix is colorized via Void::Stacktrace::Color helpers and
|
||||
/// honors Void::Stacktrace::Color::g_color_enabled. Without Stacktrace
|
||||
/// the output is uncolored.
|
||||
class ConsoleLogger final : public Logger
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ConsoleLogger(std::ostream& out,
|
||||
Mode mode = Mode::Immediate,
|
||||
std::size_t capacity = 0);
|
||||
|
||||
/// Convenience constructor — writes to std::cerr in Immediate mode.
|
||||
ConsoleLogger();
|
||||
|
||||
~ConsoleLogger() noexcept override;
|
||||
|
||||
ConsoleLogger(const ConsoleLogger&) = delete;
|
||||
ConsoleLogger& operator=(const ConsoleLogger&) = delete;
|
||||
ConsoleLogger(ConsoleLogger&&) = delete;
|
||||
ConsoleLogger& operator=(ConsoleLogger&&) = delete;
|
||||
|
||||
protected:
|
||||
|
||||
void write(const Entry& entry) override;
|
||||
|
||||
private:
|
||||
|
||||
std::ostream& m_out;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Logging/Logger.hpp>
|
||||
#include <Void/Result/Error.hpp>
|
||||
#include <Void/Result/Result.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Logger sink that appends formatted entries to a file on disk.
|
||||
///
|
||||
/// Defaults to Mode::Buffered with capacity 64 — entries are batched
|
||||
/// via on_flush() and written using std::ofstream::flush() at the end
|
||||
/// of every batch. The destructor flushes any remaining entries.
|
||||
///
|
||||
/// Two construction paths:
|
||||
/// - `FileLogger::open(path)` returns
|
||||
/// `Result<unique_ptr<FileLogger>, Error>` and never throws —
|
||||
/// prefer this in code that already uses Void::Result for error
|
||||
/// plumbing.
|
||||
/// - The throwing constructor stays for callers that prefer
|
||||
/// exceptions; it throws std::runtime_error if the path cannot
|
||||
/// be opened for append.
|
||||
class FileLogger final : public Logger
|
||||
{
|
||||
public:
|
||||
|
||||
explicit FileLogger(const std::filesystem::path& path,
|
||||
Mode mode = Mode::Buffered,
|
||||
std::size_t capacity = 64);
|
||||
|
||||
~FileLogger() noexcept override;
|
||||
|
||||
FileLogger(const FileLogger&) = delete;
|
||||
FileLogger& operator=(const FileLogger&) = delete;
|
||||
FileLogger(FileLogger&&) = delete;
|
||||
FileLogger& operator=(FileLogger&&) = delete;
|
||||
|
||||
/// Non-throwing factory. On failure returns
|
||||
/// `Failure<Error>{Error{"FileLogger: cannot open '<path>'"}}`.
|
||||
[[nodiscard]] static Void::Result::
|
||||
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
open(const std::filesystem::path& path,
|
||||
Mode mode = Mode::Buffered,
|
||||
std::size_t capacity = 64);
|
||||
|
||||
protected:
|
||||
|
||||
void write(const Entry& entry) override;
|
||||
void on_flush(std::span<const Entry> entries) override;
|
||||
|
||||
private:
|
||||
|
||||
std::ofstream m_file;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#if __has_include(<meta>) && defined(__cpp_consteval)
|
||||
#include <meta>
|
||||
#define VOID_RESULT_HAS_REFLECTION 1
|
||||
#endif
|
||||
|
||||
namespace Void::Result::Detail
|
||||
{
|
||||
/// Render a value for diagnostic / log output.
|
||||
///
|
||||
/// Resolution order:
|
||||
/// 1. If a `std::formatter<T>` exists, use `std::format("{}", v)`.
|
||||
/// 2. Otherwise, if `T` exposes a `.format()` method returning
|
||||
/// something convertible to `std::string`, call it.
|
||||
/// 3. Otherwise, if C++26 reflection is available, walk the
|
||||
/// non-static data members of `T` and render
|
||||
/// `Type{field1: value1, field2: value2}`.
|
||||
/// 4. Otherwise, return `"<unrepresentable>"`.
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value);
|
||||
|
||||
template <typename T>
|
||||
concept Formattable = std::formattable<T, char>;
|
||||
|
||||
template <typename T>
|
||||
concept HasFormatMethod = requires(const T& v) {
|
||||
{ v.format() } -> std::convertible_to<std::string>;
|
||||
};
|
||||
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
template <typename T> [[nodiscard]] std::string reflect_struct(const T& obj)
|
||||
{
|
||||
std::string out;
|
||||
out += std::meta::identifier_of(^^T);
|
||||
out += '{';
|
||||
static constexpr auto members =
|
||||
std::define_static_array(std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::unchecked()));
|
||||
bool first = true;
|
||||
template for (constexpr auto member : members)
|
||||
{
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += std::meta::identifier_of(member);
|
||||
out += ": ";
|
||||
out += repr(obj.[:member:]);
|
||||
first = false;
|
||||
}
|
||||
out += '}';
|
||||
return out;
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value)
|
||||
{
|
||||
if constexpr (Formattable<T>) {
|
||||
return std::format("{}", value);
|
||||
} else if constexpr (HasFormatMethod<T>) {
|
||||
return std::string{value.format()};
|
||||
}
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
else if constexpr (std::is_class_v<T> || std::is_union_v<T>) {
|
||||
return reflect_struct(value);
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
return "<unrepresentable>";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Void::Result::Detail
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Result
|
||||
{
|
||||
/// Default error type for Void::Result::Result<T, E>.
|
||||
///
|
||||
/// An Error carries a free-form `message` and an optional chained
|
||||
/// `cause`. New context layers can be added with `with_context()`,
|
||||
/// which returns a new Error whose `cause` is the previous error —
|
||||
/// useful for "loading config: parsing line 42: invalid number".
|
||||
///
|
||||
/// Errors are cheap to copy (the cause chain is shared via
|
||||
/// shared_ptr).
|
||||
class Error
|
||||
{
|
||||
public:
|
||||
|
||||
Error() = default;
|
||||
|
||||
explicit Error(std::string message) noexcept
|
||||
: m_message(std::move(message))
|
||||
{
|
||||
}
|
||||
|
||||
Error(std::string message, Error cause)
|
||||
: m_message(std::move(message)),
|
||||
m_cause(std::make_shared<Error>(std::move(cause)))
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::string& message() const noexcept
|
||||
{
|
||||
return m_message;
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::shared_ptr<const Error>&
|
||||
cause() const noexcept
|
||||
{
|
||||
return m_cause;
|
||||
}
|
||||
|
||||
/// Returns a new Error whose message is `ctx` and whose cause
|
||||
/// is *this.
|
||||
[[nodiscard]] Error with_context(std::string ctx) const&
|
||||
{
|
||||
return Error{std::move(ctx), *this};
|
||||
}
|
||||
|
||||
[[nodiscard]] Error with_context(std::string ctx) &&
|
||||
{
|
||||
return Error{std::move(ctx), std::move(*this)};
|
||||
}
|
||||
|
||||
/// Render the full cause chain as
|
||||
/// "outer\n caused by: middle\n caused by: inner"
|
||||
[[nodiscard]] std::string format() const
|
||||
{
|
||||
std::string out = m_message;
|
||||
const Error* cur = m_cause.get();
|
||||
while (cur != nullptr) {
|
||||
out += "\n caused by: ";
|
||||
out += cur->m_message;
|
||||
cur = cur->m_cause.get();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::string m_message;
|
||||
std::shared_ptr<const Error> m_cause;
|
||||
};
|
||||
|
||||
} // namespace Void::Result
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Result/Error.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <expected>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Result
|
||||
{
|
||||
/// `Result<T, E>` is a thin alias over `std::expected<T, E>`.
|
||||
///
|
||||
/// std::expected already provides every monadic operation we need
|
||||
/// (`and_then`, `or_else`, `transform` (= map), `transform_error`
|
||||
/// (= map_err), `value_or`). The wrappers in this module add
|
||||
/// context-chain support (see `with_context` below) and a default
|
||||
/// error type (`Void::Result::Error`).
|
||||
template <typename T, typename E = Error>
|
||||
using Result = std::expected<T, E>;
|
||||
|
||||
/// Tag wrapper for failure construction. Shorthand for
|
||||
/// `std::unexpected<E>`.
|
||||
template <typename E = Error> using Failure = std::unexpected<E>;
|
||||
|
||||
/// Convenience factory for a successful Result.
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr Result<std::remove_cvref_t<T>> ok(T&& value)
|
||||
{
|
||||
return Result<std::remove_cvref_t<T>>{std::forward<T>(value)};
|
||||
}
|
||||
|
||||
/// Convenience factory for a failed Result with the default Error type.
|
||||
[[nodiscard]] inline Failure<Error> fail(std::string message)
|
||||
{
|
||||
return Failure<Error>{Error{std::move(message)}};
|
||||
}
|
||||
|
||||
/// Convenience factory for a failed Result with an arbitrary E.
|
||||
/// Constrained so string-like types resolve to the `std::string`
|
||||
/// overload above (otherwise a literal `"..."` deduces E to a char
|
||||
/// array).
|
||||
template <typename E>
|
||||
requires(!std::convertible_to<std::remove_cvref_t<E>, std::string>)
|
||||
[[nodiscard]] constexpr Failure<std::remove_cvref_t<E>> fail(E&& error)
|
||||
{
|
||||
return Failure<std::remove_cvref_t<E>>{std::forward<E>(error)};
|
||||
}
|
||||
|
||||
/// Add a context layer to a failed Result. On success, the result is
|
||||
/// returned unchanged. Requires that `E` exposes a
|
||||
/// `with_context(std::string) const&` method (the bundled `Error`
|
||||
/// type does).
|
||||
template <typename T, typename E>
|
||||
[[nodiscard]] Result<T, E> with_context(Result<T, E> r, std::string ctx)
|
||||
{
|
||||
if (r) {
|
||||
return r;
|
||||
}
|
||||
return Failure<E>{std::move(r).error().with_context(std::move(ctx))};
|
||||
}
|
||||
|
||||
} // namespace Void::Result
|
||||
@@ -1,18 +1,31 @@
|
||||
#pragma once
|
||||
#include <Void/Result/Error.hpp>
|
||||
#include <Void/Result/Result.hpp>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ostream>
|
||||
|
||||
namespace Void::Stacktrace {
|
||||
struct StackFrame {
|
||||
std::string function_name;
|
||||
std::string source_file;
|
||||
int source_line{0};
|
||||
std::string source_snippet;
|
||||
};
|
||||
namespace Void::Stacktrace
|
||||
{
|
||||
struct StackFrame {
|
||||
std::string function_name;
|
||||
std::string source_file;
|
||||
int source_line{0};
|
||||
std::string source_snippet;
|
||||
};
|
||||
|
||||
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames = 0, unsigned max_frames = 32);
|
||||
std::string read_source_snippet(const std::string& file, int line, int context_lines = 3);
|
||||
std::string format_stacktrace(const std::vector<StackFrame>& frames);
|
||||
void print_stacktrace(std::ostream& os, const std::vector<StackFrame>& frames);
|
||||
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames = 0,
|
||||
unsigned max_frames = 32);
|
||||
|
||||
/// Read a snippet of source around `line`. On failure (file missing,
|
||||
/// not readable, etc.) returns Failure<Error> instead of an empty
|
||||
/// string — callers that want the silent fallback can still do
|
||||
/// `read_source_snippet(...).value_or("")`.
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
read_source_snippet(const std::string& file, int line,
|
||||
int context_lines = 3);
|
||||
|
||||
std::string format_stacktrace(const std::vector<StackFrame>& frames);
|
||||
void print_stacktrace(std::ostream& os,
|
||||
const std::vector<StackFrame>& frames);
|
||||
} // namespace Void::Stacktrace
|
||||
+182
-57
@@ -1,82 +1,207 @@
|
||||
#pragma once
|
||||
#include <Void/Result/Detail/Repr.hpp>
|
||||
#include <Void/Testing/Config.hpp>
|
||||
#include <Void/Testing/Detail/Registry.hpp>
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
struct TestContext {
|
||||
TestResult* current_result{nullptr};
|
||||
bool should_abort{false};
|
||||
void* fixture{nullptr};
|
||||
static TestContext& current() { thread_local TestContext ctx; return ctx; }
|
||||
};
|
||||
namespace Void::Testing::Detail
|
||||
{
|
||||
struct TestContext {
|
||||
TestResult* current_result{nullptr};
|
||||
bool should_abort{false};
|
||||
void* fixture{nullptr};
|
||||
static TestContext& current()
|
||||
{
|
||||
thread_local TestContext ctx;
|
||||
return ctx;
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
std::string repr(const T& val) {
|
||||
if constexpr (std::is_same_v<std::decay_t<T>, bool>) return val ? "true" : "false";
|
||||
else if constexpr (std::is_same_v<std::decay_t<T>, std::string> || std::is_same_v<std::decay_t<T>, std::string_view>) return std::format("\"{}\"", val);
|
||||
else if constexpr (std::is_null_pointer_v<std::decay_t<T>>) return "nullptr";
|
||||
else if constexpr (requires { std::format("{}", val); }) return std::format("{}", val);
|
||||
else return "<unrepresentable value>";
|
||||
}
|
||||
/// Render a value for assertion-failure messages. Special-cases `bool`,
|
||||
/// strings, and `nullptr` for unambiguous output, then falls through to
|
||||
/// Void::Result::Detail::repr — which uses std::format when available and
|
||||
/// C++26 reflection otherwise to walk struct fields.
|
||||
template <typename T> std::string repr(const T& val)
|
||||
{
|
||||
if constexpr (std::is_same_v<std::decay_t<T>, bool>) {
|
||||
return val ? "true" : "false";
|
||||
} else if constexpr (std::is_same_v<std::decay_t<T>, std::string> ||
|
||||
std::is_same_v<std::decay_t<T>,
|
||||
std::string_view>) {
|
||||
return std::format("\"{}\"", val);
|
||||
} else if constexpr (std::is_null_pointer_v<std::decay_t<T>>) {
|
||||
return "nullptr";
|
||||
} else {
|
||||
return Void::Result::Detail::repr(val);
|
||||
}
|
||||
}
|
||||
|
||||
void handle_assertion(AssertionResult result);
|
||||
void handle_assertion(AssertionResult result);
|
||||
|
||||
struct RequireFailure : std::runtime_error {
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
struct RequireFailure : std::runtime_error {
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
} // namespace Void::Testing::Detail
|
||||
|
||||
namespace Void::Testing {
|
||||
namespace Void::Testing
|
||||
{
|
||||
|
||||
template<typename T> requires std::convertible_to<T, bool>
|
||||
void expect(T&& condition, std::source_location loc = std::source_location::current()) {
|
||||
AssertionResult result; result.passed = static_cast<bool>(condition); result.kind = AssertKind::Expect; result.location = loc; result.expression = "expect(...)"; if (!result.passed) result.message = "expected condition to be true"; Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
template <typename T>
|
||||
requires std::convertible_to<T, bool>
|
||||
void expect(T&& condition,
|
||||
std::source_location loc = std::source_location::current())
|
||||
{
|
||||
AssertionResult result;
|
||||
result.passed = static_cast<bool>(condition);
|
||||
result.kind = AssertKind::Expect;
|
||||
result.location = loc;
|
||||
result.expression = "expect(...)";
|
||||
if (!result.passed) {
|
||||
result.message = "expected condition to be true";
|
||||
}
|
||||
Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
|
||||
template<typename T> requires std::convertible_to<T, bool>
|
||||
void require(T&& condition, std::source_location loc = std::source_location::current()) {
|
||||
AssertionResult result; result.passed = static_cast<bool>(condition); result.kind = AssertKind::Require; result.location = loc; result.expression = "require(...)"; if (!result.passed) result.message = "required condition to be true"; Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
template <typename T>
|
||||
requires std::convertible_to<T, bool>
|
||||
void require(T&& condition,
|
||||
std::source_location loc = std::source_location::current())
|
||||
{
|
||||
AssertionResult result;
|
||||
result.passed = static_cast<bool>(condition);
|
||||
result.kind = AssertKind::Require;
|
||||
result.location = loc;
|
||||
result.expression = "require(...)";
|
||||
if (!result.passed) {
|
||||
result.message = "required condition to be true";
|
||||
}
|
||||
Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
|
||||
template<typename T, typename U> requires std::equality_comparable_with<T, U>
|
||||
void expect_eq(const T& lhs, const U& rhs, std::source_location loc = std::source_location::current()) {
|
||||
AssertionResult result; result.passed = (lhs == rhs); result.kind = AssertKind::Expect; result.location = loc; result.expected_repr = Detail::repr(rhs); result.actual_repr = Detail::repr(lhs); if (!result.passed) result.message = std::format("expected {}, got {}", Detail::repr(rhs), Detail::repr(lhs)); Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
template <typename T, typename U>
|
||||
requires std::equality_comparable_with<T, U>
|
||||
void expect_eq(const T& lhs, const U& rhs,
|
||||
std::source_location loc = std::source_location::current())
|
||||
{
|
||||
AssertionResult result;
|
||||
result.passed = (lhs == rhs);
|
||||
result.kind = AssertKind::Expect;
|
||||
result.location = loc;
|
||||
result.expected_repr = Detail::repr(rhs);
|
||||
result.actual_repr = Detail::repr(lhs);
|
||||
if (!result.passed) {
|
||||
result.message = std::format("expected {}, got {}",
|
||||
Detail::repr(rhs), Detail::repr(lhs));
|
||||
}
|
||||
Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
|
||||
template<typename T, typename U> requires std::equality_comparable_with<T, U>
|
||||
void require_eq(const T& lhs, const U& rhs, std::source_location loc = std::source_location::current()) {
|
||||
AssertionResult result; result.passed = (lhs == rhs); result.kind = AssertKind::Require; result.location = loc; result.expected_repr = Detail::repr(rhs); result.actual_repr = Detail::repr(lhs); if (!result.passed) result.message = std::format("required {}, got {}", Detail::repr(rhs), Detail::repr(lhs)); Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
template <typename T, typename U>
|
||||
requires std::equality_comparable_with<T, U>
|
||||
void require_eq(const T& lhs, const U& rhs,
|
||||
std::source_location loc = std::source_location::current())
|
||||
{
|
||||
AssertionResult result;
|
||||
result.passed = (lhs == rhs);
|
||||
result.kind = AssertKind::Require;
|
||||
result.location = loc;
|
||||
result.expected_repr = Detail::repr(rhs);
|
||||
result.actual_repr = Detail::repr(lhs);
|
||||
if (!result.passed) {
|
||||
result.message = std::format("required {}, got {}",
|
||||
Detail::repr(rhs), Detail::repr(lhs));
|
||||
}
|
||||
Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
|
||||
template<typename T, typename U> requires std::equality_comparable_with<T, U>
|
||||
void expect_ne(const T& lhs, const U& rhs, std::source_location loc = std::source_location::current()) {
|
||||
AssertionResult result; result.passed = (lhs != rhs); result.kind = AssertKind::Expect; result.location = loc; if (!result.passed) result.message = "expected values to differ"; Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
template <typename T, typename U>
|
||||
requires std::equality_comparable_with<T, U>
|
||||
void expect_ne(const T& lhs, const U& rhs,
|
||||
std::source_location loc = std::source_location::current())
|
||||
{
|
||||
AssertionResult result;
|
||||
result.passed = (lhs != rhs);
|
||||
result.kind = AssertKind::Expect;
|
||||
result.location = loc;
|
||||
if (!result.passed) {
|
||||
result.message = "expected values to differ";
|
||||
}
|
||||
Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
|
||||
template<typename Exception, typename Fn> requires std::invocable<Fn>
|
||||
void expect_throw(Fn&& fn, std::source_location loc = std::source_location::current()) {
|
||||
bool threw = false; try { std::forward<Fn>(fn)(); } catch (const Exception&) { threw = true; } catch (...) {} AssertionResult result; result.passed = threw; result.kind = AssertKind::Expect; result.location = loc; if (!threw) result.message = "expected exception was not thrown"; Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
template <typename Exception, typename Fn>
|
||||
requires std::invocable<Fn>
|
||||
void
|
||||
expect_throw(Fn&& fn,
|
||||
std::source_location loc = std::source_location::current())
|
||||
{
|
||||
bool threw = false;
|
||||
try {
|
||||
std::forward<Fn>(fn)();
|
||||
} catch (const Exception&) {
|
||||
threw = true;
|
||||
} catch (...) {
|
||||
}
|
||||
AssertionResult result;
|
||||
result.passed = threw;
|
||||
result.kind = AssertKind::Expect;
|
||||
result.location = loc;
|
||||
if (!threw) {
|
||||
result.message = "expected exception was not thrown";
|
||||
}
|
||||
Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
|
||||
template<typename Fn> requires std::invocable<Fn>
|
||||
void expect_nothrow(Fn&& fn, std::source_location loc = std::source_location::current()) {
|
||||
bool threw = false; try { std::forward<Fn>(fn)(); } catch (...) { threw = true; } AssertionResult result; result.passed = !threw; result.kind = AssertKind::Expect; result.location = loc; if (threw) result.message = "expected no exception"; Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
template <typename Fn>
|
||||
requires std::invocable<Fn>
|
||||
void expect_nothrow(
|
||||
Fn&& fn, std::source_location loc = std::source_location::current())
|
||||
{
|
||||
bool threw = false;
|
||||
try {
|
||||
std::forward<Fn>(fn)();
|
||||
} catch (...) {
|
||||
threw = true;
|
||||
}
|
||||
AssertionResult result;
|
||||
result.passed = !threw;
|
||||
result.kind = AssertKind::Expect;
|
||||
result.location = loc;
|
||||
if (threw) {
|
||||
result.message = "expected no exception";
|
||||
}
|
||||
Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
|
||||
inline void fail(std::string_view message = "", std::source_location loc = std::source_location::current()) {
|
||||
AssertionResult result; result.passed = false; result.kind = AssertKind::Expect; result.location = loc; result.message = message.empty() ? "explicit failure" : std::string{message}; Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
inline void fail(std::string_view message = "",
|
||||
std::source_location loc = std::source_location::current())
|
||||
{
|
||||
AssertionResult result;
|
||||
result.passed = false;
|
||||
result.kind = AssertKind::Expect;
|
||||
result.location = loc;
|
||||
result.message =
|
||||
message.empty() ? "explicit failure" : std::string{message};
|
||||
Detail::handle_assertion(std::move(result));
|
||||
}
|
||||
|
||||
inline void skip(std::string_view reason, std::source_location loc = std::source_location::current()) {
|
||||
auto& ctx = Detail::TestContext::current(); if (ctx.current_result) { ctx.current_result->state = TestState::Skipped; ctx.current_result->skip_reason = reason; } throw Detail::RequireFailure{std::string{reason}};
|
||||
}
|
||||
inline void skip(std::string_view reason,
|
||||
[[maybe_unused]] std::source_location loc =
|
||||
std::source_location::current())
|
||||
{
|
||||
auto& ctx = Detail::TestContext::current();
|
||||
if (ctx.current_result) {
|
||||
ctx.current_result->state = TestState::Skipped;
|
||||
ctx.current_result->skip_reason = reason;
|
||||
}
|
||||
throw Detail::RequireFailure{std::string{reason}};
|
||||
}
|
||||
|
||||
} // namespace Void::Testing
|
||||
@@ -78,6 +78,7 @@ namespace Void::Testing
|
||||
std::string reporter{"console"};
|
||||
std::string output_file;
|
||||
std::string tag_filter;
|
||||
std::string log_file;
|
||||
bool list_only{false};
|
||||
bool verbose{false};
|
||||
bool no_color{false};
|
||||
|
||||
@@ -1,33 +1,151 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/TestingMock/Matcher.hpp>
|
||||
#include <source_location>
|
||||
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::TestingMock::Detail {
|
||||
namespace Void::TestingMock::Detail
|
||||
{
|
||||
|
||||
template<typename> class Expectation;
|
||||
template <typename> class Expectation;
|
||||
|
||||
template <typename R, typename... Args> class Expectation<R(Args...)>
|
||||
{
|
||||
public:
|
||||
|
||||
using MatcherTuple =
|
||||
std::tuple<MatcherHolder<std::decay_t<Args>>...>;
|
||||
/// Move-only function — supports unique_ptr-capturing lambdas
|
||||
/// and other move-only callables.
|
||||
using Action = std::move_only_function<R(Args...)>;
|
||||
|
||||
Expectation(MatcherTuple matchers, std::source_location loc)
|
||||
: m_matchers(std::move(matchers)), m_location(loc)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename U = R>
|
||||
requires(!std::is_void_v<U> && std::same_as<U, R>)
|
||||
Expectation& returns(U value)
|
||||
{
|
||||
m_action = [val = std::move(value)](Args...) mutable -> R {
|
||||
return val;
|
||||
};
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
requires std::invocable<F&, Args...>
|
||||
Expectation& invokes(F action)
|
||||
{
|
||||
m_action = std::move(action);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Expectation& times(int n)
|
||||
{
|
||||
m_min_calls = n;
|
||||
m_max_calls = n;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Expectation& once() { return times(1); }
|
||||
|
||||
bool matches(Args... args) const
|
||||
{
|
||||
return match_impl(args..., std::index_sequence_for<Args...>{});
|
||||
}
|
||||
|
||||
R execute(Args... args)
|
||||
{
|
||||
if (!m_action) {
|
||||
if constexpr (std::is_same_v<R, void>) {
|
||||
return;
|
||||
} else {
|
||||
return R{};
|
||||
}
|
||||
}
|
||||
return m_action(args...);
|
||||
}
|
||||
|
||||
void record_call() { ++m_call_count; }
|
||||
|
||||
bool is_saturated() const { return m_call_count >= m_max_calls; }
|
||||
|
||||
void verify(std::string_view func_name)
|
||||
{
|
||||
if (m_call_count < m_min_calls) {
|
||||
Void::Testing::fail(std::format(
|
||||
"unsatisfied expectation on {}: {} — {}/{} calls",
|
||||
func_name, describe_matchers(), m_call_count,
|
||||
m_min_calls));
|
||||
}
|
||||
}
|
||||
|
||||
// -------- accessors used by failure-message construction --------
|
||||
|
||||
[[nodiscard]] int call_count() const noexcept
|
||||
{
|
||||
return m_call_count;
|
||||
}
|
||||
|
||||
[[nodiscard]] int max_calls() const noexcept { return m_max_calls; }
|
||||
|
||||
[[nodiscard]] std::source_location location() const noexcept
|
||||
{
|
||||
return m_location;
|
||||
}
|
||||
|
||||
/// Render the matcher tuple as e.g. "(Eq(7), _, Gt(3))".
|
||||
[[nodiscard]] std::string describe_matchers() const
|
||||
{
|
||||
return describe_impl(std::index_sequence_for<Args...>{});
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
MatcherTuple m_matchers;
|
||||
Action m_action;
|
||||
std::source_location m_location;
|
||||
int m_min_calls{1};
|
||||
int m_max_calls{1};
|
||||
int m_call_count{0};
|
||||
|
||||
template <std::size_t... Is>
|
||||
bool match_impl(Args... args, std::index_sequence<Is...>) const
|
||||
{
|
||||
return (std::get<Is>(m_matchers).matches(args) && ...);
|
||||
}
|
||||
|
||||
template <std::size_t... Is>
|
||||
std::string describe_impl(std::index_sequence<Is...>) const
|
||||
{
|
||||
if constexpr (sizeof...(Is) == 0) {
|
||||
return "()";
|
||||
} else {
|
||||
std::string out{"("};
|
||||
bool first = true;
|
||||
auto append = [&](const auto& m) {
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += m.describe();
|
||||
first = false;
|
||||
};
|
||||
(append(std::get<Is>(m_matchers)), ...);
|
||||
out += ")";
|
||||
return out;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template<typename R, typename... Args>
|
||||
class Expectation<R(Args...)> {
|
||||
public:
|
||||
using MatcherTuple = std::tuple<MatcherHolder<std::decay_t<Args>>...>;
|
||||
using Action = std::function<R(Args...)>;
|
||||
Expectation(MatcherTuple matchers, std::source_location loc) : matchers_(std::move(matchers)), location_(loc) {}
|
||||
Expectation& returns(R value) { action_ = [val = std::move(value)](Args...) mutable -> R { return val; }; return *this; }
|
||||
Expectation& invokes(Action action) { action_ = std::move(action); return *this; }
|
||||
Expectation& times(int n) { min_calls_ = n; max_calls_ = n; return *this; }
|
||||
Expectation& once() { return times(1); }
|
||||
bool matches(Args... args) const { return match_impl(args..., std::index_sequence_for<Args...>{}); }
|
||||
R execute(Args... args) const { if(!action_) return R{}; return action_(args...); }
|
||||
void record_call() { call_count_++; }
|
||||
bool is_saturated() const { return call_count_ >= max_calls_; }
|
||||
void verify(std::string_view func_name) const {
|
||||
if(call_count_ < min_calls_) { Void::Testing::fail(std::format("Unsatisfied expectation on {}", func_name)); }
|
||||
}
|
||||
private:
|
||||
MatcherTuple matchers_; Action action_; std::source_location location_; int min_calls_{1}; int max_calls_{1}; int call_count_{0};
|
||||
template<size_t... Is> bool match_impl(Args... args, std::index_sequence<Is...>) const { return (std::get<Is>(matchers_).matches(args) && ...); }
|
||||
};
|
||||
} // namespace Void::TestingMock::Detail
|
||||
@@ -1,25 +1,279 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <string>
|
||||
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::TestingMock {
|
||||
template<typename T> class Matcher { public: virtual ~Matcher() = default; virtual bool matches(const T& value) const = 0; virtual std::string describe() const = 0; };
|
||||
template<typename T> class EqMatcher : public Matcher<T> { T expected_; public: explicit EqMatcher(T expected) : expected_(std::move(expected)) {} bool matches(const T& v) const override { return v == expected_; } std::string describe() const override { return std::format("eq({})", Void::Testing::Detail::repr(expected_)); } };
|
||||
template<typename T> class AnyMatcher : public Matcher<T> { public: bool matches(const T&) const override { return true; } std::string describe() const override { return "_"; } };
|
||||
namespace Void::TestingMock
|
||||
{
|
||||
template <typename T> class Matcher
|
||||
{
|
||||
public:
|
||||
|
||||
template<typename T> auto Eq(T v) { return std::make_unique<EqMatcher<T>>(std::move(v)); }
|
||||
template<typename T> auto _() { return std::make_unique<AnyMatcher<T>>(); }
|
||||
virtual ~Matcher() = default;
|
||||
virtual bool matches(const T& value) const = 0;
|
||||
virtual std::string describe() const = 0;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Built-in matchers
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
template <typename T> class EqMatcher : public Matcher<T>
|
||||
{
|
||||
T m_expected;
|
||||
|
||||
public:
|
||||
|
||||
explicit EqMatcher(T expected) : m_expected(std::move(expected)) {}
|
||||
|
||||
bool matches(const T& v) const override { return v == m_expected; }
|
||||
|
||||
std::string describe() const override
|
||||
{
|
||||
return std::format("Eq({})",
|
||||
Void::Testing::Detail::repr(m_expected));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class AnyMatcher : public Matcher<T>
|
||||
{
|
||||
public:
|
||||
|
||||
bool matches(const T&) const override { return true; }
|
||||
std::string describe() const override { return "_"; }
|
||||
};
|
||||
|
||||
template <typename T> class LtMatcher : public Matcher<T>
|
||||
{
|
||||
T m_bound;
|
||||
|
||||
public:
|
||||
|
||||
explicit LtMatcher(T bound) : m_bound(std::move(bound)) {}
|
||||
bool matches(const T& v) const override { return v < m_bound; }
|
||||
std::string describe() const override
|
||||
{
|
||||
return std::format("Lt({})",
|
||||
Void::Testing::Detail::repr(m_bound));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class LeMatcher : public Matcher<T>
|
||||
{
|
||||
T m_bound;
|
||||
|
||||
public:
|
||||
|
||||
explicit LeMatcher(T bound) : m_bound(std::move(bound)) {}
|
||||
bool matches(const T& v) const override { return v <= m_bound; }
|
||||
std::string describe() const override
|
||||
{
|
||||
return std::format("Le({})",
|
||||
Void::Testing::Detail::repr(m_bound));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class GtMatcher : public Matcher<T>
|
||||
{
|
||||
T m_bound;
|
||||
|
||||
public:
|
||||
|
||||
explicit GtMatcher(T bound) : m_bound(std::move(bound)) {}
|
||||
bool matches(const T& v) const override { return v > m_bound; }
|
||||
std::string describe() const override
|
||||
{
|
||||
return std::format("Gt({})",
|
||||
Void::Testing::Detail::repr(m_bound));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class GeMatcher : public Matcher<T>
|
||||
{
|
||||
T m_bound;
|
||||
|
||||
public:
|
||||
|
||||
explicit GeMatcher(T bound) : m_bound(std::move(bound)) {}
|
||||
bool matches(const T& v) const override { return v >= m_bound; }
|
||||
std::string describe() const override
|
||||
{
|
||||
return std::format("Ge({})",
|
||||
Void::Testing::Detail::repr(m_bound));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class RangeMatcher : public Matcher<T>
|
||||
{
|
||||
T m_min;
|
||||
T m_max;
|
||||
|
||||
public:
|
||||
|
||||
RangeMatcher(T min, T max)
|
||||
: m_min(std::move(min)), m_max(std::move(max))
|
||||
{
|
||||
}
|
||||
|
||||
bool matches(const T& v) const override
|
||||
{
|
||||
return v >= m_min && v <= m_max;
|
||||
}
|
||||
|
||||
std::string describe() const override
|
||||
{
|
||||
return std::format("Range({}, {})",
|
||||
Void::Testing::Detail::repr(m_min),
|
||||
Void::Testing::Detail::repr(m_max));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, typename Fn> class PredMatcher : public Matcher<T>
|
||||
{
|
||||
Fn m_pred;
|
||||
|
||||
public:
|
||||
|
||||
explicit PredMatcher(Fn p) : m_pred(std::move(p)) {}
|
||||
|
||||
bool matches(const T& v) const override { return m_pred(v); }
|
||||
|
||||
std::string describe() const override { return "Pred(...)"; }
|
||||
};
|
||||
|
||||
template <typename T> class StartsWithMatcher : public Matcher<T>
|
||||
{
|
||||
std::string m_prefix;
|
||||
|
||||
public:
|
||||
|
||||
explicit StartsWithMatcher(std::string prefix)
|
||||
: m_prefix(std::move(prefix))
|
||||
{
|
||||
}
|
||||
|
||||
bool matches(const T& v) const override
|
||||
{
|
||||
const std::string_view sv{v};
|
||||
return sv.starts_with(m_prefix);
|
||||
}
|
||||
|
||||
std::string describe() const override
|
||||
{
|
||||
return std::format("StartsWith(\"{}\")", m_prefix);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class ContainsMatcher : public Matcher<T>
|
||||
{
|
||||
std::string m_needle;
|
||||
|
||||
public:
|
||||
|
||||
explicit ContainsMatcher(std::string needle)
|
||||
: m_needle(std::move(needle))
|
||||
{
|
||||
}
|
||||
|
||||
bool matches(const T& v) const override
|
||||
{
|
||||
const std::string_view sv{v};
|
||||
return sv.find(m_needle) != std::string_view::npos;
|
||||
}
|
||||
|
||||
std::string describe() const override
|
||||
{
|
||||
return std::format("Contains(\"{}\")", m_needle);
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Factory functions
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
template <typename T> auto Eq(T v)
|
||||
{
|
||||
return std::make_unique<EqMatcher<T>>(std::move(v));
|
||||
}
|
||||
|
||||
template <typename T> auto _() { return std::make_unique<AnyMatcher<T>>(); }
|
||||
|
||||
template <typename T> auto Lt(T v)
|
||||
{
|
||||
return std::make_unique<LtMatcher<T>>(std::move(v));
|
||||
}
|
||||
|
||||
template <typename T> auto Le(T v)
|
||||
{
|
||||
return std::make_unique<LeMatcher<T>>(std::move(v));
|
||||
}
|
||||
|
||||
template <typename T> auto Gt(T v)
|
||||
{
|
||||
return std::make_unique<GtMatcher<T>>(std::move(v));
|
||||
}
|
||||
|
||||
template <typename T> auto Ge(T v)
|
||||
{
|
||||
return std::make_unique<GeMatcher<T>>(std::move(v));
|
||||
}
|
||||
|
||||
template <typename T> auto Range(T min, T max)
|
||||
{
|
||||
return std::make_unique<RangeMatcher<T>>(std::move(min),
|
||||
std::move(max));
|
||||
}
|
||||
|
||||
template <typename T, typename Fn>
|
||||
requires std::predicate<Fn, const T&>
|
||||
auto Pred(Fn p)
|
||||
{
|
||||
return std::make_unique<PredMatcher<T, Fn>>(std::move(p));
|
||||
}
|
||||
|
||||
template <typename T = std::string> auto StartsWith(std::string prefix)
|
||||
{
|
||||
return std::make_unique<StartsWithMatcher<T>>(std::move(prefix));
|
||||
}
|
||||
|
||||
template <typename T = std::string> auto Contains(std::string needle)
|
||||
{
|
||||
return std::make_unique<ContainsMatcher<T>>(std::move(needle));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// MatcherHolder — owns a Matcher<T> or wraps an exact value as Eq
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
template <typename T> class MatcherHolder
|
||||
{
|
||||
std::unique_ptr<Matcher<T>> m_matcher;
|
||||
|
||||
public:
|
||||
|
||||
MatcherHolder() : m_matcher(std::make_unique<AnyMatcher<T>>()) {}
|
||||
|
||||
MatcherHolder(std::unique_ptr<Matcher<T>> m)
|
||||
: m_matcher(std::move(m))
|
||||
{
|
||||
}
|
||||
|
||||
MatcherHolder(T exact_value)
|
||||
: m_matcher(
|
||||
std::make_unique<EqMatcher<T>>(std::move(exact_value)))
|
||||
{
|
||||
}
|
||||
|
||||
bool matches(const T& v) const { return m_matcher->matches(v); }
|
||||
|
||||
std::string describe() const { return m_matcher->describe(); }
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
class MatcherHolder {
|
||||
std::unique_ptr<Matcher<T>> matcher_;
|
||||
public:
|
||||
MatcherHolder() : matcher_(std::make_unique<AnyMatcher<T>>()) {}
|
||||
MatcherHolder(std::unique_ptr<Matcher<T>> m) : matcher_(std::move(m)) {}
|
||||
MatcherHolder(T exact_value) : matcher_(std::make_unique<EqMatcher<T>>(std::move(exact_value))) {}
|
||||
bool matches(const T& v) const { return matcher_->matches(v); }
|
||||
std::string describe() const { return matcher_->describe(); }
|
||||
};
|
||||
} // namespace Void::TestingMock
|
||||
@@ -1,10 +1,80 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
namespace Void::TestingMock {
|
||||
template<typename Derived>
|
||||
class Mock {
|
||||
public:
|
||||
Mock() = default; virtual ~Mock() = default;
|
||||
void verify_all() {}
|
||||
};
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace Void::TestingMock
|
||||
{
|
||||
namespace Detail
|
||||
{
|
||||
/// Type-erased base for MockFunction<Sig>. The aggregate
|
||||
/// MockBase::verify_all() walks a vector of these and calls
|
||||
/// verify() on each.
|
||||
class MockFunctionBase
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~MockFunctionBase() = default;
|
||||
|
||||
/// Verify all expectations were satisfied. Implementations
|
||||
/// should be idempotent — verify_all() may be called
|
||||
/// before MockFunction's destructor runs the same logic.
|
||||
virtual void verify() = 0;
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
/// Non-template aggregate base for Mock<Derived>. Holds non-owning
|
||||
/// pointers to every MockFunction registered against this mock so
|
||||
/// `verify_all()` can drive them collectively.
|
||||
class MockBase
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~MockBase() = default;
|
||||
|
||||
void register_function(Detail::MockFunctionBase* fn)
|
||||
{
|
||||
m_functions.push_back(fn);
|
||||
}
|
||||
|
||||
/// Verify every registered MockFunction. Each MockFunction
|
||||
/// also verifies in its own destructor; calling verify_all()
|
||||
/// explicitly produces failures earlier (before stack unwind)
|
||||
/// with the mock's full context still on hand.
|
||||
void verify_all()
|
||||
{
|
||||
for (auto* fn : m_functions) {
|
||||
fn->verify();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::vector<Detail::MockFunctionBase*> m_functions;
|
||||
};
|
||||
|
||||
/// CRTP base for user-defined mocks. Inherit alongside the interface
|
||||
/// being mocked; declare MockFunction members initialized with
|
||||
/// `*this` so they auto-register for `verify_all()`.
|
||||
///
|
||||
/// @code
|
||||
/// class MockDb : public Mock<MockDb>, public Database {
|
||||
/// public:
|
||||
/// MockFunction<int(std::string_view)> get_user_id{*this,
|
||||
/// "get_user_id"}; int get_user_id(std::string_view n) override {
|
||||
/// return get_user_id(n); }
|
||||
/// };
|
||||
/// @endcode
|
||||
template <typename Derived> class Mock : public MockBase
|
||||
{
|
||||
public:
|
||||
|
||||
Mock() = default;
|
||||
~Mock() override = default;
|
||||
|
||||
Mock(const Mock&) = delete;
|
||||
Mock& operator=(const Mock&) = delete;
|
||||
Mock(Mock&&) = delete;
|
||||
Mock& operator=(Mock&&) = delete;
|
||||
};
|
||||
|
||||
} // namespace Void::TestingMock
|
||||
@@ -1,5 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/TestingMock/Expectation.hpp>
|
||||
#include <Void/TestingMock/Mock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <format>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
@@ -10,17 +16,35 @@ namespace Void::TestingMock
|
||||
|
||||
template <typename> class MockFunction;
|
||||
|
||||
template <typename R, typename... Args> class MockFunction<R(Args...)>
|
||||
template <typename R, typename... Args>
|
||||
class MockFunction<R(Args...)> : public Detail::MockFunctionBase
|
||||
{
|
||||
using Expectation = Detail::Expectation<R(Args...)>;
|
||||
|
||||
public:
|
||||
|
||||
/// Standalone constructor — no auto-registration. The
|
||||
/// destructor will still call verify() so isolated tests work
|
||||
/// without a Mock<Derived> wrapper.
|
||||
explicit MockFunction(std::string name = "unnamed_mock")
|
||||
: name_(std::move(name))
|
||||
: m_name(std::move(name))
|
||||
{
|
||||
}
|
||||
~MockFunction() { verify(); }
|
||||
|
||||
/// Owner-aware constructor — registers with `owner` so
|
||||
/// `owner.verify_all()` drives this mock's verify().
|
||||
MockFunction(MockBase& owner, std::string name = "unnamed_mock")
|
||||
: m_name(std::move(name))
|
||||
{
|
||||
owner.register_function(this);
|
||||
}
|
||||
|
||||
~MockFunction() override { verify(); }
|
||||
|
||||
MockFunction(const MockFunction&) = delete;
|
||||
MockFunction& operator=(const MockFunction&) = delete;
|
||||
MockFunction(MockFunction&&) = delete;
|
||||
MockFunction& operator=(MockFunction&&) = delete;
|
||||
|
||||
template <typename... MArgs>
|
||||
Expectation& expect(std::source_location loc, MArgs&&... matchers)
|
||||
@@ -30,7 +54,7 @@ namespace Void::TestingMock
|
||||
MatcherHolder<std::decay_t<Args>>(
|
||||
std::forward<MArgs>(matchers))...},
|
||||
loc);
|
||||
expectations_.push_back(exp);
|
||||
m_expectations.push_back(exp);
|
||||
return *exp;
|
||||
}
|
||||
|
||||
@@ -43,31 +67,68 @@ namespace Void::TestingMock
|
||||
|
||||
R operator()(Args... args)
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
for (auto& exp : expectations_) {
|
||||
std::lock_guard lock{m_mutex};
|
||||
for (auto& exp : m_expectations) {
|
||||
if (!exp->is_saturated() && exp->matches(args...)) {
|
||||
exp->record_call();
|
||||
return exp->execute(args...);
|
||||
}
|
||||
}
|
||||
Void::Testing::fail(
|
||||
std::format("Unexpected call to {}", name_));
|
||||
Void::Testing::fail(build_unmatched_message(args...));
|
||||
if constexpr (!std::is_same_v<R, void>) {
|
||||
return R{};
|
||||
}
|
||||
}
|
||||
void verify()
|
||||
|
||||
void verify() override
|
||||
{
|
||||
for (auto& exp : expectations_) {
|
||||
exp->verify(name_);
|
||||
for (auto& exp : m_expectations) {
|
||||
exp->verify(m_name);
|
||||
}
|
||||
expectations_.clear();
|
||||
m_expectations.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::string name_;
|
||||
std::vector<std::shared_ptr<Expectation>> expectations_;
|
||||
std::mutex mutex_;
|
||||
std::string m_name;
|
||||
std::vector<std::shared_ptr<Expectation>> m_expectations;
|
||||
std::mutex m_mutex;
|
||||
|
||||
/// Build a multi-line error message that names the actual
|
||||
/// arguments and lists every registered expectation with its
|
||||
/// matcher tuple and call counts.
|
||||
std::string build_unmatched_message(const Args&... args) const
|
||||
{
|
||||
std::string msg =
|
||||
std::format("no expectation matched call to {}({})", m_name,
|
||||
render_args(args...));
|
||||
if (m_expectations.empty()) {
|
||||
msg += "\n (no expectations registered)";
|
||||
return msg;
|
||||
}
|
||||
for (std::size_t i = 0; i < m_expectations.size(); ++i) {
|
||||
const auto& exp = *m_expectations[i];
|
||||
msg += std::format("\n expectation {}: {} — {}/{} calls",
|
||||
i + 1, exp.describe_matchers(),
|
||||
exp.call_count(), exp.max_calls());
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
static std::string render_args(const Args&... args)
|
||||
{
|
||||
std::string out;
|
||||
bool first = true;
|
||||
auto append = [&](const auto& a) {
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += Void::Testing::Detail::repr(a);
|
||||
first = false;
|
||||
};
|
||||
(append(args), ...);
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::TestingMock
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(FileSystem
|
||||
INTERNAL_DEPS Result
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
#include <Void/Logging/ConsoleLogger.hpp>
|
||||
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
#include <Void/Stacktrace/Color.hpp>
|
||||
#endif
|
||||
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
std::string_view color_for(Level level)
|
||||
{
|
||||
using namespace Void::Stacktrace::Color;
|
||||
switch (level) {
|
||||
case Level::Trace:
|
||||
return dim;
|
||||
case Level::Debug:
|
||||
return cyan;
|
||||
case Level::Info:
|
||||
return bold_cyan;
|
||||
case Level::Warning:
|
||||
return bold_yellow;
|
||||
case Level::Error:
|
||||
return bold_red;
|
||||
case Level::Fatal:
|
||||
return bold_magenta;
|
||||
default:
|
||||
return reset;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
std::string format_entry(const Entry& entry)
|
||||
{
|
||||
auto level_str = std::string{to_string(entry.level)};
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
using namespace Void::Stacktrace::Color;
|
||||
return std::format("[{}] {}\n",
|
||||
apply(color_for(entry.level), level_str),
|
||||
entry.message);
|
||||
#else
|
||||
return std::format("[{}] {}\n", level_str, entry.message);
|
||||
#endif
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ConsoleLogger::ConsoleLogger(std::ostream& out,
|
||||
Mode mode,
|
||||
std::size_t capacity)
|
||||
: Logger(mode, capacity), m_out(out)
|
||||
{
|
||||
}
|
||||
|
||||
ConsoleLogger::ConsoleLogger() : ConsoleLogger(std::cerr) {}
|
||||
|
||||
ConsoleLogger::~ConsoleLogger() noexcept { flush(); }
|
||||
|
||||
void ConsoleLogger::write(const Entry& entry)
|
||||
{
|
||||
m_out << format_entry(entry);
|
||||
m_out.flush();
|
||||
}
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,50 @@
|
||||
#include <Void/Logging/FileLogger.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
|
||||
FileLogger::FileLogger(const std::filesystem::path& path,
|
||||
Mode mode,
|
||||
std::size_t capacity)
|
||||
: Logger(mode, capacity), m_file(path, std::ios::app)
|
||||
{
|
||||
if (!m_file.is_open()) {
|
||||
throw std::runtime_error(
|
||||
std::format("FileLogger: cannot open '{}'", path.string()));
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
FileLogger::open(const std::filesystem::path& path,
|
||||
Mode mode,
|
||||
std::size_t capacity)
|
||||
{
|
||||
try {
|
||||
return Void::Result::ok(
|
||||
std::make_unique<FileLogger>(path, mode, capacity));
|
||||
} catch (const std::exception& e) {
|
||||
return Void::Result::fail(std::string{e.what()});
|
||||
}
|
||||
}
|
||||
|
||||
FileLogger::~FileLogger() noexcept { flush(); }
|
||||
|
||||
void FileLogger::write(const Entry& entry)
|
||||
{
|
||||
m_file << std::format(
|
||||
"[{}] {}\n", to_string(entry.level), entry.message);
|
||||
m_file.flush();
|
||||
}
|
||||
|
||||
void FileLogger::on_flush(std::span<const Entry> entries)
|
||||
{
|
||||
for (const auto& e : entries) {
|
||||
m_file << std::format("[{}] {}\n", to_string(e.level), e.message);
|
||||
}
|
||||
m_file.flush();
|
||||
}
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(Logging
|
||||
INTERNAL_DEPS Result
|
||||
OPTIONAL_DEPS Stacktrace
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
void_add_module(Result)
|
||||
@@ -1,64 +1,112 @@
|
||||
#include <Void/Stacktrace/Stacktrace.hpp>
|
||||
#include <Void/Stacktrace/Color.hpp>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <format>
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
#define BOOST_STACKTRACE_USE_BACKTRACE
|
||||
#include <boost/stacktrace.hpp>
|
||||
#include <boost/core/demangle.hpp>
|
||||
#include <boost/stacktrace.hpp>
|
||||
|
||||
namespace Void::Stacktrace {
|
||||
namespace Void::Stacktrace
|
||||
{
|
||||
|
||||
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames, unsigned max_frames) {
|
||||
std::vector<StackFrame> result;
|
||||
try {
|
||||
boost::stacktrace::stacktrace bt(skip_frames + 1, max_frames);
|
||||
for (auto it = bt.begin(); it != bt.end(); ++it) {
|
||||
StackFrame frame;
|
||||
std::string name = it->name();
|
||||
if (!name.empty()) frame.function_name = boost::core::demangle(name.c_str());
|
||||
frame.source_file = it->source_file(); frame.source_line = it->source_line();
|
||||
if (!frame.source_file.empty() && frame.source_line > 0) frame.source_snippet = read_source_snippet(frame.source_file, frame.source_line, 2);
|
||||
result.push_back(std::move(frame));
|
||||
}
|
||||
} catch (...) {}
|
||||
return result;
|
||||
}
|
||||
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames,
|
||||
unsigned max_frames)
|
||||
{
|
||||
std::vector<StackFrame> result;
|
||||
try {
|
||||
boost::stacktrace::stacktrace bt(skip_frames + 1, max_frames);
|
||||
for (auto it = bt.begin(); it != bt.end(); ++it) {
|
||||
StackFrame frame;
|
||||
std::string name = it->name();
|
||||
if (!name.empty()) {
|
||||
frame.function_name = boost::core::demangle(name.c_str());
|
||||
}
|
||||
frame.source_file = it->source_file();
|
||||
frame.source_line = it->source_line();
|
||||
if (!frame.source_file.empty() && frame.source_line > 0) {
|
||||
frame.source_snippet =
|
||||
read_source_snippet(frame.source_file,
|
||||
frame.source_line, 2)
|
||||
.value_or(std::string{});
|
||||
}
|
||||
result.push_back(std::move(frame));
|
||||
}
|
||||
} catch (...) {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string read_source_snippet(const std::string& file, int line, int context_lines) {
|
||||
std::ifstream ifs{file}; if (!ifs.is_open()) return {};
|
||||
std::ostringstream result; std::string current_line; int line_num = 1;
|
||||
int start = std::max(1, line - context_lines); int end = line + context_lines;
|
||||
while (std::getline(ifs, current_line)) {
|
||||
if (line_num >= start && line_num <= end) {
|
||||
std::string prefix = (line_num == line) ? " >>> " : " ";
|
||||
result << std::format("{:>4}{}{}\n", line_num, prefix, current_line);
|
||||
}
|
||||
if (line_num > end) break; ++line_num;
|
||||
}
|
||||
return result.str();
|
||||
}
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
read_source_snippet(const std::string& file, int line,
|
||||
int context_lines)
|
||||
{
|
||||
std::ifstream ifs{file};
|
||||
if (!ifs.is_open()) {
|
||||
return Void::Result::fail(
|
||||
std::format("read_source_snippet: cannot open '{}'", file));
|
||||
}
|
||||
std::ostringstream result;
|
||||
std::string current_line;
|
||||
int line_num = 1;
|
||||
int start = std::max(1, line - context_lines);
|
||||
int end = line + context_lines;
|
||||
while (std::getline(ifs, current_line)) {
|
||||
if (line_num >= start && line_num <= end) {
|
||||
std::string prefix = (line_num == line) ? " >>> " : " ";
|
||||
result << std::format("{:>4}{}{}\n", line_num, prefix,
|
||||
current_line);
|
||||
}
|
||||
if (line_num > end) {
|
||||
break;
|
||||
}
|
||||
++line_num;
|
||||
}
|
||||
return Void::Result::ok(result.str());
|
||||
}
|
||||
|
||||
std::string format_stacktrace(const std::vector<StackFrame>& frames) {
|
||||
if (frames.empty()) return " <no stacktrace available>\n";
|
||||
std::ostringstream oss;
|
||||
for (size_t i = 0; i < frames.size(); ++i) {
|
||||
const auto& frame = frames[i];
|
||||
oss << std::format(" #{:02} ", i);
|
||||
if (!frame.function_name.empty()) oss << (Color::g_color_enabled ? Color::apply(Color::bold_cyan, frame.function_name) : frame.function_name);
|
||||
else oss << "<unknown>";
|
||||
if (!frame.source_file.empty() && frame.source_line > 0) {
|
||||
std::filesystem::path p{frame.source_file};
|
||||
oss << "\n at " << (Color::g_color_enabled ? Color::apply(Color::dim, p.filename().string()) : p.filename().string()) << ":" << frame.source_line;
|
||||
}
|
||||
oss << "\n";
|
||||
if (!frame.source_snippet.empty() && i < 5) oss << " " << (Color::g_color_enabled ? Color::apply(Color::dim, frame.source_snippet) : frame.source_snippet);
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
std::string format_stacktrace(const std::vector<StackFrame>& frames)
|
||||
{
|
||||
if (frames.empty()) {
|
||||
return " <no stacktrace available>\n";
|
||||
}
|
||||
std::ostringstream oss;
|
||||
for (size_t i = 0; i < frames.size(); ++i) {
|
||||
const auto& frame = frames[i];
|
||||
oss << std::format(" #{:02} ", i);
|
||||
if (!frame.function_name.empty()) {
|
||||
oss << (Color::g_color_enabled
|
||||
? Color::apply(Color::bold_cyan,
|
||||
frame.function_name)
|
||||
: frame.function_name);
|
||||
} else {
|
||||
oss << "<unknown>";
|
||||
}
|
||||
if (!frame.source_file.empty() && frame.source_line > 0) {
|
||||
std::filesystem::path p{frame.source_file};
|
||||
oss << "\n at "
|
||||
<< (Color::g_color_enabled
|
||||
? Color::apply(Color::dim, p.filename().string())
|
||||
: p.filename().string())
|
||||
<< ":" << frame.source_line;
|
||||
}
|
||||
oss << "\n";
|
||||
if (!frame.source_snippet.empty() && i < 5) {
|
||||
oss << " "
|
||||
<< (Color::g_color_enabled
|
||||
? Color::apply(Color::dim, frame.source_snippet)
|
||||
: frame.source_snippet);
|
||||
}
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
void print_stacktrace(std::ostream& os, const std::vector<StackFrame>& frames) { os << format_stacktrace(frames); }
|
||||
void print_stacktrace(std::ostream& os,
|
||||
const std::vector<StackFrame>& frames)
|
||||
{
|
||||
os << format_stacktrace(frames);
|
||||
}
|
||||
} // namespace Void::Stacktrace
|
||||
@@ -1,4 +1,5 @@
|
||||
void_add_module(Stacktrace
|
||||
INTERNAL_DEPS Result
|
||||
EXTERNAL_DEPS Boost::stacktrace_backtrace
|
||||
DEPS_WIN32 dbghelp
|
||||
DEPS_UNIX dl
|
||||
|
||||
+67
-1
@@ -1,5 +1,7 @@
|
||||
#include <Void/Testing/Runner.hpp>
|
||||
#include "Void/Testing/Config.hpp"
|
||||
#include <Void/Logging/FileLogger.hpp>
|
||||
#include <Void/Logging/Level.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/ConsoleReporter.hpp>
|
||||
#include <Void/Stacktrace/Color.hpp>
|
||||
@@ -10,8 +12,10 @@
|
||||
#include <algorithm>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#include <regex>
|
||||
#include <unordered_map>
|
||||
@@ -26,7 +30,7 @@ namespace Void::Testing
|
||||
std::string arg = argv[i];
|
||||
if ((arg == "--filter" || arg == "--suite" || arg == "--reporter" ||
|
||||
arg == "--output" || arg == "--tag" || arg == "--seed" ||
|
||||
arg == "--repeat") &&
|
||||
arg == "--repeat" || arg == "--log-file") &&
|
||||
i + 1 < argc) {
|
||||
std::string val = argv[++i];
|
||||
if (arg == "--filter") {
|
||||
@@ -39,6 +43,8 @@ namespace Void::Testing
|
||||
config.output_file = val;
|
||||
} else if (arg == "--tag") {
|
||||
config.tag_filter = val;
|
||||
} else if (arg == "--log-file") {
|
||||
config.log_file = val;
|
||||
} else if (arg == "--seed") {
|
||||
config.shuffle = true;
|
||||
config.random_seed = static_cast<unsigned>(std::stoul(val));
|
||||
@@ -250,6 +256,10 @@ namespace Void::Testing
|
||||
<< "\n"
|
||||
<< " " << apply(green, "--output <file> ")
|
||||
<< apply(dim, "Write reporter output to a file") << "\n"
|
||||
<< " " << apply(green, "--log-file <file> ")
|
||||
<< apply(dim,
|
||||
"Mirror test events to <file> via Void::Logging")
|
||||
<< "\n"
|
||||
<< " " << apply(green, "--verbose ")
|
||||
<< apply(dim, "Enable verbose output") << "\n"
|
||||
<< " " << apply(green, "--no-color ")
|
||||
@@ -274,6 +284,17 @@ namespace Void::Testing
|
||||
auto tests = filter_tests(all_tests, config);
|
||||
auto reporter = create_reporter(config);
|
||||
|
||||
std::unique_ptr<Void::Logging::FileLogger> log_sink;
|
||||
if (!config.log_file.empty()) {
|
||||
try {
|
||||
log_sink = std::make_unique<Void::Logging::FileLogger>(
|
||||
config.log_file);
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "warning: --log-file failed: " << e.what()
|
||||
<< "\n";
|
||||
}
|
||||
}
|
||||
|
||||
if (config.list_only) {
|
||||
for (const auto& t : tests) {
|
||||
std::cout << t.suite << "." << t.name
|
||||
@@ -284,9 +305,17 @@ namespace Void::Testing
|
||||
|
||||
RunResult run_result;
|
||||
reporter->on_run_start(config, static_cast<int>(tests.size()));
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format("run start: {} test(s) discovered",
|
||||
tests.size()));
|
||||
}
|
||||
if (config.shuffle) {
|
||||
std::shuffle(tests.begin(), tests.end(),
|
||||
std::mt19937{config.random_seed});
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format("shuffle enabled (seed = {})",
|
||||
config.random_seed));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<SuiteResult> suite_results;
|
||||
@@ -309,10 +338,41 @@ namespace Void::Testing
|
||||
return t.suite ==
|
||||
suite.name;
|
||||
}));
|
||||
if (log_sink) {
|
||||
log_sink->info(
|
||||
std::format("suite start: {}", suite.name));
|
||||
}
|
||||
}
|
||||
reporter->on_test_start(test);
|
||||
auto result = execute_test(test);
|
||||
reporter->on_test_end(result);
|
||||
if (log_sink) {
|
||||
const auto qualified =
|
||||
std::format("{}.{}", result.suite, result.name);
|
||||
switch (result.state) {
|
||||
case TestState::Passed:
|
||||
log_sink->info(
|
||||
std::format("test pass: {}", qualified));
|
||||
break;
|
||||
case TestState::Failed:
|
||||
log_sink->error(std::format(
|
||||
"test fail: {} — {}", qualified,
|
||||
result.crash_info.empty() ? "assertion failed"
|
||||
: result.crash_info));
|
||||
break;
|
||||
case TestState::Skipped:
|
||||
log_sink->warning(std::format(
|
||||
"test skip: {} ({})", qualified,
|
||||
result.skip_reason.empty() ? "no reason"
|
||||
: result.skip_reason));
|
||||
break;
|
||||
case TestState::Crashed:
|
||||
log_sink->fatal(std::format(
|
||||
"test crash: {} — {}", qualified,
|
||||
result.crash_info));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (rep == config.repeat - 1) {
|
||||
suite.tests.push_back(std::move(result));
|
||||
}
|
||||
@@ -343,6 +403,12 @@ namespace Void::Testing
|
||||
}
|
||||
run_result.total_duration = end_time - start_time;
|
||||
reporter->on_run_end(run_result);
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format(
|
||||
"run end: {} total / {} passed / {} failed / {} skipped / {} crashed",
|
||||
run_result.total, run_result.passed, run_result.failed,
|
||||
run_result.skipped, run_result.crashed));
|
||||
}
|
||||
return run_result;
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
void_add_module(Testing INTERNAL_DEPS Stacktrace)
|
||||
void_add_module(Testing INTERNAL_DEPS Stacktrace Logging Result)
|
||||
@@ -1 +1 @@
|
||||
void_add_module(TestingMock INTERNAL_DEPS Testing)
|
||||
void_add_module(TestingMock INTERNAL_DEPS Testing Result)
|
||||
@@ -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()
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
@@ -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)));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
Reference in new issue
Block a user