github.com/zerosnake0/jzon@v0.0.9-0.20230801092939-1b135cb83f7f/val_encoder_native_struct_test.go (about) 1 package jzon 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/require" 7 ) 8 9 func TestValEncoder_Native_Struct_Zero_Field(t *testing.T) { 10 t.Run("pointer", func(t *testing.T) { 11 type a struct{} 12 checkEncodeValueWithStandard(t, (*a)(nil), nil) 13 }) 14 t.Run("non pointer", func(t *testing.T) { 15 type a struct{} 16 checkEncodeValueWithStandard(t, a{}, nil) 17 }) 18 } 19 20 func TestValEncoder_Native_Struct_Mapping(t *testing.T) { 21 t.Run("unexported field", func(t *testing.T) { 22 checkEncodeValueWithStandard(t, &struct { 23 a string 24 }{ 25 a: "abc", 26 }, nil) 27 }) 28 t.Run("unexported field 2", func(t *testing.T) { 29 checkEncodeValueWithStandard(t, &struct { 30 a string 31 B int 32 }{ 33 a: "abc", 34 B: 1, 35 }, nil) 36 }) 37 t.Run("tag ignored 1", func(t *testing.T) { 38 checkEncodeValueWithStandard(t, &struct { 39 A string `json:"-"` 40 }{ 41 A: "test", 42 }, nil) 43 }) 44 t.Run("tag", func(t *testing.T) { 45 checkEncodeValueWithStandard(t, &struct { 46 A string `json:"B"` 47 }{ 48 A: "test", 49 }, nil) 50 }) 51 } 52 53 func TestValEncoder_Native_Struct_CustomTag(t *testing.T) { 54 encCfg := NewEncoderConfig(&EncoderOption{ 55 Tag: "jzon", 56 }) 57 b, err := encCfg.Marshal(&struct { 58 A string `jzon:"b"` 59 }{ 60 A: "test", 61 }) 62 require.NoError(t, err) 63 require.Equal(t, `{"b":"test"}`, string(b)) 64 } 65 66 func TestValEncoder_Native_Struct_Embedded_Unexported(t *testing.T) { 67 t.Run("not embedded", func(t *testing.T) { 68 type inner struct{} 69 type outer struct { 70 inner inner 71 } 72 checkEncodeValueWithStandard(t, &outer{ 73 inner: inner{}, 74 }, nil) 75 }) 76 t.Run("non struct", func(t *testing.T) { 77 type inner int 78 type outer struct { 79 inner 80 } 81 checkEncodeValueWithStandard(t, &outer{ 82 inner: 1, 83 }, nil) 84 }) 85 t.Run("duplicate field", func(t *testing.T) { 86 type inner struct { 87 A int `json:"a"` 88 } 89 type inner2 inner 90 type outer struct { 91 *inner 92 *inner2 93 } 94 checkEncodeValueWithStandard(t, &outer{}, nil) 95 checkEncodeValueWithStandard(t, &outer{ 96 inner: &inner{A: 1}, 97 }, nil) 98 checkEncodeValueWithStandard(t, &outer{ 99 inner: &inner{A: 1}, 100 inner2: &inner2{A: 2}, 101 }, nil) 102 }) 103 }