1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
14 from unittest import mock
18 from . import run_test_server
21 return bytearray(random.getrandbits(8) for _ in range(n))
24 class CacheTestThread(threading.Thread):
25 def __init__(self, dir):
26 super(CacheTestThread, self).__init__()
30 c = arvados.cache.SafeHTTPCache(self._dir)
31 url = 'http://example.com/foo'
35 data_in = _random(128)
36 data_in = hashlib.md5(data_in).hexdigest().encode() + b"\n" + data_in
39 digest, _, content = data_out.partition(b"\n")
40 if digest != hashlib.md5(content).hexdigest().encode():
42 except Exception as err:
44 print("cache failed: {}: {}".format(type(err), err), file=sys.stderr)
48 class CacheTest(unittest.TestCase):
50 self._dir = tempfile.mkdtemp()
53 shutil.rmtree(self._dir)
55 def test_cache_create_error(self):
56 _, filename = tempfile.mkstemp()
57 home_was = os.environ['HOME']
58 os.environ['HOME'] = filename
60 c = arvados.http_cache('test')
61 self.assertEqual(None, c)
63 os.environ['HOME'] = home_was
66 def test_cache_crud(self):
67 c = arvados.cache.SafeHTTPCache(self._dir, max_age=0)
68 url = 'https://example.com/foo?bar=baz'
71 self.assertEqual(None, c.get(url))
74 self.assertEqual(data1, c.get(url))
76 self.assertEqual(None, c.get(url))
79 self.assertEqual(data2, c.get(url))
81 def test_cache_threads(self):
84 t = CacheTestThread(dir=self._dir)
92 class CacheIntegrationTest(run_test_server.TestCaseWithServers):
95 def test_cache_used_by_default_client(self):
96 with mock.patch('arvados.cache.SafeHTTPCache.get') as getter:
97 arvados.api('v1')._rootDesc.get('foobar')
98 getter.assert_called()