|
| 1 | +import json |
| 2 | +import tempfile |
| 3 | +import unittest |
| 4 | + |
| 5 | +from common.cache import Cache |
| 6 | + |
| 7 | + |
| 8 | +class TestCache(unittest.TestCase): |
| 9 | + def setUp(self): |
| 10 | + self.cache = Cache(tempfile.gettempdir()) |
| 11 | + |
| 12 | + def test_cache_put(self): |
| 13 | + """it should store cache in specified key""" |
| 14 | + value = {"foo": "a-foo", "bar": 42} |
| 15 | + key = "a_key" |
| 16 | + |
| 17 | + # When |
| 18 | + self.cache.put(key, value) |
| 19 | + act_value = self.cache.get(key) |
| 20 | + |
| 21 | + # Then |
| 22 | + self.assertDictEqual(value, act_value) |
| 23 | + |
| 24 | + def test_cache_put_overwrite(self): |
| 25 | + """it should store updated cache value""" |
| 26 | + value = {"foo": "a-foo", "bar": 42} |
| 27 | + key = "a_key" |
| 28 | + self.cache.put(key, value) |
| 29 | + |
| 30 | + new_value = {"foo": "new-foo"} |
| 31 | + self.cache.put(key, new_value) |
| 32 | + |
| 33 | + # When |
| 34 | + updated_value = self.cache.get(key) |
| 35 | + |
| 36 | + # Then |
| 37 | + self.assertDictEqual(new_value, updated_value) |
| 38 | + |
| 39 | + def test_key_not_found(self): |
| 40 | + """it should return None if key doesn't exist""" |
| 41 | + value = self.cache.get("it-does-not-exist") |
| 42 | + self.assertIsNone(value) |
| 43 | + |
| 44 | + def test_delete(self): |
| 45 | + """it should delete key""" |
| 46 | + key = "a_key" |
| 47 | + self.cache.put(key, {"a": "b"}) |
| 48 | + self.cache.delete(key) |
| 49 | + |
| 50 | + value = self.cache.get(key) |
| 51 | + self.assertIsNone(value) |
| 52 | + |
| 53 | + def test_write_to_file(self): |
| 54 | + """it should update the cache file""" |
| 55 | + value = {"foo": "a-long-foo-so-to-make-sure-truncate-is-working", "bar": 42} |
| 56 | + key = "a_key" |
| 57 | + self.cache.put(key, value) |
| 58 | + # Add one and delete to make sure file gets updated |
| 59 | + self.cache.put("to-delete-key", {"x": "y"}) |
| 60 | + self.cache.delete("to-delete-key") |
| 61 | + |
| 62 | + # When |
| 63 | + new_value = {"a": "b"} |
| 64 | + self.cache.put(key, new_value) |
| 65 | + |
| 66 | + # Then |
| 67 | + with open(self.cache.cache_file.name, "r") as stored: |
| 68 | + content = json.loads(stored.read()) |
| 69 | + self.assertDictEqual(content[key], new_value) |
0 commit comments