From d104b0d3ad037f8b48de94c06d2beea0057fc147 Mon Sep 17 00:00:00 2001 From: John-Mark Gurney Date: Sat, 1 Feb 2020 11:49:02 -0800 Subject: [PATCH] add with support (for testing), and add global instance, and handle it --- casimport/__init__.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/casimport/__init__.py b/casimport/__init__.py index 9de2ab3..ce3c3b0 100644 --- a/casimport/__init__.py +++ b/casimport/__init__.py @@ -64,8 +64,17 @@ class CASFinder(MetaPathFinder, Loader): def __init__(self): 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) + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.disconnect() + def disconnect(self): try: sys.meta_path.remove(self) @@ -100,9 +109,19 @@ class CASFinder(MetaPathFinder, Loader): hash, load = module.__spec__.loader_state load.exec_module(hash, module) +# The global version +_casfinder = CASFinder() + import unittest 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): # That a CASFinder f = CASFinder() @@ -125,3 +144,9 @@ class Test(unittest.TestCase): # and when disconnected as second time, nothing happens 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)