Combining @eval and @testset macros

I’m trying to test two types that have similar properties. I want to perform the same set of tests on instances of the two types. If I was using Python, I would use the @pytest.mark.parametrize decorator to accomplish this.

I’ve read about using the @eval macro to generate code in Julia. The following code works for me:

for symbol in [:MyType1, :MyType2]
    @eval @testset "Test my two types" begin
        obj = $symbol(args)

        @test foo(obj)
        @test bar(obj)
    end
end

I’d like to put the symbol into the testset name so two different names are printed on the terminal during the test run, instead of the same name twice. But this fails:

for symbol in [:MyType1, :MyType2]
    @eval @testset String(symbol) begin
        obj = $symbol(args)

        @test foo(obj)
        @test bar(obj)
    end
end
ERROR: LoadError: LoadError: UndefVarError: symbol not defined

Is there any way I can insert the symbol into the testset name?

Welcome! @testset can also be applied on a for loop and you can interpolate in its name the iterator of the loop, so the standard way to do this is:

@testset "Test type $(T)" for T in (MyType1, MyType2)
    obj = T(args)

    @test foo(obj)
    @test bar(obj)
end

There is also a similar example in @testset docstring

1 Like

Thanks @giordano this worked for me!

1 Like