Help with deprecation warnings in tests

I would like to test that a function emits a deprecation warning, but I keep getting errors. Can someone please help me get the right syntax? Here is an MWE

julia> function foo()
       Base.depwarn("use an argument", :foo; force = true)
       1
       end
foo (generic function with 2 methods)

julia> function foo(x)
       1
       end
foo (generic function with 2 methods)

julia> foo()
┌ Warning: use an argument
│   caller = top-level scope at REPL[31]:1
└ @ Core REPL[31]:1
1

julia> @test_warn "use an argument" foo()
┌ Warning: use an argument
│   caller = #32 at Test.jl:633 [inlined]
└ @ Core /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.5/Test/src/Test.jl:633
Test Failed at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.5/Test/src/Test.jl:636
  Expression: contains_warn(read(fname, String), $(Expr(:escape, "use an argument")))
ERROR: There was an error during testing
1 Like

Looking at the documentation, @test_warn can’t test warnings generated with @warn. You could use @test_logs instead:

julia> @test_logs (:warn, "use an argument") foo()
1

(you should also be able to use @test_deprecated in this situation, but then I think your message would have to be formatted more like deprecation warnings coming from @deprecate)

3 Likes