trace_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2016 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 httptrace
  5. import (
  6. "bytes"
  7. "context"
  8. "testing"
  9. )
  10. func TestWithClientTrace(t *testing.T) {
  11. var buf bytes.Buffer
  12. connectStart := func(b byte) func(network, addr string) {
  13. return func(network, addr string) {
  14. buf.WriteByte(b)
  15. }
  16. }
  17. ctx := context.Background()
  18. oldtrace := &ClientTrace{
  19. ConnectStart: connectStart('O'),
  20. }
  21. ctx = WithClientTrace(ctx, oldtrace)
  22. newtrace := &ClientTrace{
  23. ConnectStart: connectStart('N'),
  24. }
  25. ctx = WithClientTrace(ctx, newtrace)
  26. trace := ContextClientTrace(ctx)
  27. buf.Reset()
  28. trace.ConnectStart("net", "addr")
  29. if got, want := buf.String(), "NO"; got != want {
  30. t.Errorf("got %q; want %q", got, want)
  31. }
  32. }
  33. func TestCompose(t *testing.T) {
  34. var buf bytes.Buffer
  35. var testNum int
  36. connectStart := func(b byte) func(network, addr string) {
  37. return func(network, addr string) {
  38. if addr != "addr" {
  39. t.Errorf(`%d. args for %q case = %q, %q; want addr of "addr"`, testNum, b, network, addr)
  40. }
  41. buf.WriteByte(b)
  42. }
  43. }
  44. tests := [...]struct {
  45. trace, old *ClientTrace
  46. want string
  47. }{
  48. 0: {
  49. want: "T",
  50. trace: &ClientTrace{
  51. ConnectStart: connectStart('T'),
  52. },
  53. },
  54. 1: {
  55. want: "TO",
  56. trace: &ClientTrace{
  57. ConnectStart: connectStart('T'),
  58. },
  59. old: &ClientTrace{ConnectStart: connectStart('O')},
  60. },
  61. 2: {
  62. want: "O",
  63. trace: &ClientTrace{},
  64. old: &ClientTrace{ConnectStart: connectStart('O')},
  65. },
  66. }
  67. for i, tt := range tests {
  68. testNum = i
  69. buf.Reset()
  70. tr := *tt.trace
  71. tr.compose(tt.old)
  72. if tr.ConnectStart != nil {
  73. tr.ConnectStart("net", "addr")
  74. }
  75. if got := buf.String(); got != tt.want {
  76. t.Errorf("%d. got = %q; want %q", i, got, tt.want)
  77. }
  78. }
  79. }