#Issue with buffered printing inside test block

1 messages · Page 1 of 1 (latest)

brittle bough
#

Version : 0.15.2

.
├── build.zig
├── build.zig.zon
├── src
│   └── main.zig
└── zig-out
    └── bin
        └── main
// src/main.zig

const std = @import("std");

pub fn main() !void {
    std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
}

pub fn bufferedPrint() !void {
    var stdout_buffer: [1024]u8 = undefined;
    var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
    const stdout = &stdout_writer.interface;

    try stdout.print("buffered print\n", .{});
    try stdout.flush();
}

test "buffered writer example" {
    try bufferedPrint();
}
// build.zig

const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "main",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    b.installArtifact(exe);

    const run_step = b.step("run", "run");
    const run_cmd = b.addRunArtifact(exe);

    run_step.dependOn(&run_cmd.step);
    run_cmd.step.dependOn(b.getInstallStep());

    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const exe_tests = b.addTest(.{
        .root_module = exe.root_module,
    });

    const run_exe_tests = b.addRunArtifact(exe_tests);

    const test_step = b.step("test", "Run tests");
    test_step.dependOn(&run_exe_tests.step);
}

This Works

# zig test src/main.zig 
buffered print
All 1 tests passed.

But this is "stuck"

# zig build test
[1/3] steps
└─ [0/1] run test
   └─ main.test.buffered writer example
rare pendant
#

the test process is a sub process of the build system which doesnt provide a stdout to it.
writing to stderr does work but it will fail the test.

if you need to verify the output of code with a test, the code should accept an *Io.Writer, that way you can provide a different implementation in the test, such as Io.Writer.fixed or Allocating which output to a buffer that you can then inspect.