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.

JEG2

JEG2

Author of Designing Elixir Systems with OTP

Yeah, sorry about this. As @josevalim pointed out, I led you astray. To try and make up for it, I’ll try to explain why this happens.

The other process dies during a GenServer.call() (Agent is just a wrapper over the GenServer layer.) If the called process dies mid-call, GenServer (or really the lower layer gen_server) will try to exit the current process.

That sounded radical to me when I first learned of it, but it makes sense, if you think about it. GenServer.call() is expected to return a value and there’s no return value that makes sense. The expected flow of operations cannot continue.

Anyway, I hope that helps. Sorry I didn’t take the time to actually understand your problem to begin with.

Where Next?

Popular in Questions Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

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
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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
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
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement