Debian Codegraph @

tests/test_lfucache.py

raw
1 import random
2 import pytest
3 import concurrent.futures
4 from deepdiff.lfucache import LFUCache
5
6
7 class TestLFUcache:
8
9 @pytest.mark.parametrize("items, size, expected_results, expected_freq", [
10 (['a', 'a', 'b', 'a', 'c', 'b', 'd'], 3, [('b', 2), ('c', 1), ('d', 1)], '1.333'),
11 (['a', 'a', 'b', 'a', 'c', 'b', 'd', 'e', 'c', 'b'], 3, [('b', 3), ('d', 1), ('e', 1)], '1.666'),
12 (['a', 'a', 'b', 'a', 'c', 'b', 'd', 'e', 'c', 'b', 'b', 'c', 'd', 'b'], 3, [('b', 5), ('c', 3), ('d', 2)], '3.333'),
13 ])
14 def test_lfu(self, items, size, expected_results, expected_freq, benchmark):
15 benchmark(self._test_lfu, items, size, expected_results, expected_freq)
16
17 def _test_lfu(self, items, size, expected_results, expected_freq):
18 lfucache = LFUCache(size)
19 for item in items:
20 lfucache.set(item, value='{}_cached'.format(item))
21 for item in items:
22 lfucache.get(item)
23 results = lfucache.get_sorted_cache_keys()
24 assert expected_results == results
25 freq = lfucache.get_average_frequency()
26 assert expected_freq == str(freq)[:5]
27
28 def test_get_multithreading(self):
29 keys = 'aaaaaaaaaaaaaaaaaaaaaaaaaaabbc'
30 lfucache = LFUCache(2)
31
32 def _do_set(cache, key):
33 cache.set(key, value='{}_cached'.format(key))
34
35 def _do_get(cache, key):
36 return cache.get(key)
37
38 def _key_gen():
39 i = 0
40 while i < 30000:
41 i += 1
42 yield random.choice(keys)
43
44 def _random_func(cache, key):
45 return random.choice([_do_get, _do_get, _do_set])(cache, key)
46
47 with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor:
48 futures = (executor.submit(_random_func, lfucache, key) for key in _key_gen())
49 for future in concurrent.futures.as_completed(futures):
50 future.result()