Issue mocking with a decorated method call in Python 2.7

戏子无情 提交于 2019-12-07 12:46:18

问题


This code:

import mock
from functools import wraps

def dec(f):
    @wraps(f)
    def f_2(*args, **kwargs):
        pass
    return f_2


class Example(object):
    def __init__(self):
        pass

    @dec
    def method_1(self, arg):
        pass

    def method_2(self, arg):
        self.method_1(arg)



def test_example():
    m = mock.create_autospec(Example)
    Example.method_2(m, "hello")
    m.method_1.assert_called_once_with("hello")

produces this error with py.test

    def test_example():
        m = mock.create_autospec(Example)
>       Example.method_2(m, "hello")

example.py:26: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
example.py:20: in method_2
    self.method_1(arg)
anaconda2/envs/arctic/lib/python2.7/site-packages/mock/mock.py:1061: in __call__
    _mock_self._mock_check_sig(*args, **kwargs)
anaconda2/envs/arctic/lib/python2.7/site-packages/mock/mock.py:227: in checksig
    sig.bind(*args, **kwargs)
anaconda2/envs/arctic/lib/python2.7/site-packages/mock/mock.py:95: in fixedbind
    return self._bind(args, kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <funcsigs.Signature object at 0x7f09b8685e10>, args = ('hello',), kwargs = {}, partial = False

    def _bind(self, args, kwargs, partial=False):
        '''Private method.  Don't use directly.'''
        arguments = OrderedDict()

        parameters = iter(self.parameters.values())
        parameters_ex = ()
        arg_vals = iter(args)

        if partial:
            # Support for binding arguments to 'functools.partial' objects.
            # See 'functools.partial' case in 'signature()' implementation
            # for details.
            for param_name, param in self.parameters.items():
                if (param._partial_kwarg and param_name not in kwargs):
                    # Simulating 'functools.partial' behavior
                    kwargs[param_name] = param.default

        while True:
            # Let's iterate through the positional arguments and corresponding
            # parameters
            try:
                arg_val = next(arg_vals)
            except StopIteration:
                # No more positional arguments
                try:
                    param = next(parameters)
                except StopIteration:
                    # No more parameters. That's it. Just need to check that
                    # we have no `kwargs` after this while loop
                    break
                else:
                    if param.kind == _VAR_POSITIONAL:
                        # That's OK, just empty *args.  Let's start parsing
                        # kwargs
                        break
                    elif param.name in kwargs:
                        if param.kind == _POSITIONAL_ONLY:
                            msg = '{arg!r} parameter is positional only, ' \
                                  'but was passed as a keyword'
                            msg = msg.format(arg=param.name)
                            raise TypeError(msg)
                        parameters_ex = (param,)
                        break
                    elif (param.kind == _VAR_KEYWORD or
                                                param.default is not _empty):
                        # That's fine too - we have a default value for this
                        # parameter.  So, lets start parsing `kwargs`, starting
                        # with the current parameter
                        parameters_ex = (param,)
                        break
                    else:
                        if partial:
                            parameters_ex = (param,)
                            break
                        else:
                            msg = '{arg!r} parameter lacking default value'
                            msg = msg.format(arg=param.name)
                            raise TypeError(msg)
            else:
                # We have a positional argument to process
                try:
                    param = next(parameters)
                except StopIteration:
                    raise TypeError('too many positional arguments')
                else:
                    if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
                        # Looks like we have no parameter for this positional
                        # argument
>                       raise TypeError('too many positional arguments')
E                       TypeError: too many positional arguments

anaconda2/envs/arctic/lib/python2.7/site-packages/funcsigs/__init__.py:716: TypeError

Is there any way to test what this code intends? If you remove the decorator, or if you make the arguments to method_1 keyword args, it magically works. I'm not sure if the bug is in Mock itself, or in funcsigs, but something is clearly amiss. Is there a workaround for this? Another way to test that method_2 calls method_1 ?

I should mention that this is with mock 1.3.0. This code works in 1.0.1 for some reason, but I need to use the latest version of mock.

UPDATE

This works:

def test_example():
    m = mock.Mock(spec=Example)
    m.method_1 = mock.Mock()
    Example.method_2(m, "hello")
    m.method_1.assert_called_once_with("hello")

回答1:


From mock 1.1.0 the framework start to check deeply methods signature. Take a look to the changelog at

Issue #17015: When it has a spec, a Mock object now inspects its signature when matching calls, so that arguments can be matched positionally or by name

Now if you change f2() signature to def f_2(arg, *args, **kwargs) it should work.

Maybe that is a new bug where the signature check cannot understand correctly that the call is correct (at least compatible). I think that you can file a bug and post here the ticket link.

As workaround you can remove the autospeccing from method_1 by add

m.method_1 = mock.Mock()


来源:https://stackoverflow.com/questions/34800832/issue-mocking-with-a-decorated-method-call-in-python-2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!