ream88

ream88

Tracing and asserting function calls

I recently encountered an issue where a partial or functional component was re-rendered multiple times, resulting in an inline function call being executed multiple times as well. This led to multiple database requests instead of just one. The problem was challenging to debug. I initially had some flaky tests and discovered that the issue was not related to render_async which was my first suspect. Instead, something else was happening with my live view. Using an IO.puts call, I found that my function was called six times instead of the expected single call.

I resolved the problem by assigning the specific assigns my function call depended on, rather than using {assigns} when rendering the partial.

My question for the Elixir community is: Is there a way to trace and debug such scenarios? I’m aware of :dbg and the possibility of mocking function calls using mox or similar tools. However, I’m wondering if there’s an existing library that allows setting expectations about function calls and asserting on them.

Marked As Solved

Also Liked

LostKobrakai

LostKobrakai

Take a look at Extrace. It’ll format traces with elixir syntax over erlang syntax.

ream88

ream88

Opps Sunday afternoon programming escalation:

defmodule Tracer do
  @moduledoc false

  import ExUnit.Assertions, only: [assert: 1]

  def start_link do
    Agent.start_link(fn -> %{expectations: %{}, traces: %{}} end, name: __MODULE__)

    :dbg.start()

    :dbg.tracer(
      :process,
      {fn {:trace, _pid, :call, {module, function, args}}, _state ->
        Agent.update(__MODULE__, fn state ->
          update_in(state, [:traces, {module, function, length(args)}], fn
            nil -> 1
            count -> count + 1
          end)
        end)
      end, nil}
    )

    :dbg.p(:all, :c)

    :ok
  end

  def expect(module, function, arity, count \\ 1) do
    Agent.update(__MODULE__, fn state ->
      put_in(state, [:expectations, {module, function, arity}], count)
    end)

    :dbg.tp(module, function, arity, [])

    :ok
  end

  def verify do
    %{expectations: expectations, traces: traces} = Agent.get(__MODULE__, & &1)
    assert expectations == traces
  end

  def verify_on_exit! do
    ExUnit.Callbacks.on_exit(Tracer, fn -> Tracer.verify() end)
  end
end

This module can be used similar to Mox like this:

test "renders list of posts", %{user: user, conn: conn} do
  Tracer.expect(MyApp.Posts, :get_posts, 1, count)
  # ...
end

Now it properly asserts that this function is called count times:

 Assertion with == failed
 code:  assert expectations == traces
 left:  %{{MyApp.Posts, : get_posts, 1} => 2}
 right: %{{MyApp.Posts, : get_posts, 1} => 1}

Will probably clean it up a little bit more (for example replace the Agent with a proper GenServer and implement nicer error messages) and then publish it on hex :blush: Any suggestions for a nice name?

ream88

ream88

I now ended up with the following helper for my ExUnit.Cases:

def setup_trace(%{trace: mfas}) when is_list(mfas) do
  :dbg.start()
  :dbg.tracer()
  :dbg.p(:all, :c)

  Enum.each(mfas, fn {mod, fun, arity} -> :dbg.tp(mod, fun, arity, []) end)

  on_exit(fn ->
    :dbg.stop()
  end)
end

def setup_trace(%{trace: mfa}), do: setup_trace(%{trace: [mfa]})

def setup_trace(_tags), do: :ok

This allows me to tag my tests:

@tag trace: {MyApp.Posts, :get_posts, 1}
test "renders list of posts", %{user: user, conn: conn} do
  # ...
end

This is better than nothing as it allows me to at least visually see multiple calls of my functions. I will maybe investigate a little bit more to check if I can come up with custom assertions.

Where Next?

Popular in Questions Top

pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

We're in Beta

About us Mission Statement