jsonlog_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. logRe := regexp.MustCompile(`\[.*\] Line that thinks that it is log line from docker`)
  31. for _, l := range lines {
  32. if !logRe.MatchString(l) {
  33. t.Fatalf("Log line not in expected format: %q", l)
  34. }
  35. }
  36. }
  37. func BenchmarkWriteLog(b *testing.B) {
  38. var buf bytes.Buffer
  39. e := json.NewEncoder(&buf)
  40. testLine := "Line that thinks that it is log line from docker\n"
  41. for i := 0; i < 30; i++ {
  42. e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
  43. }
  44. r := bytes.NewReader(buf.Bytes())
  45. w := ioutil.Discard
  46. format := timeutils.RFC3339NanoFixed
  47. b.SetBytes(int64(r.Len()))
  48. b.ResetTimer()
  49. for i := 0; i < b.N; i++ {
  50. if err := WriteLog(r, w, format); err != nil {
  51. b.Fatal(err)
  52. }
  53. b.StopTimer()
  54. r.Seek(0, 0)
  55. b.StartTimer()
  56. }
  57. }