Tests for (de)compression in jsonutil

This commit is contained in:
vishalnayak 2016-08-08 15:28:54 -04:00
parent 29989fa4c1
commit f994c7ccd3
2 changed files with 53 additions and 3 deletions

View file

@ -6,6 +6,7 @@ import (
"compress/lzw"
"fmt"
"io"
"log"
)
const (
@ -155,5 +156,6 @@ func Decompress(data []byte, config *CompressionConfig) ([]byte, bool, error) {
return nil, false, err
}
log.Printf("decompressedBytes: %s\n", string(jsonBuf.Bytes()))
return jsonBuf.Bytes(), false, nil
}

View file

@ -6,9 +6,57 @@ import (
"reflect"
"strings"
"testing"
"github.com/hashicorp/vault/helper/compressutil"
)
func Test_EncodeJSON(t *testing.T) {
func TestJSONUtil_CompressDecompressJSON(t *testing.T) {
expected := map[string]interface{}{
"test": "data",
"validation": "process",
}
// Compress an object
compressedBytes, err := EncodeJSONAndCompress(expected)
if err != nil {
t.Fatal(err)
}
if len(compressedBytes) == 0 {
t.Fatal("expected compressed data")
}
// Check if canary is present in the compressed data
if compressedBytes[0] != compressutil.CompressionCanary {
t.Fatalf("canary missing in compressed data")
}
// Decompress and decode the compressed information and verify the functional
// behavior
var actual map[string]interface{}
if err = DecompressAndDecodeJSON(compressedBytes, &actual); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("bad: expected: %#v\nactual: %#v", expected, actual)
}
for key, _ := range actual {
delete(actual, key)
}
// Test invalid data
if err = DecompressAndDecodeJSON([]byte{}, &actual); err == nil {
t.Fatalf("expected a failure")
}
// Test invalid data after the canary byte
var buf bytes.Buffer
buf.Write([]byte{compressutil.CompressionCanary})
if err = DecompressAndDecodeJSON(buf.Bytes(), &actual); err == nil {
t.Fatalf("expected a failure")
}
}
func TestJSONUtil_EncodeJSON(t *testing.T) {
input := map[string]interface{}{
"test": "data",
"validation": "process",
@ -27,7 +75,7 @@ func Test_EncodeJSON(t *testing.T) {
}
}
func Test_DecodeJSON(t *testing.T) {
func TestJSONUtil_DecodeJSON(t *testing.T) {
input := `{"test":"data","validation":"process"}`
var actual map[string]interface{}
@ -46,7 +94,7 @@ func Test_DecodeJSON(t *testing.T) {
}
}
func Test_DecodeJSONFromReader(t *testing.T) {
func TestJSONUtil_DecodeJSONFromReader(t *testing.T) {
input := `{"test":"data","validation":"process"}`
var actual map[string]interface{}