Testing different constant definitions

I have a macro, which creates / defines useful constants for the user. I would like to test if the macro created the correct constants and if they function as expected. How can I get something like the following to work?

@testset "Set 1" begin
    const A = 1
    @test A == 1

@testset "Set 2" begin
    const A = 2
    @test A == 2

Edit: depending on the argument, the macro creates different constants.

What is not working there?

Maybe if you share an example which does not work it will be easier to help.

Probably the redefining of the constant?

You might need to wrap the generation of the constants inside different modules.

julia> module T1
         const A = 1

julia> module T2
         const A = 2

julia> @test T1.A == 1
Test Passed

julia> @test T2.A == 2
Test Passed

Try the example. You get:

ERROR: LoadError: syntax: unsupported `const` declaration on local variable around

I thought about wrapping everything in modules. The only problem is that you can’t define modules within testsets. It’ll complain that the module isn’t being defined at toplevel. This means you’d have to define a bunch modules at the beginning and then test them separately, but this quickly becomes unwieldy.

May be I could use a macro that defines a module at top level, rather than locally within the testset. Let me try that.

You cannot have const variables below global scope (i.e., inside function definitions, for loops, etc…). If your macro did this then it just generated invalid code, and there is not reason to test the macro, you should discard it.

If you will always call the macro always at top level, and you want to check if its behaviour is working in this situation, then you probably should do as you pointed out: “have to define a bunch modules at the beginning and then test them separately”, or you can call the macro for the global scope of all the tests, or yet you can put the tests inside the modules where you call the macro and in the testsets you just call these test functions.

1 Like

So, I’ve fixed my problem by not using metaprogramming, when I should use more ordinary features of julia.