github.com/zerosnake0/jzon@v0.0.9-0.20230801092939-1b135cb83f7f/val_encoder_native_struct_omitempty_test.go (about)

     1  package jzon
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  func TestValEncoder_Native_Struct_OmitEmpty(t *testing.T) {
     8  	t.Run("mix", func(t *testing.T) {
     9  		type st struct {
    10  			S    string      `json:",omitempty"`
    11  			I8   int8        `json:",omitempty"`
    12  			I16  int16       `json:",omitempty"`
    13  			I32  int32       `json:",omitempty"`
    14  			I64  int64       `json:",omitempty"`
    15  			U8   uint8       `json:",omitempty"`
    16  			U16  uint16      `json:",omitempty"`
    17  			U32  uint32      `json:",omitempty"`
    18  			U64  uint64      `json:",omitempty"`
    19  			Uptr uintptr     `json:",omitempty"`
    20  			O    interface{} `json:",omitempty"`
    21  		}
    22  		checkEncodeValueWithStandard(t, st{}, nil)
    23  		i8 := int8(0)
    24  		checkEncodeValueWithStandard(t, st{
    25  			O: &i8,
    26  		}, nil)
    27  		i8 = int8(1)
    28  		checkEncodeValueWithStandard(t, st{
    29  			O: &i8,
    30  		}, nil)
    31  	})
    32  	t.Run("pointer", func(t *testing.T) {
    33  		type st struct {
    34  			PI8 *int8 `json:",omitempty"`
    35  		}
    36  		t.Run("nil", func(t *testing.T) {
    37  			checkEncodeValueWithStandard(t, st{}, nil)
    38  		})
    39  		t.Run("zero", func(t *testing.T) {
    40  			i8 := int8(0)
    41  			checkEncodeValueWithStandard(t, st{
    42  				PI8: &i8,
    43  			}, nil)
    44  		})
    45  		t.Run("non zero", func(t *testing.T) {
    46  			i8 := int8(1)
    47  			checkEncodeValueWithStandard(t, st{
    48  				PI8: &i8,
    49  			}, nil)
    50  		})
    51  	})
    52  	t.Run("struct", func(t *testing.T) {
    53  		type inner struct {
    54  			A int `json:",omitempty"`
    55  		}
    56  		type outer struct {
    57  			B inner `json:",omitempty"`
    58  		}
    59  		checkEncodeValueWithStandard(t, outer{}, nil)
    60  		checkEncodeValueWithStandard(t, outer{
    61  			B: inner{A: 1},
    62  		}, nil)
    63  	})
    64  	t.Run("struct 2", func(t *testing.T) {
    65  		type inner struct {
    66  			A int `json:",omitempty"`
    67  		}
    68  		type outer struct {
    69  			B *inner `json:",omitempty"`
    70  		}
    71  		checkEncodeValueWithStandard(t, outer{}, nil)
    72  		checkEncodeValueWithStandard(t, outer{
    73  			B: &inner{},
    74  		}, nil)
    75  		checkEncodeValueWithStandard(t, outer{
    76  			B: &inner{A: 1},
    77  		}, nil)
    78  	})
    79  }