github.com/aws-cloudformation/cloudformation-cli-go-plugin@v1.2.0/cfn/encoding/encoding_test.go (about)

     1  package encoding_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"testing"
     6  
     7  	"github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/encoding"
     8  
     9  	"github.com/google/go-cmp/cmp"
    10  
    11  	"github.com/aws/aws-sdk-go/aws"
    12  )
    13  
    14  func TestEncoding(t *testing.T) {
    15  	type Nested struct {
    16  		SP *string  `json:",omitempty"`
    17  		BP *bool    `json:",omitempty"`
    18  		IP *int     `json:"intField,omitempty"`
    19  		FP *float64 `json:"floatPointer,omitempty"`
    20  
    21  		S string `json:"stringValue,omitempty"`
    22  		B bool   `json:",omitempty"`
    23  		I int
    24  		F float64 `json:",omitempty"`
    25  	}
    26  
    27  	type Main struct {
    28  		SP *string
    29  		BP *bool    `json:",omitempty"`
    30  		IP *int     `json:",omitempty"`
    31  		FP *float64 `json:",omitempty"`
    32  		NP *Nested  `json:"nestedPointer,omitempty"`
    33  
    34  		S string `json:",omitempty"`
    35  		B bool   `json:"boolValue,omitempty"`
    36  		I int    `json:",omitempty"`
    37  		F float64
    38  		N Nested `json:",omitempty"`
    39  	}
    40  
    41  	m := Main{
    42  		SP: aws.String("foo"),
    43  		IP: aws.Int(42),
    44  		NP: &Nested{
    45  			BP: aws.Bool(true),
    46  			FP: aws.Float64(3.14),
    47  		},
    48  
    49  		B: true,
    50  		F: 2.72,
    51  		N: Nested{
    52  			S: "bar",
    53  			I: 54,
    54  		},
    55  	}
    56  
    57  	stringMap := map[string]interface{}{
    58  		"SP": "foo",
    59  		"IP": "42",
    60  		"nestedPointer": map[string]interface{}{
    61  			"BP":           "true",
    62  			"I":            "0",
    63  			"floatPointer": "3.14",
    64  		},
    65  
    66  		"boolValue": "true",
    67  		"F":         "2.72",
    68  		"N": map[string]interface{}{
    69  			"stringValue": "bar",
    70  			"I":           "54",
    71  		},
    72  	}
    73  
    74  	var err error
    75  
    76  	rep, err := encoding.Marshal(m)
    77  	if err != nil {
    78  		t.Errorf("Unexpected error: %v", err)
    79  	}
    80  
    81  	// Test that rep can be unmarshalled as regular JSON
    82  	var jsonTest map[string]interface{}
    83  	err = json.Unmarshal(rep, &jsonTest)
    84  	if err != nil {
    85  		t.Errorf("Unexpected error: %v", err)
    86  	}
    87  
    88  	// And check it matches the expected form
    89  	if diff := cmp.Diff(jsonTest, stringMap); diff != "" {
    90  		t.Errorf(diff)
    91  	}
    92  
    93  	// Now check we can get the original struct back
    94  	var b Main
    95  	err = encoding.Unmarshal(rep, &b)
    96  	if err != nil {
    97  		panic(err)
    98  	}
    99  
   100  	if diff := cmp.Diff(m, b); diff != "" {
   101  		t.Errorf(diff)
   102  	}
   103  }