Mocking a Metrics Gauge's set_value Method in Python

Demonstrates using unittest.mock.Mock with wraps to intercept a gauge's set_value call while verifying arguments and preserving real behavior.

Easy Python 3.9+ Aug 9, 2026 Observability & SRE 13 views 0 copies

Python code

20 lines
Python 3.9+
from unittest.mock import Mock

class MetricsGauge:
    def __init__(self, name):
        self.name = name
        self.value = 0.0

    def set_value(self, new_value):
        self.value = float(new_value)
        return self.value

# Usage demonstration with a mock
gauge = MetricsGauge("cpu_usage")
gauge_mock = Mock(wraps=gauge)
mock_result = gauge_mock.set_value(75.5)
print(f"Real gauge value: {gauge.value}")
print(f"Mock return value: {mock_result}")
print(f"Mock called with: {gauge_mock.set_value.call_args}")
gauge_mock.set_value.assert_called_once_with(75.5)
print("Assertion passed: set_value was called with 75.5")

Output

stdout
Real gauge value: 75.5
Mock return value: 75.5
Mock called with: call(75.5)
Assertion passed: set_value was called with 75.5

How it works

Mock(wraps=gauge) creates a mock that delegates to the real gauge methods while recording calls. Calling set_value(75.5) invokes the real implementation, so gauge.value becomes 75.5, and the mock returns that value. The mock stores call arguments, accessible via set_value.call_args. assert_called_once_with verifies the exact call, making it useful for testing metrics setters in observability code.

Common mistakes

  • Using `Mock()` without `wraps` so the real `set_value` never executes, leaving `gauge.value` unchanged.
  • Forgetting to check `call_args` before asserting, which can hide the actual call signature.
  • Asserting the mock was called with a float when the real code passed an int (though conversion handles it here).

Variations

  1. Use `create_autospec` to auto-generate a mock matching the class's signature.
  2. Use `patch` with `return_value` to stub `set_value` entirely for isolation.

Real-world use cases

  • Testing that application code calls a metrics gauge setter with the correct value during load testing.
  • Verifying a custom exporter pushes the right gauge values without hitting a real monitoring backend.
  • Auditing that periodic health-check tasks update gauges at expected intervals and magnitudes.

Sponsored

Run this sample

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

Open editor

More from Observability & SRE

Related tutorials and quizzes for this topic.