Introduction Although I try to make good use of the debugger, I am quite used to print-based debugging, especially for unit tests. I wanted to explore some tricks to improve print-based debugging, and also incorporate the debugger more. print-based debugging improved One big problem with using print debugging is spammy output. If I am running something in a loop, and only one iteration of the loop has anything interesting, I still need to filter and sort through every iteration's output. Or perhaps I am working with some data structure that has a printable representation that is easier to parse than the raw data; if I don't know where the error comes from I would have to litter print functions everywhere hoping to catch the necessary context. However, I realized that since zig tests use errors, instead of panics, it is possible to use errdefer to print something only when a test actually fails. test { errdefer std.debug.print("{f}", .{ast}); } Does a fantastic job of avoiding cluttering the code, and providing the precise context necessary when an error actually occurs. Running tests in the debugger If anything more complex is necessary, using the debugger is the way to go. However, naively trying to run seergdb or gdb -tui directly from the terminal gets difficult, as the test binaries are not in zig-out directory (understandably) but in the zig-cache directory. I learned a trick from ziggit that the build.zig can run commands, and you can feed the artifact path of a build step as an argument into the command: build.zig const debugger = b.addSystemCommand(&.{ "seergdb", "--run", "--" }); debugger.addArtifactArg(exe_unit_tests); const debug_step = b.step("debug", "Run unit tests under debugger"); debug_step.dependOn(&debugger.step); This makes it really easy to run the proper binary; however, this isn't enough on its own: the debugger only kicks into action for a breakpoint or panic, but the test runner gracefully handles errors. We can get around this by adding @br...
First seen: 2025-08-06 16:08
Last seen: 2025-08-07 06:21