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

     1  package jzon
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"runtime/debug"
     7  	"testing"
     8  )
     9  
    10  func TestValEncoder_Slice_Error(t *testing.T) {
    11  	t.Run("chain error", func(t *testing.T) {
    12  		testStreamerChainError(t, func(s *Streamer) {
    13  			(*sliceEncoder)(nil).Encode(nil, s, nil)
    14  		})
    15  	})
    16  	t.Run("error", func(t *testing.T) {
    17  		e := errors.New("test")
    18  		arr := []json.Marshaler{testJSONMarshaler{
    19  			data: `"test"`,
    20  			err:  e,
    21  		}}
    22  		checkEncodeValueWithStandard(t, arr, e)
    23  	})
    24  	debug.FreeOSMemory()
    25  }
    26  
    27  func TestValEncoder_Slice_Empty(t *testing.T) {
    28  	t.Run("nil", func(t *testing.T) {
    29  		var arr []int
    30  		checkEncodeValueWithStandard(t, arr, nil)
    31  	})
    32  	t.Run("empty", func(t *testing.T) {
    33  		arr := make([]int, 0)
    34  		checkEncodeValueWithStandard(t, arr, nil)
    35  	})
    36  	t.Run("nil pointer", func(t *testing.T) {
    37  		checkEncodeValueWithStandard(t, (*[]int)(nil), nil)
    38  	})
    39  	t.Run("empty pointer", func(t *testing.T) {
    40  		arr := make([]int, 0)
    41  		checkEncodeValueWithStandard(t, &arr, nil)
    42  	})
    43  	debug.FreeOSMemory()
    44  }
    45  
    46  func TestValEncoder_Slice(t *testing.T) {
    47  	t.Run("pointer", func(t *testing.T) {
    48  		arr := []int{1, 2, 3}
    49  		checkEncodeValueWithStandard(t, &arr, nil)
    50  	})
    51  	t.Run("non pointer", func(t *testing.T) {
    52  		arr := []int{1, 2, 3}
    53  		checkEncodeValueWithStandard(t, arr, nil)
    54  	})
    55  	t.Run("slice of pointer", func(t *testing.T) {
    56  		i := 1
    57  		arr := []*int{(*int)(nil), &i}
    58  		checkEncodeValueWithStandard(t, arr, nil)
    59  	})
    60  	debug.FreeOSMemory()
    61  }
    62  
    63  func TestValEncoder_Slice_OmitEmpty(t *testing.T) {
    64  	t.Run("normal", func(t *testing.T) {
    65  		type S []int
    66  		type st struct {
    67  			S S `json:",omitempty"`
    68  		}
    69  		t.Run("nil", func(t *testing.T) {
    70  			checkEncodeValueWithStandard(t, st{}, nil)
    71  		})
    72  		t.Run("empty", func(t *testing.T) {
    73  			checkEncodeValueWithStandard(t, st{
    74  				S: S{},
    75  			}, nil)
    76  		})
    77  		t.Run("non empty", func(t *testing.T) {
    78  			checkEncodeValueWithStandard(t, st{
    79  				S: S{1},
    80  			}, nil)
    81  		})
    82  	})
    83  }