jsonlogbytes_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637
  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. }
  23. for jsonLog, expression := range logs {
  24. var buf bytes.Buffer
  25. if err := jsonLog.MarshalJSONBuf(&buf); err != nil {
  26. t.Fatal(err)
  27. }
  28. res := buf.String()
  29. t.Logf("Result of WriteLog: %q", res)
  30. logRe := regexp.MustCompile(expression)
  31. if !logRe.MatchString(res) {
  32. t.Fatalf("Log line not in expected format [%v]: %q", expression, res)
  33. }
  34. }
  35. }