TIL

To globally mock functions in python

05.10.2023

In one of the python projects I am working on we have this central method to publish events to pubsub. We wanted to have a global mock of pubsub to avoid having to explicitly mocking it many places. Turns out this is possible with a wrapper function and pytest fixtures:

def _publish_pubsub_event(topic: str, message: PubSubMessage) -> None:
PubSubPublisher(settings.GCLOUD_PROJECT, topic).publish(message)
def publish_pubsub_event(topic: str, message: PubSubMessage) -> None:
return _publish_pubsub_event(topic, message)

The publish_pubsub_event gets imported everywhere so to mock it we need to mock it in the context is being used, but the _publish_pubsub_event is not being used anywhere else than here so we can mock it in the context of this file.

In the module level conftest.py there is a fixture with autouse=True and it mocks the _publish_pubsub_event and returns the mock so that the fixture can be loaded explicitly to assert that the mock was called in the cases we want to verify the messages sent.

@pytest.fixture(autouse=True)
def mock_pubsub_publish(mocker: MockerFixture):
return mocker.patch("app.pubsub._publish_pubsub_event")