def test_undefined_name(self): """Prevent a module with an undefined name from breaking our function.""" code = textwrap.dedent("""\ def __some_function(): pass some_undefined_name def another(): pass """) directory = tempfile.mkdtemp( suffix="_ImportNearest_test_undefined_name") atexit.register(functools.partial(shutil.rmtree, directory)) with open(os.path.join(directory, "some_name_mangled_file.py"), "w") as handler: handler.write(code) with wrapping.keep_sys_path(): sys.path.append(directory) self.assertIsNone( imports.import_nearest_module("some_name_mangled_file")) self.assertIsNone( imports.import_nearest_module( "some_name_mangled_file.another")) self.assertIsNone( imports.import_nearest_module( "some_name_mangled_file.__some_function"))
def test_function(self): """Watch a function from a module.""" with wrapping.watch_namespace( imports.import_nearest_module) as container: imports.import_nearest_module("sys") self.assertEqual([(("sys", ), dict(), sys)], [record.get_all() for record in container])
def test_invalid(self): """Fail to import if the namespace does not point to a Python module.""" self.assertEqual( None, imports.import_nearest_module("something_that_doesnt_exist"))
def test_class_attribute(self): """Import a module from a Python class attribute namespace.""" self.assertEqual( unittest, imports.import_nearest_module("unittest.TestCase.setUp"))
def test_module_attribute(self): """Import a module from a Python module attribute namespace.""" self.assertEqual(sys, imports.import_nearest_module("sys.maxsize"))
def test_function(self): """Import a module from a Python function namespace.""" self.assertEqual(textwrap, imports.import_nearest_module("textwrap.dedent"))
def test_module(self): """Import a module from a Python module namespace.""" self.assertEqual(unittest, imports.import_nearest_module("unittest"))