Extract answers from Tasks module

This commit is contained in:
Felipe Sere
2016-03-17 10:13:27 +00:00
parent b70e8ea095
commit e927ad99ca
2 changed files with 19 additions and 7 deletions

View File

@@ -4,20 +4,19 @@ defmodule Tasks do
koan "Tasks can be used for asynchronous computations with results" do koan "Tasks can be used for asynchronous computations with results" do
task = Task.async(fn -> 3 *3 end) task = Task.async(fn -> 3 *3 end)
do_other_stuff() do_other_stuff()
assert Task.await(task) + 1 == 10 assert Task.await(task) + 1 == :__
end end
koan "if you don't need a result, use start_link/1" do koan "if you don't need a result, use start_link/1" do
{:ok, _pid} = Task.start_link(fn -> 1+1 end) {:ok, _pid} = Task.start_link(fn -> 1+1 end)
end end
koan "yield returns nil if the task isn't done yet" do koan "yield returns nothing if the task isn't done yet" do
handle = Task.async(fn -> handle = Task.async(fn ->
:timer.sleep(100) :timer.sleep(100)
3 * 3 3 * 3
end) end)
assert Task.yield(handle, 10) == nil assert Task.yield(handle, 10) == :__
assert Task.await(handle) == 9
end end
koan "tasks can be aborted with shutdown" do koan "tasks can be aborted with shutdown" do
@@ -25,13 +24,13 @@ defmodule Tasks do
:timer.sleep(100) :timer.sleep(100)
3 * 3 3 * 3
end) end)
refute Task.shutdown(handle) assert Task.shutdown(handle) == :__
end end
koan "shutdown will give you an answer if it has it" do koan "shutdown will give you an answer if it has it" do
handle = Task.async(fn -> 3 * 3 end) handle = Task.async(fn -> 3 * 3 end)
:timer.sleep(10) :timer.sleep(10)
assert Task.shutdown(handle) == {:ok, 9} assert Task.shutdown(handle) == {:ok, :__}
end end
koan "you can yield to multiple tasks at once and extract the results" do koan "you can yield to multiple tasks at once and extract the results" do
@@ -40,7 +39,7 @@ defmodule Tasks do
|> Task.yield_many(100) |> Task.yield_many(100)
|> Enum.map(fn({_task,{:ok, result}}) -> result end) |> Enum.map(fn({_task,{:ok, result}}) -> result end)
assert squares == [1,4,9,16] assert squares == :__
end end
def do_other_stuff do def do_other_stuff do

View File

@@ -204,6 +204,19 @@ defmodule KoansHarnessTest do
test_all(Processes, answers) test_all(Processes, answers)
end end
test "Tasks" do
answers = [
10,
:todo,
nil,
nil,
9,
[1,4,9,16]
]
test_all(Tasks, answers)
end
def test_all(module, answers) do def test_all(module, answers) do
module.all_koans module.all_koans
|> Enum.zip(answers) |> Enum.zip(answers)