trace_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package blademaster
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. "time"
  8. "go-common/library/net/trace"
  9. )
  10. func TestTrace(t *testing.T) {
  11. wait := make(chan bool, 1)
  12. eng := New()
  13. eng.Use(Trace())
  14. eng.GET("/test-trace", func(c *Context) {
  15. if _, ok := trace.FromContext(c.Context); !ok {
  16. t.Errorf("expect get trace from context")
  17. }
  18. c.Writer.Write([]byte("pong"))
  19. wait <- true
  20. })
  21. go eng.Run("127.0.0.1:28080")
  22. time.Sleep(time.Second)
  23. http.Get("http://127.0.0.1:28080/test-trace")
  24. <-wait
  25. }
  26. func TestTraceClient(t *testing.T) {
  27. wait := make(chan bool, 1)
  28. trace.Init(nil)
  29. root := trace.New("test-title")
  30. ctx := trace.NewContext(context.Background(), root)
  31. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  32. keys := []string{trace.KeyTraceID, trace.KeyTraceSpanID, trace.KeyTraceParentID, trace.KeyTraceID}
  33. for _, key := range keys {
  34. if r.Header.Get(key) == "" {
  35. t.Errorf("empty key: %s", key)
  36. }
  37. }
  38. wait <- true
  39. }))
  40. defer srv.Close()
  41. req, err := http.NewRequest(http.MethodGet, srv.URL, nil)
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. req = req.WithContext(ctx)
  46. client := &http.Client{Transport: &TraceTransport{}}
  47. if _, err = client.Do(req); err != nil {
  48. t.Fatal(err)
  49. }
  50. <-wait
  51. }