A few simple koans about agents

This commit is contained in:
Felipe Sere
2016-04-09 21:29:37 +01:00
parent 4dd877e820
commit 12a511b309
3 changed files with 48 additions and 0 deletions

36
lib/koans/14_agents.ex Normal file
View File

@@ -0,0 +1,36 @@
defmodule Agents do
use Koans
koan "Agents maintain state, so you can ask them about it" do
Agent.start_link(fn() -> "Hi there" end, name: __MODULE__)
assert Agent.get(__MODULE__, &(&1)) == :__
end
koan "Update to update the state" do
Agent.start_link(fn() -> "Hi there" end, name: __MODULE__)
Agent.update(__MODULE__, fn(old) ->
String.upcase(old)
end)
assert Agent.get(__MODULE__, &(&1)) == :__
end
koan "Use get_and_update when you need read and change a value in one go" do
Agent.start_link(fn() -> ["Milk"] end, name: __MODULE__)
old_list = Agent.get_and_update(__MODULE__, fn(old) ->
{old, ["Bread" | old]}
end)
assert old_list == :__
assert Agent.get(__MODULE__, &(&1)) == :__
end
koan "Somebody has to switch off the light at the end of the day" do
Agent.start_link(fn() -> ["Milk"] end, name: __MODULE__)
result = Agent.stop(__MODULE__)
assert result == :__
end
end

View File

@@ -12,6 +12,7 @@ defmodule Runner do
Enums,
Processes,
Tasks,
Agents,
]
def koan?(koan), do: Enum.member?(@modules, koan)

View File

@@ -222,6 +222,17 @@ defmodule KoansHarnessTest do
test_all(Tasks, answers)
end
test "Agents" do
answers = [
"Hi there",
"HI THERE",
{:multiple, [["Milk"], ["Bread", "Milk"]]},
:ok,
]
test_all(Agents, answers)
end
def test_all(module, answers) do
module.all_koans
|> Enum.zip(answers)