Testing function with "if @generated"?

How to I test both generated and non-generated implementation paths of a function that uses if @generated? I’m sure I saw something about it once, but I can’t find it again …

1 Like

Have you found an answer to this? I’d want to know the same thing.

No, no solution yet, it seems. :frowning:

The language itself must have some testing of the @generated macro. According to git blame @jeff.bezanson wrote the if @generated functionality into the language. He might have some insight. In the mean time I’ll see if I can find some unit tests in base.

Found it!

https://github.com/JuliaLang/julia/blob/af3cd59e13c93fcb3e3788a79b0168127473d18a/test/staged.jl#L265-L289

Related: https://github.com/JuliaLang/julia/issues/25707

I also opened https://github.com/JuliaLang/julia/issues/38394

Here is my attempt at a solution:

julia> f(x, y) = @generated() ? :x : y
f (generic function with 1 method)

julia> function _invoke(f, x...; generated)
           ci = code_lowered(f, Core.Typeof(x); generated)[1]
           g = @eval @generated function g($([gensym() for _ in x]...))
               return $(QuoteNode(ci))
           end
           Base.invokelatest(g, x...)
       end
_invoke (generic function with 1 method)

julia> _invoke(f, 1, 2; generated=true)
1

julia> _invoke(f, 1, 2; generated=false)
2
3 Likes

I asked this on stack overflow a while back.
Did not get a great answer

https://stackoverflow.com/questions/58612962/how-do-i-test-both-sides-of-a-if-generated

1 Like

This answer seems a bit cleaner to me

https://stackoverflow.com/a/58613544/12884283

Just found this: https://github.com/JuliaData/Tables.jl/issues/144#issue-562125911. Haven’t looked into the details though.