3

There a FooObject class with only one version field and one update() method.

class FooObject(models.Model):
  version = models.CharField(max_length=100)

I would like to override update method for the unittest using Python's Mock tool. How would I do it? Should I use patch for it?

foo_object.update = Mock(self.version = '123')
1
  • I think the strategy would be to mock the class, and then set the version and update methods on the mocked class. Commented Jun 2, 2015 at 7:31

1 Answer 1

7

To do that you can mock the class function with the @patch like that

from mock import patch

# Our class to test
class FooObject():
    def update(self, obj):
        print obj

# Mock the update method
@patch.object(FooObject, 'update')
def test(mock1):
    # test that the update method is actually mocked
    assert FooObject.update is mock1
    foo = FooObject()
    foo.update('foo')
    return mock1

# Test if the mocked update method was called with 'foo' parameter
mock1 = test()
mock1.assert_called_once_with('foo')

You can even mock more functions like that:

from mock import patch

class FooObject():
    def update(self, obj):
        print obj

    def restore(self, obj):
        print obj

@patch.object(FooObject, 'restore')
@patch.object(FooObject, 'update')
def test(mock1, mock2):
    assert FooObject.update is mock1
    assert FooObject.restore is mock2
    foo = FooObject()
    foo.update('foo')
    foo.restore('bar')
    return mock1, mock2

mock1, mock2 = test()
mock1.assert_called_once_with('foo')
mock2.assert_called_once_with('bar')
Sign up to request clarification or add additional context in comments.

2 Comments

I don't see how you are using Mock here.
@MattSom the @patch.object() calls inject a Mock instance into the test function for mock1 and mock2. The Mock (actually, MagicMock in this case, I think) is sort of behind the scenes.

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.