jsonlogbytes_test.go 2.1 KB

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