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

     1  package jzon
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/require"
     9  )
    10  
    11  type encFace interface {
    12  	Encode(v interface{}) error
    13  
    14  	SetEscapeHTML(on bool)
    15  
    16  	// This is incompatible with standard library
    17  	// SetIndent(prefix, indent string)
    18  }
    19  
    20  var _ encFace = &json.Encoder{}
    21  var _ encFace = &Encoder{}
    22  
    23  func TestEncoder_SetEscapeHTML(t *testing.T) {
    24  	f := func(t *testing.T, o interface{}, expOn, expOff string) {
    25  		must := require.New(t)
    26  		buf := bytes.NewBuffer(nil)
    27  		f := func(enc encFace) {
    28  			// enabled
    29  			buf.Reset()
    30  			err := enc.Encode(o)
    31  			must.NoError(err)
    32  			must.Equal(expOn+"\n", buf.String(), "%T", enc)
    33  
    34  			// disabled
    35  			buf.Reset()
    36  			enc.SetEscapeHTML(false)
    37  			err = enc.Encode(o)
    38  			must.NoError(err)
    39  			must.Equal(expOff+"\n", buf.String(), "%T", enc)
    40  		}
    41  		f(json.NewEncoder(buf))
    42  		enc := NewEncoder(buf)
    43  		defer enc.Release()
    44  		f(enc)
    45  	}
    46  	t.Run("normal", func(t *testing.T) {
    47  		s := "<>&"
    48  		expOn := `"\u003c\u003e\u0026"`
    49  		expOff := `"` + s + `"`
    50  		f(t, s, expOn, expOff)
    51  	})
    52  	t.Run("struct", func(t *testing.T) {
    53  		s := struct {
    54  			A int `json:"&"`
    55  		}{}
    56  		expOn := `{"\u0026":0}`
    57  		expOff := `{"&":0}`
    58  		f(t, s, expOn, expOff)
    59  	})
    60  }
    61  
    62  // func TestEncoder_SetIndent(t *testing.T) {
    63  // 	must := require.New(t)
    64  // 	s := map[string]interface{}{
    65  // 		"k": "v",
    66  // 	}
    67  // 	buf := bytes.NewBuffer(nil)
    68  // 	f := func(enc encFace) {
    69  // 		// disabled
    70  // 		buf.Reset()
    71  // 		err := enc.Encode(s)
    72  // 		must.NoError(err)
    73  // 		must.Equal(`{"k":"v"}`+"\n", buf.String(), "%T", enc)
    74  //
    75  // 		// disabled
    76  // 		buf.Reset()
    77  // 		enc.SetIndent("p", "i")
    78  // 		err = enc.Encode(s)
    79  // 		must.NoError(err)
    80  // 		t.Logf("\n%s", buf.Bytes())
    81  // 		must.Equal("{\npi\"k\": \"v\"\np}\n", buf.String(), "%T", enc)
    82  // 	}
    83  // 	f(json.NewEncoder(buf))
    84  // 	f(NewEncoder(buf))
    85  // }