File: test_factory.py

package info (click to toggle)
aiocache 0.12.3-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 692 kB
  • sloc: python: 5,044; makefile: 221; sh: 7
file content (371 lines) | stat: -rw-r--r-- 12,887 bytes parent folder | download
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
from unittest.mock import Mock, patch

import pytest

from aiocache import AIOCACHE_CACHES, Cache, caches
from aiocache.backends.memory import SimpleMemoryCache
from aiocache.exceptions import InvalidCacheType
from aiocache.factory import _class_from_string, _create_cache
from aiocache.plugins import HitMissRatioPlugin, TimingPlugin
from aiocache.serializers import JsonSerializer, PickleSerializer


CACHE_NAMES = [Cache.MEMORY.NAME]

try:
    from aiocache.backends.memcached import MemcachedCache
except ImportError:
    MemcachedCache = None
else:
    assert Cache.MEMCACHED is not None
    CACHE_NAMES.append(Cache.MEMCACHED.NAME)

try:
    from aiocache.backends.redis import RedisCache
except ImportError:
    RedisCache = None
else:
    assert Cache.REDIS is not None
    CACHE_NAMES.append(Cache.REDIS.NAME)


@pytest.mark.redis
def test_class_from_string():
    assert _class_from_string("aiocache.RedisCache") == RedisCache


@pytest.mark.redis
def test_create_simple_cache():
    redis = _create_cache(RedisCache, endpoint="127.0.0.10", port=6378)

    assert isinstance(redis, RedisCache)
    assert redis.endpoint == "127.0.0.10"
    assert redis.port == 6378


def test_create_cache_with_everything():
    cache = _create_cache(
        SimpleMemoryCache,
        serializer={"class": PickleSerializer, "encoding": "encoding"},
        plugins=[{"class": "aiocache.plugins.TimingPlugin"}],
    )

    assert isinstance(cache.serializer, PickleSerializer)
    assert cache.serializer.encoding == "encoding"
    assert isinstance(cache.plugins[0], TimingPlugin)


class TestCache:
    def test_cache_types(self):
        assert Cache.MEMORY == SimpleMemoryCache
        assert Cache.REDIS == RedisCache
        assert Cache.MEMCACHED == MemcachedCache

    @pytest.mark.parametrize("cache_type", CACHE_NAMES)
    async def test_new(self, cache_type):
        kwargs = {"a": 1, "b": 2}
        cache_class = Cache.get_scheme_class(cache_type)

        with patch("aiocache.{}.__init__".format(cache_class.__name__)) as init:
            cache = Cache(cache_class, **kwargs)
            assert isinstance(cache, cache_class)
            init.assert_called_once_with(**kwargs)

    def test_new_defaults_to_memory(self):
        assert isinstance(Cache(), Cache.MEMORY)

    @pytest.mark.parametrize("cache_type", (None, object))
    def test_new_invalid_cache_raises(self, cache_type):
        with pytest.raises(InvalidCacheType) as e:
            Cache(cache_type)
        assert str(e.value) == "Invalid cache type, you can only use {}".format(
            list(AIOCACHE_CACHES.keys())
        )

    @pytest.mark.parametrize("scheme", CACHE_NAMES)
    def test_get_scheme_class(self, scheme):
        assert Cache.get_scheme_class(scheme) == AIOCACHE_CACHES[scheme]

    def test_get_scheme_class_invalid(self):
        with pytest.raises(InvalidCacheType):
            Cache.get_scheme_class("http")

    @pytest.mark.parametrize("scheme", CACHE_NAMES)
    def test_from_url_returns_cache_from_scheme(self, scheme):
        assert isinstance(Cache.from_url("{}://".format(scheme)), Cache.get_scheme_class(scheme))

    @pytest.mark.parametrize(
        "url,expected_args",
        [
            ("redis://", {}),
            ("redis://localhost", {"endpoint": "localhost"}),
            ("redis://localhost/", {"endpoint": "localhost"}),
            ("redis://localhost:6379", {"endpoint": "localhost", "port": 6379}),
            (
                "redis://localhost/?arg1=arg1&arg2=arg2",
                {"endpoint": "localhost", "arg1": "arg1", "arg2": "arg2"},
            ),
            (
                "redis://localhost:6379/?arg1=arg1&arg2=arg2",
                {"endpoint": "localhost", "port": 6379, "arg1": "arg1", "arg2": "arg2"},
            ),
            ("redis:///?arg1=arg1", {"arg1": "arg1"}),
            ("redis:///?arg2=arg2", {"arg2": "arg2"}),
            (
                "redis://:password@localhost:6379",
                {"endpoint": "localhost", "password": "password", "port": 6379},
            ),
            (
                "redis://:password@localhost:6379?password=pass",
                {"endpoint": "localhost", "password": "password", "port": 6379},
            ),
        ],
    )
    def test_from_url_calls_cache_with_args(self, url, expected_args):
        with patch("aiocache.factory.Cache", autospec=True) as mock:
            Cache.from_url(url)

        mock.assert_called_once_with(mock.get_scheme_class.return_value, **expected_args)

    def test_calls_parse_uri_path_from_cache(self):
        p_mock = Mock(spec_set=(), return_value={"arg1": "arg1"})
        with patch("aiocache.factory.Cache", autospec=True) as mock:
            mock.get_scheme_class.return_value.parse_uri_path = p_mock
            Cache.from_url("redis:///")

        mock.get_scheme_class.return_value.parse_uri_path.assert_called_once_with("/")
        mock.assert_called_once_with(mock.get_scheme_class.return_value, arg1="arg1")

    def test_from_url_invalid_protocol(self):
        with pytest.raises(InvalidCacheType):
            Cache.from_url("http://")


