Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock functions in Python in order to change default keyword arguments

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

like image 725
mpaf Avatar asked Dec 06 '25 08:12

mpaf


1 Answers

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]
like image 89
Francesco Montesano Avatar answered Dec 08 '25 20:12

Francesco Montesano