0leg
0leg

Reputation: 14144

Python: using Mock to override class method

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')

Upvotes: 3

Views: 13704

Answers (1)

Tim Rijavec
Tim Rijavec

Reputation: 1780

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')

Upvotes: 7

Related Questions