1defmodule Cachex.Actions.KeysTest do
2  use CachexCase
3
4  # This test verifies that it's possible to retrieve the keys inside a cache.
5  # It should be noted that the keys function takes TTL into account and only
6  # returns the keys of those records which have not expired. Order is not in
7  # any way guaranteed, even with no cache modification.
8  test "retrieving the keys inside the cache" do
9    # create a forwarding hook
10    hook = ForwardHook.create()
11
12    # create a test cache
13    cache = Helper.create_cache([ hooks: [ hook ] ])
14
15    # fill with some items
16    { :ok, true } = Cachex.put(cache, 1, 1)
17    { :ok, true } = Cachex.put(cache, 2, 2)
18    { :ok, true } = Cachex.put(cache, 3, 3)
19
20    # add some expired items
21    { :ok, true } = Cachex.put(cache, 4, 4, ttl: 1)
22    { :ok, true } = Cachex.put(cache, 5, 5, ttl: 1)
23    { :ok, true } = Cachex.put(cache, 6, 6, ttl: 1)
24
25    # let entries expire
26    :timer.sleep(2)
27
28    # clear all hook
29    Helper.flush()
30
31    # retrieve the keys
32    { status, keys } = Cachex.keys(cache)
33
34    # ensure the status is ok
35    assert(status == :ok)
36
37    # sort the keys
38    result = Enum.sort(keys)
39
40    # only 3 items should come back
41    assert(result == [ 1, 2, 3 ])
42
43    # verify the hooks were updated with the count
44    assert_receive({ { :keys, [[]] }, { ^status, ^keys } })
45  end
46end
47