Skip to content

Commit 5c9b474

Browse files
michalmuskalafishcakez
authored andcommitted
Make assert_raise fail with broken message/1 implementation
Until now, all errors would be swallowed in `Exception.message/1` and would never reach the user.
1 parent d9f11dd commit 5c9b474

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

lib/ex_unit/lib/ex_unit/assertions.ex

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,7 @@ defmodule ExUnit.Assertions do
628628

629629
cond do
630630
name == exception ->
631+
check_error_message(name, error)
631632
error
632633
name == ExUnit.AssertionError ->
633634
reraise(error, stacktrace)
@@ -639,6 +640,15 @@ defmodule ExUnit.Assertions do
639640
end
640641
end
641642

643+
defp check_error_message(module, error) do
644+
module.message(error)
645+
catch
646+
kind, reason ->
647+
stacktrace = System.stacktrace()
648+
649+
flunk "Got exception #{inspect module} but it failed to produce a message with:\n\n" <> Exception.format(kind, reason, stacktrace)
650+
end
651+
642652
@doc """
643653
Asserts that `value1` and `value2` differ by no more than `delta`.
644654

lib/ex_unit/test/ex_unit/assertions_test.exs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,15 @@ defmodule ExUnit.AssertionsTest.Value do
66
def truthy, do: true
77
end
88

9-
alias ExUnit.AssertionsTest.Value
9+
defmodule ExUnit.AssertionsTest.BrokenError do
10+
defexception [:message]
11+
12+
def message(_) do
13+
raise "error"
14+
end
15+
end
16+
17+
alias ExUnit.AssertionsTest.{BrokenError, Value}
1018

1119
defmodule ExUnit.AssertionsTest do
1220
use ExUnit.Case, async: true
@@ -548,6 +556,16 @@ defmodule ExUnit.AssertionsTest do
548556
"\n \"bar\"" = error.message
549557
end
550558

559+
test "assert raise with an exception with bad message/1 implementation" do
560+
assert_raise BrokenError, fn ->
561+
raise BrokenError
562+
end
563+
rescue
564+
error in [ExUnit.AssertionError] ->
565+
"Got exception ExUnit.AssertionsTest.BrokenError but it failed to produce a message with:" <>
566+
"\n\n** (RuntimeError) error\n" <> _ = error.message
567+
end
568+
551569
test "assert greater than operator" do
552570
true = assert 2 > 1
553571
end

0 commit comments

Comments
 (0)