diff --git a/lib/aprsme/cache.ex b/lib/aprsme/cache.ex index 5489d18..48556d8 100644 --- a/lib/aprsme/cache.ex +++ b/lib/aprsme/cache.ex @@ -172,11 +172,9 @@ defmodule Aprsme.Cache do @impl true def handle_call({:stats, cache_name}, _from, state) do result = - try do - info = :ets.info(cache_name) - {:ok, %{size: Keyword.get(info, :size, 0)}} - rescue - ArgumentError -> {:error, :no_cache} + case :ets.info(cache_name) do + :undefined -> {:error, :no_cache} + info when is_list(info) -> {:ok, %{size: Keyword.get(info, :size, 0)}} end {:reply, result, state} diff --git a/test/aprsme/cache_test.exs b/test/aprsme/cache_test.exs index b753ee9..b1af4c6 100644 --- a/test/aprsme/cache_test.exs +++ b/test/aprsme/cache_test.exs @@ -138,5 +138,52 @@ defmodule Aprsme.CacheTest do test "put returns error for non-existent table" do assert {:error, :no_cache} = Cache.put(:nonexistent_table, :key, "value") end + + test "del returns error for non-existent table" do + assert {:error, :no_cache} = Cache.del(:nonexistent_table, :key) + end + + test "clear returns error for non-existent table" do + assert {:error, :no_cache} = Cache.clear(:nonexistent_table) + end + end + + describe "stats/1" do + test "returns the current size of the cache" do + Cache.put(@table_name, :a, 1) + Cache.put(@table_name, :b, 2) + assert {:ok, %{size: size}} = Cache.stats(@table_name) + assert size == 2 + end + + test "returns error for non-existent tables" do + assert {:error, :no_cache} = Cache.stats(:does_not_exist_table) + end + end + + describe "legacy 2-element tuple lookups" do + test "get handles tuples that lack an expires_at" do + :ets.insert(@table_name, {:legacy_key, "legacy_value"}) + assert {:ok, "legacy_value"} = Cache.get(@table_name, :legacy_key) + end + + test "ttl handles legacy tuples (returns nil)" do + :ets.insert(@table_name, {:legacy_key, "legacy_value"}) + assert {:ok, nil} = Cache.ttl(@table_name, :legacy_key) + end + end + + describe "to_timeout/1 with more units" do + test "supports :millisecond/:milliseconds keys" do + assert Cache.to_timeout(millisecond: 500) == 500 + assert Cache.to_timeout(milliseconds: 250) == 250 + end + + test "ignores invalid TTL values in put/4" do + # Negative TTL → :infinity under the clause that matches `_ -> :infinity`. + assert {:ok, true} = Cache.put(@table_name, :inf_key, "val", ttl: -1) + assert {:ok, "val"} = Cache.get(@table_name, :inf_key) + assert {:ok, nil} = Cache.ttl(@table_name, :inf_key) + end end end