jsonlogbytes_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package jsonlog // import "github.com/docker/docker/daemon/logger/jsonfilelog/jsonlog"
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "regexp"
  7. "testing"
  8. "time"
  9. "gotest.tools/assert"
  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. assert.NilError(t, err)
  35. assert.Assert(t, regexP(buf.String(), expression))
  36. assert.NilError(t, json.Unmarshal(buf.Bytes(), &map[string]interface{}{}))
  37. }
  38. }
  39. func regexP(value string, pattern string) func() (bool, string) {
  40. return func() (bool, string) {
  41. re := regexp.MustCompile(pattern)
  42. msg := fmt.Sprintf("%q did not match pattern %q", value, pattern)
  43. return re.MatchString(value), msg
  44. }
  45. }