File size: 6,192 Bytes
476455e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from __future__ import absolute_import
from typing import Optional, Union
from mock.mock import MagicMock, patch
import pytest


from sagemaker.utilities import cache
import datetime


def retrieval_function(key: Optional[int] = None, value: Optional[str] = None) -> str:
    return str(hash(str(key)))


def test_cache_retrieves_item():
    my_cache = cache.LRUCache[int, Union[int, str]](
        max_cache_items=10,
        expiration_horizon=datetime.timedelta(hours=1),
        retrieval_function=retrieval_function,
    )

    my_cache.put(5)
    assert my_cache.get(5, False) == retrieval_function(key=5)

    my_cache.put(6, 7)
    assert my_cache.get(6, False) == 7
    assert len(my_cache) == 2

    my_cache.put(5, 6)
    assert my_cache.get(5, False) == 6
    assert len(my_cache) == 2

    with pytest.raises(KeyError):
        my_cache.get(21, False)


def test_cache_invalidates_old_item():
    my_cache = cache.LRUCache[int, Union[int, str]](
        max_cache_items=10,
        expiration_horizon=datetime.timedelta(milliseconds=1),
        retrieval_function=retrieval_function,
    )

    mock_curr_time = datetime.datetime.fromtimestamp(1636730651.079551)
    with patch("datetime.datetime") as mock_datetime:
        mock_datetime.now.return_value = mock_curr_time
        my_cache.put(5)
        mock_datetime.now.return_value += datetime.timedelta(milliseconds=2)
        with pytest.raises(KeyError):
            my_cache.get(5, False)

    with patch("datetime.datetime") as mock_datetime:
        mock_datetime.now.return_value = mock_curr_time
        my_cache.put(5)
        mock_datetime.now.return_value += datetime.timedelta(milliseconds=0.5)
        assert my_cache.get(5, False) == retrieval_function(key=5)


def test_cache_fetches_new_item():
    my_cache = cache.LRUCache[int, Union[int, str]](
        max_cache_items=10,
        expiration_horizon=datetime.timedelta(milliseconds=1),
        retrieval_function=retrieval_function,
    )

    mock_curr_time = datetime.datetime.fromtimestamp(1636730651.079551)
    with patch("datetime.datetime") as mock_datetime:
        mock_datetime.now.return_value = mock_curr_time
        my_cache.put(5, 10)
        mock_datetime.now.return_value += datetime.timedelta(milliseconds=2)
        assert my_cache.get(5) == retrieval_function(key=5)

    with patch("datetime.datetime") as mock_datetime:
        mock_datetime.now.return_value = mock_curr_time
        my_cache.put(5, 10)
        mock_datetime.now.return_value += datetime.timedelta(milliseconds=0.5)
        assert my_cache.get(5, False) == 10
        mock_datetime.now.return_value += datetime.timedelta(milliseconds=0.75)
        with pytest.raises(KeyError):
            my_cache.get(5, False)


def test_cache_removes_old_items_once_size_limit_reached():
    my_cache = cache.LRUCache[int, Union[int, str]](
        max_cache_items=5,
        expiration_horizon=datetime.timedelta(hours=1),
        retrieval_function=retrieval_function,
    )

    for i in [1, 2, 3, 4, 5]:
        my_cache.put(i)

    assert len(my_cache) == 5

    my_cache.put(6)
    assert len(my_cache) == 5
    with pytest.raises(KeyError):
        my_cache.get(1, False)
    assert my_cache.get(2, False) == retrieval_function(key=2)


def test_cache_get_with_data_source_fallback():
    my_cache = cache.LRUCache[int, Union[int, str]](
        max_cache_items=5,
        expiration_horizon=datetime.timedelta(hours=1),
        retrieval_function=retrieval_function,
    )

    for i in range(10):
        val = my_cache.get(i)
        assert val == retrieval_function(key=i)

    assert len(my_cache) == 5


def test_cache_gets_stored_value():
    my_cache = cache.LRUCache[int, Union[int, str]](
        max_cache_items=5,
        expiration_horizon=datetime.timedelta(hours=1),
        retrieval_function=retrieval_function,
    )

    for i in range(5):
        my_cache.put(i)

    my_cache._retrieval_function = MagicMock()
    my_cache.get(4)
    my_cache._retrieval_function.assert_not_called()

    my_cache._retrieval_function.reset_mock()
    my_cache.get(5)
    my_cache._retrieval_function.assert_called_with(key=5, value=None)

    my_cache._retrieval_function.reset_mock()
    my_cache.get(0)
    my_cache._retrieval_function.assert_called_with(key=0, value=None)


def test_cache_bad_retrieval_function():

    cache_no_retrieval_fx = cache.LRUCache[int, Union[int, str]](
        max_cache_items=5,
        expiration_horizon=datetime.timedelta(hours=1),
        retrieval_function=None,
    )

    with pytest.raises(TypeError):
        cache_no_retrieval_fx.put(1)

    cache_bad_retrieval_fx_signature = cache.LRUCache[int, Union[int, str]](
        max_cache_items=5,
        expiration_horizon=datetime.timedelta(hours=1),
        retrieval_function=lambda: 1,
    )

    with pytest.raises(TypeError):
        cache_bad_retrieval_fx_signature.put(1)

    cache_retrieval_fx_throws = cache.LRUCache[int, Union[int, str]](
        max_cache_items=5,
        expiration_horizon=datetime.timedelta(hours=1),
        retrieval_function=lambda key, value: exec("raise(RuntimeError())"),
    )

    with pytest.raises(RuntimeError):
        cache_retrieval_fx_throws.put(1)


def test_cache_clear_and_contains():
    my_cache = cache.LRUCache[int, Union[int, str]](
        max_cache_items=5,
        expiration_horizon=datetime.timedelta(hours=1),
        retrieval_function=retrieval_function,
    )

    for i in range(5):
        my_cache.put(i)
        assert i in my_cache

    my_cache.clear()
    assert len(my_cache) == 0
    with pytest.raises(KeyError):
        my_cache.get(1, False)