1try: 2 import zlib 3except ImportError: 4 try: 5 import uzlib as zlib 6 except ImportError: 7 print("SKIP") 8 raise SystemExit 9 10PATTERNS = [ 11 # Packed results produced by CPy's zlib.compress() 12 (b"0", b"x\x9c3\x00\x00\x001\x001"), 13 (b"a", b"x\x9cK\x04\x00\x00b\x00b"), 14 (b"0" * 100, b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc1"), 15 ( 16 bytes(range(64)), 17 b"x\x9cc`dbfaec\xe7\xe0\xe4\xe2\xe6\xe1\xe5\xe3\x17\x10\x14\x12\x16\x11\x15\x13\x97\x90\x94\x92\x96\x91\x95\x93WPTRVQUS\xd7\xd0\xd4\xd2\xd6\xd1\xd5\xd370426153\xb7\xb0\xb4\xb2\xb6\xb1\xb5\xb3\x07\x00\xaa\xe0\x07\xe1", 18 ), 19 (b"hello", b"x\x01\x01\x05\x00\xfa\xffhello\x06,\x02\x15"), # compression level 0 20 # adaptive/dynamic huffman tree 21 ( 22 b"13371813150|13764518736|12345678901", 23 b"x\x9c\x05\xc1\x81\x01\x000\x04\x04\xb1\x95\\\x1f\xcfn\x86o\x82d\x06Qq\xc8\x9d\xc5X}<e\xb5g\x83\x0f\x89X\x07\xab", 24 ), 25 # dynamic Huffman tree with "case 17" (repeat code for 3-10 times) 26 ( 27 b">I}\x00\x951D>I}\x00\x951D>I}\x00\x951D>I}\x00\x951D", 28 b"x\x9c\x05\xc11\x01\x00\x00\x00\x010\x95\x14py\x84\x12C_\x9bR\x8cV\x8a\xd1J1Z)F\x1fw`\x089", 29 ), 30] 31 32for unpacked, packed in PATTERNS: 33 assert zlib.decompress(packed) == unpacked 34 print(unpacked) 35 36 37# Raw DEFLATE bitstream 38v = b"\xcbH\xcd\xc9\xc9\x07\x00" 39exp = b"hello" 40out = zlib.decompress(v, -15) 41assert out == exp 42print(exp) 43# Even when you ask CPython zlib.compress to produce Raw DEFLATE stream, 44# it returns it with adler2 and oriignal size appended, as if it was a 45# zlib stream. Make sure there're no random issues decompressing such. 46v = b"\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" 47out = zlib.decompress(v, -15) 48assert out == exp 49 50# this should error 51try: 52 zlib.decompress(b"abc") 53except Exception: 54 print("Exception") 55 56# invalid block type 57try: 58 zlib.decompress(b"\x07", -15) # final-block, block-type=3 (invalid) 59except Exception as er: 60 print("Exception") 61