Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Agent

elixir/agent.livemd

Agent

Key-Value Modules

defmodule KV do
  @moduledoc """
  Documentation for KV.
  """

  def hello do
    :world
  end
end
{:module, KV, <<70, 79, 82, 49, 0, 0, 5, ...>>, {:hello, 0}}
defmodule KV.Bucket do
  use Agent

  def start_link() do
    Agent.start_link(fn -> %{} end)
  end

  def put(agent, key, value) do
    Agent.update(agent, fn state ->
      Map.put(state, key, value)
    end)
  end

  def get(agent, key) do
    Agent.get(agent, fn state ->
      Map.get(state, key)
    end)
  end

  def del(agent, key) do
    Agent.get_and_update(agent, fn state ->
      Map.pop(state, key)
    end)
  end
end
{:module, KV.Bucket, <<70, 79, 82, 49, 0, 0, 12, ...>>, {:del, 2}}

Test Suite

ExUnit.start(auto_run: false)

defmodule KVTest do
  use ExUnit.Case
  doctest KV

  test "greets the world" do
    assert KV.hello() == :world
  end
end

defmodule KV.BucketTest do
  use ExUnit.Case, async: true

  setup do
    {:ok, bucket} = KV.Bucket.start_link()
    %{bucket: bucket}
  end

  test "stores values by key", %{bucket: bucket} do
    assert KV.Bucket.get(bucket, "milk") == nil
    KV.Bucket.put(bucket, "milk", 3)
    assert KV.Bucket.get(bucket, "milk") == 3
  end

  test "deletes an existing key", %{bucket: bucket} do
    KV.Bucket.put(bucket, "milk", 3)
    assert KV.Bucket.get(bucket, "milk") == 3
    KV.Bucket.del(bucket, "milk")
    assert KV.Bucket.get(bucket, "milk") == nil
  end
end

ExUnit.run()
...
Finished in 0.00 seconds (0.00s async, 0.00s sync)
3 tests, 0 failures

Randomized with seed 832825
%{excluded: 0, failures: 0, skipped: 0, total: 3}