1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 from __future__ import print_function
6 from __future__ import absolute_import
8 from builtins import str
9 from builtins import range
22 from . import run_test_server
26 return bytearray(random.getrandbits(8) for _ in range(n))
29 class CacheTestThread(threading.Thread):
30 def __init__(self, dir):
31 super(CacheTestThread, self).__init__()
35 c = arvados.cache.SafeHTTPCache(self._dir)
36 url = 'http://example.com/foo'
40 data_in = _random(128)
41 data_in = hashlib.md5(data_in).hexdigest().encode() + b"\n" + data_in
44 digest, _, content = data_out.partition(b"\n")
45 if digest != hashlib.md5(content).hexdigest().encode():
47 except Exception as err:
49 print("cache failed: {}: {}".format(type(err), err), file=sys.stderr)
53 class CacheTest(unittest.TestCase):
55 self._dir = tempfile.mkdtemp()
58 shutil.rmtree(self._dir)
60 def test_cache_create_error(self):
61 _, filename = tempfile.mkstemp()
62 home_was = os.environ['HOME']
63 os.environ['HOME'] = filename
65 c = arvados.http_cache('test')
66 self.assertEqual(None, c)
68 os.environ['HOME'] = home_was
71 def test_cache_crud(self):
72 c = arvados.cache.SafeHTTPCache(self._dir, max_age=0)
73 url = 'https://example.com/foo?bar=baz'
76 self.assertEqual(None, c.get(url))
79 self.assertEqual(data1, c.get(url))
81 self.assertEqual(None, c.get(url))
84 self.assertEqual(data2, c.get(url))
86 def test_cache_threads(self):
89 t = CacheTestThread(dir=self._dir)
97 class CacheIntegrationTest(run_test_server.TestCaseWithServers):
100 def test_cache_used_by_default_client(self):
101 with mock.patch('arvados.cache.SafeHTTPCache.get') as getter:
102 arvados.api('v1')._rootDesc.get('foobar')
103 getter.assert_called()