Extract AST from code in tests (using ExUnit) seems not possible

Hello,
I try to modifiy the AST of a function.
In order to debug/test, I want to print the AST, but when I’m using ExUnit, it seems I can’t do it. Function can be executed properly but not ASTify (if this word exists) and printed.
Could someone help me on this or at least explain why this is happening.
I wrote a short example if you want to test.
Thank youu.

defmodule MyModule do
  def my_function(fun) do
    fun.()
  end

  def my_function_ast(fun) do
    Macro.to_string(fun)
    |> IO.inspect()
  end
end

defmodule WeirdTest do
  use ExUnit.Case

  test "function is well executed" do
    assert 2 ==
             MyModule.my_function(fn ->
               1 + 1
             end)
  end

  test "AST is not the one of the function but the test's one!!!" do
    # This returns: "#Function<0.107937300/0 in WeirdTest.\"test AST is not the one of the function but the test's one!!!\"/1>"
    MyModule.my_function_ast(fn ->
      1 + 1
    end)
  end

  # test "And this is raising an UndefinedError" do
  #   fn ->
  #     1 + 1
  #   end
  #   |> Code.string_to_quoted!()
  #   |> IO.inspect()
  # end
end

Functions get passed in values and functions are values.

If you want to pass an AST then you need a macro to call or unquote manually.

2 Likes