Debian Codegraph @

openpgp/packet/compressed_test.go

raw
1 // Copyright 2011 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 packet
6
7 import (
8 "bytes"
9 "crypto/rand"
10 "encoding/hex"
11 "io"
12 mathrand "math/rand"
13 "testing"
14 )
15
16 const (
17 maxMessageLen = 1 << 12
18 )
19
20 func TestCompressed(t *testing.T) {
21 packet, err := Read(readerFromHex(compressedHex))
22 if err != nil {
23 t.Errorf("failed to read Compressed: %s", err)
24 return
25 }
26
27 c, ok := packet.(*Compressed)
28 if !ok {
29 t.Error("didn't find Compressed packet")
30 return
31 }
32
33 contents, err := io.ReadAll(c.Body)
34 if err != nil && err != io.EOF {
35 t.Error(err)
36 return
37 }
38
39 expected, _ := hex.DecodeString(compressedExpectedHex)
40 if !bytes.Equal(expected, contents) {
41 t.Errorf("got:%x want:%x", contents, expected)
42 }
43 }
44
45 const compressedHex = "a3013b2d90c4e02b72e25f727e5e496a5e49b11e1700"
46 const compressedExpectedHex = "cb1062004d14c8fe636f6e74656e74732e0a"
47
48 func TestCompressDecompressRandomizeFast(t *testing.T) {
49 algorithms := []CompressionAlgo{
50 CompressionZIP,
51 CompressionZLIB,
52 }
53 plaintext := make([]byte, mathrand.Intn(maxMessageLen))
54 rand.Read(plaintext)
55 algo := algorithms[mathrand.Intn(len(algorithms))]
56 compConfig := &CompressionConfig{
57 Level: -1 + mathrand.Intn(11),
58 }
59 w := bytes.NewBuffer(nil)
60 wc := &noOpCloser{w: w}
61 wcomp, err := SerializeCompressed(wc, algo, compConfig)
62 if err != nil {
63 t.Fatal(err)
64 }
65 // Compress to w
66 wcomp.Write(plaintext)
67 wcomp.Close()
68 // Read the packet and decompress
69 p, err := Read(w)
70 if err != nil {
71 t.Fatal(err)
72 }
73 c, ok := p.(*Compressed)
74 if !ok {
75 t.Error("didn't find Compressed packet")
76 }
77 contents, err := io.ReadAll(c.Body)
78 if err != nil && err != io.EOF {
79 t.Error(err)
80 }
81 if !bytes.Equal(contents, plaintext) {
82 t.Error("Could not retrieve original after decompress")
83 }
84 }