def patched(target, attribute, new=None): if isinstance(target, basestring): target = _importer(target) if new is None: new = Mock() original = getattr(target, attribute) setattr(target, attribute, new) try: yield new finally: setattr(target, attribute, original)
def patched(target, attribute, new = None): if isinstance(target, basestring): target = _importer(target) if new is None: new = Mock() if hasattr(target, attribute): original = getattr(target, attribute) setattr(target, attribute, new) try: yield new finally: try: setattr(target, attribute, original) except NameError: pass
def isolate(target, excludes=None): """ ``isolate`` acts as a function decorator, class decorator or context manager. Within the function, TestCase methods or context all objects within the targets module will be patched with a new ``Mock`` object. On exiting the function or context the patch is undone. For a ``TestCase`` setUp and tearDown are wrapped. ``isolate`` is useful to quickly mock out everything in a module except the ``target``. ``excludes`` is either a string of form `'package.module.objectname'` or a list of such strings. The named objects will not be patched. If applied to a TestCase ``isolate`` will wrap the setUp and tearDown methods. This allows configuration of the mocked module attributes during setUp. ``isolate`` borrows heavily from DingusTestCase. """ target = _importer(target) return _isolate(target, excludes)
# -*- coding:utf-8 -*- import mock Bee = mock._importer("foo.bar.boo.Bee") import foo.bar.boo foo.bar.boo.Bee == Bee # => True Bee = mock._importer("foo.baar.boo.Bee") import foo foo.baar.boo.Bee == Bee # => True
def isolate(module, *exclude): if isinstance(module, basestring): module = _importer(module) exclude_tuples = set(tuple(x.split('.')) for x in exclude) return _isolate_module(module, *exclude_tuples)