Round-trip a bz2-compressed text fixture
This example uses a deliberately small text fixture: violet and orange, each followed by a newline. It encodes that text as UTF-8 bytes, compresses it with bz2.compress, and restores it with bz2.decompress. No path, temporary file, or external compressor is involved, so the fixture remains local to the test process.
The first assertion checks the conventional BZh beginning of a bzip2 stream. The next assertions are more central: the decompressed bytes equal the original payload, and decoding them produces the expected two logical lines. The printed value avoids reporting compressed length because compressed size can be a poor test contract when inputs, implementations, or compression settings change. Instead, it reports the deterministic content that the test intends to preserve.
compresslevel=9 requests the module’s highest documented compression level. It does not prove that this setting is appropriate for every fixture, and this example makes no claim about compression ratio or throughput. On Python builds where bz2 is unavailable, importing it fails because the module is optional. The one-shot functions accept bytes-like input, and bz2.decompress can process concatenated compressed streams. These APIs are available across supported Python 3 releases; see the official bz2 documentation and the bz2.compress reference.
import bz2
payload = "violet\norange\n".encode("utf-8")
compressed = bz2.compress(payload, compresslevel=9)
restored = bz2.decompress(compressed)
assert compressed.startswith(b"BZh")
assert restored == payload
assert restored.decode("utf-8").splitlines() == ["violet", "orange"]
print("restored=" + "/".join(restored.decode("utf-8").splitlines()))
restored=violet/orange
AI assistance disclosure: this article was drafted with AI assistance and should be reviewed in the context of its project.
Comments
Post a Comment