defmodule MemoryStorage.DatabaseTest do
  use ExUnit.Case, async: true

  alias MemoryStorage.Database

  test "fetch!" do
    db =
      Database.open()
      |> Database.put("key", "value")

    assert "value" == Database.fetch!(db, "key")

    assert_raise KeyError, ~r/key \"key2\" not found in: %MemoryStorage.Database{/, fn ->
      Database.fetch!(db, "key2")
    end
  end

  test "fetch" do
    db =
      Database.open()
      |> Database.put("key", "value")

    assert {:ok, "value"} == Database.fetch(db, "key")
    assert :error == Database.fetch(db, "key2")
  end

  test "fetch on empty database" do
    db = Database.open()

    assert :error == Database.fetch(db, "key")
  end

  test "get" do
    db =
      Database.open()
      |> Database.put("key", "value")

    assert "value" == Database.get(db, "key")
    assert is_nil(Database.get(db, "key2"))
  end

  test "to_list" do
    db =
      Database.open()
      |> Database.put("key", "value")
      |> Database.put("key2", "value2")
      |> Database.put("key3", "value3")
      |> Database.put("key4", "value4")

    assert [{"key", "value"}, {"key2", "value2"}, {"key3", "value3"}, {"key4", "value4"}] ==
             db
             |> Database.to_list()
             |> Enum.sort()
  end
end
