Writer in a test

I want to test an html escaping function, I have a version which results in a new allocated string which is escaped which I can test easily. However, I need a writer to test the writer version which doesn’t allocate but writes to a writer.
All I could think of is getting an Arraylist writer, but that isnt working well for me.

You can use std.Io.Writer.fixed to create a writer that writes in a buffer.

const std = @import("std");
const Writer = std.Io.Writer;

test {
    var buf: [80]u8 = undefined;
    var w: Writer = .fixed(&buf);
    try w.print("Hello", .{});
    try std.testing.expectEqualStrings("Hello", w.buffered());
}
3 Likes

Writer.Allocating is basically an ArrayList writer, so if you don’t know (or don’t want to calculate) an upper bound for the output, you can use that.

const std = @import("std");

test {
    var aw: std.Io.Writer.Allocating = .init(std.testing.allocator);
    defer aw.deinit();

    try aw.writer.print("Hello", .{});
    try std.testing.expectEqualStrings("Hello", aw.written());
}

(if you want to pass it to your writer implementation you’d pass &aw.writer)

3 Likes

Thanks for the help everyone! I will use this :>