Console output in test cases

Hi. I’m new to Zig and maybe this is just a problem of mine, but it looks like a bug.

I noticed (with Zig 0.11.0 on macOS aarch64) that debug.print doesn’t print anything inside test cases.

Also, I normally only see a message telling all tests passed but, in inside a test I output something using an stdout writer, then also info about that single test (test name…) is print.

Sorry if the described behaviors is normal, but in that case I’d like to understand the reasons behind.

1 Like

this is one of the first things that confused me as well when starting to learn zig: see testing - How to print to stdout when running tests in zig? - Stack Overflow

  • maybe putting in some newline chars \n helps
  • also note that test runs get cached, i.e. if you run the test again without changing the source code, nothing will happen.

The problem is not only outputting inside tests (I’d like to know, anyway, why std.debug doesn’t work and stdout write works).

The problems is that, using the example link you provided, I don’t see the "
Test [3/6] test.returning an error…" message unless I use a print with a newline.

Hey @FeliceMente, welcome to the forum :slight_smile:

I opened a Git issue about this quite some time ago. Tests do not handle output like you would think - they’re really designed to be pass or fail and you want to use the testing functions to report back to the user (these are found in std.testing). There’s a variety of test based outputs you can work with such as expectEqual that cover common cases.

You can certainly make an argument that the testing functionality should work like main but producing output has implementation differences.

In general, don’t use prints/output to signal from tests - use error conditions and try statements to communicate your intent.

3 Likes

I used to have the same question in mind when using std.testing.expect which is usually recommended in many example. But with that, you have no idea to learn what the actual value is, comparing with expected.

After looking at source code, I switch from ‘expect’ to ‘expectEqual’ as it does provide print-out with actual/expect value when fail.

that’s good in general, to make your tests more specific in that way. There’re more expect[Something] methods, like for instance expectStringStartsWith.

While this gives you some insight, sometimes you have to know the state of some variable over the course of a computation for efficient debugging. So there’s no way around a debugging tool, if you don’t want to put print statements everywhere (which seems inefficient again…).