1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package zlib 6 7 import ( 8 "bytes" 9 "io" 10 "testing" 11 ) 12 13 type zlibTest struct { 14 desc string 15 raw string 16 compressed []byte 17 dict []byte 18 err error 19 } 20 21 // Compare-to-golden test data was generated by the ZLIB example program at 22 // http://www.zlib.net/zpipe.c 23 24 var zlibTests = []zlibTest{ 25 { 26 "empty", 27 "", 28 []byte{0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01}, 29 nil, 30 nil, 31 }, 32 { 33 "goodbye", 34 "goodbye, world", 35 []byte{ 36 0x78, 0x9c, 0x4b, 0xcf, 0xcf, 0x4f, 0x49, 0xaa, 37 0x4c, 0xd5, 0x51, 0x28, 0xcf, 0x2f, 0xca, 0x49, 38 0x01, 0x00, 0x28, 0xa5, 0x05, 0x5e, 39 }, 40 nil, 41 nil, 42 }, 43 { 44 "bad header", 45 "", 46 []byte{0x78, 0x9f, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01}, 47 nil, 48 ErrHeader, 49 }, 50 { 51 "bad checksum", 52 "", 53 []byte{0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0xff}, 54 nil, 55 ErrChecksum, 56 }, 57 { 58 "not enough data", 59 "", 60 []byte{0x78, 0x9c, 0x03, 0x00, 0x00, 0x00}, 61 nil, 62 io.ErrUnexpectedEOF, 63 }, 64 { 65 "excess data is silently ignored", 66 "", 67 []byte{ 68 0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 69 0x78, 0x9c, 0xff, 70 }, 71 nil, 72 nil, 73 }, 74 { 75 "dictionary", 76 "Hello, World!\n", 77 []byte{ 78 0x78, 0xbb, 0x1c, 0x32, 0x04, 0x27, 0xf3, 0x00, 79 0xb1, 0x75, 0x20, 0x1c, 0x45, 0x2e, 0x00, 0x24, 80 0x12, 0x04, 0x74, 81 }, 82 []byte{ 83 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x0a, 84 }, 85 nil, 86 }, 87 { 88 "wrong dictionary", 89 "", 90 []byte{ 91 0x78, 0xbb, 0x1c, 0x32, 0x04, 0x27, 0xf3, 0x00, 92 0xb1, 0x75, 0x20, 0x1c, 0x45, 0x2e, 0x00, 0x24, 93 0x12, 0x04, 0x74, 94 }, 95 []byte{ 96 0x48, 0x65, 0x6c, 0x6c, 97 }, 98 ErrDictionary, 99 }, 100 } 101 102 func TestDecompressor(t *testing.T) { 103 b := new(bytes.Buffer) 104 for _, tt := range zlibTests { 105 in := bytes.NewReader(tt.compressed) 106 zlib, err := NewReaderDict(in, tt.dict) 107 if err != nil { 108 if err != tt.err { 109 t.Errorf("%s: NewReader: %s", tt.desc, err) 110 } 111 continue 112 } 113 defer zlib.Close() 114 b.Reset() 115 n, err := io.Copy(b, zlib) 116 if err != nil { 117 if err != tt.err { 118 t.Errorf("%s: io.Copy: %v want %v", tt.desc, err, tt.err) 119 } 120 continue 121 } 122 s := b.String() 123 if s != tt.raw { 124 t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.desc, n, s, len(tt.raw), tt.raw) 125 } 126 } 127 } 128