jsonlogbytes_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package jsonlog
  2. import (
  3. "bytes"
  4. "regexp"
  5. "testing"
  6. )
  7. func TestJSONLogsMarshalJSONBuf(t *testing.T) {
  8. logs := map[*JSONLogs]string{
  9. &JSONLogs{Log: []byte(`"A log line with \\"`)}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":}$`,
  10. &JSONLogs{Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"time\":}$`,
  11. &JSONLogs{Log: []byte("A log line with \r")}: `^{\"log\":\"A log line with \\r\",\"time\":}$`,
  12. &JSONLogs{Log: []byte("A log line with & < >")}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":}$`,
  13. &JSONLogs{Log: []byte("A log line with utf8 : 🚀 ψ ω β")}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":}$`,
  14. &JSONLogs{Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":}$`,
  15. &JSONLogs{Stream: "stdout", Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"stream\":\"stdout\",\"time\":}$`,
  16. &JSONLogs{Created: "time"}: `^{\"time\":time}$`,
  17. &JSONLogs{}: `^{\"time\":}$`,
  18. // These ones are a little weird
  19. &JSONLogs{Log: []byte("\u2028 \u2029")}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":}$`,
  20. &JSONLogs{Log: []byte{0xaF}}: `^{\"log\":\"\\ufffd\",\"time\":}$`,
  21. &JSONLogs{Log: []byte{0x7F}}: `^{\"log\":\"\x7f\",\"time\":}$`,
  22. // with raw attributes
  23. &JSONLogs{Log: []byte("A log line"), RawAttrs: []byte(`{"hello":"world","value":1234}`)}: `^{\"log\":\"A log line\",\"attrs\":{\"hello\":\"world\",\"value\":1234},\"time\":}$`,
  24. }
  25. for jsonLog, expression := range logs {
  26. var buf bytes.Buffer
  27. if err := jsonLog.MarshalJSONBuf(&buf); err != nil {
  28. t.Fatal(err)
  29. }
  30. res := buf.String()
  31. t.Logf("Result of WriteLog: %q", res)
  32. logRe := regexp.MustCompile(expression)
  33. if !logRe.MatchString(res) {
  34. t.Fatalf("Log line not in expected format [%v]: %q", expression, res)
  35. }
  36. }
  37. }