How to Mock zlib Compression for Cache Values in Python
Compress cache values with zlib and mock the compress function in unit tests to simulate cache behavior.
Python code
27 linesimport zlib
from unittest.mock import patch
def compress_value(data: bytes) -> bytes:
"""Compress data using zlib and return the compressed bytes."""
return zlib.compress(data)
def decompress_value(compressed: bytes) -> bytes:
"""Decompress zlib data and return the original bytes."""
return zlib.decompress(compressed)
if __name__ == "__main__":
original = b"cache_value_to_be_compressed"
# Real compression/decompression flow
compressed = compress_value(original)
decompressed = decompress_value(compressed)
print(f"Original size: {len(original)} bytes")
print(f"Compressed size: {len(compressed)} bytes")
print(f"Round-trip successful: {original == decompressed}")
# Mock the compress function to simulate a different behavior
with patch("__main__.compress_value", return_value=b"mocked_compressed_data") as mock_compress:
mocked_result = compress_value(original)
print(f"Mocked compress result: {mocked_result}")
mock_compress.assert_called_once_with(original)
Output
Original size: 30 bytes
Compressed size: 32 bytes
Round-trip successful: True
Mocked compress result: b'mocked_compressed_data'
How it works
The code defines two simple functions that wrap zlib.compress and zlib.decompress. Real usage compresses a byte string and confirms a round-trip. Then unittest.mock.patch replaces compress_value with a mock that returns a fixed byte string, simulating a different compression outcome. The assert_called_once_with verifies the mock was invoked exactly once with the original data. This pattern isolates the logic that uses compression from the actual zlib implementation.
Common mistakes
- Patching the wrong module path (e.g., patching `zlib.compress` instead of your wrapper function)
- Forgetting to pass a return_value, so the mock returns another Mock instead of bytes
- Not resetting the mock between tests, causing call count assertions to fail
Variations
- Use `@patch('module.compress_value')` decorator to auto-pass the mock as a test argument
- Use `MagicMock` for more complex return values or side effects
Real-world use cases
- Testing cache functions that compress values before storing in Redis, ensuring mocked behavior without real compression overhead.
- Simulating different compression ratios in unit tests to verify logging or metrics collection.
- Avoiding zlib dependency in CI environments where the compression library may not be available.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader easy
- Cache Data in Redis with Python easy
- Cache Penetration Null Object Mock in Python medium
- Cache Stampede Prevention with SingleFlight in Python medium
- Cache Warming with Python: Preload Hot Keys easy
- Coalescing duplicate in-flight requests: one shared result for concurrent callers hard
Keep learning
Related tutorials and quizzes for this topic.