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.

Medium Python 3.9+ Aug 9, 2026 Caching & Redis 12 views 0 copies

Python code

27 lines
Python 3.9+
import 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

stdout
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

  1. Use `@patch('module.compress_value')` decorator to auto-pass the mock as a test argument
  2. 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

Run this sample

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

Open editor

More from Caching & Redis

Related tutorials and quizzes for this topic.