1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
15 from unittest import mock
20 from . import run_test_server
23 return bytearray(random.getrandbits(8) for _ in range(n))
26 class CacheTestThread(threading.Thread):
27 def __init__(self, dir):
28 super(CacheTestThread, self).__init__()
32 c = arvados.cache.SafeHTTPCache(self._dir)
33 url = 'http://example.com/foo'
37 data_in = _random(128)
38 data_in = hashlib.md5(data_in).hexdigest().encode() + b"\n" + data_in
41 digest, _, content = data_out.partition(b"\n")
42 if digest != hashlib.md5(content).hexdigest().encode():
44 except Exception as err:
46 print("cache failed: {}: {}".format(type(err), err), file=sys.stderr)
50 class TestAPIHTTPCache:
51 @pytest.mark.parametrize('data_type', ['discovery', 'keep'])
52 def test_good_storage(self, tmp_path, monkeypatch, data_type):
53 def storage_path(self, subdir='.', mode=0o700):
54 path = tmp_path / subdir
57 monkeypatch.setattr(arvados.util._BaseDirectories, 'storage_path', storage_path)
58 actual = arvados.http_cache(data_type)
59 assert str(actual) == str(tmp_path / data_type)
61 @pytest.mark.parametrize('error', [RuntimeError, FileExistsError, PermissionError])
62 def test_unwritable_storage(self, monkeypatch, error):
63 def fail(self, subdir='.', mode=0o700):
65 monkeypatch.setattr(arvados.util._BaseDirectories, 'storage_path', fail)
66 actual = arvados.http_cache('unwritable')
70 class CacheTest(unittest.TestCase):
72 self._dir = tempfile.mkdtemp()
75 shutil.rmtree(self._dir)
77 def test_cache_crud(self):
78 c = arvados.cache.SafeHTTPCache(self._dir, max_age=0)
79 url = 'https://example.com/foo?bar=baz'
82 self.assertEqual(None, c.get(url))
85 self.assertEqual(data1, c.get(url))
87 self.assertEqual(None, c.get(url))
90 self.assertEqual(data2, c.get(url))
92 def test_cache_threads(self):
95 t = CacheTestThread(dir=self._dir)
100 self.assertTrue(t.ok)
103 class CacheIntegrationTest(run_test_server.TestCaseWithServers):
106 def test_cache_used_by_default_client(self):
107 with mock.patch('arvados.cache.SafeHTTPCache.get') as getter:
108 arvados.api('v1')._rootDesc.get('foobar')
109 getter.assert_called()