Updating of variables inside testset


#1

Hi everyone,

I encountered this problem already multiple times and I don’t understand the reason for this behaviour.

I don’t have a minimal working example, but the basic setup is the following:

@testset "FirstSet" begin
    a = 0.1
    b = 0.7
    @testset "SecondSet" begin
        .... Some transformations based on a and b
        .... Check that two different formulations are identical
        @test f(a,b) ≈ g(a,b)
    end
end

This works just fine. However, I would like to do the following, to make sure it works also for different values:

@testset "FirstSet" begin
    a = 0.1
    b = 0.7
    @testset "SecondSet" for a = 0.1:0.1:0.2, b = 0.7:0.1:0.8
        .... Some transformations based on a and b
        .... Check that two different formulations are identical
        @test f(a,b) ≈ g(a,b)
    end
end

Which fails four times. Indeed, even the following fails:

@testset "FirstSet" begin
    @testset "SecondSet" for a = 0.1, b = 0.7
        .... Some transformations based on a and b
        .... Check that two different formulations are identical
        @test f(a,b) ≈ g(a,b)
    end
end

Which is, according to my understand, identical to the first. It seems, however, that it isn’t. Can someone explain to me this behavior? I had this problem already a couple of times.


#2

I managed to find the error. I had inside the second @testset the following statement

g_closure(x) = g(x, y = 1)
term1        = g_closure.(x)

g_closure(x) = g(x,y = 0)
term2        = g_closure.(x)

return term1 - term2

It seems that redefining g_closure does not work inside the begin...end environment. However, the following works:

g_closure1(x) = g(x, y = 1)
term1         = g_closure1.(x)

g_closure2(x) = g(x,y = 0)
term2         = g_closure2.(x)

return term1 - term2

Can someone explain why the first example works in the REPL, but not inside a function?