marshal_json_escape_test.go 918 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package test
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "testing"
  6. jsoniter "github.com/json-iterator/go"
  7. "github.com/stretchr/testify/require"
  8. )
  9. var marshalConfig = jsoniter.Config{
  10. EscapeHTML: false,
  11. SortMapKeys: true,
  12. ValidateJsonRawMessage: true,
  13. }.Froze()
  14. type Container struct {
  15. Bar interface{}
  16. }
  17. func (c *Container) MarshalJSON() ([]byte, error) {
  18. return marshalConfig.Marshal(&c.Bar)
  19. }
  20. func TestEncodeEscape(t *testing.T) {
  21. should := require.New(t)
  22. container := &Container{
  23. Bar: []string{"123<ab>", "ooo"},
  24. }
  25. out, err := marshalConfig.Marshal(container)
  26. should.Nil(err)
  27. bufout := string(out)
  28. var stdbuf bytes.Buffer
  29. stdenc := json.NewEncoder(&stdbuf)
  30. stdenc.SetEscapeHTML(false)
  31. err = stdenc.Encode(container)
  32. should.Nil(err)
  33. stdout := string(stdbuf.Bytes())
  34. if stdout[len(stdout)-1:] == "\n" {
  35. stdout = stdout[:len(stdout)-1]
  36. }
  37. should.Equal(stdout, bufout)
  38. }