def testModuleSnapshot(self): """Verify `ctx.module_snapshot`""" # Make sure this module hasn't been imported yet. This should never # be used by this unittest. self.assertNotIn('sparts.tests.dummy', sys.modules) with ctx.module_snapshot(): # Import the module import sparts.tests.dummy self.assertIn('sparts.tests.dummy', sys.modules) self.assertIs(sys.modules['sparts.tests.dummy'], sparts.tests.dummy) # Make sure it's been removed self.assertNotIn('sparts.tests.dummy', sys.modules)
def importPython(self, path): """Create a new module from code at `path`. Does not pollute python's module cache""" assert os.path.exists(path) # Any special variables we want to include in execution context orig_locals = {} exec_locals = orig_locals.copy() # Keep a copy of the module cache prior to execution with ctx.module_snapshot(): execfile(path, exec_locals, exec_locals) # Generate a new module object, and assign the modified locals # as attributes on it. result = imp.new_module(path) for k, v in exec_locals.iteritems(): setattr(result, k, v) return result