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!

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

1 Like

This answer seems a bit cleaner to me

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