class TestCacheHandler:
    @pytest.fixture(autouse=True)
    def remove_caches(self):
        caches._caches = {}

    def test_add_new_entry(self):
        alias = "memory"
        config = {
            "cache": "aiocache.SimpleMemoryCache",
            "serializer": {"class": "aiocache.serializers.StringSerializer"},
        }
        caches.add(alias, config)

        assert caches.get_config()[alias] == config

    def test_add_updates_existing_entry(self):
        alias = "memory"
        config = {
            "cache": "aiocache.SimpleMemoryCache",
            "serializer": {"class": "aiocache.serializers.StringSerializer"},
        }
        caches.add(alias, {})
        caches.add(alias, config)

        assert caches.get_config()[alias] == config

    def test_get_wrong_alias(self):
        with pytest.raises(KeyError):
            caches.get("wrong_cache")

        with pytest.raises(KeyError):
            caches.create("wrong_cache")

    def test_reuse_instance(self):
        assert caches.get("default") is caches.get("default")

    def test_create_not_reuse(self):
        assert caches.create("default") is not caches.create("default")

    @pytest.mark.redis
    def test_create_extra_args(self):
        caches.set_config(
            {
                "default": {
                    "cache": "aiocache.RedisCache",
                    "endpoint": "127.0.0.9",
                    "db": 10,
                    "port": 6378,
                }
            }
        )
        cache = caches.create("default", namespace="whatever", endpoint="127.0.0.10", db=10)
        assert cache.namespace == "whatever"
        assert cache.endpoint == "127.0.0.10"
        assert cache.db == 10

    @pytest.mark.redis
    def test_retrieve_cache(self):
        caches.set_config(
            {
                "default": {
                    "cache": "aiocache.RedisCache",
                    "endpoint": "127.0.0.10",
                    "port": 6378,
                    "ttl": 10,
                    "serializer": {
                        "class": "aiocache.serializers.PickleSerializer",
                        "encoding": "encoding",
                    },
                    "plugins": [
                        {"class": "aiocache.plugins.HitMissRatioPlugin"},
                        {"class": "aiocache.plugins.TimingPlugin"},
                    ],
                }
            }
        )

        cache = caches.get("default")
        assert isinstance(cache, RedisCache)
        assert cache.endpoint == "127.0.0.10"
        assert cache.port == 6378
        assert cache.ttl == 10
        assert isinstance(cache.serializer, PickleSerializer)
        assert cache.serializer.encoding == "encoding"
        assert len(cache.plugins) == 2

    @pytest.mark.redis
    def test_retrieve_cache_new_instance(self):
        caches.set_config(
            {
                "default": {
                    "cache": "aiocache.RedisCache",
                    "endpoint": "127.0.0.10",
                    "port": 6378,
                    "serializer": {
                        "class": "aiocache.serializers.PickleSerializer",
                        "encoding": "encoding",
                    },
                    "plugins": [
                        {"class": "aiocache.plugins.HitMissRatioPlugin"},
                        {"class": "aiocache.plugins.TimingPlugin"},
                    ],
                }
            }
        )

        cache = caches.create("default")
        assert isinstance(cache, RedisCache)
        assert cache.endpoint == "127.0.0.10"
        assert cache.port == 6378
        assert isinstance(cache.serializer, PickleSerializer)
        assert cache.serializer.encoding == "encoding"
        assert len(cache.plugins) == 2

    @pytest.mark.redis
    def test_multiple_caches(self):
        caches.set_config(
            {
                "default": {
                    "cache": "aiocache.RedisCache",
                    "endpoint": "127.0.0.10",
                    "port": 6378,
                    "serializer": {"class": "aiocache.serializers.PickleSerializer"},
                    "plugins": [
                        {"class": "aiocache.plugins.HitMissRatioPlugin"},
                        {"class": "aiocache.plugins.TimingPlugin"},
                    ],
                },
                "alt": {"cache": "aiocache.SimpleMemoryCache"},
            }
        )

        default = caches.get("default")
        alt = caches.get("alt")

        assert isinstance(default, RedisCache)
        assert default.endpoint == "127.0.0.10"
        assert default.port == 6378
        assert isinstance(default.serializer, PickleSerializer)
        assert len(default.plugins) == 2

        assert isinstance(alt, SimpleMemoryCache)

    def test_default_caches(self):
        assert caches.get_config() == {
            "default": {
                "cache": "aiocache.SimpleMemoryCache",
                "serializer": {"class": "aiocache.serializers.NullSerializer"},
            }
        }

    def test_get_alias_config(self):
        assert caches.get_alias_config("default") == {
            "cache": "aiocache.SimpleMemoryCache",
            "serializer": {"class": "aiocache.serializers.NullSerializer"},
        }

    def test_set_empty_config(self):
        with pytest.raises(ValueError):
            caches.set_config({})

    def test_set_config_updates_existing_values(self):
        assert not isinstance(caches.get("default").serializer, JsonSerializer)
        caches.set_config(
            {
                "default": {
                    "cache": "aiocache.SimpleMemoryCache",
                    "serializer": {"class": "aiocache.serializers.JsonSerializer"},
                }
            }
        )
        assert isinstance(caches.get("default").serializer, JsonSerializer)

    def test_set_config_removes_existing_caches(self):
        caches.set_config(
            {
                "default": {"cache": "aiocache.SimpleMemoryCache"},
                "alt": {"cache": "aiocache.SimpleMemoryCache"},
            }
        )
        caches.get("default")
        caches.get("alt")
        assert len(caches._caches) == 2

        caches.set_config(
            {
                "default": {"cache": "aiocache.SimpleMemoryCache"},
                "alt": {"cache": "aiocache.SimpleMemoryCache"},
            }
        )
        assert caches._caches == {}

    def test_set_config_no_default(self):
        with pytest.raises(ValueError):
            caches.set_config(
                {
                    "no_default": {
                        "cache": "aiocache.RedisCache",
                        "endpoint": "127.0.0.10",
                        "port": 6378,
                        "serializer": {"class": "aiocache.serializers.PickleSerializer"},
                        "plugins": [
                            {"class": "aiocache.plugins.HitMissRatioPlugin"},
                            {"class": "aiocache.plugins.TimingPlugin"},
                        ],
                    }
                }
            )

    @pytest.mark.redis
    def test_ensure_plugins_order(self):
        caches.set_config(
            {
                "default": {
                    "cache": "aiocache.RedisCache",
                    "plugins": [
                        {"class": "aiocache.plugins.HitMissRatioPlugin"},
                        {"class": "aiocache.plugins.TimingPlugin"},
                    ],
                }
            }
        )

        cache = caches.get("default")
        assert isinstance(cache.plugins[0], HitMissRatioPlugin)

        cache = caches.create("default")
        assert isinstance(cache.plugins[0], HitMissRatioPlugin)