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.
Python code
20 linesfrom 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
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
- Use `create_autospec` to auto-generate a mock matching the class's signature.
- 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
More from Observability & SRE
- Adding a Correlation ID to Log Context in Python medium
- Calculate Error Rate from Log Stream in Python easy
- Check if a Timestamp Falls in a Daily Maintenance Window in Python easy
- Export Metrics with OTLP Mock in Python medium
- Generate Mock CPU and Memory Metrics in Python easy
- Generate Prometheus Text Exposition Format in Python easy
Keep learning
Related tutorials and quizzes for this topic.