| 1 | import gzip |
| 2 | import hashlib |
| 3 | import io |
| 4 | import json |
| 5 | import tarfile |
| 6 | import zlib |
| 7 | |
| 8 | |
| 9 | def gzip_bytes(payload): |
| 10 | archive = io.BytesIO() |
| 11 | with gzip.GzipFile(filename="", mode="wb", compresslevel=6, fileobj=archive, mtime=0) as writer: |
| 12 | writer.write(payload) |
| 13 | return archive.getvalue() |
| 14 | |
| 15 | |
| 16 | def build(): |
| 17 | payload = b"123456789" |
| 18 | archive = io.BytesIO() |
| 19 | with tarfile.open(fileobj=archive, mode="w", format=tarfile.USTAR_FORMAT) as writer: |
| 20 | info = tarfile.TarInfo("digits.txt") |
| 21 | info.size = len(payload) |
| 22 | info.mode = 0o644 |
| 23 | info.mtime = 0 |
| 24 | writer.addfile(info, io.BytesIO(payload)) |
| 25 | tar_bytes = archive.getvalue()[:2048] |
| 26 | values = { |
| 27 | "digits": payload, |
| 28 | "gzip_digits": gzip_bytes(payload), |
| 29 | "gzip_empty": gzip_bytes(b""), |
| 30 | "ustar_one": tar_bytes, |
| 31 | "ustar_sha256": hashlib.sha256(tar_bytes).digest(), |
| 32 | } |
| 33 | if gzip.decompress(values["gzip_digits"]) != payload: |
| 34 | raise RuntimeError("GZip fixture 검증 실패") |
| 35 | with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:") as reader: |
| 36 | if reader.getnames() != ["digits.txt"] or reader.extractfile("digits.txt").read() != payload: |
| 37 | raise RuntimeError("USTAR fixture 검증 실패") |
| 38 | metadata = { |
| 39 | "provenance": "Python 표준 gzip/zlib와 tarfile USTAR_FORMAT으로 만든 합성 bytes임", |
| 40 | "gzip": {"mtime": 0, "level": 6, "crc32": zlib.crc32(payload)}, |
| 41 | "ustar": {"trimmed_length": 2048, "terminator_blocks": 2, "mtime": 0, "mode": "0644"}, |
| 42 | "files": {name: {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()} |
| 43 | for name, data in sorted(values.items())}, |
| 44 | "limitations": "ZIP 결과는 native 호출과 비교함. 독립 ZIP parser나 codec 검증이 아님", |
| 45 | } |
| 46 | return ( |
| 47 | "".join(name + " " + data.hex() + "\n" for name, data in sorted(values.items())), |
| 48 | json.dumps(metadata, ensure_ascii=False, indent=4) + "\n", |
| 49 | ) |