#include #include #include #include "strawberry/hash_utils.hpp" #include #include #include #include #include void test_sha256_data() { const char* test_data = "Hello, World!"; std::string hash = strawberry::HashUtils::sha256_data( reinterpret_cast(test_data), strlen(test_data) ); // Expected SHA256 of "Hello, World!" std::string expected = "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"; std::cout << "Test SHA256 data:" << std::endl; std::cout << " Input: " << test_data << std::endl; std::cout << " Hash: " << hash << std::endl; std::cout << " Expected: " << expected << std::endl; assert(hash == expected); std::cout << " PASSED" << std::endl; } void test_sha256_file() { // Create a temporary test file const char* test_file = "/tmp/strawberry_test.txt"; { std::ofstream file(test_file); file << "Test content for hashing"; } std::string hash = strawberry::HashUtils::sha256_file(test_file); std::cout << "Test SHA256 file:" << std::endl; std::cout << " File: " << test_file << std::endl; std::cout << " Hash: " << hash << std::endl; assert(!hash.empty()); assert(hash.length() == 64); // SHA256 produces 64 hex characters std::cout << " PASSED" << std::endl; // Cleanup std::remove(test_file); } void test_to_hex() { std::vector data = {0x12, 0x34, 0xAB, 0xCD}; std::string hex = strawberry::HashUtils::to_hex(data); std::cout << "Test to_hex:" << std::endl; std::cout << " Hex: " << hex << std::endl; assert(hex == "1234abcd"); std::cout << " PASSED" << std::endl; } void test_sha256_fd_matches_file_hash() { std::cout << "Test sha256_fd:" << std::endl; const auto path = std::filesystem::temp_directory_path() / "strawberry_sha256_fd_test.bin"; { std::ofstream out(path, std::ios::binary); out << "strawberry fd hashing"; } const int fd = ::open(path.c_str(), O_RDONLY); assert(fd >= 0); const auto from_fd = strawberry::HashUtils::sha256_fd(fd); // Reading must not depend on (or move) the descriptor's offset. assert(strawberry::HashUtils::sha256_fd(fd) == from_fd); ::close(fd); assert(from_fd == strawberry::HashUtils::sha256_file(path.string())); assert(strawberry::HashUtils::sha256_fd(-1).empty()); std::filesystem::remove(path); std::cout << " PASSED" << std::endl; } int main() { std::cout << "Running HashUtils tests..." << std::endl << std::endl; try { test_sha256_data(); test_sha256_file(); test_to_hex(); test_sha256_fd_matches_file_hash(); std::cout << std::endl << "All tests passed!" << std::endl; return 0; } catch (const std::exception& e) { std::cerr << "Test failed with exception: " << e.what() << std::endl; return 1; } }