jsonlog_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package jsonlog
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io/ioutil"
  6. "regexp"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/docker/docker/pkg/timeutils"
  11. )
  12. func TestWriteLog(t *testing.T) {
  13. var buf bytes.Buffer
  14. e := json.NewEncoder(&buf)
  15. testLine := "Line that thinks that it is log line from docker\n"
  16. for i := 0; i < 30; i++ {
  17. e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
  18. }
  19. w := bytes.NewBuffer(nil)
  20. format := timeutils.RFC3339NanoFixed
  21. if err := WriteLog(&buf, w, format); err != nil {
  22. t.Fatal(err)
  23. }
  24. res := w.String()
  25. t.Logf("Result of WriteLog: %q", res)
  26. lines := strings.Split(strings.TrimSpace(res), "\n")
  27. if len(lines) != 30 {
  28. t.Fatalf("Must be 30 lines but got %d", len(lines))
  29. }
  30. // 30+ symbols, five more can come from system timezone
  31. logRe := regexp.MustCompile(`.{30,} Line that thinks that it is log line from docker`)
  32. for _, l := range lines {
  33. if !logRe.MatchString(l) {
  34. t.Fatalf("Log line not in expected format: %q", l)
  35. }
  36. }
  37. }
  38. func BenchmarkWriteLog(b *testing.B) {
  39. var buf bytes.Buffer
  40. e := json.NewEncoder(&buf)
  41. testLine := "Line that thinks that it is log line from docker\n"
  42. for i := 0; i < 30; i++ {
  43. e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
  44. }
  45. r := bytes.NewReader(buf.Bytes())
  46. w := ioutil.Discard
  47. format := timeutils.RFC3339NanoFixed
  48. b.SetBytes(int64(r.Len()))
  49. b.ResetTimer()
  50. for i := 0; i < b.N; i++ {
  51. if err := WriteLog(r, w, format); err != nil {
  52. b.Fatal(err)
  53. }
  54. b.StopTimer()
  55. r.Seek(0, 0)
  56. b.StartTimer()
  57. }
  58. }