Test macro that checks no exception was thrown?

I want to implement a test that just need to know the function did not throw any exception. There’s @test_throws but that’s the exact opposite of what I need. Is there anything like that?

I could work around by using regular @test with an expected result but I don’t really care about the calculation in this case.

2 Likes

Option 1:

@test_nowarn foo()

Option 2:

@test foo() isa Any
7 Likes

The following gives a fail instead of an error when an exception is thrown:

@test try foo()
    true
catch
    false
end
1 Like

It’s not clear to me that @test_nowarn is really the correct idiom here. For example, @test_nowarn sqrt(-1) results in a test error rather than a test failure:

julia> @testset "hello" begin
           @test true
           @test_nowarn sqrt(-1)
       end
hello: Error During Test at REPL[74]:1
  Got exception outside of a @test
  DomainError with -1.0:
  sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
  Stacktrace: # Stacktrace omitted for clarity.
Test Summary: | Pass  Error  Total  Time
hello         |    1      1      2  0.1s
ERROR: Some tests did not pass: 1 passed, 0 failed, 1 errored, 0 broken.

Note that the second line of output says that there was an exception outside of a @test, and the last line says that 0 tests failed and 1 errored. It still alerts us that something went wrong, but philosophically it seems like what we want is a test failure (which is what the try-catch approach gives us).

4 Likes