Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trapping GenServer exits in ExUnit tests #3507

Closed
whatyouhide opened this issue Jul 18, 2015 · 2 comments
Closed

Trapping GenServer exits in ExUnit tests #3507

whatyouhide opened this issue Jul 18, 2015 · 2 comments

Comments

@whatyouhide
Copy link
Member

I'm not sure if this a bug or if I'm doing something wrong. Assume the following GenServer:

defmodule Foo do
  use GenServer

  def handle_call(_, _, _) do
    raise "foo"
  end
end

Say I want to trap exits from this genserver. In IEX, it works fine:

iex> Process.flag :trap_exit, true
iex> {:ok, pid} = GenServer.start_link Foo, nil
iex> GenServer.call(pid, :whatever)
** logs a bunch of stuff but doesn't crash IEx
iex> flush()
{:EXIT, ...}

If I do this in an ExUnit test though, the test crashes:

defmodule FooTest do
  use ExUnit.Case

  test "foo shouldn't crash" do
    Process.flag :trap_exit, true
    {:ok, pid} = GenServer.start_link Foo, nil
    GenServer.call(pid, :whatever)

    assert_receive {:EXIT, _, _} # crashes before arriving here
  end
end

What do you think? Also, I made a small Mix project that shows this behaviour (here), if you want you can clone it and run mix test to see it fail, then iex -S mix with the commands above to see exits are trapped indeed.

@ericmj
Copy link
Member

ericmj commented Jul 18, 2015

It's not a bug. If the process exits during a GenServer.call the call will raise [1]. You can try wrapping the call in catch_exit/1 and asserting on that.

[1] https://github.com/erlang/otp/blob/maint/lib/stdlib/src/gen.erl#L175-L176

@whatyouhide
Copy link
Member Author

Hey @ericmj, thanks for the link to the source, very informative. Sorry to have cluttered the issue tracker with a non-issue :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants