Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards.
175720
def with_fakes(method):
    
    @wraps(method)
    def apply_clear_and_verify(*args, **kw):
        clear_calls()
        method(*args, **kw)
        verify() # if no exceptions
    return apply_clear_and_verify
597877
def cached_method(func):
    
    @functools.wraps(func)
    def wrapper(self, *args):
        if not hasattr(self, "_cache"):
            self._cache = {}
        key = _argstring((func.__name__,) + args)
        if key not in self._cache:
            self._cache[key] = func(self, *args)
        return self._cache[key]
    return wrapper
647520
def reset_mock(self,  visited=None, return_value=False, side_effect=False):
        ""
        if visited is None:
            visited = []
        if id(self) in visited:
            return
        visited.append(id(self))

        self.called = False
        self.call_args = None
        self.call_count = 0
        self.mock_calls = _CallList()
        self.call_args_list = _CallList()
        self.method_calls = _CallList()

        if return_value:
            self._mock_return_value = DEFAULT
        if side_effect:
            self._mock_side_effect = None

        for child in self._mock_children.values():
            if isinstance(child, _SpecState):
                continue
            child.reset_mock(visited)

        ret = self._mock_return_value
        if _is_instance_mock(ret) and ret is not self:
            ret.reset_mock(visited)
20067
def _check_decorator(fct):
        """"""
        def wrapper(self, *args, **kw):
            if self.is_enable():
                ret = fct(self, *args, **kw)
            else:
                ret = self.stats
            return ret
        return wrapper
1186320
def runcall(self, func, *args, **kw):
        
        # XXX where is this used ? can be removed ?
        self.enable_by_count()
        try:
            return func(*args, **kw)
        finally:
            self.disable_by_count()
971337
def synchronised(func):
        """"""

        # pylint: disable=E0213
        def Wrapper(main_obj, *args, **kwargs):
            main_obj._lock.acquire()  # pylint: disable=W0212
            try:
                return func(main_obj, *args, **kwargs)  # pylint: disable=E1102
            finally:
                main_obj._lock.release()  # pylint: disable=W0212

        return Wrapper
753740
def _onFunction(self, name, line, pos, absPosition,
                    keywordLine, keywordPos,
                    colonLine, colonPos, level,
                    isAsync, returnAnnotation):
        """"""
        self.__flushLevel(level)
        f = Function(name, line, pos, absPosition, keywordLine, keywordPos,
                     colonLine, colonPos, isAsync, returnAnnotation)
        if self.__lastDecorators is not None:
            f.decorators = self.__lastDecorators
            self.__lastDecorators = None
        self.objectsStack.append(f)
457656
def decorate(func, caller):
    
    evaldict = dict(_call_=caller, _func_=func)
    fun = FunctionMaker.create(
        func, "return _call_(_func_, %(shortsignature)s)",
        evaldict, __wrapped__=func)
    if hasattr(func, '__qualname__'):
        fun.__qualname__ = func.__qualname__
    return fun
805193
def _deprecated(func):
    """"""
    @wraps(func)
    def with_warning(*args, **kwargs):
        warnings.warn(
            ('The %s method is deprecated and will be removed in v2.*.*' %
             func.__name__),
            DeprecationWarning
        )
        return func(*args, **kwargs)
    return with_warning
919202
def decorator(caller, func=None):
    
    if func is None: # returns a decorator
        fun = FunctionMaker(caller)
        first_arg = inspect.getargspec(caller)[0][0]
        src = 'def %s(%s): return _call_(caller, %s)' % (
            caller.__name__, first_arg, first_arg)
        return fun.make(src, dict(caller=caller, _call_=decorator),
                        undecorated=caller)
    else: # returns a decorated function
        fun = FunctionMaker(func)
        src = """def %(name)s(%(signature)s):
    return _call_(_func_, %(signature)s)"""
        return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func)
