trace_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package trace
  5. import (
  6. "fmt"
  7. "net/http"
  8. "reflect"
  9. "testing"
  10. )
  11. type s struct{}
  12. func (s) String() string { return "lazy string" }
  13. // TestReset checks whether all the fields are zeroed after reset.
  14. func TestReset(t *testing.T) {
  15. tr := New("foo", "bar")
  16. tr.LazyLog(s{}, false)
  17. tr.LazyPrintf("%d", 1)
  18. tr.SetRecycler(func(_ interface{}) {})
  19. tr.SetTraceInfo(3, 4)
  20. tr.SetMaxEvents(100)
  21. tr.SetError()
  22. tr.Finish()
  23. tr.(*trace).reset()
  24. if !reflect.DeepEqual(tr, new(trace)) {
  25. t.Errorf("reset didn't clear all fields: %+v", tr)
  26. }
  27. }
  28. // TestResetLog checks whether all the fields are zeroed after reset.
  29. func TestResetLog(t *testing.T) {
  30. el := NewEventLog("foo", "bar")
  31. el.Printf("message")
  32. el.Errorf("error")
  33. el.Finish()
  34. el.(*eventLog).reset()
  35. if !reflect.DeepEqual(el, new(eventLog)) {
  36. t.Errorf("reset didn't clear all fields: %+v", el)
  37. }
  38. }
  39. func TestAuthRequest(t *testing.T) {
  40. testCases := []struct {
  41. host string
  42. want bool
  43. }{
  44. {host: "192.168.23.1", want: false},
  45. {host: "192.168.23.1:8080", want: false},
  46. {host: "malformed remote addr", want: false},
  47. {host: "localhost", want: true},
  48. {host: "localhost:8080", want: true},
  49. {host: "127.0.0.1", want: true},
  50. {host: "127.0.0.1:8080", want: true},
  51. {host: "::1", want: true},
  52. {host: "[::1]:8080", want: true},
  53. }
  54. for _, tt := range testCases {
  55. req := &http.Request{RemoteAddr: tt.host}
  56. any, sensitive := AuthRequest(req)
  57. if any != tt.want || sensitive != tt.want {
  58. t.Errorf("AuthRequest(%q) = %t, %t; want %t, %t", tt.host, any, sensitive, tt.want, tt.want)
  59. }
  60. }
  61. }
  62. func benchmarkTrace(b *testing.B, maxEvents, numEvents int) {
  63. numSpans := (b.N + numEvents + 1) / numEvents
  64. for i := 0; i < numSpans; i++ {
  65. tr := New("test", "test")
  66. tr.SetMaxEvents(maxEvents)
  67. for j := 0; j < numEvents; j++ {
  68. tr.LazyPrintf("%d", j)
  69. }
  70. tr.Finish()
  71. }
  72. }
  73. func BenchmarkTrace(b *testing.B) {
  74. for _, maxEvents := range []int{0, 10, 100, 1000} {
  75. for _, numEvents := range []int{2, 10, 100, 1000, 10000} {
  76. name := fmt.Sprintf("%d-%d", maxEvents, numEvents)
  77. b.Run(name, func(b *testing.B) {
  78. benchmarkTrace(b, maxEvents, numEvents)
  79. })
  80. }
  81. }
  82. }