1 from __future__ import print_function
2 from __future__ import absolute_import
4 from builtins import str
5 from builtins import range
18 from . import run_test_server
22 return bytearray(random.getrandbits(8) for _ in range(n))
25 class CacheTestThread(threading.Thread):
26 def __init__(self, dir):
27 super(CacheTestThread, self).__init__()
31 c = arvados.cache.SafeHTTPCache(self._dir)
32 url = 'http://example.com/foo'
36 data_in = _random(128)
37 data_in = hashlib.md5(data_in).hexdigest().encode() + b"\n" + data_in
40 digest, _, content = data_out.partition(b"\n")
41 if digest != hashlib.md5(content).hexdigest().encode():
43 except Exception as err:
45 print("cache failed: {}: {}".format(type(err), err), file=sys.stderr)
49 class CacheTest(unittest.TestCase):
51 self._dir = tempfile.mkdtemp()
54 shutil.rmtree(self._dir)
56 def test_cache_create_error(self):
57 _, filename = tempfile.mkstemp()
58 home_was = os.environ['HOME']
59 os.environ['HOME'] = filename
61 c = arvados.http_cache('test')
62 self.assertEqual(None, c)
64 os.environ['HOME'] = home_was
67 def test_cache_crud(self):
68 c = arvados.cache.SafeHTTPCache(self._dir, max_age=0)
69 url = 'https://example.com/foo?bar=baz'
72 self.assertEqual(None, c.get(url))
75 self.assertEqual(data1, c.get(url))
77 self.assertEqual(None, c.get(url))
80 self.assertEqual(data2, c.get(url))
82 def test_cache_threads(self):
85 t = CacheTestThread(dir=self._dir)
93 class CacheIntegrationTest(run_test_server.TestCaseWithServers):
96 def test_cache_used_by_default_client(self):
97 with mock.patch('arvados.cache.SafeHTTPCache.get') as getter:
98 arvados.api('v1')._rootDesc.get('foobar')
99 getter.assert_called()