From 3ee2dd1186c3c754313ce1a666466216ee9159ff Mon Sep 17 00:00:00 2001 From: Gabriel Ionita Date: Mon, 27 Oct 2025 13:30:00 +0100 Subject: [PATCH] add Symbol class unit tests --- tests/test_symbol.cpp | 99 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 tests/test_symbol.cpp diff --git a/tests/test_symbol.cpp b/tests/test_symbol.cpp new file mode 100644 index 0000000..3fc4467 --- /dev/null +++ b/tests/test_symbol.cpp @@ -0,0 +1,99 @@ +#include +#include "../src/symbol.hpp" +#include +#include +#include + +TEST_CASE("VarInfo struct construction", "[symbol]") { + VarInfo info{"test_var", 0x1000, 4}; + + REQUIRE(info.name == "test_var"); + REQUIRE(info.address == 0x1000); + REQUIRE(info.size == 4); +} + +TEST_CASE("VarInfo struct with different sizes", "[symbol]") { + SECTION("1 byte variable") { + VarInfo info{"char_var", 0x2000, 1}; + REQUIRE(info.size == 1); + } + + SECTION("2 byte variable") { + VarInfo info{"short_var", 0x2000, 2}; + REQUIRE(info.size == 2); + } + + SECTION("4 byte variable") { + VarInfo info{"int_var", 0x2000, 4}; + REQUIRE(info.size == 4); + } + + SECTION("8 byte variable") { + VarInfo info{"long_var", 0x2000, 8}; + REQUIRE(info.size == 8); + } +} + +TEST_CASE("Symbol class finds global variables in test binary", "[symbol][integration]") { + // Use the test_access binary if it exists + std::filesystem::path test_binary = "./test_access"; + + if (!std::filesystem::exists(test_binary)) { + WARN("test_access binary not found, skipping integration test"); + return; + } + + int fd = open(test_binary.c_str(), O_RDONLY); + REQUIRE(fd >= 0); + + Dwarf_Debug dbg = nullptr; + Dwarf_Error err; + int res = dwarf_init_b(fd, DW_GROUPNUMBER_ANY, nullptr, nullptr, &dbg, &err); + + if (res != DW_DLV_OK) { + close(fd); + WARN("Failed to initialize DWARF for test_access, skipping test"); + return; + } + + Symbol symbol; + auto var_info = symbol.find_global_var(dbg, "global_counter"); + + dwarf_finish(dbg); + close(fd); + + REQUIRE(var_info.has_value()); + REQUIRE(var_info->name == "global_counter"); + REQUIRE(var_info->size > 0); + REQUIRE(var_info->size <= 8); +} + +TEST_CASE("Symbol class returns nullopt for non-existent variable", "[symbol][integration]") { + std::filesystem::path test_binary = "./test_access"; + + if (!std::filesystem::exists(test_binary)) { + WARN("test_access binary not found, skipping integration test"); + return; + } + + int fd = open(test_binary.c_str(), O_RDONLY); + REQUIRE(fd >= 0); + + Dwarf_Debug dbg = nullptr; + Dwarf_Error err; + int res = dwarf_init_b(fd, DW_GROUPNUMBER_ANY, nullptr, nullptr, &dbg, &err); + + if (res != DW_DLV_OK) { + close(fd); + WARN("Failed to initialize DWARF for test_access, skipping test"); + return; + } + + Symbol symbol; + auto var_info = symbol.find_global_var(dbg, "nonexistent_variable_xyz"); + + dwarf_finish(dbg); + close(fd); + + REQUIRE_FALSE(var_info.has_value()); +}