Import python modules by their hash.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

814 lines
21 KiB

  1. # Copyright 2020 John-Mark Gurney.
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions
  6. # are met:
  7. # 1. Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  14. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  17. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  19. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  20. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  23. # SUCH DAMAGE.
  24. import configparser
  25. import contextlib
  26. import filecmp
  27. import functools
  28. import glob
  29. import hashlib
  30. import importlib.resources
  31. import mock
  32. import os.path
  33. import pathlib
  34. import shutil
  35. import sys
  36. import tempfile
  37. import urllib.request
  38. from importlib.abc import MetaPathFinder, Loader
  39. from importlib.machinery import ModuleSpec
  40. __author__ = 'John-Mark Gurney'
  41. __copyright__ = 'Copyright 2020 John-Mark Gurney. All rights reserved.'
  42. __license__ = '2-clause BSD license'
  43. __version__ = '0.1.0.dev'
  44. def _printanyexc(f): # pragma: no cover
  45. '''Prints any exception that gets raised by the wrapped function.'''
  46. @functools.wraps(f)
  47. def wrapper(*args, **kwargs):
  48. try:
  49. return f(*args, **kwargs)
  50. except Exception:
  51. import traceback
  52. traceback.print_exc()
  53. raise
  54. return wrapper
  55. @contextlib.contextmanager
  56. def tempset(obj, key, value):
  57. '''A context (with) manager for changing the value of an item in a
  58. dictionary, and restoring it after the with block.
  59. Example usage:
  60. ```
  61. d = dict(a=5, b=10)
  62. with tempset(d, 'a', 15):
  63. print(repr(d['a'])
  64. print(repr(d['a'])
  65. ```
  66. '''
  67. try:
  68. dodelitem = False
  69. if key in obj:
  70. oldvalue = obj[key]
  71. else:
  72. dodelitem = True
  73. obj[key] = value
  74. yield
  75. finally:
  76. if not dodelitem:
  77. obj[key] = oldvalue
  78. else:
  79. del obj[key]
  80. @contextlib.contextmanager
  81. def tempattrset(obj, key, value):
  82. '''A context (with) manager for changing the value of an attribute
  83. of an object, and restoring it after the with block.
  84. If the attribute does not exist, it will be deleted afterward.
  85. Example usage:
  86. ```
  87. with tempattrset(someobj, 'a', 15):
  88. print(repr(someobj.a)
  89. print(repr(someobj.a)
  90. ```
  91. '''
  92. try:
  93. dodelattr = False
  94. if hasattr(obj, key):
  95. oldvalue = getattr(obj, key)
  96. else:
  97. dodelattr = True
  98. setattr(obj, key, value)
  99. yield
  100. finally:
  101. if not dodelattr:
  102. setattr(obj, key, oldvalue)
  103. else:
  104. delattr(obj, key)
  105. def urlfetch(url):
  106. with urllib.request.urlopen(url) as req:
  107. if req.status // 100 != 2:
  108. raise RuntimeError('bad fetch')
  109. return req.read()
  110. class HTTPSCAS(object):
  111. @classmethod
  112. def fromconfig(cls, conf):
  113. return cls()
  114. def fetch_data(self, url):
  115. if url.scheme != 'https':
  116. raise ValueError('cannot handle scheme %s' %
  117. repr(url.scheme))
  118. url = urllib.parse.urlunparse(url)
  119. return urlfetch(url)
  120. class IPFSCAS(object):
  121. gwhost = 'gateway.ipfs.io'
  122. gwhost = 'cloudflare-ipfs.com'
  123. @classmethod
  124. def fromconfig(cls, conf):
  125. return cls()
  126. def make_url(self, url):
  127. return urllib.parse.urlunparse(('https', self.gwhost,
  128. '/ipfs/' + url.netloc) + ('', ) * 3)
  129. def fetch_data(self, url):
  130. if url.scheme != 'ipfs':
  131. raise ValueError('cannot handle scheme %s' %
  132. repr(url.scheme))
  133. gwurl = self.make_url(url)
  134. return urlfetch(gwurl)
  135. class FileDirCAS(object):
  136. '''A file loader for CAS that operates on a directory. It looks
  137. at files, caches their hash, and loads them upon request.'''
  138. def __init__(self, path):
  139. self._path = pathlib.Path(path)
  140. self._path.mkdir(exist_ok=True)
  141. self._hashes = {}
  142. @classmethod
  143. def fromconfig(cls, conf):
  144. return cls(os.path.expanduser(conf['path']))
  145. def refresh_dir(self):
  146. '''Internal method to refresh the internal cache of
  147. hashes.'''
  148. for i in glob.glob(os.path.join(self._path, '*.py')):
  149. _, hash = self.read_hash_file(i)
  150. self._hashes[hash] = i
  151. @staticmethod
  152. def read_hash_file(fname):
  153. '''Helper function that will read the file at fname, and
  154. return the tuple of it's contents and it's hash.'''
  155. with open(fname, 'rb') as fp:
  156. data = fp.read()
  157. hash = hashlib.sha256(data).hexdigest()
  158. return data, hash
  159. def is_package(self, hash):
  160. '''Decode the provided hash, and decide if it's a package
  161. or not.'''
  162. return False
  163. def fetch_data(self, url):
  164. '''Given the URL (must be a hash URL), return the code for
  165. it.'''
  166. self.refresh_dir()
  167. hashurl = url
  168. if hashurl.scheme != 'hash' or hashurl.netloc != 'sha256':
  169. raise ValueError('invalid hash url')
  170. hash = hashurl.path[1:]
  171. fname = self._hashes[hash]
  172. data, fhash = self.read_hash_file(fname)
  173. if fhash != hash:
  174. raise ValueError('file no longer matches hash on disk')
  175. return data
  176. class CASFinder(MetaPathFinder, Loader):
  177. '''Overall class for using Content Addressable Storage to load
  178. Python modules into your code. It contains code to dispatch to
  179. the various loaders to attempt to load the hash.'''
  180. def __init__(self):
  181. self._loaders = []
  182. self._aliases = {}
  183. if [ x for x in sys.meta_path if
  184. isinstance(x, self.__class__) ]:
  185. raise RuntimeError(
  186. 'cannot register more than on CASFinder')
  187. sys.meta_path.append(self)
  188. def __enter__(self):
  189. return self
  190. def __exit__(self, exc_type, exc_value, traceback):
  191. self.disconnect()
  192. def load_aliases(self, data):
  193. self._aliases.update(self._parsealiases(data))
  194. def load_mod_aliases(self, name):
  195. '''Load the aliases from the module with the passed in name.'''
  196. aliases = importlib.resources.read_text(sys.modules[name],
  197. 'cas_aliases.txt')
  198. self.load_aliases(aliases)
  199. @staticmethod
  200. def _makebasichashurl(url):
  201. try:
  202. hashurl = urllib.parse.urlparse(url)
  203. except AttributeError:
  204. hashurl = url
  205. return urllib.parse.urlunparse(hashurl[:3] + ('', '', ''))
  206. @classmethod
  207. def _parsealiases(cls, data):
  208. ret = {}
  209. lines = data.split('\n')
  210. for i in lines:
  211. if not i:
  212. continue
  213. name, hash = i.split()
  214. ret.setdefault(name, []).append(hash)
  215. # split out the hashes
  216. for items in list(ret.values()):
  217. lst = [ x for x in items if
  218. not x.startswith('hash://') ]
  219. for h in [ x for x in items if
  220. x.startswith('hash://') ]:
  221. h = cls._makebasichashurl(h)
  222. ret[h] = lst
  223. return ret
  224. def disconnect(self):
  225. '''Disconnect this Finder from being used to load modules.
  226. As this claims an entire namespace, only the first loaded
  227. one will work, and any others will be hidden until the
  228. first one is disconnected.
  229. This can be used w/ a with block to automatically
  230. disconnect when no longer needed. This is mostly useful
  231. for testing.'''
  232. try:
  233. sys.meta_path.remove(self)
  234. except ValueError:
  235. pass
  236. def register(self, loader):
  237. '''Register a loader w/ this finder. This will attempt
  238. to load the hash passed to it. It is also (currently)
  239. responsible for executing the code in the module.'''
  240. self._loaders.append(loader)
  241. # MetaPathFinder methods
  242. def find_spec(self, fullname, path, target=None):
  243. if path is None:
  244. ms = ModuleSpec(fullname, self, is_package=True)
  245. else:
  246. parts = fullname.split('.')
  247. ver, typ, arg = parts[1].split('_')
  248. if typ == 'f':
  249. # make hash url:
  250. hashurl = ('hash://sha256/%s' %
  251. bytes.fromhex(arg).hex())
  252. hashurl = urllib.parse.urlparse(hashurl)
  253. for l in self._loaders:
  254. ispkg = l.is_package(hashurl)
  255. break
  256. else:
  257. return None
  258. else:
  259. # an alias
  260. for i in self._aliases[arg]:
  261. hashurl = urllib.parse.urlparse(i)
  262. if hashurl.scheme == 'hash':
  263. break
  264. else:
  265. raise ValueError('unable to find base hash url for alias %s' % repr(arg))
  266. # fix up the full name:
  267. fullname = 'cas.v1_f_%s' % hashurl.path[1:]
  268. ms = ModuleSpec(fullname, self, is_package=False,
  269. loader_state=(hashurl,))
  270. return ms
  271. def invalidate_caches(self):
  272. return None
  273. # Loader methods
  274. def exec_module(self, module):
  275. if module.__name__ == 'cas':
  276. pass
  277. else:
  278. (url,) = module.__spec__.loader_state
  279. for load in self._loaders:
  280. try:
  281. data = load.fetch_data(url)
  282. break
  283. except Exception:
  284. pass
  285. else:
  286. for url in self._aliases[
  287. self._makebasichashurl(url)]:
  288. url = urllib.parse.urlparse(url)
  289. for load in self._loaders:
  290. try:
  291. data = load.fetch_data(url)
  292. break
  293. except Exception:
  294. pass
  295. else:
  296. continue
  297. break
  298. else:
  299. raise ValueError('unable to find loader for url %s' % repr(urllib.parse.urlunparse(url)))
  300. exec(data, module.__dict__)
  301. _supportedmodules = {
  302. 'https': HTTPSCAS.fromconfig,
  303. 'ipfs': IPFSCAS.fromconfig,
  304. 'cache': FileDirCAS.fromconfig,
  305. }
  306. def defaultinit(casf):
  307. basedir = pathlib.Path.home() / '.casimport'
  308. basedir.mkdir(exist_ok=True)
  309. conffile = pathlib.Path(os.environ.get('CASIMPORT_CONF', basedir / 'casimport.conf'))
  310. if not conffile.exists():
  311. import casimport
  312. with importlib.resources.path(casimport,
  313. 'default.conf') as defconf:
  314. shutil.copy(defconf, conffile)
  315. cp = configparser.ConfigParser()
  316. cp.read(conffile)
  317. modorder = [ x.strip() for x in
  318. cp['casimport']['module_prio'].split(',') ]
  319. for i in modorder:
  320. modfun = _supportedmodules[cp[i]['type']]
  321. casf.register(modfun(cp[i]))
  322. cachedir = basedir / 'cache'
  323. cachedir.mkdir(parents=True, exist_ok=True)
  324. casf.register(FileDirCAS(cachedir))
  325. casf.register(IPFSCAS())
  326. casf.register(HTTPSCAS())
  327. # The global version
  328. _casfinder = CASFinder()
  329. load_mod_aliases = _casfinder.load_mod_aliases
  330. defaultinit(_casfinder)
  331. import unittest
  332. class TestHelpers(unittest.TestCase):
  333. def test_testset(self):
  334. origobj = object()
  335. d = dict(a=origobj, b=10)
  336. # that when we temporarily set it
  337. with tempset(d, 'a', 15):
  338. # the new value is there
  339. self.assertEqual(d['a'], 15)
  340. # and that the original object is restored
  341. self.assertIs(d['a'], origobj)
  342. def test_testattrset(self):
  343. class TestObj(object):
  344. pass
  345. testobj = TestObj()
  346. # that when we temporarily set it
  347. with tempattrset(testobj, 'a', 15):
  348. # the new value is there
  349. self.assertEqual(testobj.a, 15)
  350. # and that there is no object
  351. self.assertFalse(hasattr(testobj, 'a'))
  352. origobj = object()
  353. newobj = object()
  354. testobj.b = origobj
  355. # that when we temporarily set it
  356. with tempattrset(testobj, 'b', newobj):
  357. # the new value is there
  358. self.assertIs(testobj.b, newobj)
  359. # and the original value is restored
  360. self.assertIs(testobj.b, origobj)
  361. class Test(unittest.TestCase):
  362. def setUp(self):
  363. # clear out the default casfinder if there is one
  364. self.old_meta_path = sys.meta_path
  365. sys.meta_path = [ x for x in sys.meta_path if
  366. not isinstance(x, CASFinder) ]
  367. # setup temporary directory
  368. d = pathlib.Path(os.path.realpath(tempfile.mkdtemp()))
  369. self.basetempdir = d
  370. self.tempdir = d / 'subdir'
  371. self.tempdir.mkdir()
  372. self.fixtures = \
  373. pathlib.Path(__file__).parent.parent / 'fixtures'
  374. def tearDown(self):
  375. # restore environment
  376. sys.meta_path = self.old_meta_path
  377. importlib.invalidate_caches()
  378. # clean up sys.modules
  379. [ sys.modules.pop(x) for x in list(sys.modules.keys()) if
  380. x == 'cas' or x.startswith('cas.') ]
  381. shutil.rmtree(self.basetempdir)
  382. self.tempdir = None
  383. def test_filedircas(self):
  384. cachedir = self.tempdir / 'cache'
  385. fd = FileDirCAS(cachedir)
  386. self.assertTrue(cachedir.exists())
  387. def test_filedircas_limit_refresh(self):
  388. # XXX - only refresh when the dir has changed, and each
  389. # file has changed
  390. pass
  391. def test_casimport(self):
  392. # That a CASFinder
  393. f = CASFinder()
  394. # make sure that we can't import anything at first
  395. with self.assertRaises(ImportError):
  396. import cas.v1_f_2398472398
  397. # when registering the fixtures directory
  398. f.register(FileDirCAS(self.fixtures))
  399. # can import the function
  400. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  401. name = 'Olof'
  402. # and run the code
  403. self.assertEqual(hello(name), 'hello ' + name)
  404. # and when finished, can disconnect
  405. f.disconnect()
  406. # and is no longer in the meta_path
  407. self.assertNotIn(f, sys.meta_path)
  408. # and when disconnected as second time, nothing happens
  409. f.disconnect()
  410. def test_conforder(self):
  411. conf = self.fixtures / 'ordertest.conf'
  412. # that w/ a custom config
  413. with tempset(os.environ, 'CASIMPORT_CONF', str(conf)), \
  414. CASFinder() as f:
  415. # that is gets loaded
  416. defaultinit(f)
  417. # and that the first loader is the HTTPSCAS
  418. self.assertIsInstance(f._loaders[0], HTTPSCAS)
  419. # and that the second loader is the IPFSCAS
  420. self.assertIsInstance(f._loaders[1], IPFSCAS)
  421. def test_defaultinit(self):
  422. temphome = self.tempdir / 'home'
  423. temphome.mkdir()
  424. defcachedir = temphome / '.casimport' / 'cache'
  425. # testing w/ default config
  426. with tempset(os.environ, 'HOME', str(temphome)):
  427. with CASFinder() as f:
  428. # Setup the defaults
  429. defaultinit(f)
  430. # That the default.conf file got copied over.
  431. filecmp.cmp(defcachedir.parent /
  432. 'casimport.conf',
  433. pathlib.Path(__file__).parent / 'default.conf')
  434. # that the cache got created
  435. self.assertTrue(defcachedir.is_dir())
  436. # and that when hello.py is copied to the cache
  437. shutil.copy(self.fixtures / 'hello.py', defcachedir)
  438. # it can be imported
  439. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  440. # and that the second loader is the IPFSCAS
  441. self.assertIsInstance(f._loaders[1], IPFSCAS)
  442. # and that the third loader is the HTTPSCAS
  443. self.assertIsInstance(f._loaders[2], HTTPSCAS)
  444. with CASFinder() as f:
  445. defaultinit(f)
  446. # and that a new CASFinder can still find it
  447. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  448. def test_multiplecas(self):
  449. # that once we have one
  450. with CASFinder() as f:
  451. # if we try to create a second, it fails
  452. self.assertRaises(RuntimeError, CASFinder)
  453. def test_parsealiases(self):
  454. with open(self.fixtures / 'randpkg' / 'cas_aliases.txt') as fp:
  455. aliasdata = fp.read()
  456. res = CASFinder._parsealiases(aliasdata)
  457. self.assertEqual(res, {
  458. 'hello': [
  459. 'hash://sha256/330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3?type=text/x-python',
  460. 'ipfs://bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym',
  461. 'https://www.funkthat.com/gitea/jmg/casimport/raw/commit/753e64f53c73d9d1afc4d8a617edb9d3542dcea2/fixtures/hello.py',
  462. ],
  463. 'hash://sha256/330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3': [
  464. 'ipfs://bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym',
  465. 'https://www.funkthat.com/gitea/jmg/casimport/raw/commit/753e64f53c73d9d1afc4d8a617edb9d3542dcea2/fixtures/hello.py',
  466. ],
  467. })
  468. def test_aliasmulti(self):
  469. # setup the cache
  470. cachedir = self.tempdir / 'cache'
  471. cachedir.mkdir()
  472. with CASFinder() as f, \
  473. tempattrset(sys.modules[__name__],
  474. 'load_mod_aliases', f.load_mod_aliases):
  475. f.register(FileDirCAS(cachedir))
  476. # and that hello.py is in the cache
  477. shutil.copy(self.fixtures / 'hello.py',
  478. cachedir)
  479. # and that the aliases are loaded
  480. with open(self.fixtures / 'randpkg' / 'cas_aliases.txt') as fp:
  481. f.load_aliases(fp.read())
  482. # that when we load the alias first
  483. from cas.v1_a_hello import hello as hello_alias
  484. # and then load the same module via hash
  485. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello as hello_hash
  486. # they are the same
  487. self.assertIs(hello_alias, hello_hash)
  488. def test_aliasimports(self):
  489. # setup the cache
  490. cachedir = self.tempdir / 'cache'
  491. cachedir.mkdir()
  492. # add the test module's path
  493. fixdir = str(self.fixtures)
  494. sys.path.append(fixdir)
  495. try:
  496. with CASFinder() as f, \
  497. tempattrset(sys.modules[__name__],
  498. 'load_mod_aliases', f.load_mod_aliases):
  499. f.register(FileDirCAS(cachedir))
  500. # and that hello.py is in the cache
  501. shutil.copy(self.fixtures / 'hello.py',
  502. cachedir)
  503. self.assertNotIn('randpkg', sys.modules)
  504. # that the import is successful
  505. import randpkg
  506. # and pulled in the method
  507. self.assertTrue(hasattr(randpkg, 'hello'))
  508. del sys.modules['randpkg']
  509. finally:
  510. sys.path.remove(fixdir)
  511. def test_aliasipfsimports(self):
  512. # add the test module's path
  513. fixdir = str(self.fixtures)
  514. sys.path.append(fixdir)
  515. # that a fake ipfsloader
  516. with open(self.fixtures / 'hello.py') as fp:
  517. # that returns the correct data
  518. fakedata = fp.read()
  519. def fakeload(url, fd=fakedata):
  520. if url.scheme != 'ipfs' or url.netloc != 'bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym':
  521. raise ValueError
  522. return fd
  523. fakeipfsloader = mock.MagicMock()
  524. fakeipfsloader.fetch_data = fakeload
  525. try:
  526. with CASFinder() as f, \
  527. tempattrset(sys.modules[__name__], 'load_mod_aliases',
  528. f.load_mod_aliases):
  529. f.register(fakeipfsloader)
  530. self.assertNotIn('randpkg', sys.modules)
  531. # that the import is successful
  532. import randpkg
  533. # and pulled in the method
  534. self.assertTrue(hasattr(randpkg, 'hello'))
  535. del sys.modules['randpkg']
  536. finally:
  537. sys.path.remove(fixdir)
  538. @mock.patch('urllib.request.urlopen')
  539. def test_ipfscasloader(self, uomock):
  540. # prep return test data
  541. with open(self.fixtures / 'hello.py') as fp:
  542. # that returns the correct data
  543. ipfsdata = fp.read()
  544. # that the ipfs CAS loader
  545. ipfs = IPFSCAS()
  546. # that the request is successfull
  547. uomock.return_value.__enter__.return_value.status = 200
  548. # and returns the correct data
  549. uomock.return_value.__enter__.return_value.read.return_value = ipfsdata
  550. # that when called
  551. hashurl = urllib.parse.urlparse('ipfs://bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym')
  552. data = ipfs.fetch_data(hashurl)
  553. # it opens the correct url
  554. uomock.assert_called_with('https://cloudflare-ipfs.com/ipfs/bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym')
  555. # and returns the correct data
  556. self.assertEqual(data, ipfsdata)
  557. with self.assertRaises(ValueError):
  558. # that a hash url fails
  559. ipfs.fetch_data(urllib.parse.urlparse('hash://sha256/asldfkj'))
  560. # that when the request fails
  561. uomock.return_value.__enter__.return_value.status = 400
  562. # it raises a RuntimeError
  563. with self.assertRaises(RuntimeError):
  564. ipfs.fetch_data(hashurl)
  565. # Note: mostly copied from above, test_ipfscasloader
  566. @mock.patch('urllib.request.urlopen')
  567. def test_httpscasloader(self, uomock):
  568. # prep return test data
  569. with open(self.fixtures / 'hello.py') as fp:
  570. # that returns the correct data
  571. httpsdata = fp.read()
  572. # that the https CAS loader
  573. httpsldr = HTTPSCAS()
  574. # that the request is successfull
  575. uomock.return_value.__enter__.return_value.status = 200
  576. # and returns the correct data
  577. uomock.return_value.__enter__.return_value.read.return_value = httpsdata
  578. # that when called
  579. hashurl = urllib.parse.urlparse('https://www.funkthat.com/gitea/jmg/casimport/raw/commit/753e64f53c73d9d1afc4d8a617edb9d3542dcea2/fixtures/hello.py')
  580. data = httpsldr.fetch_data(hashurl)
  581. # it opens the correct url
  582. uomock.assert_called_with('https://www.funkthat.com/gitea/jmg/casimport/raw/commit/753e64f53c73d9d1afc4d8a617edb9d3542dcea2/fixtures/hello.py')
  583. # and returns the correct data
  584. self.assertEqual(data, httpsdata)
  585. with self.assertRaises(ValueError):
  586. # that a hash url fails
  587. httpsldr.fetch_data(urllib.parse.urlparse('hash://sha256/asldfkj'))
  588. # that when the request fails
  589. uomock.return_value.__enter__.return_value.status = 400
  590. # it raises a RuntimeError
  591. with self.assertRaises(RuntimeError):
  592. httpsldr.fetch_data(hashurl)
  593. @unittest.skip('todo')
  594. def test_overlappingaliases(self):
  595. # make sure that an aliases file is consistent and does not
  596. # override other urls. That is that any hashes are
  597. # consistent, and that they have at least one root hash that
  598. # is the same, and will be used for fetching.
  599. #
  600. # Likely will also have to deal w/ an issue where two
  601. # aliases share sha256, and a third shares sha512, which in
  602. # this case, BOTH hashse have to be checked.
  603. pass
  604. @unittest.skip('todo')
  605. def test_loaderpriority(self):
  606. # XXX - write test to allow you to specify the priority of
  607. # a loader, to ensure that cache stays at top.
  608. # Maybe also think of a way to say local/remote, because
  609. # some loaders may be "more local" than others, like using
  610. # a local ipfs gateway makes more sense than hitting a
  611. # public gateway
  612. pass
  613. def test_filecorruption(self):
  614. cachedir = self.tempdir / 'cachedir'
  615. cachedir.mkdir()
  616. # that an existing file
  617. shutil.copy(self.fixtures / 'hello.py', cachedir)
  618. # is in the cache
  619. fdcas = FileDirCAS(cachedir)
  620. # that when refresh is surpressed
  621. fdcas.refresh_dir = lambda: None
  622. # and has a bogus hash
  623. fdcas._hashes['0000'] = cachedir / 'hello.py'
  624. # that when read raises an exception
  625. with self.assertRaises(ValueError):
  626. fdcas.fetch_data(urllib.parse.urlparse('hash://sha256/0000'))
  627. # that when passed an invalid url
  628. with self.assertRaises(ValueError):
  629. fdcas.fetch_data(urllib.parse.urlparse('https://sha256/0000'))