Skip to content

Commit 9431338

Browse files
author
José Valim
committed
Add timeouts to ExUnit, closes #2660
1 parent 88be750 commit 9431338

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

lib/ex_unit/lib/ex_unit.ex

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,15 @@ defmodule ExUnit do
109109
tests: [ExUnit.Test.t]}
110110
end
111111

112+
defmodule TimeoutError do
113+
defexception [:timeout]
114+
115+
def message(%{timeout: timeout}) do
116+
"test timed out after #{timeout}ms (you can change the test timeout " <>
117+
"by setting \"@tag timeout: x\" where x is an integer in miliseconds)"
118+
end
119+
end
120+
112121
use Application
113122

114123
@doc false

lib/ex_unit/lib/ex_unit/runner.ex

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,12 +208,18 @@ defmodule ExUnit.Runner do
208208
exit(:shutdown)
209209
end)
210210

211+
timeout = Map.get(test.tags, :timeout, 30_000)
212+
211213
test =
212214
receive do
213215
{^test_pid, :test_finished, test} ->
214216
test
215217
{:DOWN, ^test_ref, :process, ^test_pid, error} ->
216218
%{test | state: {:failed, {{:EXIT, test_pid}, error, []}}}
219+
after
220+
timeout ->
221+
Process.exit(test_pid, :kill)
222+
%{test | state: {:failed, {:error, %ExUnit.TimeoutError{timeout: timeout}, []}}}
217223
end
218224

219225
exec_on_exit(test, test_pid)

lib/ex_unit/test/ex_unit_test.exs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,20 @@ defmodule ExUnitTest do
4040
end) =~ "1 tests, 1 failures"
4141
end
4242

43+
test "it supports timeouts" do
44+
defmodule TimeoutTest do
45+
use ExUnit.Case
46+
47+
@tag timeout: 10
48+
test "ok" do
49+
:timer.sleep(:infinity)
50+
end
51+
end
52+
53+
assert capture_io(fn -> ExUnit.run end) =~
54+
"** (ExUnit.TimeoutError) test timed out after 10ms"
55+
end
56+
4357
test "filtering cases with tags" do
4458
defmodule ParityTest do
4559
use ExUnit.Case

0 commit comments

Comments
 (0)