Import python modules by their hash.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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