Warn() vs @warn

Hello,

I’m upgrading a package to 0.7 and I was prompted to use @warn instead of warn. I did but got faced with an error which I suspect is due to a poor understanding of macros and string interpolation. Here’s a simplified MWE:

using Test

function foo(x)
    if x<1
        warn("Got $x expected something >= 1, returning 0")
        return 0
    else
        x
    end
end

foo(-1) # deprecation warning + throws the correct warning message "Got -1 ..."
@test_warn "Got -1 expected something >= 1, returning 0" foo(-1) # test passes

Using @warn:

function bar(x)
    if x<1
        @warn "Got $x expected something >= 1, returning 0"
        return 0
    else
        x
    end
end
bar(-1) # shows the right warning message
@test_warn "Got -1 expected something >= 1, returning 0" bar(-1) # test fails

With:

Test Failed at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v0.7/Test/src/Test.jl:605
  Expression: contains_warn(read(fname, String), $(Expr(:escape, "Got x expected something >= 1, returning 0")))

Solution

Thanks to Kristoffer’s redirect to this Julia issue, this is how I ended up fixing it (using @test_logs instead of @test_warn which should be deprecated)

@test_logs (:warn, "Got -1 expected something >= 1, returning 0")  bar(-1)
1 Like

See https://github.com/JuliaLang/julia/issues/28549

2 Likes