Fix broken hash tests to work with current CLI architecture: - Update import to use @import(src) module system - Add hash module export to utils.zig - Make validatePath() public for testing - Fix Zig 0.15 API: writeFile options struct, var tmp_dir for cleanup - Fix file paths: use tmp_dir realpath for hashFile - Replace std.fs.MAX_PATH_BYTES with 4096 buffer All hash tests now passing.
77 lines
2.4 KiB
Zig
77 lines
2.4 KiB
Zig
const std = @import("std");
|
|
const src = @import("src");
|
|
const hash = src.utils.hash;
|
|
|
|
test "hash single file" {
|
|
const allocator = std.testing.allocator;
|
|
|
|
// Create a temporary file
|
|
var tmp_dir = std.testing.tmpDir(.{});
|
|
defer tmp_dir.cleanup();
|
|
|
|
const test_content = "hello world";
|
|
try tmp_dir.dir.writeFile(.{
|
|
.sub_path = "test.txt",
|
|
.data = test_content,
|
|
});
|
|
|
|
// Get the temp directory path
|
|
var path_buf: [4096]u8 = undefined;
|
|
const tmp_path = try tmp_dir.dir.realpath(".", &path_buf);
|
|
const file_path = try std.fs.path.join(allocator, &[_][]const u8{ tmp_path, "test.txt" });
|
|
defer allocator.free(file_path);
|
|
|
|
// Hash the file
|
|
var hasher = try hash.DatasetHash.init(allocator, 0);
|
|
defer hasher.deinit();
|
|
|
|
const file_hash = try hasher.hashFile(file_path);
|
|
try std.testing.expectEqual(@as(usize, 64), file_hash.len);
|
|
}
|
|
|
|
test "hash empty file" {
|
|
const allocator = std.testing.allocator;
|
|
|
|
// Create a temporary empty file
|
|
var tmp_dir = std.testing.tmpDir(.{});
|
|
defer tmp_dir.cleanup();
|
|
|
|
try tmp_dir.dir.writeFile(.{
|
|
.sub_path = "empty.txt",
|
|
.data = "",
|
|
});
|
|
|
|
// Get the temp directory path
|
|
var path_buf: [4096]u8 = undefined;
|
|
const tmp_path = try tmp_dir.dir.realpath(".", &path_buf);
|
|
const file_path = try std.fs.path.join(allocator, &[_][]const u8{ tmp_path, "empty.txt" });
|
|
defer allocator.free(file_path);
|
|
|
|
var hasher = try hash.DatasetHash.init(allocator, 0);
|
|
defer hasher.deinit();
|
|
|
|
const file_hash = try hasher.hashFile(file_path);
|
|
try std.testing.expectEqual(@as(usize, 64), file_hash.len);
|
|
}
|
|
|
|
test "path validation" {
|
|
// Valid paths
|
|
try hash.validatePath("/home/user/file.txt");
|
|
try hash.validatePath("./relative/path");
|
|
try hash.validatePath("normal_file");
|
|
|
|
// Path traversal should fail
|
|
try std.testing.expectError(error.PathTraversalAttempt, hash.validatePath("../etc/passwd"));
|
|
try std.testing.expectError(error.PathTraversalAttempt, hash.validatePath("foo/../../../etc/passwd"));
|
|
|
|
// Null bytes should fail
|
|
try std.testing.expectError(error.NullByteInPath, hash.validatePath("/path\x00with\x00null"));
|
|
}
|
|
|
|
test "bytes to hex conversion" {
|
|
var hex_buf: [64]u8 = undefined;
|
|
const bytes = [_]u8{ 0xAB, 0xCD, 0xEF, 0x12 };
|
|
hash.bytesToHex(&bytes, &hex_buf);
|
|
|
|
try std.testing.expectEqualStrings("abcdef12", hex_buf[0..8]);
|
|
}
|