diff options
author | Jesús Eduardo <heckyel@hyperbola.info> | 2018-01-17 19:28:25 -0500 |
---|---|---|
committer | Jesús Eduardo <heckyel@hyperbola.info> | 2018-01-17 19:28:25 -0500 |
commit | c6791d41d97f8c27fe966d0d716cf4c85d294da5 (patch) | |
tree | 839b52085ddb639465b0719c1bd8e048ae2b45b2 | |
parent | b7dfa2417b2f39b5996be185d089969004211802 (diff) | |
download | librevideoconverter-c6791d41d97f8c27fe966d0d716cf4c85d294da5.tar.lz librevideoconverter-c6791d41d97f8c27fe966d0d716cf4c85d294da5.tar.xz librevideoconverter-c6791d41d97f8c27fe966d0d716cf4c85d294da5.zip |
pep8 en test/mock.py
-rw-r--r-- | test/mock.py | 149 |
1 files changed, 53 insertions, 96 deletions
diff --git a/test/mock.py b/test/mock.py index 93b90d8..f87177c 100644 --- a/test/mock.py +++ b/test/mock.py @@ -30,7 +30,7 @@ __all__ = ( ) -__version__ = '1.0b1' +__version__ = '1.1' import pprint @@ -93,6 +93,7 @@ except AttributeError: import keyword import re regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I) + def _isidentifier(string): if string in keyword.kwlist: return False @@ -206,7 +207,7 @@ def _check_signature(func, mock, skipfirst, instance=False): def _copy_func_details(func, funcopy): funcopy.__name__ = func.__name__ funcopy.__doc__ = func.__doc__ - #funcopy.__dict__.update(func.__dict__) + # funcopy.__dict__.update(func.__dict__) funcopy.__module__ = func.__module__ if not inPy3k: funcopy.func_defaults = func.func_defaults @@ -288,18 +289,22 @@ def _setup_func(funcopy, mock): def assert_called_with(*args, **kwargs): return mock.assert_called_with(*args, **kwargs) + def assert_called_once_with(*args, **kwargs): return mock.assert_called_once_with(*args, **kwargs) + def assert_has_calls(*args, **kwargs): return mock.assert_has_calls(*args, **kwargs) + def assert_any_call(*args, **kwargs): return mock.assert_any_call(*args, **kwargs) + def reset_mock(): funcopy.method_calls = _CallList() funcopy.mock_calls = _CallList() mock.reset_mock() ret = funcopy.return_value - if _is_instance_mock(ret) and not ret is mock: + if _is_instance_mock(ret) and ret is not mock: ret.reset_mock() funcopy.called = False @@ -381,11 +386,13 @@ _allowed_names = set( def _delegating_property(name): _allowed_names.add(name) _the_name = '_mock_' + name + def _get(self, name=name, _the_name=_the_name): sig = self._mock_delegate if sig is None: return getattr(self, _the_name) return getattr(sig, name) + def _set(self, value, name=name, _the_name=_the_name): sig = self._mock_delegate if sig is None: @@ -396,7 +403,6 @@ def _delegating_property(name): return property(_get, _set) - class _CallList(list): def __contains__(self, value): @@ -421,8 +427,8 @@ def _check_and_set_parent(parent, value, name, new_name): if not _is_instance_mock(value): return False if ((value._mock_name or value._mock_new_name) or - (value._mock_parent is not None) or - (value._mock_new_parent is not None)): + (value._mock_parent is not None) or + (value._mock_new_parent is not None)): return False _parent = parent @@ -442,15 +448,14 @@ def _check_and_set_parent(parent, value, name, new_name): return True - class Base(object): _mock_return_value = DEFAULT _mock_side_effect = None + def __init__(self, *args, **kwargs): pass - class NonCallableMock(Base): """A non-callable version of `Mock`""" @@ -462,12 +467,10 @@ class NonCallableMock(Base): instance = object.__new__(new) return instance - def __init__( self, spec=None, wraps=None, name=None, spec_set=None, parent=None, _spec_state=None, _new_name='', _new_parent=None, - **kwargs - ): + **kwargs): if _new_parent is None: _new_parent = parent @@ -503,7 +506,6 @@ class NonCallableMock(Base): _spec_state ) - def attach_mock(self, mock, attribute): """ Attach a mock as an attribute of this one, replacing its name and @@ -516,7 +518,6 @@ class NonCallableMock(Base): setattr(self, attribute, mock) - def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as @@ -525,7 +526,6 @@ class NonCallableMock(Base): If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) - def _mock_add_spec(self, spec, spec_set): _spec_class = None @@ -542,7 +542,6 @@ class NonCallableMock(Base): __dict__['_spec_set'] = spec_set __dict__['_mock_methods'] = spec - def __get_return_value(self): ret = self._mock_return_value if self._mock_delegate is not None: @@ -555,7 +554,6 @@ class NonCallableMock(Base): self.return_value = ret return ret - def __set_return_value(self, value): if self._mock_delegate is not None: self._mock_delegate.return_value = value @@ -567,7 +565,6 @@ class NonCallableMock(Base): return_value = property(__get_return_value, __set_return_value, __return_value_doc) - @property def __class__(self): if self._spec_class is None: @@ -580,7 +577,6 @@ class NonCallableMock(Base): call_args_list = _delegating_property('call_args_list') mock_calls = _delegating_property('mock_calls') - def __get_side_effect(self): sig = self._mock_delegate if sig is None: @@ -597,7 +593,6 @@ class NonCallableMock(Base): side_effect = property(__get_side_effect, __set_side_effect) - def reset_mock(self): "Restore the mock object to its initial state." self.called = False @@ -616,7 +611,6 @@ class NonCallableMock(Base): if _is_instance_mock(ret) and ret is not self: ret.reset_mock() - def configure_mock(self, **kwargs): """Set attributes on the mock through keyword arguments. @@ -638,7 +632,6 @@ class NonCallableMock(Base): obj = getattr(obj, entry) setattr(obj, final, val) - def __getattr__(self, name): if name == '_mock_methods': raise AttributeError(name) @@ -662,18 +655,17 @@ class NonCallableMock(Base): parent=self, name=name, wraps=wraps, _new_name=name, _new_parent=self ) - self._mock_children[name] = result + self._mock_children[name] = result elif isinstance(result, _SpecState): result = create_autospec( result.spec, result.spec_set, result.instance, result.parent, result.name ) - self._mock_children[name] = result + self._mock_children[name] = result return result - def __repr__(self): _name_list = [self._mock_new_name] _parent = self._mock_new_parent @@ -723,7 +715,6 @@ class NonCallableMock(Base): id(self) ) - def __dir__(self): """Filter the output of `dir(mock)` to only useful members. XXXX @@ -739,14 +730,13 @@ class NonCallableMock(Base): return sorted(set(extras + from_type + from_dict + list(self._mock_children))) - def __setattr__(self, name, value): if name in _allowed_names: # property setters go through here return object.__setattr__(self, name, value) elif (self._spec_set and self._mock_methods is not None and - name not in self._mock_methods and - name not in self.__dict__): + name not in self._mock_methods and + name not in self.__dict__): raise AttributeError("Mock object has no attribute '%s'" % name) elif name in _unsupported_magics: msg = 'Attempting to set unsupported magic method %r.' % name @@ -758,7 +748,10 @@ class NonCallableMock(Base): if not _is_instance_mock(value): setattr(type(self), name, _get_method(name, value)) original = value - value = lambda *args, **kw: original(self, *args, **kw) + + def value(*args, **kw): + return original(self, *arg, **kw) + # value = lambda *args, **kw: original(self, *args, **kw) else: # only set _new_name and not name so that mock_calls is tracked # but not method calls @@ -773,7 +766,6 @@ class NonCallableMock(Base): self._mock_children[name] = value return object.__setattr__(self, name, value) - def __delattr__(self, name): if name in _all_magics and name in type(self).__dict__: delattr(type(self), name) @@ -792,13 +784,10 @@ class NonCallableMock(Base): del self._mock_children[name] self._mock_children[name] = _deleted - - def _format_mock_call_signature(self, args, kwargs): name = self._mock_name or 'mock' return _format_call_signature(name, args, kwargs) - def _format_mock_failure_message(self, args, kwargs): message = 'Expected call: %s\nActual call: %s' expected_string = self._format_mock_call_signature(args, kwargs) @@ -808,7 +797,6 @@ class NonCallableMock(Base): actual_string = self._format_mock_call_signature(*call_args) return message % (expected_string, actual_string) - def assert_called_with(_mock_self, *args, **kwargs): """assert that the mock was called with the specified arguments. @@ -823,7 +811,6 @@ class NonCallableMock(Base): msg = self._format_mock_failure_message(args, kwargs) raise AssertionError(msg) - def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and with the specified arguments.""" @@ -834,7 +821,6 @@ class NonCallableMock(Base): raise AssertionError(msg) return self.assert_called_with(*args, **kwargs) - def assert_has_calls(self, calls, any_order=False): """assert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. @@ -866,7 +852,6 @@ class NonCallableMock(Base): '%r not all found in call list' % (tuple(not_found),) ) - def assert_any_call(self, *args, **kwargs): """assert the mock has been called with the specified arguments. @@ -880,7 +865,6 @@ class NonCallableMock(Base): '%s call not found' % expected_string ) - def _get_child_mock(self, **kw): """Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. @@ -893,14 +877,13 @@ class NonCallableMock(Base): if not issubclass(_type, CallableMixin): if issubclass(_type, NonCallableMagicMock): klass = MagicMock - elif issubclass(_type, NonCallableMock) : + elif issubclass(_type, NonCallableMock): klass = Mock else: klass = _type.__mro__[1] return klass(**kw) - def _try_iter(obj): if obj is None: return obj @@ -916,7 +899,6 @@ def _try_iter(obj): return obj - class CallableMixin(Base): def __init__(self, spec=None, side_effect=None, return_value=DEFAULT, @@ -931,19 +913,16 @@ class CallableMixin(Base): self.side_effect = side_effect - def _mock_check_sig(self, *args, **kwargs): # stub method that can be replaced with one with a specific signature pass - def __call__(_mock_self, *args, **kwargs): # can't use self in-case a function / method we are mocking uses self # in the signature _mock_self._mock_check_sig(*args, **kwargs) return _mock_self._mock_call(*args, **kwargs) - def _mock_call(_mock_self, *args, **kwargs): self = _mock_self self.called = True @@ -1009,14 +988,13 @@ class CallableMixin(Base): ret_val = self.return_value if (self._mock_wraps is not None and - self._mock_return_value is DEFAULT): + self._mock_return_value is DEFAULT): return self._mock_wraps(*args, **kwargs) if ret_val is DEFAULT: ret_val = self.return_value return ret_val - class Mock(CallableMixin, NonCallableMock): """ Create a new `Mock` object. `Mock` takes several optional arguments @@ -1072,7 +1050,6 @@ class Mock(CallableMixin, NonCallableMock): """ - def _dot_lookup(thing, comp, import_path): try: return getattr(thing, comp) @@ -1104,8 +1081,7 @@ class _patch(object): def __init__( self, getter, attribute, new, spec, create, - spec_set, autospec, new_callable, kwargs - ): + spec_set, autospec, new_callable, kwargs): if new_callable is not None: if new is not DEFAULT: raise ValueError( @@ -1128,7 +1104,6 @@ class _patch(object): self.kwargs = kwargs self.additional_patchers = [] - def copy(self): patcher = _patch( self.getter, self.attribute, self.new, self.spec, @@ -1141,13 +1116,11 @@ class _patch(object): ] return patcher - def __call__(self, func): if isinstance(func, ClassTypes): return self.decorate_class(func) return self.decorate_callable(func) - def decorate_class(self, klass): for attr in dir(klass): if not attr.startswith(patch.TEST_PREFIX): @@ -1161,7 +1134,6 @@ class _patch(object): setattr(klass, attr, patcher(attr_value)) return klass - def decorate_callable(self, func): if hasattr(func, 'patchings'): func.patchings.append(self) @@ -1190,7 +1162,7 @@ class _patch(object): return func(*args, **keywargs) except: if (patching not in entered_patchers and - _is_started(patching)): + _is_started(patching)): # the patcher may have been started, but an exception # raised whilst entering one of its additional_patchers entered_patchers.append(patching) @@ -1211,7 +1183,6 @@ class _patch(object): ) return patched - def get_original(self): target = self.getter() name = self.attribute @@ -1232,7 +1203,6 @@ class _patch(object): ) return original, local - def __enter__(self): """Perform the patch.""" new, spec, spec_set = self.new, self.spec, self.spec_set @@ -1251,7 +1221,7 @@ class _patch(object): if spec is not None and autospec is not None: raise TypeError("Can't specify spec and autospec") if ((spec is not None or autospec is not None) and - spec_set not in (True, None)): + spec_set not in (True, None)): raise TypeError("Can't provide explicit spec_set *and* spec or autospec") original, local = self.get_original() @@ -1300,7 +1270,7 @@ class _patch(object): # add a name to mocks if (isinstance(Klass, type) and - issubclass(Klass, NonCallableMock) and self.attribute): + issubclass(Klass, NonCallableMock) and self.attribute): _kwargs['name'] = self.attribute _kwargs.update(kwargs) @@ -1313,7 +1283,7 @@ class _patch(object): if spec_set is not None: this_spec = spec_set if (not _is_list(this_spec) and not - _instance_callable(this_spec)): + _instance_callable(this_spec)): Klass = NonCallableMagicMock _kwargs.pop('name') @@ -1349,7 +1319,7 @@ class _patch(object): if self.attribute_name is not None: extra_args = {} if self.new is DEFAULT: - extra_args[self.attribute_name] = new + extra_args[self.attribute_name] = new for patching in self.additional_patchers: arg = patching.__enter__() if patching.new is DEFAULT: @@ -1358,7 +1328,6 @@ class _patch(object): return new - def __exit__(self, *exc_info): """Undo the patch.""" if not _is_started(self): @@ -1379,36 +1348,35 @@ class _patch(object): if _is_started(patcher): patcher.__exit__(*exc_info) - def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() self._active_patches.add(self) return result - def stop(self): """Stop an active patch.""" self._active_patches.discard(self) return self.__exit__() - def _get_target(target): try: target, attribute = target.rsplit('.', 1) except (TypeError, ValueError): raise TypeError("Need a valid target to patch. You supplied: %r" % (target,)) - getter = lambda: _importer(target) + + def getter(): + return _importer(target) + # getter = lambda: _importer(target) return getter, attribute def _patch_object( target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, - new_callable=None, **kwargs - ): + new_callable=None, **kwargs): """ patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) @@ -1425,7 +1393,10 @@ def _patch_object( When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ - getter = lambda: target + + def getter(): + return target + # getter = lambda: target return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs @@ -1455,9 +1426,15 @@ def _patch_multiple(target, spec=None, create=False, spec_set=None, for choosing which methods to wrap. """ if type(target) in (unicode, str): - getter = lambda: _importer(target) + + def getter(): + return _importer(target) + # getter = lambda: _importer(target) else: - getter = lambda: target + + def getter(): + return target + # getter = lambda: target if not kwargs: raise ValueError( @@ -1483,8 +1460,7 @@ def _patch_multiple(target, spec=None, create=False, spec_set=None, def patch( target, new=DEFAULT, spec=None, create=False, - spec_set=None, autospec=None, new_callable=None, **kwargs - ): + spec_set=None, autospec=None, new_callable=None, **kwargs): """ `patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` @@ -1596,10 +1572,10 @@ class _patch_dict(object): self.clear = clear self._original = None - def __call__(self, f): if isinstance(f, ClassTypes): return self.decorate_class(f) + @wraps(f) def _inner(*args, **kw): self._patch_dict() @@ -1610,23 +1586,20 @@ class _patch_dict(object): return _inner - def decorate_class(self, klass): for attr in dir(klass): attr_value = getattr(klass, attr) if (attr.startswith(patch.TEST_PREFIX) and - hasattr(attr_value, "__call__")): + hasattr(attr_value, "__call__")): decorator = _patch_dict(self.in_dict, self.values, self.clear) decorated = decorator(attr_value) setattr(klass, attr, decorated) return klass - def __enter__(self): """Patch the dict.""" self._patch_dict() - def _patch_dict(self): values = self.values in_dict = self.in_dict @@ -1652,7 +1625,6 @@ class _patch_dict(object): for key in values: in_dict[key] = values[key] - def _unpatch_dict(self): in_dict = self.in_dict original = self._original @@ -1665,7 +1637,6 @@ class _patch_dict(object): for key in original: in_dict[key] = original[key] - def __exit__(self, *args): """Unpatch the dict.""" self._unpatch_dict() @@ -1786,6 +1757,7 @@ def _get_eq(self): return self is other return __eq__ + def _get_ne(self): def __ne__(other): if self.__ne__._mock_return_value is not DEFAULT: @@ -1793,6 +1765,7 @@ def _get_ne(self): return self is not other return __ne__ + def _get_iter(self): def __iter__(): ret_val = self.__iter__._mock_return_value @@ -1810,7 +1783,6 @@ _side_effect_methods = { } - def _set_return_value(mock, method, name): fixed = _return_values.get(name, DEFAULT) if fixed is not DEFAULT: @@ -1833,13 +1805,11 @@ def _set_return_value(mock, method, name): method.side_effect = side_effector(mock) - class MagicMixin(object): def __init__(self, *args, **kw): _super(MagicMixin, self).__init__(*args, **kw) self._mock_set_magics() - def _mock_set_magics(self): these_magics = _magics @@ -1862,7 +1832,6 @@ class MagicMixin(object): setattr(_type, entry, MagicProxy(entry, self)) - class NonCallableMagicMock(MagicMixin, NonCallableMock): """A version of `MagicMock` that isn't callable.""" def mock_add_spec(self, spec, spec_set=False): @@ -1875,7 +1844,6 @@ class NonCallableMagicMock(MagicMixin, NonCallableMock): self._mock_set_magics() - class MagicMock(MagicMixin, Mock): """ MagicMock is a subclass of Mock with default implementations @@ -1897,7 +1865,6 @@ class MagicMock(MagicMixin, Mock): self._mock_set_magics() - class MagicProxy(object): def __init__(self, name, parent): self.name = name @@ -1920,7 +1887,6 @@ class MagicProxy(object): return self.create_mock() - class _ANY(object): "A helper object that compares equal to everything." @@ -1936,7 +1902,6 @@ class _ANY(object): ANY = _ANY() - def _format_call_signature(name, args, kwargs): message = '%s(%%s)' % name formatted_args = '' @@ -1954,7 +1919,6 @@ def _format_call_signature(name, args, kwargs): return message % formatted_args - class _Call(tuple): """ A tuple for holding the results of a call to a mock, either in the form @@ -2006,14 +1970,12 @@ class _Call(tuple): return tuple.__new__(cls, (name, args, kwargs)) - def __init__(self, value=(), name=None, parent=None, two=False, from_kall=True): self.name = name self.parent = parent self.from_kall = from_kall - def __eq__(self, other): if other is ANY: return True @@ -2063,11 +2025,9 @@ class _Call(tuple): # this order is important for ANY to work! return (other_args, other_kwargs) == (self_args, self_kwargs) - def __ne__(self, other): return not self.__eq__(other) - def __call__(self, *args, **kwargs): if self.name is None: return _Call(('', args, kwargs), name='()') @@ -2075,14 +2035,12 @@ class _Call(tuple): name = self.name + '()' return _Call((self.name, args, kwargs), name=name, parent=self) - def __getattr__(self, attr): if self.name is None: return _Call(name=attr, from_kall=False) name = '%s.%s' % (self.name, attr) return _Call(name=name, parent=self, from_kall=False) - def __repr__(self): if not self.from_kall: name = self.name or 'call' @@ -2103,7 +2061,6 @@ class _Call(tuple): name = 'call%s' % name return _format_call_signature(name, args, kwargs) - def call_list(self): """For a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the @@ -2120,7 +2077,6 @@ class _Call(tuple): call = _Call(from_kall=False) - def create_autospec(spec, spec_set=False, instance=False, _parent=None, _name=None, **kwargs): """Create a mock object using another object as a spec. Attributes on the @@ -2352,5 +2308,6 @@ class PropertyMock(Mock): def __get__(self, obj, obj_type): return self() + def __set__(self, obj, val): self(val) |