...

Source file src/github.com/ProtonMail/go-crypto/openpgp/packet/compressed_test.go

Documentation: github.com/ProtonMail/go-crypto/openpgp/packet

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

View as plain text