693612
def clear(self):
        
        with self._hlock:
            self.handlers.clear()
        with self._mlock:
            self.memoize.clear()
430865
def decorate(func, caller):
    
    evaldict = func.__globals__.copy()
    evaldict['_call_'] = caller
    evaldict['_func_'] = func
    fun = FunctionMaker.create(
        func, "return _call_(_func_, %(shortsignature)s)",
        evaldict, __wrapped__=func)
    if hasattr(func, '__qualname__'):
        fun.__qualname__ = func.__qualname__
    return fun
1368103
def memorize(func):
    
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        if (len(args) > 0 and len(kwargs) > 0): 
            cacheKey = list(args)
            cacheKey.append(kwargs)
        elif (len(args) > 0): 
            cacheKey = args
        else:
            cacheKey = func.__name__
            
        global __cache__
        result = __cache__.get(cacheKey)
        if result is None:
            result = func(*args, **kwargs)
            __cache__[cacheKey] = result
        return result

    return wrapped_func
167161
def atexit_unregister(func, *args, **kwargs):
    
    try:
        atexit.unregister(func, *args, **kwargs)
    except AttributeError:
        # This code runs in Python 2.7 *only*
        # Only replace with a noop, don't delete during iteration
        for i in range(len(atexit._exithandlers)):
            if atexit._exithandlers[i] == (func, args, kwargs):
                atexit._exithandlers[i] = (lambda: None, [], {})
                break
1274940
def call_user_func(settings_module, func_name, *args, **kwargs):
    
    if settings_module:
        if hasattr(settings_module, func_name):
            func = getattr(settings_module, func_name)
            try:
                return func(*args, **kwargs)
            finally:
                # cleanup user function
                delattr(settings_module, func_name)
1135094
def cleanup(self):
        

        pending_exits_to_remove = defaultdict(list)

        for func_addr in self._updated_functions:
            if func_addr not in self._jobs:
                continue
            jobs = self._jobs[func_addr]
            for i, pe in enumerate(jobs):
                if pe.returning_source is None:
                    # The original call failed. This pending exit must be followed.
                    continue

                func = self._functions.function(pe.returning_source)
                if func is None:
                    # Why does it happen?
                    l.warning("An expected function at %s is not found. Please report it to Fish.",
                              pe.returning_source if pe.returning_source is not None else 'None')
                    continue

                if func.returning is False:
                    # Oops, it's not returning
                    # Remove this pending exit
                    pending_exits_to_remove[pe.returning_source].append(i)

        for func_addr, indices in pending_exits_to_remove.items():
            jobs = self._jobs[func_addr]
            for index in reversed(indices):
                job = jobs[index]
                self._deregister_job_callback(job.func_addr, job)
                del jobs[index]
                self._job_count -= 1
            if not jobs:
                del self._jobs[func_addr]

        self.clear_updated_functions()
435156
def validate_call(kwargs, returns, is_method=False):
    
    def decorator(func):
        @wraps(func)
        def inner(*passed_args, **passed_kwargs):
            # Enforce no positional args
            # first argument of instance method and class method is always positonal so we need
            # to make expception for them. Static methods are still validated according to standard rules
            # this check happens before methods are bound, so instance method is still a regular function
            max_allowed_passed_args_len = 0
            if is_method and type(func) in (types.FunctionType, classmethod):
                max_allowed_passed_args_len = 1

            if len(passed_args) > max_allowed_passed_args_len:
                raise PositionalError('You cannot call this with positional arguments.')
            # Validate keyword arguments
            validate(kwargs, passed_kwargs, 'keyword arguments')
            # Call callable
            return_value = func(*passed_args, **passed_kwargs)
            # Validate return value
            validate(returns, return_value, 'return value')
            return return_value
        inner.__wrapped__ = func
        # caveat: checking for f.__validated__ will only work if @validate_call
        # is not masked by other decorators except for @classmethod or @staticmethod
        inner.__validated__ = True
        return inner
    return decorator