Looping over macro call produce unexpected results

Hello community

I have found a macro here on Julia Discourse to help me with some testing. The macro looks as follows:

macro testmsg(ex, str)
    quote
        try 
            @test $ex
        catch e
            $str |> println
        end
    end
end

The macro lets us define a custom message if @test fails. So…

julia> k = 1
1

julia> @testmsg k in 1:3 "No"
Test Passed

And

julia> k = 4
4

julia> @testmsg k in 1:10 "No"
Test Failed at c:\Users\s174460\.julia\dev\Scheduling\test\runtests_solution.jl:263
  Expression: k in 1:3
   Evaluated: 4 in 1:3
No

But if I loop over it I get:

julia> for k in 1:4
           @testmsg k in 1:3 "No"
       end
Test Failed at c:\Users\s174460\.julia\dev\Scheduling\test\runtests_solution.jl:263
  Expression: k in 1:3
   Evaluated: 4 in 1:3
No
Test Failed at c:\Users\s174460\.julia\dev\Scheduling\test\runtests_solution.jl:263
  Expression: k in 1:3
   Evaluated: 4 in 1:3
No
Test Failed at c:\Users\s174460\.julia\dev\Scheduling\test\runtests_solution.jl:263
  Expression: k in 1:3
   Evaluated: 4 in 1:3
No
Test Failed at c:\Users\s174460\.julia\dev\Scheduling\test\runtests_solution.jl:263
  Expression: k in 1:3
   Evaluated: 4 in 1:3
No

Like the for loop does not really update the value of k before inserting it into the macro. Does any of you have an idea of how to make this work?

Kind regards

Try

macro testmsg(ex, str)
    quote
        try 
            @test $(esc(ex))
        catch e
            $str |> println
        end
    end
end
3 Likes