trace_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package context
  2. import (
  3. "runtime"
  4. "testing"
  5. "time"
  6. )
  7. // TestWithTrace ensures that tracing has the expected values in the context.
  8. func TestWithTrace(t *testing.T) {
  9. pc, file, _, _ := runtime.Caller(0) // get current caller.
  10. f := runtime.FuncForPC(pc)
  11. base := []valueTestCase{
  12. {
  13. key: "trace.id",
  14. notnilorempty: true,
  15. },
  16. {
  17. key: "trace.file",
  18. expected: file,
  19. notnilorempty: true,
  20. },
  21. {
  22. key: "trace.line",
  23. notnilorempty: true,
  24. },
  25. {
  26. key: "trace.start",
  27. notnilorempty: true,
  28. },
  29. }
  30. ctx, done := WithTrace(Background())
  31. defer done("this will be emitted at end of test")
  32. checkContextForValues(t, ctx, append(base, valueTestCase{
  33. key: "trace.func",
  34. expected: f.Name(),
  35. }))
  36. traced := func() {
  37. parentID := ctx.Value("trace.id") // ensure the parent trace id is correct.
  38. pc, _, _, _ := runtime.Caller(0) // get current caller.
  39. f := runtime.FuncForPC(pc)
  40. ctx, done := WithTrace(ctx)
  41. defer done("this should be subordinate to the other trace")
  42. time.Sleep(time.Second)
  43. checkContextForValues(t, ctx, append(base, valueTestCase{
  44. key: "trace.func",
  45. expected: f.Name(),
  46. }, valueTestCase{
  47. key: "trace.parent.id",
  48. expected: parentID,
  49. }))
  50. }
  51. traced()
  52. time.Sleep(time.Second)
  53. }
  54. type valueTestCase struct {
  55. key string
  56. expected interface{}
  57. notnilorempty bool // just check not empty/not nil
  58. }
  59. func checkContextForValues(t *testing.T, ctx Context, values []valueTestCase) {
  60. for _, testcase := range values {
  61. v := ctx.Value(testcase.key)
  62. if testcase.notnilorempty {
  63. if v == nil || v == "" {
  64. t.Fatalf("value was nil or empty for %q: %#v", testcase.key, v)
  65. }
  66. continue
  67. }
  68. if v != testcase.expected {
  69. t.Fatalf("unexpected value for key %q: %v != %v", testcase.key, v, testcase.expected)
  70. }
  71. }
  72. }