diff --git a/.gitignore b/.gitignore index 378eac2..7dde1b5 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ build +CLAUDE.md diff --git a/CMakeLists.txt b/CMakeLists.txt index c02d781..869189a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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}" ) diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index 48c2843..d0abe87 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -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) diff --git a/cmake/Module.cmake b/cmake/Module.cmake index 0233235..d893bc1 100644 --- a/cmake/Module.cmake +++ b/cmake/Module.cmake @@ -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} diff --git a/cmake/VoidConfig.cmake.in b/cmake/VoidConfig.cmake.in index 481e13f..019561e 100644 --- a/cmake/VoidConfig.cmake.in +++ b/cmake/VoidConfig.cmake.in @@ -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@") diff --git a/cmake/VoidTestScanner.cmake b/cmake/VoidTestScanner.cmake new file mode 100644 index 0000000..bc158da --- /dev/null +++ b/cmake/VoidTestScanner.cmake @@ -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${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${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 \n" + "#include \n" + "#include \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" +) diff --git a/cmake/VoidTesting.cmake b/cmake/VoidTesting.cmake new file mode 100644 index 0000000..734d3ae --- /dev/null +++ b/cmake/VoidTesting.cmake @@ -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 if 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 . 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 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() diff --git a/include/Void/Testing/Assert.hpp b/include/Void/Testing/Assert.hpp new file mode 100644 index 0000000..b30f8c9 --- /dev/null +++ b/include/Void/Testing/Assert.hpp @@ -0,0 +1,82 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 +std::string repr(const T& val) { + if constexpr (std::is_same_v, bool>) return val ? "true" : "false"; + else if constexpr (std::is_same_v, std::string> || std::is_same_v, std::string_view>) return std::format("\"{}\"", val); + else if constexpr (std::is_null_pointer_v>) return "nullptr"; + else if constexpr (requires { std::format("{}", val); }) return std::format("{}", val); + else return ""; +} + +void handle_assertion(AssertionResult result); + +struct RequireFailure : std::runtime_error { + using std::runtime_error::runtime_error; +}; +} // namespace Void::Testing::Detail + +namespace Void::Testing { + +template requires std::convertible_to +void expect(T&& condition, std::source_location loc = std::source_location::current()) { + AssertionResult result; result.passed = static_cast(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 requires std::convertible_to +void require(T&& condition, std::source_location loc = std::source_location::current()) { + AssertionResult result; result.passed = static_cast(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 requires std::equality_comparable_with +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 requires std::equality_comparable_with +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 requires std::equality_comparable_with +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 requires std::invocable +void expect_throw(Fn&& fn, std::source_location loc = std::source_location::current()) { + bool threw = false; try { std::forward(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 requires std::invocable +void expect_nothrow(Fn&& fn, std::source_location loc = std::source_location::current()) { + bool threw = false; try { std::forward(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 diff --git a/include/Void/Testing/Config.hpp b/include/Void/Testing/Config.hpp new file mode 100644 index 0000000..fc7d4a7 --- /dev/null +++ b/include/Void/Testing/Config.hpp @@ -0,0 +1,90 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 run; + std::string name; + std::string suite; + std::string file; + int line{0}; + bool disabled{false}; + std::string skip_reason; + std::vector tags; + std::function fixture_create; + std::function fixture_destroy; + std::function fixture_setup; + std::function fixture_teardown; + }; + + struct TestResult { + std::string name; + std::string suite; + TestState state{TestState::Passed}; + std::chrono::nanoseconds duration{0}; + std::vector assertions; + std::string skip_reason; + std::string crash_info; + std::string stacktrace; + std::vector tags; + }; + + struct SuiteResult { + std::string name; + std::vector tests; + }; + + struct RunResult { + std::vector 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 diff --git a/include/Void/Testing/ConsoleReporter.hpp b/include/Void/Testing/ConsoleReporter.hpp new file mode 100644 index 0000000..41de3ca --- /dev/null +++ b/include/Void/Testing/ConsoleReporter.hpp @@ -0,0 +1,23 @@ +#pragma once +#include +#include +#include + +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 diff --git a/include/Void/Testing/Detail/Color.hpp b/include/Void/Testing/Detail/Color.hpp new file mode 100644 index 0000000..735d31f --- /dev/null +++ b/include/Void/Testing/Detail/Color.hpp @@ -0,0 +1,34 @@ +#pragma once +#include +#include + +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 diff --git a/include/Void/Testing/Detail/Registrar.hpp b/include/Void/Testing/Detail/Registrar.hpp new file mode 100644 index 0000000..8669d6b --- /dev/null +++ b/include/Void/Testing/Detail/Registrar.hpp @@ -0,0 +1,107 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace Void::Testing::Detail { + +template +struct function_traits; + +template +struct function_traits { + using return_type = R; + using class_type = void; + static constexpr bool is_member = false; +}; + +template +struct function_traits { + using return_type = R; + using class_type = C; + static constexpr bool is_member = true; +}; + +template +struct function_traits { + using return_type = R; + using class_type = C; + static constexpr bool is_member = true; +}; + +template +class test_registrar { +public: + explicit test_registrar(const char* suite, const char* file, int line, + const char* test_name_str, + std::vector 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) { + using Class = typename function_traits::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(p); }, + .fixture_setup = [](void* p) { + if constexpr (requires { static_cast(p)->setup(); }) + static_cast(p)->setup(); + }, + .fixture_teardown = [](void* p) { + if constexpr (requires { static_cast(p)->teardown(); }) + static_cast(p)->teardown(); + } + }); + + const_cast(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(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 +Detail::test_registrar test{}; +} // namespace Void::Testing diff --git a/include/Void/Testing/Detail/Registry.hpp b/include/Void/Testing/Detail/Registry.hpp new file mode 100644 index 0000000..138198a --- /dev/null +++ b/include/Void/Testing/Detail/Registry.hpp @@ -0,0 +1,25 @@ +#pragma once +#include +#include +#include +#include +#include + +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& tests() const { return tests_; } +private: + Registry() = default; + std::vector tests_; + std::mutex mutex_; +}; +} // namespace Void::Testing::Detail diff --git a/include/Void/Testing/Detail/SignalHandler.hpp b/include/Void/Testing/Detail/SignalHandler.hpp new file mode 100644 index 0000000..9f70e71 --- /dev/null +++ b/include/Void/Testing/Detail/SignalHandler.hpp @@ -0,0 +1,19 @@ +#pragma once +#include +#include + +#ifndef _WIN32 +#include +#endif + +namespace Void::Testing::Detail { +using CrashCallback = std::function; +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 diff --git a/include/Void/Testing/Detail/Stacktrace.hpp b/include/Void/Testing/Detail/Stacktrace.hpp new file mode 100644 index 0000000..ba55890 --- /dev/null +++ b/include/Void/Testing/Detail/Stacktrace.hpp @@ -0,0 +1,18 @@ +#pragma once +#include +#include +#include + +namespace Void::Testing::Detail { +struct StackFrame { + std::string function_name; + std::string source_file; + int source_line{0}; + std::string source_snippet; +}; + +std::vector 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& frames); +void print_stacktrace(std::ostream& os, const std::vector& frames); +} // namespace Void::Testing::Detail diff --git a/include/Void/Testing/Detail/Symbol.hpp b/include/Void/Testing/Detail/Symbol.hpp new file mode 100644 index 0000000..0178104 --- /dev/null +++ b/include/Void/Testing/Detail/Symbol.hpp @@ -0,0 +1,11 @@ +#pragma once +#include +#include + +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 diff --git a/include/Void/Testing/Fixture.hpp b/include/Void/Testing/Fixture.hpp new file mode 100644 index 0000000..385078f --- /dev/null +++ b/include/Void/Testing/Fixture.hpp @@ -0,0 +1,10 @@ +#pragma once + +namespace Void::Testing { +class Fixture { +public: + virtual ~Fixture() = default; + virtual void setup() {} + virtual void teardown() {} +}; +} // namespace Void::Testing diff --git a/include/Void/Testing/JUnitReporter.hpp b/include/Void/Testing/JUnitReporter.hpp new file mode 100644 index 0000000..70bc443 --- /dev/null +++ b/include/Void/Testing/JUnitReporter.hpp @@ -0,0 +1,20 @@ +#pragma once +#include +#include + +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 suite_results_; + static std::string xml_escape(std::string_view s); +}; +} // namespace Void::Testing diff --git a/include/Void/Testing/Manager.hpp b/include/Void/Testing/Manager.hpp deleted file mode 100644 index 6f70f09..0000000 --- a/include/Void/Testing/Manager.hpp +++ /dev/null @@ -1 +0,0 @@ -#pragma once diff --git a/include/Void/Testing/Reporter.hpp b/include/Void/Testing/Reporter.hpp new file mode 100644 index 0000000..ed77405 --- /dev/null +++ b/include/Void/Testing/Reporter.hpp @@ -0,0 +1,17 @@ +#pragma once +#include +#include +#include + +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 diff --git a/include/Void/Testing/Runner.hpp b/include/Void/Testing/Runner.hpp new file mode 100644 index 0000000..abc8830 --- /dev/null +++ b/include/Void/Testing/Runner.hpp @@ -0,0 +1,23 @@ +#pragma once +#include +#include +#include + +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 filter_tests(const std::vector& tests, const RunConfig& config); + std::unique_ptr create_reporter(const RunConfig& config); + TestResult execute_test(TestCase& test_case); + void run_test_body(TestCase& test_case, TestResult& result); +}; +} // namespace Void::Testing diff --git a/include/Void/Testing/Test.hpp b/include/Void/Testing/Test.hpp new file mode 100644 index 0000000..28c0544 --- /dev/null +++ b/include/Void/Testing/Test.hpp @@ -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. +using Test = void; +using DisabledTest = void; + +} // namespace Void::Testing diff --git a/include/Void/TestingMock/Expectation.hpp b/include/Void/TestingMock/Expectation.hpp new file mode 100644 index 0000000..43bb11d --- /dev/null +++ b/include/Void/TestingMock/Expectation.hpp @@ -0,0 +1,33 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace Void::TestingMock::Detail { + +template class Expectation; + +template +class Expectation { +public: + using MatcherTuple = std::tuple>...>; + using Action = std::function; + 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{}); } + 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 bool match_impl(Args... args, std::index_sequence) const { return (std::get(matchers_).matches(args) && ...); } +}; +} // namespace Void::TestingMock::Detail diff --git a/include/Void/TestingMock/Matcher.hpp b/include/Void/TestingMock/Matcher.hpp new file mode 100644 index 0000000..ce0cff2 --- /dev/null +++ b/include/Void/TestingMock/Matcher.hpp @@ -0,0 +1,25 @@ +#pragma once +#include +#include +#include +#include + +namespace Void::TestingMock { +template class Matcher { public: virtual ~Matcher() = default; virtual bool matches(const T& value) const = 0; virtual std::string describe() const = 0; }; +template class EqMatcher : public Matcher { 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 class AnyMatcher : public Matcher { public: bool matches(const T&) const override { return true; } std::string describe() const override { return "_"; } }; + +template auto Eq(T v) { return std::make_unique>(std::move(v)); } +template auto _() { return std::make_unique>(); } + +template +class MatcherHolder { + std::unique_ptr> matcher_; +public: + MatcherHolder() : matcher_(std::make_unique>()) {} + MatcherHolder(std::unique_ptr> m) : matcher_(std::move(m)) {} + MatcherHolder(T exact_value) : matcher_(std::make_unique>(std::move(exact_value))) {} + bool matches(const T& v) const { return matcher_->matches(v); } + std::string describe() const { return matcher_->describe(); } +}; +} // namespace Void::TestingMock diff --git a/include/Void/TestingMock/Mock.hpp b/include/Void/TestingMock/Mock.hpp new file mode 100644 index 0000000..9c2240c --- /dev/null +++ b/include/Void/TestingMock/Mock.hpp @@ -0,0 +1,10 @@ +#pragma once +#include +namespace Void::TestingMock { +template +class Mock { +public: + Mock() = default; virtual ~Mock() = default; + void verify_all() {} +}; +} // namespace Void::TestingMock diff --git a/include/Void/TestingMock/MockFunction.hpp b/include/Void/TestingMock/MockFunction.hpp new file mode 100644 index 0000000..0d2805c --- /dev/null +++ b/include/Void/TestingMock/MockFunction.hpp @@ -0,0 +1,73 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace Void::TestingMock +{ + + template class MockFunction; + + template class MockFunction + { + using Expectation = Detail::Expectation; + + public: + + explicit MockFunction(std::string name = "unnamed_mock") + : name_(std::move(name)) + { + } + ~MockFunction() { verify(); } + + template + Expectation& expect(std::source_location loc, MArgs&&... matchers) + { + auto exp = std::make_shared( + typename Expectation::MatcherTuple{ + MatcherHolder>( + std::forward(matchers))...}, + loc); + expectations_.push_back(exp); + return *exp; + } + + template + Expectation& expect(MArgs&&... matchers) + { + return expect(std::source_location::current(), + std::forward(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) { + return R{}; + } + } + void verify() + { + for (auto& exp : expectations_) { + exp->verify(name_); + } + expectations_.clear(); + } + + private: + + std::string name_; + std::vector> expectations_; + std::mutex mutex_; + }; +} // namespace Void::TestingMock diff --git a/src/Testing/Assert.cpp b/src/Testing/Assert.cpp new file mode 100644 index 0000000..279cf65 --- /dev/null +++ b/src/Testing/Assert.cpp @@ -0,0 +1,18 @@ +#include +#include +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 diff --git a/src/Testing/ConsoleReporter.cpp b/src/Testing/ConsoleReporter.cpp new file mode 100644 index 0000000..e7d327f --- /dev/null +++ b/src/Testing/ConsoleReporter.cpp @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include +#include + +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(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(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 diff --git a/src/Testing/JUnitReporter.cpp b/src/Testing/JUnitReporter.cpp new file mode 100644 index 0000000..8df851b --- /dev/null +++ b/src/Testing/JUnitReporter.cpp @@ -0,0 +1,35 @@ +#include +#include +#include + +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(result.total_duration).count(); + os_ << "\n\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(t.duration).count(); + os_ << " \n"; + for (const auto& test : suite.tests) { + double tt = std::chrono::duration(test.duration).count(); + os_ << " \n \n \n"; + else if (test.state == TestState::Failed) { os_ << ">\n"; for (const auto& ar : test.assertions) if(!ar.passed) os_ << " \n"; os_ << " \n"; } + else if (test.state == TestState::Crashed) os_ << ">\n \n \n"; + else os_ << "/>\n"; + } + os_ << " \n"; + } + os_ << "\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 diff --git a/src/Testing/Main.cpp b/src/Testing/Main.cpp new file mode 100644 index 0000000..0841c93 --- /dev/null +++ b/src/Testing/Main.cpp @@ -0,0 +1,2 @@ +#include +int main(int argc, char** argv) { return Void::Testing::Runner::instance().main(argc, argv); } diff --git a/src/Testing/Registry.cpp b/src/Testing/Registry.cpp new file mode 100644 index 0000000..4d85b11 --- /dev/null +++ b/src/Testing/Registry.cpp @@ -0,0 +1,2 @@ +#include +namespace Void::Testing::Detail {} diff --git a/src/Testing/Runner.cpp b/src/Testing/Runner.cpp new file mode 100644 index 0000000..4f8f525 --- /dev/null +++ b/src/Testing/Runner.cpp @@ -0,0 +1,355 @@ +#include +#include "Void/Testing/Config.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(std::stoul(val)); + } else if (arg == "--repeat") { + config.repeat = static_cast(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 + Runner::filter_tests(const std::vector& tests, + const RunConfig& config) + { + std::vector 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 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(file); + } + return std::make_unique(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, "") << " " + << apply(dim, "[options]") << "\n" + << "\n" + << " " << apply(bold_white, "OPTIONS:") << "\n" + << " " << apply(green, "--filter ") + << apply(dim, "Run tests matching the regex pattern") << "\n" + << " " << apply(green, "--suite ") + << apply(dim, "Run only tests in the specified suite") << "\n" + << " " << apply(green, "--tag ") + << 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 ") + << apply(dim, "Set the random seed (implies --shuffle)") << "\n" + << " " << apply(green, "--repeat ") + << apply(dim, "Repeat the test run n times") << "\n" + << " " << apply(green, "--reporter ") + << apply(dim, "Choose the output reporter: console, junit") + << "\n" + << " " << apply(green, "--output ") + << 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(tests.size())); + if (config.shuffle) { + std::shuffle(tests.begin(), tests.end(), + std::mt19937{config.random_seed}); + } + + std::vector suite_results; + std::unordered_map 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 diff --git a/src/Testing/SignalHandler.cpp b/src/Testing/SignalHandler.cpp new file mode 100644 index 0000000..d05cbd7 --- /dev/null +++ b/src/Testing/SignalHandler.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +#include + +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 diff --git a/src/Testing/Stacktrace.cpp b/src/Testing/Stacktrace.cpp new file mode 100644 index 0000000..b4b8f6a --- /dev/null +++ b/src/Testing/Stacktrace.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include +#include +#include +#include + +#define BOOST_STACKTRACE_USE_BACKTRACE +#include +#include + +namespace Void::Testing::Detail { + +std::vector capture_stacktrace(unsigned skip_frames, unsigned max_frames) { + std::vector 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& frames) { + if (frames.empty()) return " \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 << ""; + 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& frames) { os << format_stacktrace(frames); } +} // namespace Void::Testing::Detail diff --git a/src/Testing/Symbol.cpp b/src/Testing/Symbol.cpp new file mode 100644 index 0000000..ed1a83f --- /dev/null +++ b/src/Testing/Symbol.cpp @@ -0,0 +1,63 @@ +#include +#include +#include + +#ifdef _WIN32 + #define WIN32_LEAN_AND_MEAN + #include + #include + #pragma comment(lib, "dbghelp.lib") +#else + #include + #ifdef __GNUC__ + #include + #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(buffer); + symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = MAX_SYM_NAME; + DWORD64 displacement = 0; + if (SymFromAddr(GetCurrentProcess(), reinterpret_cast(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 ""; + 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 diff --git a/src/Testing/module.cmake b/src/Testing/module.cmake new file mode 100644 index 0000000..c94734e --- /dev/null +++ b/src/Testing/module.cmake @@ -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() diff --git a/src/TestingMock/module.cmake b/src/TestingMock/module.cmake new file mode 100644 index 0000000..5465836 --- /dev/null +++ b/src/TestingMock/module.cmake @@ -0,0 +1 @@ +void_add_module(TestingMock INTERNAL_DEPS Testing) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index af34e87..e886798 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -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//. 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() diff --git a/tests/standalone/Logging/FileLogger.cpp b/tests/standalone/Logging/FileLogger.cpp index 4365b17..8c398de 100644 --- a/tests/standalone/Logging/FileLogger.cpp +++ b/tests/standalone/Logging/FileLogger.cpp @@ -1,427 +1,127 @@ #include +#include +#include +#include -#include #include #include #include #include #include #include -#include -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 entries) override + void on_flush( + std::span 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(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(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( - 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 -#include -#include -#include -#include - -// --------------------------------------------------------------------------- -// 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(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(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(f)), {}); + Void::Testing::expect(content.find("entry 4") + != std::string::npos); + } +}; diff --git a/tests/standalone/Testing/ContainerFixture.cpp b/tests/standalone/Testing/ContainerFixture.cpp new file mode 100644 index 0000000..b93d469 --- /dev/null +++ b/tests/standalone/Testing/ContainerFixture.cpp @@ -0,0 +1,28 @@ +#include +#include +#include + +#include + +class VectorFixture : public Void::Testing::Fixture +{ + public: + + std::vector 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); + } +}; diff --git a/tests/standalone/Testing/Math.cpp b/tests/standalone/Testing/Math.cpp new file mode 100644 index 0000000..e86f3d1 --- /dev/null +++ b/tests/standalone/Testing/Math.cpp @@ -0,0 +1,23 @@ +#include +#include + +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"); +} diff --git a/tests/standalone/TestingMock/Mock.cpp b/tests/standalone/TestingMock/Mock.cpp new file mode 100644 index 0000000..dfac966 --- /dev/null +++ b/tests/standalone/TestingMock/Mock.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +#include + +struct Database +{ + virtual ~Database() = default; + virtual int get_user_id(std::string_view name) = 0; +}; + +class MockDatabase : public Void::TestingMock::Mock, + public Database +{ + public: + + Void::TestingMock::MockFunction + 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("alice")).returns(42); + db.get_user_id_mock.expect(_()).returns(-1); + Void::Testing::expect_eq(db.get_user_id("alice"), 42); + Void::Testing::expect_eq(db.get_user_id("bob"), -1); +}