Files
zigp2p/src/files/mock_fs.zig

780 lines
24 KiB
Zig

//! Mock Filesystem for Testing
//!
//! Provides an in-memory filesystem implementation for unit testing file operations
//! without touching the real filesystem. This enables deterministic, fast, and
//! isolated testing of file-related code.
//!
//! Usage:
//! ```zig
//! var mock_fs = MockFS.init(allocator);
//! defer mock_fs.deinit();
//!
//! // Create a file with content
//! try mock_fs.writeFile("/test/file.txt", "Hello, World!");
//!
//! // Read the file back
//! const content = try mock_fs.readFile(allocator, "/test/file.txt");
//! defer allocator.free(content);
//! ```
const std = @import("std");
const platform_time = @import("platform").time;
const Allocator = std.mem.Allocator;
/// Error types for MockFS operations
pub const MockFSError = error{
FileNotFound,
DirectoryNotFound,
FileAlreadyExists,
DirectoryAlreadyExists,
NotAFile,
NotADirectory,
InvalidPath,
OutOfMemory,
PermissionDenied,
DiskFull,
IOError,
};
/// Represents a file in the mock filesystem
pub const MockFile = struct {
allocator: Allocator,
data: []u8,
created_at: i64,
modified_at: i64,
is_readonly: bool = false,
pub fn init(allocator: Allocator) MockFile {
return .{
.allocator = allocator,
.data = &[_]u8{},
.created_at = platform_time.timestamp(),
.modified_at = platform_time.timestamp(),
};
}
pub fn deinit(self: *MockFile) void {
if (self.data.len > 0) {
self.allocator.free(self.data);
}
}
pub fn size(self: *const MockFile) usize {
return self.data.len;
}
pub fn setContent(self: *MockFile, content: []const u8) !void {
// FIX: Allocate new data BEFORE freeing old to prevent use-after-free
// if dupe fails. Previously, if dupe failed after free, self.data
// would be a dangling pointer.
const new_data = try self.allocator.dupe(u8, content);
if (self.data.len > 0) {
self.allocator.free(self.data);
}
self.data = new_data;
self.modified_at = platform_time.timestamp();
}
pub fn resize(self: *MockFile, new_size: usize) !void {
if (new_size == self.data.len) return;
const new_data = try self.allocator.alloc(u8, new_size);
const copy_len = @min(self.data.len, new_size);
if (copy_len > 0) {
@memcpy(new_data[0..copy_len], self.data[0..copy_len]);
}
// Zero-fill any new bytes
if (new_size > self.data.len) {
@memset(new_data[self.data.len..], 0);
}
if (self.data.len > 0) {
self.allocator.free(self.data);
}
self.data = new_data;
self.modified_at = platform_time.timestamp();
}
};
/// Mock file handle for read/write operations
pub const MockFileHandle = struct {
fs: *MockFS,
path: []const u8,
position: usize = 0,
read_only: bool,
/// Read data from current position
pub fn read(self: *MockFileHandle, buffer: []u8) MockFSError!usize {
const file = self.fs.files.get(self.path) orelse return MockFSError.FileNotFound;
const content = file.data;
if (self.position >= content.len) {
return 0; // EOF
}
const available = content.len - self.position;
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[self.position..][0..to_read]);
self.position += to_read;
return to_read;
}
/// Read at specific offset (like pread)
pub fn pread(self: *MockFileHandle, buffer: []u8, offset: u64) MockFSError!usize {
const file = self.fs.files.get(self.path) orelse return MockFSError.FileNotFound;
const content = file.data;
const off: usize = @intCast(@min(offset, content.len));
if (off >= content.len) {
return 0;
}
const available = content.len - off;
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[off..][0..to_read]);
return to_read;
}
/// Write data at current position
pub fn write(self: *MockFileHandle, data: []const u8) MockFSError!usize {
if (self.read_only) return MockFSError.PermissionDenied;
const file = self.fs.files.getPtr(self.path) orelse return MockFSError.FileNotFound;
// Extend file if necessary
if (self.position + data.len > file.data.len) {
const new_len = self.position + data.len;
file.resize(new_len) catch return MockFSError.OutOfMemory;
}
// Copy data
@memcpy(file.data[self.position..][0..data.len], data);
self.position += data.len;
file.modified_at = platform_time.timestamp();
return data.len;
}
/// Write at specific offset (like pwrite)
pub fn pwrite(self: *MockFileHandle, data: []const u8, offset: u64) MockFSError!usize {
if (self.read_only) return MockFSError.PermissionDenied;
const file = self.fs.files.getPtr(self.path) orelse return MockFSError.FileNotFound;
const off: usize = @intCast(offset);
// Extend file if necessary
if (off + data.len > file.data.len) {
const new_len = off + data.len;
file.resize(new_len) catch return MockFSError.OutOfMemory;
}
// Copy data
@memcpy(file.data[off..][0..data.len], data);
file.modified_at = platform_time.timestamp();
return data.len;
}
/// Seek to position
pub fn seekTo(self: *MockFileHandle, position: u64) void {
self.position = @intCast(position);
}
/// Get current position
pub fn getPos(self: *const MockFileHandle) u64 {
return self.position;
}
/// Get file size
pub fn stat(self: *const MockFileHandle) MockFSError!MockFileStat {
const file = self.fs.files.get(self.path) orelse return MockFSError.FileNotFound;
return MockFileStat{
.size = file.data.len,
.created_at = file.created_at,
.modified_at = file.modified_at,
};
}
/// Set file end position (truncate/extend)
pub fn setEndPos(self: *MockFileHandle, size: u64) MockFSError!void {
if (self.read_only) return MockFSError.PermissionDenied;
const file = self.fs.files.getPtr(self.path) orelse return MockFSError.FileNotFound;
file.resize(@intCast(size)) catch return MockFSError.OutOfMemory;
}
/// Sync (no-op for mock)
pub fn sync(self: *MockFileHandle) void {
_ = self;
}
/// Close handle (no-op for mock since we don't track open handles)
pub fn close(self: *MockFileHandle) void {
_ = self;
}
};
/// File statistics
pub const MockFileStat = struct {
size: usize,
created_at: i64,
modified_at: i64,
};
/// In-memory mock filesystem
pub const MockFS = struct {
allocator: Allocator,
files: std.StringHashMap(MockFile),
directories: std.StringHashMap(void),
/// Simulated disk space limit (0 = unlimited)
disk_limit: usize = 0,
/// Current total size of all files
disk_used: usize = 0,
/// Inject errors for testing error handling
inject_error: ?MockFSError = null,
pub fn init(allocator: Allocator) MockFS {
var fs = MockFS{
.allocator = allocator,
.files = std.StringHashMap(MockFile).init(allocator),
.directories = std.StringHashMap(void).init(allocator),
};
// Root directory always exists - allocate the key so it can be freed in deinit
const root = allocator.dupe(u8, "/") catch return fs;
fs.directories.put(root, {}) catch {
allocator.free(root);
};
return fs;
}
pub fn deinit(self: *MockFS) void {
var file_iter = self.files.iterator();
while (file_iter.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
entry.value_ptr.deinit();
}
self.files.deinit();
var dir_iter = self.directories.iterator();
while (dir_iter.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
}
self.directories.deinit();
}
/// Set disk space limit for testing disk full scenarios
pub fn setDiskLimit(self: *MockFS, limit: usize) void {
self.disk_limit = limit;
}
/// Inject an error to be returned on the next operation
pub fn injectError(self: *MockFS, err: MockFSError) void {
self.inject_error = err;
}
/// Clear injected error
pub fn clearError(self: *MockFS) void {
self.inject_error = null;
}
fn checkError(self: *MockFS) MockFSError!void {
if (self.inject_error) |err| {
self.inject_error = null;
return err;
}
}
/// Create a directory (and parents if needed)
pub fn makeDir(self: *MockFS, path: []const u8) MockFSError!void {
try self.checkError();
// Normalize path
const norm_path = try self.normalizePath(path);
if (self.directories.contains(norm_path)) {
self.allocator.free(norm_path);
return; // Already exists, success
}
// Create parent directories
var parent_end = norm_path.len;
while (parent_end > 1) {
parent_end -= 1;
if (norm_path[parent_end] == '/') {
const parent = norm_path[0..parent_end];
if (!self.directories.contains(parent)) {
const parent_copy = self.allocator.dupe(u8, parent) catch return MockFSError.OutOfMemory;
self.directories.put(parent_copy, {}) catch {
self.allocator.free(parent_copy);
return MockFSError.OutOfMemory;
};
}
}
}
self.directories.put(norm_path, {}) catch {
self.allocator.free(norm_path);
return MockFSError.OutOfMemory;
};
}
/// Create a file (parent directory must exist)
pub fn createFile(self: *MockFS, path: []const u8) MockFSError!MockFileHandle {
try self.checkError();
const norm_path = try self.normalizePath(path);
if (self.files.contains(norm_path)) {
self.allocator.free(norm_path);
return MockFSError.FileAlreadyExists;
}
var file = MockFile.init(self.allocator);
self.files.put(norm_path, file) catch {
file.deinit();
self.allocator.free(norm_path);
return MockFSError.OutOfMemory;
};
return MockFileHandle{
.fs = self,
.path = norm_path,
.read_only = false,
};
}
/// Open an existing file
pub fn openFile(self: *MockFS, path: []const u8, read_only: bool) MockFSError!MockFileHandle {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
if (!self.files.contains(norm_path)) {
return MockFSError.FileNotFound;
}
// Get the stored key (which we own)
const entry = self.files.getEntry(norm_path) orelse return MockFSError.FileNotFound;
return MockFileHandle{
.fs = self,
.path = entry.key_ptr.*,
.read_only = read_only,
};
}
/// Write entire content to a file (convenience method)
pub fn writeFile(self: *MockFS, path: []const u8, content: []const u8) MockFSError!void {
try self.checkError();
// Check disk space
if (self.disk_limit > 0 and self.disk_used + content.len > self.disk_limit) {
return MockFSError.DiskFull;
}
const norm_path = try self.normalizePath(path);
// Create parent directories
var last_slash: usize = 0;
for (norm_path, 0..) |c, i| {
if (c == '/') last_slash = i;
}
if (last_slash > 0) {
try self.makeDir(norm_path[0..last_slash]);
}
if (self.files.getPtr(norm_path)) |existing| {
// Update existing file
self.disk_used -= existing.data.len;
existing.setContent(content) catch return MockFSError.OutOfMemory;
self.disk_used += content.len;
self.allocator.free(norm_path);
} else {
// Create new file
var file = MockFile.init(self.allocator);
file.setContent(content) catch {
file.deinit();
self.allocator.free(norm_path);
return MockFSError.OutOfMemory;
};
self.files.put(norm_path, file) catch {
file.deinit();
self.allocator.free(norm_path);
return MockFSError.OutOfMemory;
};
self.disk_used += content.len;
}
}
/// Read entire file content
pub fn readFile(self: *MockFS, allocator: Allocator, path: []const u8) MockFSError![]u8 {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
const file = self.files.get(norm_path) orelse return MockFSError.FileNotFound;
const content = allocator.dupe(u8, file.data) catch return MockFSError.OutOfMemory;
return content;
}
/// Check if file exists
pub fn fileExists(self: *MockFS, path: []const u8) bool {
const norm_path = self.normalizePath(path) catch return false;
defer self.allocator.free(norm_path);
return self.files.contains(norm_path);
}
/// Check if directory exists
pub fn dirExists(self: *MockFS, path: []const u8) bool {
const norm_path = self.normalizePath(path) catch return false;
defer self.allocator.free(norm_path);
return self.directories.contains(norm_path);
}
/// Delete a file
pub fn deleteFile(self: *MockFS, path: []const u8) MockFSError!void {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
const entry = self.files.fetchRemove(norm_path) orelse return MockFSError.FileNotFound;
self.disk_used -= entry.value.data.len;
self.allocator.free(entry.key);
var file = entry.value;
file.deinit();
}
/// Rename/move a file
pub fn rename(self: *MockFS, old_path: []const u8, new_path: []const u8) MockFSError!void {
try self.checkError();
const old_norm = try self.normalizePath(old_path);
defer self.allocator.free(old_norm);
const new_norm = try self.normalizePath(new_path);
const entry = self.files.fetchRemove(old_norm) orelse {
self.allocator.free(new_norm);
return MockFSError.FileNotFound;
};
self.allocator.free(entry.key);
self.files.put(new_norm, entry.value) catch {
self.allocator.free(new_norm);
return MockFSError.OutOfMemory;
};
}
/// Get file stats
pub fn stat(self: *MockFS, path: []const u8) MockFSError!MockFileStat {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
const file = self.files.get(norm_path) orelse return MockFSError.FileNotFound;
return MockFileStat{
.size = file.data.len,
.created_at = file.created_at,
.modified_at = file.modified_at,
};
}
/// List files in directory
pub fn listDir(self: *MockFS, allocator: Allocator, path: []const u8) MockFSError![][]const u8 {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
if (!self.directories.contains(norm_path)) {
return MockFSError.DirectoryNotFound;
}
const prefix_len = if (std.mem.eql(u8, norm_path, "/")) 1 else norm_path.len + 1;
// Count matching entries first
var count: usize = 0;
var iter = self.files.iterator();
while (iter.next()) |entry| {
const file_path = entry.key_ptr.*;
if (std.mem.startsWith(u8, file_path, norm_path) and
file_path.len > prefix_len and
std.mem.indexOfScalar(u8, file_path[prefix_len..], '/') == null)
{
count += 1;
}
}
// Allocate result array
const entries = allocator.alloc([]const u8, count) catch return MockFSError.OutOfMemory;
errdefer allocator.free(entries);
// Fill entries
var idx: usize = 0;
iter = self.files.iterator();
while (iter.next()) |entry| {
const file_path = entry.key_ptr.*;
if (std.mem.startsWith(u8, file_path, norm_path) and
file_path.len > prefix_len and
std.mem.indexOfScalar(u8, file_path[prefix_len..], '/') == null)
{
entries[idx] = allocator.dupe(u8, file_path[prefix_len..]) catch {
// Free already allocated entries
for (entries[0..idx]) |e| allocator.free(e);
return MockFSError.OutOfMemory;
};
idx += 1;
}
}
return entries;
}
/// Normalize path (remove trailing slashes, ensure leading slash)
fn normalizePath(self: *MockFS, path: []const u8) MockFSError![]u8 {
if (path.len == 0) return MockFSError.InvalidPath;
// First pass: calculate the normalized length
var len: usize = 0;
var prev_slash = false;
var ends_with_slash = false;
// Account for leading slash if missing
if (path[0] != '/') {
len = 1;
}
// Count characters after normalization
for (path) |c| {
if (c == '/') {
if (!prev_slash) {
len += 1;
ends_with_slash = true;
}
prev_slash = true;
} else {
len += 1;
prev_slash = false;
ends_with_slash = false;
}
}
// Remove trailing slash (unless root)
if (len > 1 and ends_with_slash) {
len -= 1;
}
// Allocate exact size needed
const result = self.allocator.alloc(u8, len) catch return MockFSError.OutOfMemory;
// Second pass: fill the buffer
var idx: usize = 0;
// Ensure leading slash
if (path[0] != '/') {
result[idx] = '/';
idx += 1;
}
// Copy path, normalizing double slashes
prev_slash = false;
for (path) |c| {
if (idx >= len) break;
if (c == '/') {
if (!prev_slash) {
result[idx] = '/';
idx += 1;
}
prev_slash = true;
} else {
result[idx] = c;
idx += 1;
prev_slash = false;
}
}
return result;
}
};
// ============================================================================
// Tests
// ============================================================================
test "MockFS: create and read file" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/test.txt", "Hello, World!");
const content = try fs.readFile(allocator, "/test.txt");
defer allocator.free(content);
try std.testing.expectEqualStrings("Hello, World!", content);
}
test "MockFS: file handle operations" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
// Create and write via handle
var handle = try fs.createFile("/data.bin");
_ = try handle.write("First part");
_ = try handle.write(" Second part");
handle.close();
// Read back
var read_handle = try fs.openFile("/data.bin", true);
var buffer: [100]u8 = undefined;
const n = try read_handle.read(&buffer);
try std.testing.expectEqualStrings("First part Second part", buffer[0..n]);
}
test "MockFS: pread/pwrite operations" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/random.bin", "0123456789");
var handle = try fs.openFile("/random.bin", false);
// pwrite at offset 5
_ = try handle.pwrite("XXXXX", 5);
// pread to verify
var buffer: [10]u8 = undefined;
const n = try handle.pread(&buffer, 0);
try std.testing.expectEqualStrings("01234XXXXX", buffer[0..n]);
}
test "MockFS: directory operations" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.makeDir("/foo/bar/baz");
try std.testing.expect(fs.dirExists("/foo"));
try std.testing.expect(fs.dirExists("/foo/bar"));
try std.testing.expect(fs.dirExists("/foo/bar/baz"));
}
test "MockFS: file not found" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
const result = fs.readFile(allocator, "/nonexistent.txt");
try std.testing.expectError(MockFSError.FileNotFound, result);
}
test "MockFS: disk full simulation" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
fs.setDiskLimit(100);
try fs.writeFile("/small.txt", "Small file");
try std.testing.expectEqual(@as(usize, 10), fs.disk_used);
// This should fail
const result = fs.writeFile("/large.txt", "A" ** 200);
try std.testing.expectError(MockFSError.DiskFull, result);
}
test "MockFS: error injection" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/test.txt", "content");
// Inject error
fs.injectError(MockFSError.IOError);
// Next operation should fail
const result = fs.readFile(allocator, "/test.txt");
try std.testing.expectError(MockFSError.IOError, result);
// Subsequent operations should work
const content = try fs.readFile(allocator, "/test.txt");
defer allocator.free(content);
try std.testing.expectEqualStrings("content", content);
}
test "MockFS: rename file" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/old.txt", "content");
try fs.rename("/old.txt", "/new.txt");
try std.testing.expect(!fs.fileExists("/old.txt"));
try std.testing.expect(fs.fileExists("/new.txt"));
const content = try fs.readFile(allocator, "/new.txt");
defer allocator.free(content);
try std.testing.expectEqualStrings("content", content);
}
test "MockFS: delete file" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/to_delete.txt", "content");
try std.testing.expect(fs.fileExists("/to_delete.txt"));
try fs.deleteFile("/to_delete.txt");
try std.testing.expect(!fs.fileExists("/to_delete.txt"));
}
test "MockFS: file stats" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/stats.txt", "Hello!");
const s = try fs.stat("/stats.txt");
try std.testing.expectEqual(@as(usize, 6), s.size);
try std.testing.expect(s.created_at > 0);
try std.testing.expect(s.modified_at >= s.created_at);
}
test "MockFS: list directory" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/dir/file1.txt", "1");
try fs.writeFile("/dir/file2.txt", "2");
try fs.writeFile("/dir/subdir/file3.txt", "3");
const entries = try fs.listDir(allocator, "/dir");
defer {
for (entries) |e| allocator.free(e);
allocator.free(entries);
}
try std.testing.expectEqual(@as(usize, 2), entries.len);
}