github.com/boxboat/in-toto-golang@v0.0.3-0.20210303203820-2fa16ecbe6f6/in_toto/canonicaljson_test.go (about)

     1  package in_toto
     2  
     3  import (
     4  	"bytes"
     5  	"strings"
     6  	"testing"
     7  )
     8  
     9  func TestEncodeCanonical(t *testing.T) {
    10  	objects := []interface{}{
    11  		Key{},
    12  		Key{
    13  			KeyVal: KeyVal{
    14  				Private: "priv",
    15  				Public:  "pub",
    16  			},
    17  			KeyIDHashAlgorithms: []string{"hash"},
    18  			KeyID:               "id",
    19  			KeyType:             "type",
    20  			Scheme:              "scheme",
    21  		},
    22  		map[string]interface{}{
    23  			"true":   true,
    24  			"false":  false,
    25  			"nil":    nil,
    26  			"int":    3,
    27  			"int2":   float64(42),
    28  			"string": `\"`,
    29  		},
    30  	}
    31  	expectedResult := []string{
    32  		`{"keyid":"","keyid_hash_algorithms":null,"keytype":"","keyval":{"private":"","public":""},"scheme":""}`,
    33  		`{"keyid":"id","keyid_hash_algorithms":["hash"],"keytype":"type","keyval":{"private":"priv","public":"pub"},"scheme":"scheme"}`,
    34  		`{"false":false,"int":3,"int2":42,"nil":null,"string":"\\\"","true":true}`,
    35  		"",
    36  	}
    37  	for i := 0; i < len(objects); i++ {
    38  		result, err := EncodeCanonical(objects[i])
    39  
    40  		if string(result) != expectedResult[i] || err != nil {
    41  			t.Errorf("EncodeCanonical returned (%s, %s), expected (%s, nil)",
    42  				result, err, expectedResult[i])
    43  		}
    44  	}
    45  }
    46  
    47  func TestEncodeCanonicalErr(t *testing.T) {
    48  	objects := []interface{}{
    49  		map[string]interface{}{"float": 3.14159265359},
    50  		TestEncodeCanonical,
    51  	}
    52  	errPart := []string{
    53  		"Can't canonicalize floating point number",
    54  		"unsupported type: func(",
    55  	}
    56  
    57  	for i := 0; i < len(objects); i++ {
    58  		result, err := EncodeCanonical(objects[i])
    59  		if err == nil || !strings.Contains(err.Error(), errPart[i]) {
    60  			t.Errorf("EncodeCanonical returned (%s, %s), expected '%s' error",
    61  				result, err, errPart[i])
    62  		}
    63  	}
    64  }
    65  
    66  func TestencodeCanonical(t *testing.T) {
    67  	expectedError := "Can't canonicalize"
    68  
    69  	objects := []interface{}{
    70  		TestencodeCanonical,
    71  		[]interface{}{TestencodeCanonical},
    72  	}
    73  
    74  	for i := 0; i < len(objects); i++ {
    75  		var result bytes.Buffer
    76  		err := encodeCanonical(objects[i], &result)
    77  		if err == nil || !strings.Contains(err.Error(), expectedError) {
    78  			t.Errorf("EncodeCanonical returned '%s', expected '%s' error",
    79  				err, expectedError)
    80  		}
    81  	}
    82  }