How to Mock BugSnag Notify in Python

Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 16 views 0 copies

Python code

11 lines
Python 3.9+
import mock

bugsnag = mock.MagicMock()

def notify_error(message, severity="error"):
    bugsnag.notify(message, severity=severity)

if __name__ == "__main__":
    notify_error("Test error", severity="warning")
    bugsnag.notify.assert_called_once_with("Test error", severity="warning")
    print("Mocked BugSnag notified successfully:", bugsnag.notify.call_args)

Output

stdout
Mocked BugSnag notified successfully: call('Test error', severity='warning')

How it works

This code creates a MagicMock object named bugsnag to stand in for the real BugSnag client. The notify_error function calls bugsnag.notify with the message and severity, which records the call on the mock. After the function runs, assert_called_once_with verifies that notify was called exactly once with the expected arguments. Finally, printing call_args shows how the method was invoked, confirming the mock works as a lightweight test double.

Common mistakes

  • Forgetting to assert on the mock's method instead of the mock itself
  • Using the real BugSnag client in tests instead of patching it
  • Calling notify_error more than once and failing assert_called_once_with

Variations

  1. Use unittest.mock.patch to replace BugSnag globally in tests

Real-world use cases

  • Unit-testing error-handling functions that report failures to BugSnag without sending real notifications.
  • Verifying that specific error messages and severity levels are passed to your monitoring service during CI.
  • Simulating BugSnag in integration tests to avoid network calls and keep test suites fast and deterministic.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.