Julia: how to prepare and cleanup @testset

Viewed 158

I wonder what Julia best practices are to prepare and cleanup tests? Other programming languages have before and after, or similar named functions. Julia seems to be missing them.

2 Answers

You just write the lines in the testset. Those having @test in front of them are the tests and the other lines are the setup. As easy as that.


julia> using Test

julia> @testset "my big set" begin
       x=4
       y=2
       @test 2y == x
       end
Test Summary: | Pass  Total
my big set    |    1      1
Test.DefaultTestSet("my big set", Any[], 1, false)

Similarly after @test lines you can de-allocate resources etc.

You can do setup just as Przemysław proposed. However, in order to ensure proper cleanup you need to handle it manually. The reason is that if an uncaught exception is thrown within @testset but outside @test it will lead to termination immediately:

julia> @testset begin
       throw(ArgumentError("something went wrong"))
       @test true
       @test false
       end
test set: Error During Test at REPL[5]:1
  Got exception outside of a @test
  ArgumentError: something went wrong
...

Test Summary: | Error  Total
test set      |     1      1
ERROR: Some tests did not pass: 0 passed, 0 failed, 1 errored, 0 broken.

Therefore if you have some code that might throw an exception you have to handle it manually, e.g.:

julia> @testset begin
       try
           @test true
           throw(ArgumentError("some error"))
           @test false
       catch
           @info "caught"
       finally
           @info "cleanup"
       end
       end
[ Info: caught
[ Info: cleanup
Test Summary: | Pass  Total
test set      |    1      1
Test.DefaultTestSet("test set", Any[], 1, false)

(note that the second test was not run, as earlier an exception outside of @test was thrown)

Related