How to test the value of a variable from info log

Is there any way to test the appearance of a string inside one of the variables being printed from @info? In the example below, I want to test the string world appearing in the info log. I don’t really care where it appears but if we can also test that it comes from variable s then it would perfect.

julia> function foo() 
           s = "world"
           @info "hello" s
       end

julia> foo()
┌ Info: hello
└   s = "world"

julia> @test_logs (:info, "hello") foo()

julia> @test_logs (:info, r"world") foo()
Log Test Failed at REPL[40]:1
  Expression: foo()
  Log Pattern: (:info, r"world")
  Captured Logs: 
    Test.LogRecord(Info, "hello", Main, Symbol("REPL[36]"), :Main_1f7f3d29, "REPL[36]", 3, Base.Iterators.Pairs(:s => "world"))

ERROR: There was an error during testing

I worked around it by capturing the output but it would be nice to know if there’s any better way to do this…

let buf = IOBuffer()
    with_logger(ConsoleLogger(buf)) do
        s = "world"
        @info "hello" s
    end
    @test occursin("world", String(take!(buf)))
end

Maybe something like

logs, value = Test.collect_test_logs() do
    foo()
end
sym, val = collect(pairs(logs[1].kwargs))[1]
@test sym ≡ :s && occursin(r"world", val)

It would be great to have more of this functionality documented/exported.

1 Like