github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/courier/transport_http/transform/utils_test.go (about)

     1  package transform
     2  
     3  import (
     4  	"encoding/json"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestGetTagValueAndFlags(t *testing.T) {
    11  	tt := assert.New(t)
    12  
    13  	cases := []struct {
    14  		tag   string
    15  		v     string
    16  		flags TagFlags
    17  	}{
    18  		{
    19  			tag:   "json",
    20  			v:     "json",
    21  			flags: TagFlags{},
    22  		},
    23  		{
    24  			tag: "json,omitempty",
    25  			v:   "json",
    26  			flags: TagFlags{
    27  				"omitempty": true,
    28  			},
    29  		},
    30  	}
    31  
    32  	for _, tc := range cases {
    33  		v, flags := GetTagValueAndFlags(tc.tag)
    34  		tt.Equal(tc.v, v)
    35  		tt.Equal(tc.flags, flags)
    36  	}
    37  }
    38  
    39  type TestDataForLocateJSONPath struct {
    40  	Data struct {
    41  		Bool        bool `json:"bool"`
    42  		StructSlice []struct {
    43  			Name string `json:"name"`
    44  		} `json:"structSlice"`
    45  		StringSlice []string `json:"stringSlice"`
    46  		NestedSlice []struct {
    47  			Names []string `json:"names"`
    48  		} `json:"nestedSlice"`
    49  	} `json:"data"`
    50  }
    51  
    52  func TestLocateJSONPath(t *testing.T) {
    53  	tt := assert.New(t)
    54  
    55  	data := TestDataForLocateJSONPath{}
    56  
    57  	{
    58  		d := []byte(`
    59  {
    60   	"data": {
    61  		"bool":   ""
    62  	}
    63  }
    64  `)
    65  		typeError := json.Unmarshal(d, &data).(*json.UnmarshalTypeError)
    66  		tt.Equal("data.bool", LocateJSONPath(d, typeError.Offset))
    67  	}
    68  
    69  	{
    70  		d := []byte(`
    71  {
    72  		"data": {
    73  			"structSlice": [
    74  				{"name":"{"},
    75  				{"name":"1"},
    76  				{"name": { "test": 1 }},
    77  				{"name":"1"}
    78  			]
    79  		}
    80  }
    81  `)
    82  		typeError := json.Unmarshal(d, &data).(*json.UnmarshalTypeError)
    83  		tt.Equal("data.structSlice[2].name", LocateJSONPath(d, typeError.Offset))
    84  	}
    85  
    86  	{
    87  		d := []byte(`
    88  	{
    89  		"data": {
    90  			"stringSlice":["1","2",3]
    91  		}
    92  	}
    93  	`)
    94  		typeError := json.Unmarshal(d, &data).(*json.UnmarshalTypeError)
    95  		tt.Equal("data.stringSlice[2]", LocateJSONPath(d, typeError.Offset))
    96  	}
    97  
    98  	{
    99  		d := []byte(`
   100  	{
   101  		"data": {
   102  			"bool": true,
   103  			"nestedSlice": [
   104  				{ "names": ["1","2","3"] },
   105  	            { "names": ["1","\"2", 3] }
   106  			]
   107  		}
   108  	}
   109  	`)
   110  		typeError := json.Unmarshal(d, &data).(*json.UnmarshalTypeError)
   111  		tt.Equal("data.nestedSlice[1].names[2]", LocateJSONPath(d, typeError.Offset))
   112  	}
   113  }