Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Lib/test/test_gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import os
import struct
import sys
import tarfile
import unittest
from subprocess import PIPE, Popen
from unittest import mock
Expand Down Expand Up @@ -790,6 +791,51 @@ def test_compress_mtime_default(self):
f.read(1) # to set mtime attribute
self.assertGreater(f.mtime, 1)

def assertReproducibleGzipMetadata(self, datac, data_size):
self.assertEqual(datac[:4], b"\x1f\x8b\x08\x00")
self.assertEqual(struct.unpack("<I", datac[4:8])[0], 0)
self.assertEqual(datac[9], 255)
self.assertEqual(struct.unpack("<I", datac[-4:])[0], data_size)

def test_reproducible_output_metadata(self):
data = b"Hello world"

def gzip_file():
buf = io.BytesIO()
with gzip.GzipFile(fileobj=buf, mode="wb", mtime=0) as f:
f.write(data)
return buf.getvalue()

def gzip_open():
buf = io.BytesIO()
with gzip.open(buf, mode="wb", mtime=0) as f:
f.write(data)
return buf.getvalue()

def gzipped_tarfile():
buf = io.BytesIO()
tarinfo = tarfile.TarInfo("data")
tarinfo.size = len(data)
tarinfo.mtime = 0
with tarfile.open(fileobj=buf, mode="w:gz", mtime=0) as tar:
tar.addfile(tarinfo, io.BytesIO(data))
return buf.getvalue()

cases = [
("compress default mtime", lambda: gzip.compress(data), len(data)),
("compress explicit mtime", lambda: gzip.compress(data, mtime=0), len(data)),
("GzipFile", gzip_file, len(data)),
("gzip.open", gzip_open, len(data)),
("gzipped tarfile", gzipped_tarfile, None),
]
for name, make_gzip, data_size in cases:
with self.subTest(name):
datac = make_gzip()
self.assertEqual(datac, make_gzip())
if data_size is None:
data_size = len(gzip.decompress(datac))
self.assertReproducibleGzipMetadata(datac, data_size)

def test_compress_correct_level(self):
for mtime in (0, 42):
with self.subTest(mtime=mtime):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add tests for reproducible gzip output metadata.
Loading