propagation_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2018, OpenCensus Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ochttp
  15. import (
  16. "context"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "net/http/httptest"
  21. "testing"
  22. "go.opencensus.io/plugin/ochttp/propagation/b3"
  23. "go.opencensus.io/plugin/ochttp/propagation/tracecontext"
  24. "go.opencensus.io/trace"
  25. "go.opencensus.io/trace/propagation"
  26. )
  27. func TestRoundTripAllFormats(t *testing.T) {
  28. // TODO: test combinations of different formats for chains of calls
  29. formats := []propagation.HTTPFormat{
  30. &b3.HTTPFormat{},
  31. &tracecontext.HTTPFormat{},
  32. }
  33. ctx := context.Background()
  34. ctx, span := trace.StartSpan(ctx, "test", trace.WithSampler(trace.AlwaysSample()))
  35. sc := span.SpanContext()
  36. wantStr := fmt.Sprintf("trace_id=%x, span_id=%x, options=%d", sc.TraceID, sc.SpanID, sc.TraceOptions)
  37. defer span.End()
  38. for _, format := range formats {
  39. srv := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  40. sc, ok := format.SpanContextFromRequest(req)
  41. if !ok {
  42. resp.WriteHeader(http.StatusBadRequest)
  43. }
  44. fmt.Fprintf(resp, "trace_id=%x, span_id=%x, options=%d", sc.TraceID, sc.SpanID, sc.TraceOptions)
  45. }))
  46. req, err := http.NewRequest("GET", srv.URL, nil)
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. format.SpanContextToRequest(span.SpanContext(), req)
  51. resp, err := http.DefaultClient.Do(req)
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. if resp.StatusCode != 200 {
  56. t.Fatal(resp.Status)
  57. }
  58. body, err := ioutil.ReadAll(resp.Body)
  59. if err != nil {
  60. t.Fatal(err)
  61. }
  62. resp.Body.Close()
  63. if got, want := string(body), wantStr; got != want {
  64. t.Errorf("%s; want %s", got, want)
  65. }
  66. srv.Close()
  67. }
  68. }