Browse Source

add with support (for testing), and add global instance, and handle it

main
John-Mark Gurney 4 years ago
parent
commit
d104b0d3ad
1 changed files with 25 additions and 0 deletions
  1. +25
    -0
      casimport/__init__.py

+ 25
- 0
casimport/__init__.py View File

@@ -64,8 +64,17 @@ class CASFinder(MetaPathFinder, Loader):
def __init__(self): def __init__(self):
self._loaders = [] self._loaders = []


if [ x for x in sys.meta_path if isinstance(x, self.__class__) ]:
raise RuntimeError('cannot register more than on CASFinder')

sys.meta_path.append(self) sys.meta_path.append(self)


def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
self.disconnect()

def disconnect(self): def disconnect(self):
try: try:
sys.meta_path.remove(self) sys.meta_path.remove(self)
@@ -100,9 +109,19 @@ class CASFinder(MetaPathFinder, Loader):
hash, load = module.__spec__.loader_state hash, load = module.__spec__.loader_state
load.exec_module(hash, module) load.exec_module(hash, module)


# The global version
_casfinder = CASFinder()

import unittest import unittest


class Test(unittest.TestCase): class Test(unittest.TestCase):
def setUp(self):
self.old_meta_path = sys.meta_path
sys.meta_path = [ x for x in sys.meta_path if not isinstance(x, CASFinder) ]

def tearDown(self):
sys.meta_path = self.old_meta_path

def test_casimport(self): def test_casimport(self):
# That a CASFinder # That a CASFinder
f = CASFinder() f = CASFinder()
@@ -125,3 +144,9 @@ class Test(unittest.TestCase):


# and when disconnected as second time, nothing happens # and when disconnected as second time, nothing happens
f.disconnect() f.disconnect()

def test_multiplecas(self):
# that once we have one
with CASFinder() as f:
# if we try to create a second, it fails
self.assertRaises(RuntimeError, CASFinder)

Loading…
Cancel
Save