1 parent
4fc129fb7e
commit
e7186f17f0
42 files changed
+1816
-413
No files matched your search
@@ -1 +1,2 @@
|
||||
build
|
||||
CLAUDE.md
|
||||
+7
-1
@@ -6,6 +6,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
include(CMakePackageConfigHelpers)
|
||||
|
||||
set(EXPORT_SET_NAME ${PROJECT_NAME}Targets)
|
||||
|
||||
include(cmake/Module.cmake)
|
||||
@@ -20,9 +21,12 @@ foreach(module_path ${children})
|
||||
endif()
|
||||
endif()
|
||||
endforeach()
|
||||
if(VOID_ENABLE_TESTING)
|
||||
|
||||
add_subdirectory(tests)
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
|
||||
endif()
|
||||
get_property(ALL_DISCOVERED_MODULES GLOBAL PROPERTY VOID_MODULES)
|
||||
get_property(ALL_EXTERNAL_DEPS GLOBAL PROPERTY VOID_EXT_DEPS)
|
||||
|
||||
@@ -52,5 +56,7 @@ install(EXPORT ${EXPORT_SET_NAME}
|
||||
install(FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTesting.cmake"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTestScanner.cmake"
|
||||
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
|
||||
)
|
||||
@@ -1,6 +1,10 @@
|
||||
include(FetchContent)
|
||||
|
||||
function(void_fetch_dependency DEP_NAME)
|
||||
if(DEP_NAME STREQUAL "Boost")
|
||||
find_package(Boost REQUIRED COMPONENTS stacktrace_backtrace)
|
||||
return()
|
||||
endif()
|
||||
# FIXME: Add if needed external
|
||||
# if(DEP_NAME STREQUAL "glaze")
|
||||
# if(NOT glaze_POPULATED)
|
||||
|
||||
+7
-2
@@ -22,9 +22,13 @@ function(void_add_module MODULE_NAME)
|
||||
else()
|
||||
set(LIB_TYPE "SHARED")
|
||||
set(SCOPE "PUBLIC")
|
||||
add_library(${TGT} SHARED)
|
||||
if (MODULE_NAME STREQUAL "Testing")
|
||||
add_library(${TGT} STATIC)
|
||||
else()
|
||||
add_library(${TGT} SHARED)
|
||||
endif()
|
||||
target_sources(${TGT} PRIVATE ${SRC})
|
||||
target_compile_features(${TGT} PRIVATE cxx_std_23)
|
||||
target_compile_features(${TGT} PUBLIC cxx_std_23)
|
||||
endif()
|
||||
add_library(${ALIAS} ALIAS ${TGT})
|
||||
|
||||
@@ -56,6 +60,7 @@ function(void_add_module MODULE_NAME)
|
||||
CXX_STANDARD 23
|
||||
CXX_STANDARD_REQUIRED ON
|
||||
CXX_EXTENSIONS OFF
|
||||
EXPORT_NAME ${MODULE_NAME}
|
||||
)
|
||||
target_sources(${TGT} ${SCOPE} FILE_SET HEADERS BASE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/include" FILES ${HDR})
|
||||
target_include_directories(${TGT} ${SCOPE}
|
||||
|
||||
@@ -4,11 +4,19 @@ include(CMakeFindDependencyMacro)
|
||||
|
||||
set(_void_external_deps "@VOID_EXTERNAL_DEPS_LIST@")
|
||||
foreach(dep IN LISTS _void_external_deps)
|
||||
if(NOT TARGET ${dep})
|
||||
if(dep STREQUAL "Boost")
|
||||
find_dependency(Boost REQUIRED COMPONENTS stacktrace_backtrace)
|
||||
elseif(NOT TARGET ${dep})
|
||||
find_dependency(${dep})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/@EXPORT_SET_NAME@.cmake")
|
||||
|
||||
# Auto-load the testing helper so consumers get void_add_tests + the
|
||||
# auto-scan sweep just by find_package(Void).
|
||||
if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/VoidTesting.cmake")
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/VoidTesting.cmake")
|
||||
endif()
|
||||
|
||||
check_required_components("@PROJECT_NAME@")
|
||||
@@ -0,0 +1,147 @@
|
||||
if(NOT INPUT_FILE OR NOT OUTPUT_FILE OR NOT SUITE_NAME)
|
||||
message(FATAL_ERROR "INPUT_FILE, OUTPUT_FILE, and SUITE_NAME must be provided.")
|
||||
endif()
|
||||
|
||||
file(STRINGS ${INPUT_FILE} lines)
|
||||
|
||||
set(registrations "")
|
||||
set(in_fixture_class FALSE)
|
||||
set(fixture_class_name "")
|
||||
set(fixture_indent "")
|
||||
set(line_number 0)
|
||||
|
||||
# Accumulators for preceding comments
|
||||
set(current_tags "")
|
||||
set(current_skip "")
|
||||
|
||||
foreach(line IN LISTS lines)
|
||||
math(EXPR line_number "${line_number} + 1")
|
||||
|
||||
# Parse preceding comments for @tag and @skip
|
||||
string(REGEX MATCH "//[ \t]*@tag[ \t]+(.*)" _tag_match "${line}")
|
||||
if(_tag_match)
|
||||
string(REGEX REPLACE ".*@tag[ \t]+" "" _tag_str "${line}")
|
||||
string(REGEX REPLACE "//.*" "" _tag_str "${_tag_str}")
|
||||
string(REPLACE " " "" _tag_str "${_tag_str}")
|
||||
string(REPLACE "," ";" _tag_list "${_tag_str}")
|
||||
foreach(t ${_tag_list})
|
||||
list(APPEND current_tags "${t}")
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
string(REGEX MATCH "//[ \t]*@skip[ \t]+(.*)" _skip_match "${line}")
|
||||
if(_skip_match)
|
||||
string(REGEX REPLACE ".*@skip[ \t]+" "" current_skip "${line}")
|
||||
string(STRIP "${current_skip}" current_skip)
|
||||
# Wrap as a C++ string literal unless the user already quoted it.
|
||||
if(NOT current_skip MATCHES "^\".*\"$")
|
||||
string(REPLACE "\\" "\\\\" current_skip "${current_skip}")
|
||||
string(REPLACE "\"" "\\\"" current_skip "${current_skip}")
|
||||
set(current_skip "\"${current_skip}\"")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Track fixture classes
|
||||
string(REGEX MATCH "^[ \t]*class[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*:.*Void::Testing::Fixture" _match "${line}")
|
||||
if(_match)
|
||||
string(REGEX REPLACE "^[ \t]*class[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*:.*" "\\1" fixture_class_name "${line}")
|
||||
set(in_fixture_class TRUE)
|
||||
string(REGEX MATCH "^[ \t]*" fixture_indent "${line}")
|
||||
endif()
|
||||
|
||||
if(in_fixture_class)
|
||||
string(REGEX MATCH "^${fixture_indent}\\};" _close "${line}")
|
||||
if(_close)
|
||||
set(in_fixture_class FALSE)
|
||||
set(fixture_class_name "")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Match test functions
|
||||
set(func_name "")
|
||||
set(return_type "")
|
||||
set(is_skipped_str "false")
|
||||
|
||||
if(in_fixture_class)
|
||||
string(REGEX MATCH "(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\)[ \t]*(const)?" _func_match "${line}")
|
||||
if(_func_match)
|
||||
string(REGEX REPLACE ".*(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\).*" "\\3" func_name "${line}")
|
||||
string(REGEX REPLACE ".*(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\).*" "\\2" return_type "${line}")
|
||||
endif()
|
||||
else()
|
||||
string(REGEX MATCH "^(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\)" _func_match "${line}")
|
||||
if(_func_match)
|
||||
string(REGEX REPLACE "^(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\).*" "\\3" func_name "${line}")
|
||||
string(REGEX REPLACE "^(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\).*" "\\2" return_type "${line}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(func_name)
|
||||
if(return_type STREQUAL "DisabledTest")
|
||||
set(is_skipped_str "true")
|
||||
if(NOT current_skip)
|
||||
set(current_skip "\"disabled\"")
|
||||
endif()
|
||||
endif()
|
||||
if(NOT current_skip)
|
||||
set(current_skip "\"\"")
|
||||
endif()
|
||||
|
||||
# Build tags C++
|
||||
set(tags_cpp "{}")
|
||||
list(LENGTH current_tags num_tags)
|
||||
if(num_tags GREATER 0)
|
||||
set(tags_list_cpp "")
|
||||
foreach(t ${current_tags})
|
||||
list(APPEND tags_list_cpp "\"${t}\"")
|
||||
endforeach()
|
||||
string(REPLACE ";" ", " tags_cpp "${tags_list_cpp}")
|
||||
set(tags_cpp "{${tags_cpp}}")
|
||||
endif()
|
||||
|
||||
set(safe_func_name "${func_name}")
|
||||
if(in_fixture_class)
|
||||
set(safe_func_name "${fixture_class_name}_${func_name}")
|
||||
endif()
|
||||
|
||||
# Escape path for C++ string literals
|
||||
string(REPLACE "\\" "/" INPUT_FILE_FORWARD "${INPUT_FILE}")
|
||||
|
||||
if(in_fixture_class)
|
||||
string(APPEND registrations
|
||||
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
||||
)
|
||||
else()
|
||||
string(APPEND registrations
|
||||
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
||||
)
|
||||
endif()
|
||||
|
||||
# Reset accumulators after consuming them
|
||||
set(current_tags "")
|
||||
set(current_skip "")
|
||||
else()
|
||||
# If line is code (not comment/empty), break the comment association
|
||||
string(REGEX MATCH "^[ \t]*$" _is_empty "${line}")
|
||||
string(REGEX MATCH "^[ \t]*//" _is_comment "${line}")
|
||||
if(NOT _is_empty AND NOT _is_comment)
|
||||
set(current_tags "")
|
||||
set(current_skip "")
|
||||
endif()
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# The generated file MUST include the original file so function addresses can be resolved
|
||||
file(WRITE ${OUTPUT_FILE}
|
||||
"#include <Void/Testing/Detail/Registrar.hpp>\n"
|
||||
"#include <vector>\n"
|
||||
"#include <string>\n"
|
||||
"\n"
|
||||
"// Include the original test file to resolve function definitions\n"
|
||||
"#include \"${INPUT_FILE_FORWARD}\"\n"
|
||||
"\n"
|
||||
"// Auto-generated by VoidTestScanner.cmake. Do not edit.\n"
|
||||
"namespace {\n"
|
||||
"${registrations}"
|
||||
"}\n"
|
||||
)
|
||||
@@ -0,0 +1,142 @@
|
||||
if(_VOID_TESTING_INCLUDED)
|
||||
return()
|
||||
endif()
|
||||
set(_VOID_TESTING_INCLUDED TRUE)
|
||||
|
||||
set(VOID_TESTING_SCANNER "${CMAKE_CURRENT_LIST_DIR}/VoidTestScanner.cmake"
|
||||
CACHE INTERNAL "Path to VoidTestScanner.cmake")
|
||||
|
||||
# Returns TRUE in <out_var> if <target> transitively links Void::Testing.
|
||||
function(_void_testing_links_testing target out_var)
|
||||
set(${out_var} FALSE PARENT_SCOPE)
|
||||
set(_visited "")
|
||||
set(_queue "${target}")
|
||||
while(_queue)
|
||||
list(POP_FRONT _queue _current)
|
||||
if(_current IN_LIST _visited)
|
||||
continue()
|
||||
endif()
|
||||
list(APPEND _visited "${_current}")
|
||||
|
||||
if(_current STREQUAL "Void::Testing" OR _current STREQUAL "Void_Testing")
|
||||
set(${out_var} TRUE PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(NOT TARGET ${_current})
|
||||
continue()
|
||||
endif()
|
||||
|
||||
get_target_property(_libs ${_current} LINK_LIBRARIES)
|
||||
if(_libs)
|
||||
list(APPEND _queue ${_libs})
|
||||
endif()
|
||||
get_target_property(_iflibs ${_current} INTERFACE_LINK_LIBRARIES)
|
||||
if(_iflibs)
|
||||
list(APPEND _queue ${_iflibs})
|
||||
endif()
|
||||
endwhile()
|
||||
endfunction()
|
||||
|
||||
# Apply the scan/HEADER_FILE_ONLY rewrite to <target>. Idempotent.
|
||||
function(_void_testing_apply_scan target)
|
||||
if(NOT TARGET ${target})
|
||||
return()
|
||||
endif()
|
||||
|
||||
get_target_property(_done ${target} VOID_TESTING_SCANNED)
|
||||
if(_done)
|
||||
return()
|
||||
endif()
|
||||
set_target_properties(${target} PROPERTIES VOID_TESTING_SCANNED TRUE)
|
||||
|
||||
get_target_property(_target_dir ${target} BINARY_DIR)
|
||||
set(_gen_dir "${_target_dir}/void_testing_generated")
|
||||
file(MAKE_DIRECTORY "${_gen_dir}")
|
||||
|
||||
get_target_property(_sources ${target} SOURCES)
|
||||
set(_generated)
|
||||
|
||||
foreach(_src ${_sources})
|
||||
if(NOT _src MATCHES "\\.cpp$")
|
||||
continue()
|
||||
endif()
|
||||
if(_src MATCHES "\\.void_tests\\.cpp$")
|
||||
continue()
|
||||
endif()
|
||||
|
||||
get_filename_component(_abs ${_src} ABSOLUTE)
|
||||
get_filename_component(_stem ${_src} NAME_WE)
|
||||
set(_gen "${_gen_dir}/${_stem}.void_tests.cpp")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${_gen}
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DINPUT_FILE=${_abs}
|
||||
-DOUTPUT_FILE=${_gen}
|
||||
-DSUITE_NAME=${_stem}
|
||||
-P ${VOID_TESTING_SCANNER}
|
||||
DEPENDS ${_abs} ${VOID_TESTING_SCANNER}
|
||||
COMMENT "Scanning ${_src} for Void::Testing tests"
|
||||
)
|
||||
|
||||
list(APPEND _generated ${_gen})
|
||||
set_source_files_properties(${_src} PROPERTIES HEADER_FILE_ONLY TRUE)
|
||||
set_source_files_properties(${_gen} PROPERTIES GENERATED TRUE)
|
||||
endforeach()
|
||||
|
||||
if(_generated)
|
||||
target_sources(${target} PRIVATE ${_generated})
|
||||
endif()
|
||||
|
||||
if(NOT TEST ${target})
|
||||
add_test(NAME ${target} COMMAND ${target})
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Public entry point — explicit opt-in. Idempotent with the auto-scan sweep.
|
||||
function(void_add_tests target)
|
||||
if(NOT TARGET ${target})
|
||||
message(FATAL_ERROR "void_add_tests: '${target}' is not a target")
|
||||
endif()
|
||||
target_link_libraries(${target} PRIVATE Void::Testing)
|
||||
_void_testing_apply_scan(${target})
|
||||
endfunction()
|
||||
|
||||
# Sweep: visit every executable in <dir> and its subdirectories. If the
|
||||
# executable transitively links Void::Testing and has not opted out via
|
||||
# VOID_TESTING_NO_AUTO_SCAN, apply the scan rewrite.
|
||||
function(_void_testing_sweep_directory dir)
|
||||
get_property(_targets DIRECTORY "${dir}" PROPERTY BUILDSYSTEM_TARGETS)
|
||||
foreach(_target IN LISTS _targets)
|
||||
if(NOT TARGET ${_target})
|
||||
continue()
|
||||
endif()
|
||||
get_target_property(_type ${_target} TYPE)
|
||||
if(NOT _type STREQUAL "EXECUTABLE")
|
||||
continue()
|
||||
endif()
|
||||
get_target_property(_optout ${_target} VOID_TESTING_NO_AUTO_SCAN)
|
||||
if(_optout)
|
||||
continue()
|
||||
endif()
|
||||
_void_testing_links_testing(${_target} _links)
|
||||
if(_links)
|
||||
_void_testing_apply_scan(${_target})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
get_property(_subdirs DIRECTORY "${dir}" PROPERTY SUBDIRECTORIES)
|
||||
foreach(_subdir IN LISTS _subdirs)
|
||||
_void_testing_sweep_directory("${_subdir}")
|
||||
endforeach()
|
||||
endfunction()
|
||||
|
||||
# Schedule the sweep at the end of the include-site directory so the
|
||||
# generated custom commands and target_sources() additions land in the
|
||||
# same directory scope as the test targets that consume them.
|
||||
if(NOT _VOID_TESTING_SWEEP_REGISTERED)
|
||||
set(_VOID_TESTING_SWEEP_REGISTERED TRUE)
|
||||
cmake_language(DEFER DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
|
||||
CALL _void_testing_sweep_directory "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
endif()
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Config.hpp>
|
||||
#include <Void/Testing/Detail/Registry.hpp>
|
||||
#include <source_location>
|
||||
#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; }
|
||||
};
|
||||
|
||||
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>";
|
||||
}
|
||||
|
||||
void handle_assertion(AssertionResult result);
|
||||
|
||||
struct RequireFailure : std::runtime_error {
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
} // namespace Void::Testing::Detail
|
||||
|
||||
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 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 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 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));
|
||||
}
|
||||
|
||||
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}};
|
||||
}
|
||||
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Testing
|
||||
{
|
||||
|
||||
enum class AssertKind : uint8_t { Expect, Require, Assert };
|
||||
enum class TestState : uint8_t { Passed, Failed, Skipped, Crashed };
|
||||
|
||||
struct AssertionResult {
|
||||
bool passed{true};
|
||||
AssertKind kind{AssertKind::Expect};
|
||||
std::string expression;
|
||||
std::string expected_repr;
|
||||
std::string actual_repr;
|
||||
std::string message;
|
||||
std::source_location location;
|
||||
static AssertionResult
|
||||
ok(std::source_location loc = std::source_location::current())
|
||||
{
|
||||
return {.passed = true, .location = loc};
|
||||
}
|
||||
};
|
||||
|
||||
struct TestCase {
|
||||
std::function<void()> run;
|
||||
std::string name;
|
||||
std::string suite;
|
||||
std::string file;
|
||||
int line{0};
|
||||
bool disabled{false};
|
||||
std::string skip_reason;
|
||||
std::vector<std::string> tags;
|
||||
std::function<void*()> fixture_create;
|
||||
std::function<void(void*)> fixture_destroy;
|
||||
std::function<void(void*)> fixture_setup;
|
||||
std::function<void(void*)> fixture_teardown;
|
||||
};
|
||||
|
||||
struct TestResult {
|
||||
std::string name;
|
||||
std::string suite;
|
||||
TestState state{TestState::Passed};
|
||||
std::chrono::nanoseconds duration{0};
|
||||
std::vector<AssertionResult> assertions;
|
||||
std::string skip_reason;
|
||||
std::string crash_info;
|
||||
std::string stacktrace;
|
||||
std::vector<std::string> tags;
|
||||
};
|
||||
|
||||
struct SuiteResult {
|
||||
std::string name;
|
||||
std::vector<TestResult> tests;
|
||||
};
|
||||
|
||||
struct RunResult {
|
||||
std::vector<SuiteResult> suites;
|
||||
std::chrono::nanoseconds total_duration{0};
|
||||
int passed{0};
|
||||
int failed{0};
|
||||
int skipped{0};
|
||||
int crashed{0};
|
||||
int total{0};
|
||||
};
|
||||
|
||||
struct RunConfig {
|
||||
std::string filter_pattern;
|
||||
std::string suite_filter;
|
||||
std::string reporter{"console"};
|
||||
std::string output_file;
|
||||
std::string tag_filter;
|
||||
bool list_only{false};
|
||||
bool verbose{false};
|
||||
bool no_color{false};
|
||||
bool shuffle{false};
|
||||
bool show_help{false};
|
||||
unsigned repeat{1};
|
||||
unsigned random_seed{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Reporter.hpp>
|
||||
#include <Void/Testing/Detail/Color.hpp>
|
||||
#include <ostream>
|
||||
|
||||
namespace Void::Testing {
|
||||
class ConsoleReporter final : public Reporter {
|
||||
public:
|
||||
explicit ConsoleReporter(std::ostream& os, bool color_enabled = true) : os_(os) {
|
||||
Detail::Color::g_color_enabled = color_enabled;
|
||||
}
|
||||
void on_run_start(const RunConfig& config, int total_tests) override;
|
||||
void on_suite_start(const std::string& suite_name, int test_count) override;
|
||||
void on_test_start(const TestCase& test) override;
|
||||
void on_test_end(const TestResult& result) override;
|
||||
void on_suite_end(const SuiteResult& result) override;
|
||||
void on_run_end(const RunResult& result) override;
|
||||
private:
|
||||
std::ostream& os_;
|
||||
void print_assertion_failure(const AssertionResult& ar);
|
||||
void print_crash_info(const TestResult& result);
|
||||
};
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
#include <string_view>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Testing::Detail::Color {
|
||||
inline bool g_color_enabled{true};
|
||||
|
||||
constexpr std::string_view reset = "\033[0m";
|
||||
constexpr std::string_view bold = "\033[1m";
|
||||
constexpr std::string_view dim = "\033[2m";
|
||||
constexpr std::string_view bold_red = "\033[1;31m";
|
||||
constexpr std::string_view bold_green = "\033[1;32m";
|
||||
constexpr std::string_view bold_yellow = "\033[1;33m";
|
||||
constexpr std::string_view bold_blue = "\033[1;34m";
|
||||
constexpr std::string_view bold_magenta = "\033[1;35m";
|
||||
constexpr std::string_view bold_cyan = "\033[1;36m";
|
||||
constexpr std::string_view bold_white = "\033[1;37m";
|
||||
constexpr std::string_view red = "\033[31m";
|
||||
constexpr std::string_view green = "\033[32m";
|
||||
constexpr std::string_view yellow = "\033[33m";
|
||||
constexpr std::string_view cyan = "\033[36m";
|
||||
|
||||
inline std::string apply(std::string_view code, std::string_view text) {
|
||||
if (!g_color_enabled) return std::string{text};
|
||||
return std::string{code} + std::string{text} + std::string{reset};
|
||||
}
|
||||
inline std::string success(std::string_view text) { return apply(bold_green, text); }
|
||||
inline std::string fail(std::string_view text) { return apply(bold_red, text); }
|
||||
inline std::string skip(std::string_view text) { return apply(bold_yellow, text); }
|
||||
inline std::string info(std::string_view text) { return apply(bold_cyan, text); }
|
||||
inline std::string hint(std::string_view text) { return apply(dim, text); }
|
||||
inline std::string heading(std::string_view text) { return apply(bold_blue, text); }
|
||||
inline std::string emphasis(std::string_view text) { return apply(bold, text); }
|
||||
} // namespace Void::Testing::Detail::Color
|
||||
@@ -0,0 +1,107 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Config.hpp>
|
||||
#include <Void/Testing/Detail/Registry.hpp>
|
||||
#include <source_location>
|
||||
#include <type_traits>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
|
||||
template<typename T>
|
||||
struct function_traits;
|
||||
|
||||
template<typename R, typename... Args>
|
||||
struct function_traits<R(*)(Args...)> {
|
||||
using return_type = R;
|
||||
using class_type = void;
|
||||
static constexpr bool is_member = false;
|
||||
};
|
||||
|
||||
template<typename R, typename C, typename... Args>
|
||||
struct function_traits<R(C::*)(Args...) const> {
|
||||
using return_type = R;
|
||||
using class_type = C;
|
||||
static constexpr bool is_member = true;
|
||||
};
|
||||
|
||||
template<typename R, typename C, typename... Args>
|
||||
struct function_traits<R(C::*)(Args...)> {
|
||||
using return_type = R;
|
||||
using class_type = C;
|
||||
static constexpr bool is_member = true;
|
||||
};
|
||||
|
||||
template<auto Fn>
|
||||
class test_registrar {
|
||||
public:
|
||||
explicit test_registrar(const char* suite, const char* file, int line,
|
||||
const char* test_name_str,
|
||||
std::vector<std::string> tags = {},
|
||||
bool is_skipped = false,
|
||||
std::string skip_reason = "") {
|
||||
auto& reg = Registry::instance();
|
||||
std::string test_name = test_name_str;
|
||||
|
||||
if (test_name.empty()) {
|
||||
test_name = std::format("test_at_line_{}", line);
|
||||
}
|
||||
|
||||
if constexpr (std::is_member_function_pointer_v<decltype(Fn)>) {
|
||||
using Class = typename function_traits<decltype(Fn)>::class_type;
|
||||
reg.add(TestCase{
|
||||
.name = std::move(test_name),
|
||||
.suite = suite,
|
||||
.file = file,
|
||||
.line = line,
|
||||
.disabled = is_skipped,
|
||||
.skip_reason = std::move(skip_reason),
|
||||
.tags = std::move(tags),
|
||||
.fixture_create = []() -> void* { return new Class(); },
|
||||
.fixture_destroy = [](void* p) { delete static_cast<Class*>(p); },
|
||||
.fixture_setup = [](void* p) {
|
||||
if constexpr (requires { static_cast<Class*>(p)->setup(); })
|
||||
static_cast<Class*>(p)->setup();
|
||||
},
|
||||
.fixture_teardown = [](void* p) {
|
||||
if constexpr (requires { static_cast<Class*>(p)->teardown(); })
|
||||
static_cast<Class*>(p)->teardown();
|
||||
}
|
||||
});
|
||||
|
||||
const_cast<TestCase&>(reg.tests().back()).run =
|
||||
[ptr = Fn, idx = reg.tests().size() - 1]() {
|
||||
auto& tc = Registry::instance().tests()[idx];
|
||||
void* fixture = tc.fixture_create();
|
||||
try {
|
||||
tc.fixture_setup(fixture);
|
||||
(static_cast<Class*>(fixture)->*ptr)();
|
||||
tc.fixture_teardown(fixture);
|
||||
} catch (...) {
|
||||
tc.fixture_teardown(fixture);
|
||||
tc.fixture_destroy(fixture);
|
||||
throw;
|
||||
}
|
||||
tc.fixture_destroy(fixture);
|
||||
};
|
||||
} else {
|
||||
reg.add(TestCase{
|
||||
.run = Fn,
|
||||
.name = std::move(test_name),
|
||||
.suite = suite,
|
||||
.file = file,
|
||||
.line = line,
|
||||
.disabled = is_skipped,
|
||||
.skip_reason = std::move(skip_reason),
|
||||
.tags = std::move(tags)
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::Testing::Detail
|
||||
|
||||
namespace Void::Testing {
|
||||
template<auto Fn>
|
||||
Detail::test_registrar<Fn> test{};
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Config.hpp>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
class Registry {
|
||||
public:
|
||||
static Registry& instance() {
|
||||
static Registry reg;
|
||||
return reg;
|
||||
}
|
||||
void add(TestCase test_case) {
|
||||
std::lock_guard lock{mutex_};
|
||||
tests_.push_back(std::move(test_case));
|
||||
}
|
||||
const std::vector<TestCase>& tests() const { return tests_; }
|
||||
private:
|
||||
Registry() = default;
|
||||
std::vector<TestCase> tests_;
|
||||
std::mutex mutex_;
|
||||
};
|
||||
} // namespace Void::Testing::Detail
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include <string>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <csetjmp>
|
||||
#endif
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
using CrashCallback = std::function<void(int signal, const std::string& stacktrace)>;
|
||||
void install_signal_handlers(CrashCallback on_crash);
|
||||
void uninstall_signal_handlers();
|
||||
const char* signal_name(int sig);
|
||||
|
||||
#ifndef _WIN32
|
||||
sigjmp_buf& get_jump_buffer();
|
||||
void set_jump_ready(bool ready);
|
||||
#endif
|
||||
} // namespace Void::Testing::Detail
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ostream>
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
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);
|
||||
} // namespace Void::Testing::Detail
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
std::string resolve_symbol_name(const void* address);
|
||||
std::string demangle(std::string_view mangled);
|
||||
std::string pretty_name(const void* address);
|
||||
std::string extract_test_name(std::string_view pretty_symbol);
|
||||
std::string suite_from_file(std::string_view file_path);
|
||||
} // namespace Void::Testing::Detail
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
namespace Void::Testing {
|
||||
class Fixture {
|
||||
public:
|
||||
virtual ~Fixture() = default;
|
||||
virtual void setup() {}
|
||||
virtual void teardown() {}
|
||||
};
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Reporter.hpp>
|
||||
#include <ostream>
|
||||
|
||||
namespace Void::Testing {
|
||||
class JUnitReporter final : public Reporter {
|
||||
public:
|
||||
explicit JUnitReporter(std::ostream& os) : os_(os) {}
|
||||
void on_run_start(const RunConfig& config, int total_tests) override;
|
||||
void on_suite_start(const std::string& suite_name, int test_count) override;
|
||||
void on_test_start(const TestCase& test) override;
|
||||
void on_test_end(const TestResult& result) override;
|
||||
void on_suite_end(const SuiteResult& result) override;
|
||||
void on_run_end(const RunResult& result) override;
|
||||
private:
|
||||
std::ostream& os_;
|
||||
std::vector<SuiteResult> suite_results_;
|
||||
static std::string xml_escape(std::string_view s);
|
||||
};
|
||||
} // namespace Void::Testing
|
||||
@@ -1 +0,0 @@
|
||||
#pragma once
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Config.hpp>
|
||||
#include <ostream>
|
||||
#include <memory>
|
||||
|
||||
namespace Void::Testing {
|
||||
class Reporter {
|
||||
public:
|
||||
virtual ~Reporter() = default;
|
||||
virtual void on_run_start(const RunConfig& config, int total_tests) = 0;
|
||||
virtual void on_suite_start(const std::string& suite_name, int test_count) = 0;
|
||||
virtual void on_test_start(const TestCase& test) = 0;
|
||||
virtual void on_test_end(const TestResult& result) = 0;
|
||||
virtual void on_suite_end(const SuiteResult& result) = 0;
|
||||
virtual void on_run_end(const RunResult& result) = 0;
|
||||
};
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Config.hpp>
|
||||
#include <Void/Testing/Reporter.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace Void::Testing {
|
||||
class Runner {
|
||||
public:
|
||||
static Runner& instance() {
|
||||
static Runner r;
|
||||
return r;
|
||||
}
|
||||
RunConfig parse_args(int argc, char** argv);
|
||||
RunResult run(const RunConfig& config);
|
||||
int main(int argc, char** argv);
|
||||
private:
|
||||
Runner() = default;
|
||||
std::vector<TestCase> filter_tests(const std::vector<TestCase>& tests, const RunConfig& config);
|
||||
std::unique_ptr<Reporter> create_reporter(const RunConfig& config);
|
||||
TestResult execute_test(TestCase& test_case);
|
||||
void run_test_body(TestCase& test_case, TestResult& result);
|
||||
};
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
namespace Void::Testing {
|
||||
|
||||
// Aliases to void so users can omit return statements safely
|
||||
// and avoid compiler warnings/errors. Perfectly matches std::function<void()>.
|
||||
using Test = void;
|
||||
using DisabledTest = void;
|
||||
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
#include <Void/TestingMock/Matcher.hpp>
|
||||
#include <source_location>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
|
||||
namespace Void::TestingMock::Detail {
|
||||
|
||||
template<typename> class Expectation;
|
||||
|
||||
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
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
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 "_"; } };
|
||||
|
||||
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>
|
||||
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
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
namespace Void::TestingMock {
|
||||
template<typename Derived>
|
||||
class Mock {
|
||||
public:
|
||||
Mock() = default; virtual ~Mock() = default;
|
||||
void verify_all() {}
|
||||
};
|
||||
} // namespace Void::TestingMock
|
||||
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
#include <Void/TestingMock/Expectation.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::TestingMock
|
||||
{
|
||||
|
||||
template <typename> class MockFunction;
|
||||
|
||||
template <typename R, typename... Args> class MockFunction<R(Args...)>
|
||||
{
|
||||
using Expectation = Detail::Expectation<R(Args...)>;
|
||||
|
||||
public:
|
||||
|
||||
explicit MockFunction(std::string name = "unnamed_mock")
|
||||
: name_(std::move(name))
|
||||
{
|
||||
}
|
||||
~MockFunction() { verify(); }
|
||||
|
||||
template <typename... MArgs>
|
||||
Expectation& expect(std::source_location loc, MArgs&&... matchers)
|
||||
{
|
||||
auto exp = std::make_shared<Expectation>(
|
||||
typename Expectation::MatcherTuple{
|
||||
MatcherHolder<std::decay_t<Args>>(
|
||||
std::forward<MArgs>(matchers))...},
|
||||
loc);
|
||||
expectations_.push_back(exp);
|
||||
return *exp;
|
||||
}
|
||||
|
||||
template <typename... MArgs>
|
||||
Expectation& expect(MArgs&&... matchers)
|
||||
{
|
||||
return expect(std::source_location::current(),
|
||||
std::forward<MArgs>(matchers)...);
|
||||
}
|
||||
|
||||
R operator()(Args... args)
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
for (auto& exp : expectations_) {
|
||||
if (!exp->is_saturated() && exp->matches(args...)) {
|
||||
exp->record_call();
|
||||
return exp->execute(args...);
|
||||
}
|
||||
}
|
||||
Void::Testing::fail(
|
||||
std::format("Unexpected call to {}", name_));
|
||||
if constexpr (!std::is_same_v<R, void>) {
|
||||
return R{};
|
||||
}
|
||||
}
|
||||
void verify()
|
||||
{
|
||||
for (auto& exp : expectations_) {
|
||||
exp->verify(name_);
|
||||
}
|
||||
expectations_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::string name_;
|
||||
std::vector<std::shared_ptr<Expectation>> expectations_;
|
||||
std::mutex mutex_;
|
||||
};
|
||||
} // namespace Void::TestingMock
|
||||
@@ -0,0 +1,18 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Detail/Stacktrace.hpp>
|
||||
namespace Void::Testing::Detail {
|
||||
void handle_assertion(AssertionResult result) {
|
||||
auto& ctx = TestContext::current();
|
||||
if (ctx.current_result) {
|
||||
ctx.current_result->assertions.push_back(std::move(result));
|
||||
const auto& last = ctx.current_result->assertions.back();
|
||||
if (!last.passed) {
|
||||
ctx.current_result->state = TestState::Failed;
|
||||
if (last.kind == AssertKind::Require || last.kind == AssertKind::Assert) {
|
||||
ctx.should_abort = true;
|
||||
throw RequireFailure{last.message};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace Void::Testing::Detail
|
||||
@@ -0,0 +1,71 @@
|
||||
#include <Void/Testing/ConsoleReporter.hpp>
|
||||
#include <Void/Testing/Detail/Color.hpp>
|
||||
#include <Void/Testing/Detail/SignalHandler.hpp>
|
||||
#include <format>
|
||||
#include <chrono>
|
||||
#include <algorithm>
|
||||
|
||||
namespace Void::Testing {
|
||||
using namespace Detail::Color;
|
||||
|
||||
void ConsoleReporter::on_run_start(const RunConfig&, int total_tests) {
|
||||
os_ << "\n" << apply(bold_blue, "╭──────────────────────────────────────────────╮") << "\n"
|
||||
<< apply(bold_blue, "│") << apply(bold_white, " Void Testing") << apply(dim, " v1.0") << std::string(31, ' ') << apply(bold_blue, "│") << "\n"
|
||||
<< std::format("{}│{} Discovered {} test{}{}│\n", apply(bold_blue, "╰"), apply(dim, ""), apply(bold_white, std::to_string(total_tests)), total_tests != 1 ? "s" : "", std::string(total_tests < 10 ? 33 : 28, ' '))
|
||||
<< apply(bold_blue, "╰──────────────────────────────────────────────╯") << "\n\n";
|
||||
}
|
||||
|
||||
void ConsoleReporter::on_suite_start(const std::string& suite_name, int test_count) {
|
||||
os_ << std::format(" {} {} [{} test{}]\n", apply(bold_blue, "◆"), apply(bold_white, suite_name), apply(dim, std::to_string(test_count)), test_count != 1 ? "s" : "");
|
||||
}
|
||||
|
||||
void ConsoleReporter::on_test_start(const TestCase&) {}
|
||||
void ConsoleReporter::on_suite_end(const SuiteResult&) {}
|
||||
|
||||
void ConsoleReporter::on_test_end(const TestResult& result) {
|
||||
double ms = std::chrono::duration<double, std::milli>(result.duration).count();
|
||||
std::string time_str = ms < 1.0 ? std::format("{:.3f}ms", ms) : std::format("{:.1f}ms", ms);
|
||||
std::string tags_str;
|
||||
if (!result.tags.empty()) { for(const auto& t : result.tags) tags_str += "[" + t + "]"; tags_str = " " + apply(dim, tags_str); }
|
||||
|
||||
switch (result.state) {
|
||||
case TestState::Passed: os_ << std::format(" {} {:<40s}{}{}\n", apply(bold_green, "✔"), apply(green, result.name), tags_str, apply(dim, time_str)); break;
|
||||
case TestState::Failed:
|
||||
os_ << std::format(" {} {:<40s}{}{}\n", apply(bold_red, "✘"), apply(red, result.name), tags_str, apply(dim, time_str));
|
||||
for (const auto& ar : result.assertions) if (!ar.passed) print_assertion_failure(ar);
|
||||
if (!result.crash_info.empty()) print_crash_info(result);
|
||||
break;
|
||||
case TestState::Skipped: os_ << std::format(" {} {:<40s}{}\n", apply(bold_yellow, "⊘"), apply(yellow, result.name), apply(dim, std::format("[SKIPPED: {}]", result.skip_reason.empty() ? "no reason" : result.skip_reason))); break;
|
||||
case TestState::Crashed: os_ << std::format(" {} {:<40s}{}\n", apply(bold_red, "⚡"), apply(red, result.name), apply(dim, time_str)); print_crash_info(result); break;
|
||||
}
|
||||
}
|
||||
|
||||
void ConsoleReporter::print_assertion_failure(const AssertionResult& ar) {
|
||||
os_ << apply(red, " ╭─── Assertion Failed") << apply(dim, " ──────────────────────╮") << "\n";
|
||||
std::filesystem::path p{ar.location.file_name()};
|
||||
os_ << std::format(" │ {}:{}\n", apply(bold_white, p.filename().string()), ar.location.line());
|
||||
if (!ar.expression.empty()) os_ << std::format(" │ {}\n", apply(cyan, ar.expression));
|
||||
if (!ar.expected_repr.empty()) os_ << std::format(" │ {} {}\n", apply(bold_white, "expected:"), apply(green, ar.expected_repr));
|
||||
if (!ar.actual_repr.empty()) os_ << std::format(" │ {} {}\n", apply(bold_white, "actual: "), apply(red, ar.actual_repr));
|
||||
if (!ar.message.empty()) os_ << std::format(" │ {}\n", ar.message);
|
||||
os_ << apply(red, " ╰────────────────────────────────────────────╯") << "\n";
|
||||
}
|
||||
|
||||
void ConsoleReporter::print_crash_info(const TestResult& result) {
|
||||
os_ << apply(bold_red, " ╭─── Crash") << apply(dim, " ───────────────────────────╮") << "\n";
|
||||
if (!result.crash_info.empty()) os_ << std::format(" │ {}\n", apply(red, result.crash_info));
|
||||
os_ << apply(bold_red, " ╰────────────────────────────────────────────╯") << "\n";
|
||||
if (!result.stacktrace.empty()) os_ << apply(dim, " Stacktrace:\n") << result.stacktrace << "\n";
|
||||
}
|
||||
|
||||
void ConsoleReporter::on_run_end(const RunResult& result) {
|
||||
os_ << "\n" << apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n"
|
||||
<< std::format(" {} tests: ", apply(bold_white, std::to_string(result.total)));
|
||||
if (result.passed > 0) os_ << std::format("{} {} ", apply(bold_green, std::to_string(result.passed)), apply(green, "✔"));
|
||||
if (result.failed + result.crashed > 0) os_ << std::format("{} {} ", apply(bold_red, std::to_string(result.failed + result.crashed)), apply(red, "✘"));
|
||||
if (result.skipped > 0) os_ << std::format("{} {} ", apply(bold_yellow, std::to_string(result.skipped)), apply(yellow, "⊘"));
|
||||
double total_ms = std::chrono::duration<double, std::milli>(result.total_duration).count();
|
||||
os_ << std::format(" {} {}\n", apply(dim, "in"), apply(bold_cyan, total_ms < 1000 ? std::format("{:.1f}ms", total_ms) : std::format("{:.2f}s", total_ms / 1000.0)))
|
||||
<< apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n\n";
|
||||
}
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,35 @@
|
||||
#include <Void/Testing/JUnitReporter.hpp>
|
||||
#include <format>
|
||||
#include <chrono>
|
||||
|
||||
namespace Void::Testing {
|
||||
void JUnitReporter::on_run_start(const RunConfig&, int) {}
|
||||
void JUnitReporter::on_suite_start(const std::string&, int) {}
|
||||
void JUnitReporter::on_test_start(const TestCase&) {}
|
||||
void JUnitReporter::on_test_end(const TestResult&) {}
|
||||
void JUnitReporter::on_suite_end(const SuiteResult& result) { suite_results_.push_back(result); }
|
||||
|
||||
void JUnitReporter::on_run_end(const RunResult& result) {
|
||||
double total_seconds = std::chrono::duration<double>(result.total_duration).count();
|
||||
os_ << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"" << result.total << "\" failures=\"" << result.failed << "\" errors=\"" << result.crashed << "\" time=\"" << std::format("{:.3f}", total_seconds) << "\">\n";
|
||||
for (const auto& suite : suite_results_) {
|
||||
int sf=0, se=0, ss=0; for (const auto& t : suite.tests) { if(t.state==TestState::Failed) sf++; if(t.state==TestState::Crashed) se++; if(t.state==TestState::Skipped) ss++; }
|
||||
double st=0; for (const auto& t : suite.tests) st += std::chrono::duration<double>(t.duration).count();
|
||||
os_ << " <testsuite name=\"" << xml_escape(suite.name) << "\" tests=\"" << suite.tests.size() << "\" failures=\"" << sf << "\" errors=\"" << se << "\" skipped=\"" << ss << "\" time=\"" << std::format("{:.3f}", st) << "\">\n";
|
||||
for (const auto& test : suite.tests) {
|
||||
double tt = std::chrono::duration<double>(test.duration).count();
|
||||
os_ << " <testcase name=\"" << xml_escape(test.name) << "\" classname=\"" << xml_escape(test.suite) << "\" time=\"" << std::format("{:.3f}", tt) << "\"";
|
||||
if (test.state == TestState::Skipped) os_ << ">\n <skipped message=\"" << xml_escape(test.skip_reason) << "\"/>\n </testcase>\n";
|
||||
else if (test.state == TestState::Failed) { os_ << ">\n"; for (const auto& ar : test.assertions) if(!ar.passed) os_ << " <failure message=\"" << xml_escape(ar.message) << "\"/>\n"; os_ << " </testcase>\n"; }
|
||||
else if (test.state == TestState::Crashed) os_ << ">\n <error message=\"" << xml_escape(test.crash_info) << "\"/>\n </testcase>\n";
|
||||
else os_ << "/>\n";
|
||||
}
|
||||
os_ << " </testsuite>\n";
|
||||
}
|
||||
os_ << "</testsuites>\n";
|
||||
}
|
||||
|
||||
std::string JUnitReporter::xml_escape(std::string_view s) {
|
||||
std::string r; r.reserve(s.size()); for(char c : s) { switch(c) { case '&': r+="&"; break; case '<': r+="<"; break; case '>': r+=">"; break; case '"': r+="""; break; case '\'': r+="'"; break; default: r+=c; } } return r;
|
||||
}
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,2 @@
|
||||
#include <Void/Testing/Runner.hpp>
|
||||
int main(int argc, char** argv) { return Void::Testing::Runner::instance().main(argc, argv); }
|
||||
@@ -0,0 +1,2 @@
|
||||
#include <Void/Testing/Detail/Registry.hpp>
|
||||
namespace Void::Testing::Detail {}
|
||||
@@ -0,0 +1,355 @@
|
||||
#include <Void/Testing/Runner.hpp>
|
||||
#include "Void/Testing/Config.hpp"
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/ConsoleReporter.hpp>
|
||||
#include <Void/Testing/Detail/Color.hpp>
|
||||
#include <Void/Testing/Detail/Registry.hpp>
|
||||
#include <Void/Testing/Detail/SignalHandler.hpp>
|
||||
#include <Void/Testing/Detail/Stacktrace.hpp>
|
||||
#include <Void/Testing/JUnitReporter.hpp>
|
||||
#include <algorithm>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <regex>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Void::Testing
|
||||
{
|
||||
|
||||
RunConfig Runner::parse_args(int argc, char** argv)
|
||||
{
|
||||
RunConfig config;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string arg = argv[i];
|
||||
if ((arg == "--filter" || arg == "--suite" || arg == "--reporter" ||
|
||||
arg == "--output" || arg == "--tag" || arg == "--seed" ||
|
||||
arg == "--repeat") &&
|
||||
i + 1 < argc) {
|
||||
std::string val = argv[++i];
|
||||
if (arg == "--filter") {
|
||||
config.filter_pattern = val;
|
||||
} else if (arg == "--suite") {
|
||||
config.suite_filter = val;
|
||||
} else if (arg == "--reporter") {
|
||||
config.reporter = val;
|
||||
} else if (arg == "--output") {
|
||||
config.output_file = val;
|
||||
} else if (arg == "--tag") {
|
||||
config.tag_filter = val;
|
||||
} else if (arg == "--seed") {
|
||||
config.shuffle = true;
|
||||
config.random_seed = static_cast<unsigned>(std::stoul(val));
|
||||
} else if (arg == "--repeat") {
|
||||
config.repeat = static_cast<unsigned>(std::stoul(val));
|
||||
}
|
||||
|
||||
} else if (arg == "--help") {
|
||||
config.show_help = true;
|
||||
} else if (arg == "--list") {
|
||||
config.list_only = true;
|
||||
} else if (arg == "--verbose") {
|
||||
config.verbose = true;
|
||||
} else if (arg == "--no-color") {
|
||||
config.no_color = true;
|
||||
} else if (arg == "--shuffle") {
|
||||
config.shuffle = true;
|
||||
std::random_device rd;
|
||||
config.random_seed = rd();
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
std::vector<TestCase>
|
||||
Runner::filter_tests(const std::vector<TestCase>& tests,
|
||||
const RunConfig& config)
|
||||
{
|
||||
std::vector<TestCase> result;
|
||||
std::regex filter_regex{".*"};
|
||||
if (!config.filter_pattern.empty()) {
|
||||
try {
|
||||
filter_regex = std::regex{config.filter_pattern};
|
||||
} catch (...) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
for (const auto& test : tests) {
|
||||
if (!config.suite_filter.empty() &&
|
||||
test.suite != config.suite_filter) {
|
||||
continue;
|
||||
}
|
||||
if (!std::regex_search(test.name, filter_regex) &&
|
||||
!std::regex_search(test.suite + "." + test.name,
|
||||
filter_regex)) {
|
||||
continue;
|
||||
}
|
||||
if (!config.tag_filter.empty()) {
|
||||
bool has = false;
|
||||
for (const auto& t : test.tags) {
|
||||
if (t == config.tag_filter) {
|
||||
has = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!has) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.push_back(test);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::unique_ptr<Reporter> Runner::create_reporter(const RunConfig& config)
|
||||
{
|
||||
if (config.reporter == "junit") {
|
||||
static std::ofstream file{config.output_file.empty()
|
||||
? "test_results.xml"
|
||||
: config.output_file};
|
||||
return std::make_unique<JUnitReporter>(file);
|
||||
}
|
||||
return std::make_unique<ConsoleReporter>(std::cout, !config.no_color);
|
||||
}
|
||||
|
||||
TestResult Runner::execute_test(TestCase& test_case)
|
||||
{
|
||||
TestResult result;
|
||||
result.name = test_case.name;
|
||||
result.suite = test_case.suite;
|
||||
result.tags = test_case.tags;
|
||||
if (test_case.disabled) {
|
||||
result.state = TestState::Skipped;
|
||||
result.skip_reason = test_case.skip_reason.empty()
|
||||
? "disabled"
|
||||
: test_case.skip_reason;
|
||||
return result;
|
||||
}
|
||||
Detail::TestContext::current().current_result = &result;
|
||||
Detail::TestContext::current().should_abort = false;
|
||||
|
||||
int crash_signal = 0;
|
||||
std::string crash_stacktrace;
|
||||
Detail::install_signal_handlers([&](int sig, const std::string& trace) {
|
||||
crash_signal = sig;
|
||||
crash_stacktrace = trace;
|
||||
});
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
|
||||
try {
|
||||
#ifndef _WIN32
|
||||
if (sigsetjmp(Detail::get_jump_buffer(), 1) == 0) {
|
||||
Detail::set_jump_ready(true);
|
||||
run_test_body(test_case, result);
|
||||
} else {
|
||||
result.state = TestState::Crashed;
|
||||
result.crash_info = std::format(
|
||||
"Signal: {}", Detail::signal_name(crash_signal));
|
||||
result.stacktrace = crash_stacktrace;
|
||||
}
|
||||
Detail::set_jump_ready(false);
|
||||
#else
|
||||
run_test_body(test_case, result);
|
||||
#endif
|
||||
} catch (const Detail::RequireFailure&) {
|
||||
if (result.state != TestState::Skipped) {
|
||||
result.state = TestState::Failed;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
result.state = TestState::Failed;
|
||||
result.crash_info =
|
||||
std::format("Unhandled exception: {}", e.what());
|
||||
result.stacktrace =
|
||||
Detail::format_stacktrace(Detail::capture_stacktrace(1, 8));
|
||||
} catch (...) {
|
||||
result.state = TestState::Failed;
|
||||
result.crash_info = "Unhandled unknown exception";
|
||||
result.stacktrace =
|
||||
Detail::format_stacktrace(Detail::capture_stacktrace(1, 8));
|
||||
}
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
result.duration = end - start;
|
||||
Detail::uninstall_signal_handlers();
|
||||
Detail::TestContext::current().current_result = nullptr;
|
||||
|
||||
if (result.state != TestState::Skipped &&
|
||||
result.state != TestState::Crashed) {
|
||||
bool any =
|
||||
std::any_of(result.assertions.begin(), result.assertions.end(),
|
||||
[](const auto& a) { return !a.passed; });
|
||||
result.state = any ? TestState::Failed : TestState::Passed;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void Runner::run_test_body(TestCase& test_case, TestResult&)
|
||||
{
|
||||
if (test_case.fixture_create) {
|
||||
void* fixture = test_case.fixture_create();
|
||||
Detail::TestContext::current().fixture = fixture;
|
||||
try {
|
||||
test_case.fixture_setup(fixture);
|
||||
test_case.run();
|
||||
test_case.fixture_teardown(fixture);
|
||||
} catch (...) {
|
||||
test_case.fixture_teardown(fixture);
|
||||
test_case.fixture_destroy(fixture);
|
||||
Detail::TestContext::current().fixture = nullptr;
|
||||
throw;
|
||||
}
|
||||
test_case.fixture_destroy(fixture);
|
||||
Detail::TestContext::current().fixture = nullptr;
|
||||
} else {
|
||||
test_case.run();
|
||||
}
|
||||
}
|
||||
|
||||
RunResult Runner::run(const RunConfig& config)
|
||||
{
|
||||
Detail::Color::g_color_enabled = !config.no_color;
|
||||
if (config.show_help) {
|
||||
using namespace Detail::Color;
|
||||
|
||||
std::cout
|
||||
<< "\n"
|
||||
<< apply(bold_blue, "╭─────────────────────────────────────────"
|
||||
"─────────────────────────╮")
|
||||
<< "\n"
|
||||
<< apply(bold_blue, "│") << apply(bold_white, " Void Testing")
|
||||
<< apply(dim, " — Command Line Interface")
|
||||
<< std::string(28, ' ') << apply(bold_blue, "│") << "\n"
|
||||
<< apply(bold_blue, "╰─────────────────────────────────────────"
|
||||
"─────────────────────────╯")
|
||||
<< "\n"
|
||||
<< "\n"
|
||||
<< " " << apply(bold_white, "USAGE:") << "\n"
|
||||
<< " " << apply(cyan, "<executable>") << " "
|
||||
<< apply(dim, "[options]") << "\n"
|
||||
<< "\n"
|
||||
<< " " << apply(bold_white, "OPTIONS:") << "\n"
|
||||
<< " " << apply(green, "--filter <pattern> ")
|
||||
<< apply(dim, "Run tests matching the regex pattern") << "\n"
|
||||
<< " " << apply(green, "--suite <name> ")
|
||||
<< apply(dim, "Run only tests in the specified suite") << "\n"
|
||||
<< " " << apply(green, "--tag <name> ")
|
||||
<< apply(dim, "Run only tests with the specified tag") << "\n"
|
||||
<< " " << apply(green, "--list ")
|
||||
<< apply(dim, "List discovered tests without running them")
|
||||
<< "\n"
|
||||
<< " " << apply(green, "--shuffle ")
|
||||
<< apply(dim, "Randomize the order of test execution") << "\n"
|
||||
<< " " << apply(green, "--seed <n> ")
|
||||
<< apply(dim, "Set the random seed (implies --shuffle)") << "\n"
|
||||
<< " " << apply(green, "--repeat <n> ")
|
||||
<< apply(dim, "Repeat the test run n times") << "\n"
|
||||
<< " " << apply(green, "--reporter <type> ")
|
||||
<< apply(dim, "Choose the output reporter: console, junit")
|
||||
<< "\n"
|
||||
<< " " << apply(green, "--output <file> ")
|
||||
<< apply(dim, "Write reporter output to a file") << "\n"
|
||||
<< " " << apply(green, "--verbose ")
|
||||
<< apply(dim, "Enable verbose output") << "\n"
|
||||
<< " " << apply(green, "--no-color ")
|
||||
<< apply(dim, "Disable colored console output") << "\n"
|
||||
<< " " << apply(green, "--help ")
|
||||
<< apply(dim, "Show this help message") << "\n"
|
||||
<< "\n"
|
||||
<< " " << apply(bold_white, "EXAMPLES:") << "\n"
|
||||
<< " " << apply(cyan, "./run_tests") << " "
|
||||
<< apply(yellow, "--filter") << " \"math_tests.*\"" << "\n"
|
||||
<< " " << apply(cyan, "./run_tests") << " "
|
||||
<< apply(yellow, "--tag") << " integration "
|
||||
<< apply(yellow, "--shuffle") << "\n"
|
||||
<< " " << apply(cyan, "./run_tests") << " "
|
||||
<< apply(yellow, "--reporter") << " junit "
|
||||
<< apply(yellow, "--output") << " results.xml" << "\n"
|
||||
<< "\n";
|
||||
|
||||
return {};
|
||||
}
|
||||
auto all_tests = Detail::Registry::instance().tests();
|
||||
auto tests = filter_tests(all_tests, config);
|
||||
auto reporter = create_reporter(config);
|
||||
|
||||
if (config.list_only) {
|
||||
for (const auto& t : tests) {
|
||||
std::cout << t.suite << "." << t.name
|
||||
<< (t.disabled ? " [DISABLED]" : "") << "\n";
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
RunResult run_result;
|
||||
reporter->on_run_start(config, static_cast<int>(tests.size()));
|
||||
if (config.shuffle) {
|
||||
std::shuffle(tests.begin(), tests.end(),
|
||||
std::mt19937{config.random_seed});
|
||||
}
|
||||
|
||||
std::vector<SuiteResult> suite_results;
|
||||
std::unordered_map<std::string, size_t> suite_index;
|
||||
for (auto& test : tests) {
|
||||
if (suite_index.find(test.suite) == suite_index.end()) {
|
||||
suite_index[test.suite] = suite_results.size();
|
||||
suite_results.push_back({.name = test.suite});
|
||||
}
|
||||
}
|
||||
auto start_time = std::chrono::high_resolution_clock::now();
|
||||
|
||||
for (unsigned rep = 0; rep < config.repeat; ++rep) {
|
||||
for (auto& test : tests) {
|
||||
auto& suite = suite_results[suite_index[test.suite]];
|
||||
if (rep == 0) {
|
||||
reporter->on_suite_start(
|
||||
suite.name, std::count_if(tests.begin(), tests.end(),
|
||||
[&](const auto& t) {
|
||||
return t.suite ==
|
||||
suite.name;
|
||||
}));
|
||||
}
|
||||
reporter->on_test_start(test);
|
||||
auto result = execute_test(test);
|
||||
reporter->on_test_end(result);
|
||||
if (rep == config.repeat - 1) {
|
||||
suite.tests.push_back(std::move(result));
|
||||
}
|
||||
}
|
||||
}
|
||||
auto end_time = std::chrono::high_resolution_clock::now();
|
||||
|
||||
for (auto& suite : suite_results) {
|
||||
for (const auto& test : suite.tests) {
|
||||
switch (test.state) {
|
||||
case TestState::Passed:
|
||||
run_result.passed++;
|
||||
break;
|
||||
case TestState::Failed:
|
||||
run_result.failed++;
|
||||
break;
|
||||
case TestState::Skipped:
|
||||
run_result.skipped++;
|
||||
break;
|
||||
case TestState::Crashed:
|
||||
run_result.crashed++;
|
||||
break;
|
||||
}
|
||||
run_result.total++;
|
||||
}
|
||||
reporter->on_suite_end(suite);
|
||||
run_result.suites.push_back(std::move(suite));
|
||||
}
|
||||
run_result.total_duration = end_time - start_time;
|
||||
reporter->on_run_end(run_result);
|
||||
return run_result;
|
||||
}
|
||||
|
||||
int Runner::main(int argc, char** argv)
|
||||
{
|
||||
auto config = parse_args(argc, argv);
|
||||
auto result = run(config);
|
||||
return (result.failed + result.crashed > 0) ? 1 : 0;
|
||||
}
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,59 @@
|
||||
#include <Void/Testing/Detail/SignalHandler.hpp>
|
||||
#include <Void/Testing/Detail/Stacktrace.hpp>
|
||||
#include <csignal>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
static CrashCallback g_crash_callback;
|
||||
static int g_last_signal{0};
|
||||
|
||||
#ifndef _WIN32
|
||||
static sigjmp_buf g_jump_buffer;
|
||||
static bool g_jump_ready{false};
|
||||
sigjmp_buf& get_jump_buffer() { return g_jump_buffer; }
|
||||
void set_jump_ready(bool ready) { g_jump_ready = ready; }
|
||||
#endif
|
||||
|
||||
const char* signal_name(int sig) {
|
||||
switch (sig) {
|
||||
case SIGSEGV: return "SIGSEGV (segmentation fault)";
|
||||
case SIGABRT: return "SIGABRT (abort)";
|
||||
case SIGFPE: return "SIGFPE (floating point exception)";
|
||||
case SIGILL: return "SIGILL (illegal instruction)";
|
||||
#ifdef SIGBUS
|
||||
case SIGBUS: return "SIGBUS (bus error)";
|
||||
#endif
|
||||
default: return "UNKNOWN SIGNAL";
|
||||
}
|
||||
}
|
||||
|
||||
static void crash_handler(int sig) {
|
||||
g_last_signal = sig;
|
||||
auto frames = capture_stacktrace(1, 16);
|
||||
auto trace = format_stacktrace(frames);
|
||||
if (g_crash_callback) g_crash_callback(sig, trace);
|
||||
#ifndef _WIN32
|
||||
if (g_jump_ready) { g_jump_ready = false; siglongjmp(g_jump_buffer, sig); }
|
||||
#endif
|
||||
std::_Exit(128 + sig);
|
||||
}
|
||||
|
||||
void install_signal_handlers(CrashCallback on_crash) {
|
||||
g_crash_callback = std::move(on_crash);
|
||||
struct sigaction sa{}; sa.sa_handler = crash_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0;
|
||||
sigaction(SIGSEGV, &sa, nullptr); sigaction(SIGABRT, &sa, nullptr); sigaction(SIGFPE, &sa, nullptr); sigaction(SIGILL, &sa, nullptr);
|
||||
#ifdef SIGBUS
|
||||
sigaction(SIGBUS, &sa, nullptr);
|
||||
#endif
|
||||
}
|
||||
|
||||
void uninstall_signal_handlers() {
|
||||
struct sigaction sa{}; sa.sa_handler = SIG_DFL;
|
||||
sigaction(SIGSEGV, &sa, nullptr); sigaction(SIGABRT, &sa, nullptr); sigaction(SIGFPE, &sa, nullptr); sigaction(SIGILL, &sa, nullptr);
|
||||
#ifdef SIGBUS
|
||||
sigaction(SIGBUS, &sa, nullptr);
|
||||
#endif
|
||||
g_crash_callback = nullptr;
|
||||
}
|
||||
} // namespace Void::Testing::Detail
|
||||
@@ -0,0 +1,64 @@
|
||||
#include <Void/Testing/Detail/Stacktrace.hpp>
|
||||
#include <Void/Testing/Detail/Color.hpp>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <format>
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
|
||||
#define BOOST_STACKTRACE_USE_BACKTRACE
|
||||
#include <boost/stacktrace.hpp>
|
||||
#include <boost/core/demangle.hpp>
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
|
||||
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::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();
|
||||
}
|
||||
|
||||
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); }
|
||||
} // namespace Void::Testing::Detail
|
||||
@@ -0,0 +1,63 @@
|
||||
#include <Void/Testing/Detail/Symbol.hpp>
|
||||
#include <filesystem>
|
||||
#include <algorithm>
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <dbghelp.h>
|
||||
#pragma comment(lib, "dbghelp.lib")
|
||||
#else
|
||||
#include <dlfcn.h>
|
||||
#ifdef __GNUC__
|
||||
#include <cxxabi.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace Void::Testing::Detail {
|
||||
|
||||
std::string resolve_symbol_name(const void* address) {
|
||||
#ifdef _WIN32
|
||||
static bool sym_initialized = false;
|
||||
if (!sym_initialized) { SymInitialize(GetCurrentProcess(), nullptr, TRUE); sym_initialized = true; }
|
||||
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
|
||||
auto* symbol = reinterpret_cast<SYMBOL_INFO*>(buffer);
|
||||
symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = MAX_SYM_NAME;
|
||||
DWORD64 displacement = 0;
|
||||
if (SymFromAddr(GetCurrentProcess(), reinterpret_cast<DWORD64>(address), &displacement, symbol)) return symbol->Name;
|
||||
return {};
|
||||
#else
|
||||
Dl_info info{}; if (dladdr(address, &info) && info.dli_sname) return info.dli_sname; return {};
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string demangle(std::string_view mangled) {
|
||||
if (mangled.empty()) return {};
|
||||
#ifdef _WIN32
|
||||
return std::string{mangled};
|
||||
#else
|
||||
#ifdef __GNUC__
|
||||
int status = 0; char* demangled = abi::__cxa_demangle(mangled.data(), nullptr, nullptr, &status);
|
||||
if (status == 0 && demangled) { std::string result{demangled}; std::free(demangled); return result; }
|
||||
return std::string{mangled};
|
||||
#else
|
||||
return std::string{mangled};
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string pretty_name(const void* address) { auto m = resolve_symbol_name(address); return m.empty() ? "" : demangle(m); }
|
||||
|
||||
std::string extract_test_name(std::string_view pretty_symbol) {
|
||||
if (pretty_symbol.empty()) return "<unnamed>";
|
||||
auto paren = pretty_symbol.find('(');
|
||||
std::string_view name_part = (paren != std::string_view::npos) ? pretty_symbol.substr(0, paren) : pretty_symbol;
|
||||
auto last_colon = name_part.rfind("::");
|
||||
if (last_colon != std::string_view::npos) name_part = name_part.substr(last_colon + 2);
|
||||
while (!name_part.empty() && name_part.front() == ' ') name_part.remove_prefix(1);
|
||||
while (!name_part.empty() && name_part.back() == ' ') name_part.remove_suffix(1);
|
||||
return std::string{name_part};
|
||||
}
|
||||
|
||||
std::string suite_from_file(std::string_view file_path) { return std::filesystem::path{file_path}.stem().string(); }
|
||||
} // namespace Void::Testing::Detail
|
||||
@@ -0,0 +1,8 @@
|
||||
void_add_module(Testing EXTERNAL_DEPS Boost::stacktrace_backtrace)
|
||||
|
||||
if(WIN32)
|
||||
target_link_libraries(Void_Testing PUBLIC dbghelp)
|
||||
else()
|
||||
target_link_libraries(Void_Testing PUBLIC dl)
|
||||
target_compile_options(Void_Testing PRIVATE -g -fno-omit-frame-pointer)
|
||||
endif()
|
||||
@@ -0,0 +1 @@
|
||||
void_add_module(TestingMock INTERNAL_DEPS Testing)
|
||||
+19
-24
@@ -1,53 +1,48 @@
|
||||
if(NOT VOID_ENABLE_TESTING)
|
||||
message("Tests disabled")
|
||||
return()
|
||||
endif()
|
||||
include(${CMAKE_SOURCE_DIR}/cmake/VoidTesting.cmake)
|
||||
|
||||
enable_testing()
|
||||
# Get the list of modules that were actually successfully created
|
||||
get_property(ACTIVE_MODULES GLOBAL PROPERTY VOID_MODULES)
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# PART 1: Internal "Kitchen Sink" Test (One Executable to rule them all)
|
||||
# PART 1: Internal kitchen-sink test (links every module).
|
||||
# ------------------------------------------------------------------------------
|
||||
file(GLOB_RECURSE INTERNAL_SOURCES CONFIGURE_DEPENDS "internal/*.cpp")
|
||||
|
||||
if(INTERNAL_SOURCES)
|
||||
add_executable(VoidInternalTests ${INTERNAL_SOURCES})
|
||||
|
||||
# Always link the Testing framework
|
||||
target_link_libraries(VoidInternalTests PRIVATE Void::Testing)
|
||||
|
||||
# Link against EVERY active module in the project
|
||||
foreach(mod ${ACTIVE_MODULES})
|
||||
# Avoid self-linking if Testing is in the list
|
||||
if(NOT mod STREQUAL "Testing")
|
||||
if(NOT mod STREQUAL "Testing" AND NOT mod STREQUAL "TestingMock")
|
||||
target_link_libraries(VoidInternalTests PRIVATE Void::${mod})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
add_test(NAME AllInternalTests COMMAND VoidInternalTests)
|
||||
if(TARGET Void::TestingMock)
|
||||
target_link_libraries(VoidInternalTests PRIVATE Void::TestingMock)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# PART 2: Standalone Tests (Isolated Executables per Module)
|
||||
# PART 2: Standalone tests — one executable per source file under
|
||||
# tests/standalone/<Module>/. Auto-scan picks each one up via the deferred
|
||||
# sweep registered by cmake/VoidTesting.cmake.
|
||||
# ------------------------------------------------------------------------------
|
||||
foreach(mod ${ACTIVE_MODULES})
|
||||
# Look for a subdirectory in standalone/ that matches the module name
|
||||
set(STANDALONE_MOD_DIR "${CMAKE_CURRENT_SOURCE_DIR}/standalone/${mod}")
|
||||
|
||||
|
||||
if(IS_DIRECTORY ${STANDALONE_MOD_DIR})
|
||||
file(GLOB test_files CONFIGURE_DEPENDS "${STANDALONE_MOD_DIR}/*.cpp")
|
||||
|
||||
|
||||
foreach(test_src ${test_files})
|
||||
get_filename_component(test_file_name ${test_src} NAME_WE)
|
||||
set(EXE_NAME "test_standalone_${mod}_${test_file_name}")
|
||||
|
||||
|
||||
add_executable(${EXE_NAME} ${test_src})
|
||||
# Only links against its specific module
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Void::${mod})
|
||||
|
||||
add_test(NAME ${EXE_NAME} COMMAND ${EXE_NAME})
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Void::Testing)
|
||||
if(NOT mod STREQUAL "Testing" AND NOT mod STREQUAL "TestingMock")
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Void::${mod})
|
||||
endif()
|
||||
if(TARGET Void::TestingMock)
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Void::TestingMock)
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
endforeach()
|
||||
@@ -1,427 +1,127 @@
|
||||
#include <Void/Logging/Logger.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Fixture.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Example
|
||||
namespace
|
||||
{
|
||||
|
||||
class FileLogger final : public Void::Logging::Logger
|
||||
{
|
||||
public:
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Construction / destruction
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// @param path Path to the log file (created or appended to).
|
||||
/// @param capacity Number of entries to buffer before
|
||||
/// auto-flushing.
|
||||
/// Defaults to 64 — tune to your I/O budget.
|
||||
explicit FileLogger(const std::filesystem::path& path,
|
||||
explicit FileLogger(const std::filesystem::path &path,
|
||||
std::size_t capacity = 64)
|
||||
: Logger(Void::Logging::Mode::Buffered, capacity),
|
||||
m_file(path,
|
||||
std::ios::app) // append so restarts don't truncate
|
||||
m_file(path, std::ios::app)
|
||||
{
|
||||
if (!m_file.is_open()) {
|
||||
throw std::runtime_error(std::format(
|
||||
"FileLogger: cannot open '{}'", path.string()));
|
||||
}
|
||||
|
||||
// Write a session separator so restarts are visible in the
|
||||
// file.
|
||||
m_file << "\n──────────────────────────────────────────────────"
|
||||
"──────\n"
|
||||
<< " Session started\n"
|
||||
<< "────────────────────────────────────────────────────"
|
||||
"────\n\n";
|
||||
m_file.flush();
|
||||
if (!m_file.is_open())
|
||||
throw std::runtime_error(
|
||||
std::format("FileLogger: cannot open '{}'",
|
||||
path.string()));
|
||||
}
|
||||
|
||||
/// Flush remaining buffered entries before the file handle is
|
||||
/// closed. IMPORTANT: always call flush() in the derived destructor
|
||||
/// — the base destructor cannot call pure-virtual write() safely.
|
||||
~FileLogger() noexcept override
|
||||
{
|
||||
flush(); // drains Logger's internal buffer → calls our
|
||||
// on_flush()
|
||||
~FileLogger() noexcept override { flush(); }
|
||||
|
||||
// Write a closing marker so the file makes sense when tailed
|
||||
// live.
|
||||
if (m_file.is_open()) {
|
||||
m_file << "\n──────────────────────────────────────────────"
|
||||
"──────────\n"
|
||||
<< " Session ended\n"
|
||||
<< "────────────────────────────────────────────────"
|
||||
"────────\n";
|
||||
m_file.flush();
|
||||
}
|
||||
}
|
||||
|
||||
// Not copyable or movable (file handle + non-movable base).
|
||||
FileLogger(const FileLogger&) = delete;
|
||||
FileLogger& operator=(const FileLogger&) = delete;
|
||||
FileLogger(FileLogger&&) = delete;
|
||||
FileLogger& operator=(FileLogger&&) = delete;
|
||||
FileLogger(const FileLogger &) = delete;
|
||||
FileLogger &operator=(const FileLogger &) = delete;
|
||||
FileLogger(FileLogger &&) = delete;
|
||||
FileLogger &operator=(FileLogger &&) = delete;
|
||||
|
||||
protected:
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// on_flush — batch write (preferred path)
|
||||
//
|
||||
// Called by Logger when the buffer reaches capacity or flush() is
|
||||
// called. All entries are formatted into a single std::string
|
||||
// before writing so we minimise the number of write() syscalls.
|
||||
// -------------------------------------------------------------------------
|
||||
void
|
||||
on_flush(std::span<const Void::Logging::Entry> entries) override
|
||||
void on_flush(
|
||||
std::span<const Void::Logging::Entry> entries) override
|
||||
{
|
||||
std::string batch;
|
||||
batch.reserve(entries.size() * 120); // rough estimate per entry
|
||||
|
||||
for (const auto& entry : entries) {
|
||||
format_entry(batch, entry);
|
||||
}
|
||||
|
||||
m_file.write(batch.data(),
|
||||
static_cast<std::streamsize>(batch.size()));
|
||||
m_file.flush(); // ensure OS buffers are flushed to disk
|
||||
for (const auto &e : entries)
|
||||
m_file << std::format("[{}] {}\n",
|
||||
Void::Logging::to_string(e.level),
|
||||
e.message);
|
||||
m_file.flush();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// write — single-entry path (Immediate mode, or base-class default
|
||||
// on_flush falls back here — we override on_flush so this is only
|
||||
// reached if someone calls set_mode(Immediate) at runtime).
|
||||
// -------------------------------------------------------------------------
|
||||
void write(const Void::Logging::Entry& entry) override
|
||||
void write(const Void::Logging::Entry &entry) override
|
||||
{
|
||||
std::string line;
|
||||
line.reserve(120);
|
||||
format_entry(line, entry);
|
||||
m_file.write(line.data(),
|
||||
static_cast<std::streamsize>(line.size()));
|
||||
m_file << std::format("[{}] {}\n",
|
||||
Void::Logging::to_string(entry.level),
|
||||
entry.message);
|
||||
m_file.flush();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Formatting helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// Append one formatted entry to `out`.
|
||||
static void format_entry(std::string& out,
|
||||
const Void::Logging::Entry& e)
|
||||
{
|
||||
using Void::Logging::Kind;
|
||||
|
||||
switch (e.kind) {
|
||||
case Kind::ScopeEnter:
|
||||
format_scope_enter(out, e);
|
||||
break;
|
||||
case Kind::ScopeExit:
|
||||
format_scope_exit(out, e);
|
||||
break;
|
||||
default:
|
||||
format_message(out, e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// "2025-06-01 14:32:00.123"
|
||||
static std::string
|
||||
format_timestamp(std::chrono::system_clock::time_point tp)
|
||||
{
|
||||
// Floor to milliseconds for readability.
|
||||
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
tp.time_since_epoch()) %
|
||||
1000;
|
||||
auto tt = std::chrono::system_clock::to_time_t(tp);
|
||||
std::tm tm{};
|
||||
#if defined(_WIN32)
|
||||
::localtime_s(&tm, &tt);
|
||||
#else
|
||||
::localtime_r(&tt, &tm);
|
||||
#endif
|
||||
return std::format("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec,
|
||||
ms.count());
|
||||
}
|
||||
|
||||
/// Build the indented scope prefix from entry.scopes.
|
||||
/// Each nesting level adds two spaces.
|
||||
static std::string scope_indent(const Void::Logging::Entry& e)
|
||||
{
|
||||
return std::string(e.scopes.size() * 2, ' ');
|
||||
}
|
||||
|
||||
/// Regular message:
|
||||
/// 2025-06-01 14:32:00.123 [INFO ] [network > tls] handshake
|
||||
/// complete
|
||||
static void format_message(std::string& out,
|
||||
const Void::Logging::Entry& e)
|
||||
{
|
||||
// Scope breadcrumb, e.g. "[network > tls]"
|
||||
std::string breadcrumb;
|
||||
if (!e.scopes.empty()) {
|
||||
breadcrumb = " [";
|
||||
for (std::size_t i = 0; i < e.scopes.size(); ++i) {
|
||||
if (i > 0) {
|
||||
breadcrumb += " > ";
|
||||
}
|
||||
breadcrumb += e.scopes[i];
|
||||
}
|
||||
breadcrumb += ']';
|
||||
}
|
||||
|
||||
std::format_to(std::back_inserter(out),
|
||||
"{} [{:<7}]{}{} {}\n",
|
||||
format_timestamp(e.timestamp),
|
||||
Void::Logging::to_string(e.level),
|
||||
breadcrumb,
|
||||
scope_indent(e),
|
||||
e.message);
|
||||
}
|
||||
|
||||
/// Scope enter:
|
||||
/// 2025-06-01 14:32:00.123 [TRACE ] ┌─ network
|
||||
static void format_scope_enter(std::string& out,
|
||||
const Void::Logging::Entry& e)
|
||||
{
|
||||
// The entering scope is already the last element of e.scopes.
|
||||
// Parent indent = (depth - 1) levels.
|
||||
std::size_t parent_depth =
|
||||
e.scopes.size() > 0 ? e.scopes.size() - 1 : 0;
|
||||
std::string indent(parent_depth * 2, ' ');
|
||||
|
||||
std::format_to(std::back_inserter(out),
|
||||
"{} [{:<7}] {}┌─ {}\n",
|
||||
format_timestamp(e.timestamp),
|
||||
Void::Logging::to_string(e.level),
|
||||
indent,
|
||||
e.message);
|
||||
}
|
||||
|
||||
/// Scope exit:
|
||||
/// 2025-06-01 14:32:00.123 [TRACE ] └─ network
|
||||
static void format_scope_exit(std::string& out,
|
||||
const Void::Logging::Entry& e)
|
||||
{
|
||||
std::size_t parent_depth =
|
||||
e.scopes.size() > 0 ? e.scopes.size() - 1 : 0;
|
||||
std::string indent(parent_depth * 2, ' ');
|
||||
|
||||
std::format_to(std::back_inserter(out),
|
||||
"{} [{:<7}] {}└─ {}\n",
|
||||
format_timestamp(e.timestamp),
|
||||
Void::Logging::to_string(e.level),
|
||||
indent,
|
||||
e.message);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Data
|
||||
// -------------------------------------------------------------------------
|
||||
std::ofstream m_file;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
} // namespace Example
|
||||
|
||||
// =============================================================================
|
||||
// main.cpp — FileLogger usage example
|
||||
//
|
||||
// Demonstrates:
|
||||
// 1. Basic buffered file logging
|
||||
// 2. push_scope() — RAII scope that annotates child entries AND emits
|
||||
// ScopeEnter / ScopeExit boundary entries
|
||||
// 3. scope() — lightweight marker pair (no stack mutation)
|
||||
// 4. Nested scopes — entries carry the full breadcrumb automatically
|
||||
// 5. Presets — bake in a level (and optional prefix), call with msg
|
||||
// 6. Formatted log calls with std::format-style args
|
||||
// 7. Level filtering — show how Debug entries are suppressed in production
|
||||
// 8. Manual flush — force a write mid-session without waiting for the
|
||||
// buffer to fill
|
||||
//
|
||||
// Expected output (app.log):
|
||||
// ──────────────────────────────────────────────────────
|
||||
// Session started
|
||||
// ──────────────────────────────────────────────────────
|
||||
//
|
||||
// 2025-06-01 14:32:00.001 [INFO ] Application starting up (v2.3.1)
|
||||
// 2025-06-01 14:32:00.002 [TRACE ] ┌─ network
|
||||
// 2025-06-01 14:32:00.003 [INFO ] [network] Resolving host: api.example.com
|
||||
// 2025-06-01 14:32:00.004 [DEBUG ] [network] Raw IP: 93.184.216.34
|
||||
// 2025-06-01 14:32:00.005 [TRACE ] ┌─ tls
|
||||
// 2025-06-01 14:32:00.006 [DEBUG ] [network > tls] Cipher:
|
||||
// TLS_AES_256_GCM_SHA384 2025-06-01 14:32:00.007 [INFO ] [network > tls]
|
||||
// Handshake complete 2025-06-01 14:32:00.008 [TRACE ] └─ tls 2025-06-01
|
||||
// 14:32:00.009 [INFO ] [network] Connected — 42 ms 2025-06-01 14:32:00.010
|
||||
// [TRACE ] └─ network 2025-06-01 14:32:00.011 [TRACE ] ┌─ render 2025-06-01
|
||||
// 14:32:00.012 [TRACE ] └─ render 2025-06-01 14:32:00.013 [INFO ] All
|
||||
// systems nominal 2025-06-01 14:32:00.014 [ERROR ] [db] Query failed: timeout
|
||||
// after 5000 ms 2025-06-01 14:32:00.015 [WARN ] [db] Retrying (attempt 2 of
|
||||
// 3) 2025-06-01 14:32:00.016 [FATAL ] [db] Unrecoverable: connection pool
|
||||
// exhausted
|
||||
//
|
||||
// ──────────────────────────────────────────────────────
|
||||
// Session ended
|
||||
// ──────────────────────────────────────────────────────
|
||||
// =============================================================================
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Simulated subsystem functions — each receives the logger by reference.
|
||||
// Real code would inject it via a constructor or service locator.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Simulates a TLS handshake — demonstrates a nested scope.
|
||||
void do_tls_handshake(Void::Logging::Logger& log)
|
||||
class FileLoggerTests : public Void::Testing::Fixture
|
||||
{
|
||||
// push_scope: "tls" is pushed onto the thread-local stack.
|
||||
// All entries logged inside this block carry scopes = {"network", "tls"}.
|
||||
// A ScopeEnter entry is emitted here; ScopeExit fires on scope destruction.
|
||||
auto tls_scope = log.push_scope("tls", Void::Logging::Level::Trace);
|
||||
public:
|
||||
|
||||
log.debug("Cipher: TLS_AES_256_GCM_SHA384");
|
||||
log.info("Handshake complete");
|
||||
// ← ScopeExit "tls" emitted here automatically
|
||||
}
|
||||
std::filesystem::path path;
|
||||
|
||||
/// Simulates a network connection — demonstrates scope with a nested call.
|
||||
void connect(Void::Logging::Logger& log, std::string_view host)
|
||||
{
|
||||
// Outer RAII scope — annotates every entry logged inside this function
|
||||
// and inside any function called from here (e.g. do_tls_handshake).
|
||||
auto net_scope = log.push_scope("network", Void::Logging::Level::Trace);
|
||||
void setup() override
|
||||
{
|
||||
path = std::filesystem::temp_directory_path()
|
||||
/ "void_filelogger_test.log";
|
||||
std::filesystem::remove(path);
|
||||
}
|
||||
|
||||
log.info("Resolving host: {}", host);
|
||||
log.debug("Raw IP: 93.184.216.34");
|
||||
void teardown() override { std::filesystem::remove(path); }
|
||||
|
||||
do_tls_handshake(log);
|
||||
Void::Testing::Test creates_file()
|
||||
{
|
||||
{
|
||||
FileLogger log(path);
|
||||
log.info("hello");
|
||||
}
|
||||
Void::Testing::expect(std::filesystem::exists(path));
|
||||
}
|
||||
|
||||
// Pretend the connection took 42 ms.
|
||||
log.info("Connected — 42 ms");
|
||||
Void::Testing::Test writes_messages()
|
||||
{
|
||||
{
|
||||
FileLogger log(path, /*capacity=*/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);
|
||||
}
|
||||
|
||||
// ← ScopeExit "network" emitted here automatically
|
||||
}
|
||||
Void::Testing::Test level_filtering()
|
||||
{
|
||||
{
|
||||
FileLogger log(path, /*capacity=*/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);
|
||||
}
|
||||
|
||||
/// Simulates a render pass — demonstrates the lightweight scope() call.
|
||||
/// scope() emits ScopeEnter+ScopeExit immediately but does NOT push onto the
|
||||
/// scope stack, so entries inside the block are NOT annotated with a
|
||||
/// breadcrumb. Use this when you only want visual delimiters in the log, not
|
||||
/// full annotation.
|
||||
void render_frame(Void::Logging::Logger& log)
|
||||
{
|
||||
// Emits "┌─ render" then "└─ render" immediately — no stack change.
|
||||
log.scope("render", Void::Logging::Level::Trace);
|
||||
|
||||
// This entry has no scope breadcrumb because the stack was not modified.
|
||||
// (Uncomment to observe the difference vs push_scope.)
|
||||
// log.debug("Drawing {} triangles", 14'200);
|
||||
}
|
||||
|
||||
/// Simulates a database subsystem — demonstrates Preset usage.
|
||||
void database_operations(Void::Logging::Logger& log)
|
||||
{
|
||||
// Presets bake in the level (and an optional prefix string).
|
||||
// Useful when a subsystem always logs at the same level, or when you want
|
||||
// a consistent tag without scoping the stack.
|
||||
auto db_err = log.make_preset(Void::Logging::Level::Error, "[db] ");
|
||||
auto db_warn = log.make_preset(Void::Logging::Level::Warning, "[db] ");
|
||||
auto db_fatal = log.make_preset(Void::Logging::Level::Fatal, "[db] ");
|
||||
|
||||
// Call exactly like a function — source location captured transparently.
|
||||
db_err("Query failed: timeout after {} ms", 5000);
|
||||
db_warn("Retrying (attempt {} of {})", 2, 3);
|
||||
db_fatal("Unrecoverable: connection pool exhausted");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// main
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
int main()
|
||||
{
|
||||
// -----------------------------------------------------------------------
|
||||
// 1. Construct the logger
|
||||
// Mode::Buffered with capacity=8 means entries are held until 8 have
|
||||
// accumulated, then the whole batch is written to disk at once.
|
||||
// A capacity of 8 is tiny — chosen here so the auto-flush triggers
|
||||
// visibly during the example. Real code would use 64–512.
|
||||
// -----------------------------------------------------------------------
|
||||
Example::FileLogger log("app.log", /*capacity=*/8);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 2. Set the minimum level.
|
||||
// Level::Debug — Debug + Info + Warning + Error + Fatal are written.
|
||||
// Level::Trace entries (scope boundaries) are written too because the
|
||||
// default is Trace; if you raise this to Info, scope markers disappear.
|
||||
// -----------------------------------------------------------------------
|
||||
log.set_level(Void::Logging::Level::Trace);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 3. Plain log calls — no scope, no format args
|
||||
// -----------------------------------------------------------------------
|
||||
log.info("Application starting up (v2.3.1)");
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 4. RAII scopes with nested child scope
|
||||
// connect() pushes "network"; inside it do_tls_handshake() pushes
|
||||
// "tls". Every entry logged inside those functions carries the
|
||||
// breadcrumb automatically — no extra work at the call site.
|
||||
// -----------------------------------------------------------------------
|
||||
connect(log, "api.example.com");
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 5. Lightweight scope marker (no stack mutation)
|
||||
// render_frame() calls log.scope("render") which emits Enter+Exit
|
||||
// immediately. Entries inside the function body are NOT annotated.
|
||||
// -----------------------------------------------------------------------
|
||||
render_frame(log);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 6. Manual flush — useful after a critical startup phase to ensure the
|
||||
// log is on disk before entering the main loop.
|
||||
// -----------------------------------------------------------------------
|
||||
log.flush();
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 7. Info after the flush — will go into a fresh buffer.
|
||||
// -----------------------------------------------------------------------
|
||||
log.info("All systems nominal");
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 8. Presets — fixed level + prefix, variable message
|
||||
// -----------------------------------------------------------------------
|
||||
database_operations(log);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 9. Level filtering demo (commented out by default)
|
||||
//
|
||||
// Raise the level to Info — subsequent Debug/Trace calls are dropped
|
||||
// before they even enter the buffer.
|
||||
// -----------------------------------------------------------------------
|
||||
// log.set_level(Void::Logging::Level::Info);
|
||||
// log.debug("This will be silently dropped");
|
||||
// log.info("But this will appear");
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 10. FileLogger destructor calls flush() — remaining buffered entries
|
||||
// are written to disk here before the file handle closes.
|
||||
// -----------------------------------------------------------------------
|
||||
std::cout << "Done. Check app.log.\n";
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
Void::Testing::Test buffered_flush()
|
||||
{
|
||||
{
|
||||
FileLogger log(path, /*capacity=*/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);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Fixture.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
class VectorFixture : public Void::Testing::Fixture
|
||||
{
|
||||
public:
|
||||
|
||||
std::vector<int> vec;
|
||||
|
||||
void setup() override { vec = {1, 2, 3}; }
|
||||
void teardown() override { vec.clear(); }
|
||||
|
||||
Void::Testing::Test size()
|
||||
{
|
||||
Void::Testing::expect_eq(vec.size(), 3u);
|
||||
}
|
||||
|
||||
// @tag slow
|
||||
Void::Testing::Test push_back()
|
||||
{
|
||||
vec.push_back(4);
|
||||
Void::Testing::expect_eq(vec.size(), 4u);
|
||||
Void::Testing::expect_eq(vec.back(), 4);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
Void::Testing::Test addition()
|
||||
{
|
||||
int a = 1 + 1;
|
||||
Void::Testing::expect_eq(a, 2);
|
||||
}
|
||||
|
||||
// @tag integration, database
|
||||
Void::Testing::Test db_query() { Void::Testing::expect(true); }
|
||||
|
||||
// @skip "Feature #42 not implemented"
|
||||
Void::Testing::DisabledTest broken_feature()
|
||||
{
|
||||
Void::Testing::fail("this is not ready yet");
|
||||
}
|
||||
|
||||
// @skip not ready yet
|
||||
Void::Testing::DisabledTest unquoted_skip()
|
||||
{
|
||||
Void::Testing::fail("must not run");
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/TestingMock/Mock.hpp>
|
||||
#include <Void/TestingMock/MockFunction.hpp>
|
||||
|
||||
#include <string_view>
|
||||
|
||||
struct Database
|
||||
{
|
||||
virtual ~Database() = default;
|
||||
virtual int get_user_id(std::string_view name) = 0;
|
||||
};
|
||||
|
||||
class MockDatabase : public Void::TestingMock::Mock<MockDatabase>,
|
||||
public Database
|
||||
{
|
||||
public:
|
||||
|
||||
Void::TestingMock::MockFunction<int(std::string_view)>
|
||||
get_user_id_mock{"get_user_id"};
|
||||
|
||||
int get_user_id(std::string_view name) override
|
||||
{
|
||||
return get_user_id_mock(name);
|
||||
}
|
||||
};
|
||||
|
||||
// @tag mock
|
||||
Void::Testing::Test mock_database()
|
||||
{
|
||||
using namespace Void::TestingMock;
|
||||
MockDatabase db;
|
||||
db.get_user_id_mock.expect(Eq<std::string_view>("alice")).returns(42);
|
||||
db.get_user_id_mock.expect(_<std::string_view>()).returns(-1);
|
||||
Void::Testing::expect_eq(db.get_user_id("alice"), 42);
|
||||
Void::Testing::expect_eq(db.get_user_id("bob"), -1);
|
||||
}
|
||||
Reference in new issue
Block a user