github.com/DoNewsCode/core@v0.12.3/codec/json/json_test.go (about)

     1  package json
     2  
     3  import (
     4  	"bytes"
     5  	"strings"
     6  	"testing"
     7  )
     8  
     9  type testEmbed struct {
    10  	Level1a int `json:"a"`
    11  	Level1b int `json:"b"`
    12  	Level1c int `json:"c"`
    13  }
    14  
    15  type testMessage struct {
    16  	Field1 string     `json:"a"`
    17  	Field2 string     `json:"b"`
    18  	Field3 string     `json:"c"`
    19  	Embed  *testEmbed `json:"embed,omitempty"`
    20  }
    21  
    22  func TestJSON_Marshal(t *testing.T) {
    23  	tests := []struct {
    24  		input   interface{}
    25  		expect  string
    26  		options []Option
    27  	}{
    28  		{
    29  			input:   &testMessage{},
    30  			expect:  `{"a":"","b":"","c":""}`,
    31  			options: nil,
    32  		},
    33  		{
    34  			input:   &testMessage{Field1: "a", Field2: "b", Field3: "c"},
    35  			expect:  `{"a":"a","b":"b","c":"c"}`,
    36  			options: nil,
    37  		},
    38  		{
    39  			input: &testMessage{Field1: "a", Field2: "b", Field3: "c"},
    40  			expect: `{
    41   "a": "a",
    42   "b": "b",
    43   "c": "c"
    44  }`,
    45  			options: []Option{WithIndent(" ")},
    46  		},
    47  	}
    48  	for _, v := range tests {
    49  		data, err := (NewCodec(v.options...)).Marshal(v.input)
    50  		if err != nil {
    51  			t.Errorf("marshal(%#v): %s", v.input, err)
    52  		}
    53  		if got, want := string(data), v.expect; got != want {
    54  			if strings.Contains(want, "\n") {
    55  				t.Errorf("marshal(%#v):\nHAVE:\n%s\nWANT:\n%s", v.input, got, want)
    56  			} else {
    57  				t.Errorf("marshal(%#v):\nhave %#q\nwant %#q", v.input, got, want)
    58  			}
    59  		}
    60  	}
    61  }
    62  
    63  func TestJSON_Unmarshal(t *testing.T) {
    64  	p := &testMessage{}
    65  	tests := []struct {
    66  		input  string
    67  		expect interface{}
    68  	}{
    69  		{
    70  			input:  `{"a":"","b":"","c":""}`,
    71  			expect: &testMessage{},
    72  		},
    73  		{
    74  			input:  `{"a":"a","b":"b","c":"c"}`,
    75  			expect: &p,
    76  		},
    77  	}
    78  	for _, v := range tests {
    79  		want := []byte(v.input)
    80  		err := (Codec{}).Unmarshal(want, &v.expect)
    81  		if err != nil {
    82  			t.Errorf("marshal(%#v): %s", v.input, err)
    83  		}
    84  		got, err := Codec{}.Marshal(v.expect)
    85  		if err != nil {
    86  			t.Errorf("marshal(%#v): %s", v.input, err)
    87  		}
    88  		if !bytes.Equal(got, want) {
    89  			t.Errorf("marshal(%#v):\nhave %#q\nwant %#q", v.input, got, want)
    90  		}
    91  	}
    92  }