[Python-Dev] isolating import state during tests (original) (raw)

Brett Cannon brett at python.org
Sun Apr 22 03:25:44 CEST 2012


On Sat, Apr 21, 2012 at 21:02, Eric Snow <ericsnowcurrently at gmail.com>wrote:

It looks like the test suite accommodates a stable import state to some extent, but would it be worth having a PEP-405-esque context manager to help with this? For example, something along these lines:

class ImportState: # sys.modules is part of the interpreter state, so # repopulate (don't replace) def enter(self): self.path = sys.path[:] self.modules = sys.modules.copy() self.metapath = sys.metapath[:] self.pathhooks = sys.pathhooks[:] self.pathimportercache = sys.pathimportercache.copy() sys.path = site.getsitepackages() sys.modules.clear() sys.metapath = [] sys.pathhooks = [] sys.pathimportercache = {} def exit(self, *args, **kwargs): sys.path = self.path sys.modules.clear() sys.modules.update(self.modules) sys.metapath = self.metapath sys.pathhooks = self.pathhooks sys.pathimportercache = self.pathimportercache

# in some unit test: with ImportState(): ... # tests

That practically all done for you with a combination of importlib.test.util.uncache and importlib.test.util.import_state. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20120421/5d2762b9/attachment.html>



More information about the Python-Dev mailing list