1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
15 from unittest import mock
20 from arvados._internal import basedirs
22 from . import run_test_server
25 return bytearray(random.getrandbits(8) for _ in range(n))
27 class CacheTestThread(threading.Thread):
28 def __init__(self, dir):
29 super(CacheTestThread, self).__init__()
33 c = arvados.api.ThreadSafeHTTPCache(self._dir)
34 url = 'http://example.com/foo'
38 data_in = _random(128)
39 data_in = hashlib.md5(data_in).hexdigest().encode() + b"\n" + data_in
42 digest, _, content = data_out.partition(b"\n")
43 if digest != hashlib.md5(content).hexdigest().encode():
45 except Exception as err:
47 print("cache failed: {}: {}".format(type(err), err), file=sys.stderr)
51 class TestAPIHTTPCache:
52 @pytest.mark.parametrize('data_type', ['discovery', 'keep'])
53 def test_good_storage(self, tmp_path, monkeypatch, data_type):
54 def storage_path(self, subdir='.', mode=0o700):
55 path = tmp_path / subdir
58 monkeypatch.setattr(basedirs.BaseDirectories, 'storage_path', storage_path)
59 actual = arvados.http_cache(data_type)
60 assert str(actual) == str(tmp_path / data_type)
62 @pytest.mark.parametrize('error', [RuntimeError, FileExistsError, PermissionError])
63 def test_unwritable_storage(self, monkeypatch, error):
64 def fail(self, subdir='.', mode=0o700):
66 monkeypatch.setattr(basedirs.BaseDirectories, 'storage_path', fail)
67 actual = arvados.http_cache('unwritable')
71 class CacheTest(unittest.TestCase):
73 self._dir = tempfile.mkdtemp()
76 shutil.rmtree(self._dir)
78 def test_cache_crud(self):
79 c = arvados.api.ThreadSafeHTTPCache(self._dir, max_age=0)
80 url = 'https://example.com/foo?bar=baz'
83 self.assertEqual(None, c.get(url))
86 self.assertEqual(data1, c.get(url))
88 self.assertEqual(None, c.get(url))
91 self.assertEqual(data2, c.get(url))
93 def test_cache_threads(self):
96 t = CacheTestThread(dir=self._dir)
101 self.assertTrue(t.ok)
104 class CacheIntegrationTest(run_test_server.TestCaseWithServers):
107 def test_cache_used_by_default_client(self):
108 with mock.patch('arvados.api.ThreadSafeHTTPCache.get') as getter:
109 arvados.api('v1')._rootDesc.get('foobar')
110 getter.assert_called()