Some patterns I have started to use when writing zig code with unit tests.
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 error s, 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
... continue reading