From d6a67abcdf9cd3138941690ace822e441e58ecc2 Mon Sep 17 00:00:00 2001 From: RedPhoenixQ Date: Wed, 14 May 2025 22:04:07 +0200 Subject: [PATCH] snapshots: use hashes of WidgetData state to create snapshots The previous implementation using images for snapshots was unreliable and was never fully developed. This new snapshot implementation can be used to take a snapshot of the dvui logic, e.g the sizes, positions and options used on each widget. --- src/Options.zig | 43 +++++++++++++++++++++++++++++++++ src/WidgetData.zig | 8 +++++++ src/testing.zig | 60 +++++++++++++++++++--------------------------- 3 files changed, 75 insertions(+), 36 deletions(-) diff --git a/src/Options.zig b/src/Options.zig index 80797599..59598daa 100644 --- a/src/Options.zig +++ b/src/Options.zig @@ -382,6 +382,49 @@ pub fn padSize(self: *const Options, s: Size) Size { return s.pad(self.paddingGet()).pad(self.borderGet()).pad(self.marginGet()); } +/// Hashes all the values of the options +/// +/// Only useful to check exact equality between two `Options` +pub fn hash(self: *const Options) u32 { + const asBytes = std.mem.asBytes; + var hasher = dvui.fnv.init(); + + hasher.update(asBytes(&self.min_size_contentGet())); + hasher.update(asBytes(&self.max_size_contentGet())); + if (self.rect) |rect| hasher.update(asBytes(&rect)); + + hasher.update(asBytes(&self.borderGet())); + hasher.update(asBytes(&self.marginGet())); + hasher.update(asBytes(&self.paddingGet())); + + hasher.update(asBytes(&self.corner_radiusGet())); + hasher.update(asBytes(&self.gravityGet())); + hasher.update(asBytes(&self.expandGet())); + hasher.update(asBytes(&self.rotationGet())); + hasher.update(asBytes(&self.background)); + + hasher.update(asBytes(&self.color_accent)); + hasher.update(asBytes(&self.color_text)); + hasher.update(asBytes(&self.color_text_press)); + hasher.update(asBytes(&self.color_fill)); + hasher.update(asBytes(&self.color_fill_hover)); + hasher.update(asBytes(&self.color_fill_press)); + hasher.update(asBytes(&self.color_border)); + + hasher.update(asBytes(&self.font_style)); + const font = self.fontGet(); + hasher.update(font.name); + hasher.update(asBytes(&font.line_height_factor)); + hasher.update(asBytes(&font.size)); + + hasher.update(asBytes(&self.tab_index)); + hasher.update(asBytes(&self.id_extra)); + if (self.tag) |tag| hasher.update(tag); + if (self.name) |name| hasher.update(name); + + return hasher.final(); +} + //pub fn format(self: *const Options, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { // try std.fmt.format(writer, "Options{{ .background = {?}, .color_style = {?} }}", .{ self.background, self.color_style }); //} diff --git a/src/WidgetData.zig b/src/WidgetData.zig index 42a73af2..8fa1e3a2 100644 --- a/src/WidgetData.zig +++ b/src/WidgetData.zig @@ -81,6 +81,14 @@ pub fn register(self: *WidgetData) !void { cw.last_focused_id_this_frame = self.id; } + if (dvui.testing.widget_hasher) |*hasher| { + hasher.update(std.mem.asBytes(&self.init_options)); + hasher.update(std.mem.asBytes(&self.options.hash())); + hasher.update(std.mem.asBytes(&self.rectScale())); + hasher.update(std.mem.asBytes(&self.visible())); + hasher.update(std.mem.asBytes(&(self.id == focused_widget_id))); + } + if (cw.debug_under_focus and self.id == focused_widget_id) { cw.debug_widget_id = self.id; } diff --git a/src/testing.zig b/src/testing.zig index 74393e96..c7205711 100644 --- a/src/testing.zig +++ b/src/testing.zig @@ -6,6 +6,9 @@ snapshot_dir: []const u8, snapshot_index: u8 = 0, +/// Used to hash widget data during a frame for snapshot testing +pub var widget_hasher: ?dvui.fnv = null; + /// Moves the mouse to the center of the widget pub fn moveTo(tag: []const u8) !void { const tag_data = dvui.tagGet(tag) orelse { @@ -189,14 +192,13 @@ pub fn capturePng(self: *Self, frame: dvui.App.frameFunction, rect: ?dvui.Rect.P return png_data; } -const png_extension = ".png"; -/// Captures one frame and compares to an earilier captured frame, returning an error if they are not the same +/// Runs exactly one frame, creating a hash of the state of that frame and compares to an earilier saved hash, +/// returning an error if they are not the same. /// /// IMPORTANT: Snapshots are unstable and both backend and platform dependent. Changing any of these might fail the test. /// /// All snapshot tests can be ignored (without skipping the whole test) by setting the environment variable `DVUI_SNAPSHOT_IGNORE`. -/// This function will always run exactly one frame. /// /// Set the environment variable `DVUI_SNAPSHOT_WRITE` to create/overwrite the snapshot files /// @@ -211,70 +213,56 @@ pub fn snapshot(self: *Self, src: std.builtin.SourceLocation, frame: dvui.App.fr } defer self.snapshot_index += 1; - const filename = try std.fmt.allocPrint(self.allocator, "{s}-{s}-{d}" ++ png_extension, .{ src.file, src.fn_name, self.snapshot_index }); + const filename = try std.fmt.allocPrint(self.allocator, "{s}-{s}-{d}", .{ src.file, src.fn_name, self.snapshot_index }); defer self.allocator.free(filename); // NOTE: do fs operation through cwd to handle relative and absolute paths var dir = std.fs.cwd().openDir(self.snapshot_dir, .{}) catch |err| switch (err) { error.FileNotFound => { std.debug.print("{s}:{d}:{d}: Snapshot directory did not exist! Run the test with DVUI_SNAPSHOT_WRITE to create all snapshot files\n", .{ src.file, src.line, src.column }); - return error.SkipZigTest; // FIXME: Test should fail with missing snapshots, but we don't want to commit snapshots while they are unstable, so skip tests instead + return error.MissingSnapshotFile; }, else => return err, }; defer dir.close(); - const png_data = try self.capturePng(frame, null); - defer self.allocator.free(png_data); + widget_hasher = .init(); + defer widget_hasher = null; + _ = try step(frame); + const HashInt = u32; + const hash: HashInt = widget_hasher.?.final(); - const file = dir.openFile(filename, .{}) catch |err| switch (err) { + const file = dir.openFile(filename, .{ .mode = .read_write }) catch |err| switch (err) { std.fs.File.OpenError.FileNotFound => { if (should_write_snapshots()) { - try dir.writeFile(.{ .sub_path = filename, .data = png_data, .flags = .{} }); + const file = try dir.createFile(filename, .{}); + try file.writer().print("{X}", .{hash}); std.debug.print("Snapshot: Created file \"{s}\"\n", .{filename}); return; } std.debug.print("{s}:{d}:{d}: Snapshot file did not exist! Run the test with `DVUI_SNAPSHOT_WRITE` to create all snapshot files\n", .{ src.file, src.line, src.column }); - return error.SkipZigTest; // FIXME: Test should fail with missing snapshots, but we don't want to commit snapshots while they are unstable, so skip tests instead + return error.MissingSnapshotFile; }, else => return err, }; - const prev_hash = try hash_png(file.reader().any()); - file.close(); + defer file.close(); - var png_reader = std.io.fixedBufferStream(png_data); - const new_hash = try hash_png(png_reader.reader().any()); + var hash_buf: [@sizeOf(HashInt) * 2]u8 = undefined; + _ = try file.readAll(&hash_buf); + const prev_hash = try std.fmt.parseUnsigned(HashInt, &hash_buf, 16); - if (prev_hash != new_hash) { + if (prev_hash != hash) { if (should_write_snapshots()) { - try dir.writeFile(.{ .sub_path = filename, .data = png_data, .flags = .{} }); + try file.seekTo(0); + try file.writer().print("{X}", .{hash}); std.debug.print("Snapshot: Overwrote file \"{s}\"\n", .{filename}); return; } - const failed_filename = try std.fmt.allocPrint(self.allocator, "{s}-failed" ++ png_extension, .{filename[0 .. filename.len - png_extension.len]}); - defer self.allocator.free(failed_filename); - try dir.writeFile(.{ .sub_path = failed_filename, .data = png_data, .flags = .{} }); - - std.debug.print("Snapshot did not match! See the \"{s}\" for the current output", .{failed_filename}); - return SnapshotError.SnapshotsDidNotMatch; } } -fn hash_png(png_reader: std.io.AnyReader) !u32 { - var hasher = dvui.fnv.init(); - - var read_buf: [1024 * 4]u8 = undefined; - var len: usize = read_buf.len; - // len < read_buf indicates the end of the data - while (len == read_buf.len) { - len = try png_reader.readAll(&read_buf); - hasher.update(read_buf[0..len]); - } - return hasher.final(); -} - fn should_ignore_snapshots() bool { - return Backend.kind == .testing or std.process.hasEnvVarConstant("DVUI_SNAPSHOT_IGNORE"); + return std.process.hasEnvVarConstant("DVUI_SNAPSHOT_IGNORE"); } fn should_write_snapshots() bool { -- knotmirror 0.0.1