[Python] Using Python mock to spy on calls to an existing object

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página