jsonlogbytes_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package jsonlog
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "regexp"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/stretchr/testify/require"
  10. )
  11. func TestJSONLogsMarshalJSONBuf(t *testing.T) {
  12. logs := map[*JSONLogs]string{
  13. {Log: []byte(`"A log line with \\"`)}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":`,
  14. {Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"time\":`,
  15. {Log: []byte("A log line with \r")}: `^{\"log\":\"A log line with \\r\",\"time\":`,
  16. {Log: []byte("A log line with & < >")}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":`,
  17. {Log: []byte("A log line with utf8 : 🚀 ψ ω β")}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":`,
  18. {Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":`,
  19. {Stream: "stdout", Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"stream\":\"stdout\",\"time\":`,
  20. {Created: time.Date(2017, 9, 1, 1, 1, 1, 1, time.UTC)}: `^{\"time\":"2017-09-01T01:01:01.000000001Z"}$`,
  21. {}: `^{\"time\":"0001-01-01T00:00:00Z"}$`,
  22. // These ones are a little weird
  23. {Log: []byte("\u2028 \u2029")}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":`,
  24. {Log: []byte{0xaF}}: `^{\"log\":\"\\ufffd\",\"time\":`,
  25. {Log: []byte{0x7F}}: `^{\"log\":\"\x7f\",\"time\":`,
  26. // with raw attributes
  27. {Log: []byte("A log line"), RawAttrs: []byte(`{"hello":"world","value":1234}`)}: `^{\"log\":\"A log line\",\"attrs\":{\"hello\":\"world\",\"value\":1234},\"time\":`,
  28. // with Tag set
  29. {Log: []byte("A log line with tag"), RawAttrs: []byte(`{"hello":"world","value":1234}`)}: `^{\"log\":\"A log line with tag\",\"attrs\":{\"hello\":\"world\",\"value\":1234},\"time\":`,
  30. }
  31. for jsonLog, expression := range logs {
  32. var buf bytes.Buffer
  33. err := jsonLog.MarshalJSONBuf(&buf)
  34. require.NoError(t, err)
  35. assert.Regexp(t, regexp.MustCompile(expression), buf.String())
  36. assert.NoError(t, json.Unmarshal(buf.Bytes(), &map[string]interface{}{}))
  37. }
  38. }