File: compressed_test.go

package info (click to toggle)
golang-github-protonmail-go-crypto 1.1.6-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,932 kB
  • sloc: makefile: 10
file content (84 lines) | stat: -rw-r--r-- 1,851 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package packet

import (
	"bytes"
	"crypto/rand"
	"encoding/hex"
	"io"
	mathrand "math/rand"
	"testing"
)

const (
	maxMessageLen = 1 << 12
)

func TestCompressed(t *testing.T) {
	packet, err := Read(readerFromHex(compressedHex))
	if err != nil {
		t.Errorf("failed to read Compressed: %s", err)
		return
	}

	c, ok := packet.(*Compressed)
	if !ok {
		t.Error("didn't find Compressed packet")
		return
	}

	contents, err := io.ReadAll(c.Body)
	if err != nil && err != io.EOF {
		t.Error(err)
		return
	}

	expected, _ := hex.DecodeString(compressedExpectedHex)
	if !bytes.Equal(expected, contents) {
		t.Errorf("got:%x want:%x", contents, expected)
	}
}

const compressedHex = "a3013b2d90c4e02b72e25f727e5e496a5e49b11e1700"
const compressedExpectedHex = "cb1062004d14c8fe636f6e74656e74732e0a"

func TestCompressDecompressRandomizeFast(t *testing.T) {
	algorithms := []CompressionAlgo{
		CompressionZIP,
		CompressionZLIB,
	}
	plaintext := make([]byte, mathrand.Intn(maxMessageLen))
	rand.Read(plaintext)
	algo := algorithms[mathrand.Intn(len(algorithms))]
	compConfig := &CompressionConfig{
		Level: -1 + mathrand.Intn(11),
	}
	w := bytes.NewBuffer(nil)
	wc := &noOpCloser{w: w}
	wcomp, err := SerializeCompressed(wc, algo, compConfig)
	if err != nil {
		t.Fatal(err)
	}
	// Compress to w
	wcomp.Write(plaintext)
	wcomp.Close()
	// Read the packet and decompress
	p, err := Read(w)
	if err != nil {
		t.Fatal(err)
	}
	c, ok := p.(*Compressed)
	if !ok {
		t.Error("didn't find Compressed packet")
	}
	contents, err := io.ReadAll(c.Body)
	if err != nil && err != io.EOF {
		t.Error(err)
	}
	if !bytes.Equal(contents, plaintext) {
		t.Error("Could not retrieve original after decompress")
	}
}