brainbag

brainbag

Can't figure out how to assert error in linked process with ExUnit

I am using an Agent for state. Nothing I have tried for asserting an ArgumentError raised in the Agent has worked! The test fails and the process dies without the assertion working.

Here’s some code that demonstrates. In this function add_action, I want to verify that the value of the map key :actions is a list, and hasn’t been changed to something else.

def start_link do
  Agent.start_link(@name, :init, [], name: @name)
end

def init do 
  %{actions: []}
end

def add_action(action) when is_atom(action) do
  Agent.get_and_update(@name, fn(map) ->
    result = Map.update!(map, :actions, fn
      list when is_list(list) -> [action | list]
      _ -> raise ArgumentError, message: "key :actions is not a list!"
    end)

    {result, result}
  end)
end

Here is the test:

setup do
  {:ok, pid} = State.start_link
  [pid: pid]
end

test "action example", context do 
  # assume State.actions is `42` here instead of `[]`
  assert_raise ArgumentError, fn ->
    # the process dies here, so `assert_raise` is never called
    State.add_action :failure 
  end
end

I have tried catch_exit, catch_error, catch_throw, catch_pokemon, Process.monitor, receive, etc. No matter what, I still get this error message

=ERROR REPORT==== 1-Oct-2016::19:39:16 ===
** Generic server 'Elixir.ManOrActionMan.State' terminating 
** Last message in was {get_and_update,
                           #Fun<Elixir.DepsInstall.State.0.35286781>}
*snip*

I can’t seem to figure out how to catch that ArgumentError, or if that’s even the right approach to raising errors in a process.

Any help is much appreciated!

Marked As Solved

josevalim

josevalim

Creator of Elixir

Trapping exits means that the test process won’t be terminated when the linked process terminates. The call to State.add_action :failure will still fail though so you’ll need to catch_exit it.

Btw, I am also wondering why are you getting exits formatted using the Erlang logger instead of the Elixir one in your initial report. :slight_smile:

Also Liked

brainbag

brainbag

Thanks @JEG2 and @josevalim by your powers combined I am Captain Solution! The tests are passing now. :heart:

In case anyone else ever stumbles through this, here’s my final(?) working test:

test "fails if actions is not a list", context do
  State.set_actions 
  Process.flag :trap_exit, true
  catch_exit do
    State.add_action(:secret)
  end

  pid = context[:pid]
  assert_received({:EXIT, ^pid, {%ArgumentError{message: "actions is not a list"}, _}})
end

@josevalim Your message prompted me to remember that I removed :logger from mix.exs a while ago as a newbie mistake; putting it back changed the Erlang error to an Elixir one. I still see an error print out during the test run, but it passes. I’m sure it’s my fault somehow. :smiley:

josevalim

josevalim

Creator of Elixir

Great! Btw, adding “@tag :capture_log” before the test should silence the
log reports.

JEG2

JEG2

Author of Designing Elixir Systems with OTP

I cracked up at catch_pokemon. :laughing:

You can’t catch the error because it doesn’t happen in the test process. Test it as follows:

  1. Have the test process trap exits
  2. assert_received on the {:EXIT, …} message

Hope that helps.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
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
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
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 47930 226
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

We're in Beta

About us Mission Statement