Skip to content

Commit febee82

Browse files
committed
Merge pull request #1974 from ericmj/exunit-teardown
ex_unit teardown should run even if setup fails
2 parents 66d8cdc + 8d59c00 commit febee82

File tree

1 file changed

+36
-19
lines changed

1 file changed

+36
-19
lines changed

lib/ex_unit/lib/ex_unit/runner.ex

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -153,30 +153,18 @@ defmodule ExUnit.Runner do
153153

154154
# Run test in a new process so that we can trap exits for a single test
155155
self_pid = self
156-
{ test_pid, test_ref } = Process.spawn_monitor fn ->
157-
{ us, test } = :timer.tc(fn ->
158-
try do
159-
context = context |> Keyword.merge(test.tags) |> Keyword.put(:test, test.name)
160-
{ :ok, context } = case_name.__ex_unit__(:setup, context)
161-
162-
test = try do
163-
apply case_name, test.name, [context]
164-
test.state(:passed)
165-
catch
166-
kind1, error1 ->
167-
test.state { :failed, { kind1, Exception.normalize(kind1, error1), pruned_stacktrace } }
168-
end
156+
{ test_pid, test_ref } = Process.spawn_monitor(fn ->
169157

170-
case_name.__ex_unit__(:teardown, context)
171-
test
172-
catch
173-
kind2, error2 ->
174-
test.state { :failed, { kind2, Exception.normalize(kind2, error2), pruned_stacktrace } }
158+
{ us, test } = :timer.tc(fn ->
159+
{ test, context } = exec_setup(test, context)
160+
if nil?(test.state) do
161+
test = exec_test(test, context)
175162
end
163+
exec_teardown(test, context)
176164
end)
177165

178166
self_pid <- { self, :test_finished, test.time(us) }
179-
end
167+
end)
180168

181169
receive do
182170
{ ^test_pid, :test_finished, test } ->
@@ -190,6 +178,35 @@ defmodule ExUnit.Runner do
190178
test.state { :skip, "due to #{mismatch} filter" }
191179
end
192180

181+
defp exec_setup(ExUnit.Test[] = test, context) do
182+
context = context |> Keyword.merge(test.tags) |> Keyword.put(:test, test.name)
183+
{ :ok, context } = test.case.__ex_unit__(:setup, context)
184+
{ test, context }
185+
catch
186+
kind2, error2 ->
187+
{ test.state({ :failed, { kind2, Exception.normalize(kind2, error2), pruned_stacktrace } }), context }
188+
end
189+
190+
defp exec_test(ExUnit.Test[] = test, context) do
191+
apply(test.case, test.name, [context])
192+
test.state(:passed)
193+
catch
194+
kind, error ->
195+
test.state { :failed, { kind, Exception.normalize(kind, error), pruned_stacktrace } }
196+
end
197+
198+
defp exec_teardown(ExUnit.Test[] = test, context) do
199+
{ :ok, _context } = test.case.__ex_unit__(:teardown, context)
200+
test
201+
catch
202+
kind, error ->
203+
if nil?(test.state) do
204+
test.state { :failed, { kind, Exception.normalize(kind, error), pruned_stacktrace } }
205+
else
206+
test
207+
end
208+
end
209+
193210
## Helpers
194211

195212
defp take_async_cases(Config[] = config, count) do

0 commit comments

Comments
 (0)