2

I have the following code in module a:

class MyManager(models.Manager):

    def dowork(self, value1, value2):
        print value1, value2

In module b:

class MyModel(models.Model):
    objects = MyManager()
    value1 = ...        
    value2 = ...

    def call_manager(self):
        self.objects.dowork(self.value1, self.value2)

In unittest I am patching the dowork with a different body, such as:

def new_dowork(self, value1, value2):
    print 123

with patch('a.MyManager.dowork', new_callable=new_dowork):
    record = MyModel(value=111)
    record.call_manager()
    ...

But I am getting TypeError: new_dowork() takes exactly 3 arguments (0 given)

0

1 Answer 1

5

I don't know much about Mock, but I think the main issue is that you should pass the mock function in the new argument, not in new_callable, and use patch.object to actually overwrite a method within an object.

This seems to work:

from mock import patch

class MyManager(object):

    def dowork(self, value1, value2):
        print value1, value2

class MyModel(object):
    objects = MyManager()
    value1 = 'foo'        
    value2 = 'bar'

    def __init__(self, value=0):
        # You don't need this __init__... Is just so I don't have to 
        # use models.MyModel thingy
        pass

    def call_manager(self):
        self.objects.dowork(self.value1, self.value2)

def new_dowork(self, value1, value2):
    print "Mock called"
    print 123

with patch.object(MyManager, 'dowork', new=new_dowork):
    record = MyModel(value=111)
    record.call_manager()

This outputs:

Mock called
123
Sign up to request clarification or add additional context in comments.

2 Comments

Cool, using new worked, I still seem to have trouble understand when to use new or new_callable
From the docs: new_callable allows you to specify a different class, or callable object, that will be called to create the new object. By default MagicMock is used. So it looks like it's used if you want to replace the default MagicMock "mocker" class which I'm guessing is something you'd rarely need (It seems to be trying to instantiate a class, therefore, in this particular example, ends up running your function) But this is just a guess (I don't know nearly enough about Mock to be sure of this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.