Вопрос

I'm using the mock library and unittest2 in order to test different aspects of my software project.

At the moment I have the following question: is it possible to mock a function so that the default keyword argument is different, but the functionality remains?

Say I have the following code

class C():
  def fun(self, bool_arg = True):
    if bool_arg:
      return True
    else
      return False

What if I want to mock C.fun:

C.fun = mock.Mock(???)

so that every instance of C will replace keyword 'bool_arg' with False, instead of True and the result of:

c = C()
c.fun()

returns:

False

Это было полезно?

Решение

you can also try to wrap your function. Something on the line of

def wrapper(func, bool_arg):
    def inner(*args, **kwargs):
        kwargs['bool_arg']=bool_arg
        return func(*args, **kwargs)
    return inner

and

class C():
    def fun(...):
        ...

c = C()
c.fun = wrapper(fun, False)

should work

Edit

If you want to change the default for the class and not for a particular instance you can create a derived class and redefine fun wrapping the method of C. Something on the line (I don't have now the time to test it):

class D(C):
    def fun(self, *args, **kwargs):
        f = wrapper(C.f, False)
        return f(*args, **kwargs)

Then about the suggestion of @Ber, you can define def wrapper(func, **wrapkwargs) and then instead of kwargs['bool_arg']=bool_arg do

for i in wrapkwargs.iteritems():  #wrapkwargs is a dictionary
    kwargs[i[0]] = i[1]

Другие советы

You can try to use this code:

>>> import mock
>>> 
>>> class C():
...   def fun(self, bool_arg = True):
...     if bool_arg:
...       print "True"
...     else:
...       print "False"
... 
>>> c = C()
>>> funCopy = c.fun
>>> c.fun = mock.Mock(side_effect=lambda bool_arg=False: funCopy(bool_arg=bool_arg))
>>> c.fun()
False

Hope this helps

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top