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

     1  package jzon
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestStreamer_String_ChainError(t *testing.T) {
    13  	testStreamerChainError(t, func(s *Streamer) {
    14  		s.String("test")
    15  	})
    16  }
    17  
    18  func testStreamerStringEscape(t *testing.T, s string, escape bool) {
    19  	var (
    20  		encCfg *EncoderConfig
    21  		b      bytes.Buffer
    22  	)
    23  	jsEnc := json.NewEncoder(&b)
    24  	jsEnc.SetEscapeHTML(escape)
    25  	jsEnc.Encode(s)
    26  	if escape {
    27  		encCfg = DefaultEncoderConfig
    28  	} else {
    29  		encCfg = NewEncoderConfig(&EncoderOption{
    30  			EscapeHTML: false,
    31  		})
    32  	}
    33  	// json.Encoder will add a newline at the end
    34  	exp := strings.TrimSpace(b.String())
    35  
    36  	streamer := encCfg.NewStreamer()
    37  	defer streamer.Release()
    38  	streamer.String(s)
    39  	require.NoError(t, streamer.Error)
    40  	require.Equal(t, exp, string(streamer.buffer))
    41  }
    42  
    43  func testStreamerString(t *testing.T, s string) {
    44  	testStreamerStringEscape(t, s, true)
    45  	testStreamerStringEscape(t, s, false)
    46  }
    47  
    48  func TestStreamer_String(t *testing.T) {
    49  	t.Run("empty", func(t *testing.T) {
    50  		testStreamerString(t, ``)
    51  	})
    52  	t.Run("quote", func(t *testing.T) {
    53  		testStreamerString(t, `"`)
    54  	})
    55  	t.Run("backslash", func(t *testing.T) {
    56  		testStreamerString(t, `\`)
    57  	})
    58  	t.Run("normal", func(t *testing.T) {
    59  		testStreamerString(t, "test")
    60  	})
    61  	t.Run("Line Feed", func(t *testing.T) {
    62  		testStreamerString(t, "\n")
    63  	})
    64  	t.Run("Carriage Return", func(t *testing.T) {
    65  		testStreamerString(t, "\r")
    66  	})
    67  	t.Run("tab", func(t *testing.T) {
    68  		testStreamerString(t, "\t")
    69  	})
    70  	t.Run("eof", func(t *testing.T) {
    71  		testStreamerString(t, "\u0000")
    72  	})
    73  	t.Run("utf8", func(t *testing.T) {
    74  		testStreamerString(t, "δΈ­")
    75  	})
    76  }
    77  
    78  func TestStreamer_String_Html(t *testing.T) {
    79  	t.Run("bracket", func(t *testing.T) {
    80  		testStreamerString(t, "<>")
    81  	})
    82  	t.Run("and", func(t *testing.T) {
    83  		testStreamerString(t, "&")
    84  	})
    85  	t.Run("rune error", func(t *testing.T) {
    86  		testStreamerString(t, "\xFF")
    87  	})
    88  	t.Run("2028", func(t *testing.T) {
    89  		testStreamerString(t, "\u2028")
    90  	})
    91  	t.Run("2029", func(t *testing.T) {
    92  		testStreamerString(t, "\u2029")
    93  	})
    94  }