pythonunit-testingmocking

Using Python mock to spy on calls to an existing object


I'm using the Python mock module for tests. I would like to replace an active object with a mock, and automatically have all calls made to the mock object forwarded to the original object. I think this is called a "Spy" in standard testing terminology. At the moment I'm doing inside a test:

# Insert a mock replacement
orig_active_attr = server.active_attr
server.active_attr = mock.Mock()

# Set up side effects to 'proxy' to the original object
server.active_attr.meth1.side_effect = orig_active_attr.meth1
server.active_attr.meth2.side_effect = orig_active_attr.meth2

# Call the method being tested
server.method_being_tested()

# Assert stuff on the mock.
server.active_attr.meth2.assert_called_once()

It would be nice if all method calls on the mock could be forwarded to the live object automatically without the boilerplate.


Solution

  • I seem to have stumbled across the solution:

    import mock
    
    class A(object):
        def meth(self, a):
            return a
    a = A()
    ma = mock.Mock(wraps=a)
    

    Seems to work okay for functions, methods and properties, but not for class or instance attributes.

    See the documentation.