1package tracing
2
3// Copyright 2018 Microsoft Corporation
4//
5//  Licensed under the Apache License, Version 2.0 (the "License");
6//  you may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at
8//
9//      http://www.apache.org/licenses/LICENSE-2.0
10//
11//  Unless required by applicable law or agreed to in writing, software
12//  distributed under the License is distributed on an "AS IS" BASIS,
13//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14//  See the License for the specific language governing permissions and
15//  limitations under the License.
16
17import (
18	"context"
19	"net/http"
20	"testing"
21)
22
23func TestDisabled(t *testing.T) {
24	if IsEnabled() {
25		t.Fatal("unexpected enabled tracing")
26	}
27	if tr := NewTransport(&http.Transport{}); tr != nil {
28		t.Fatal("unexpected non-nil transport")
29	}
30	if ctx := StartSpan(context.Background(), "foo"); ctx != context.Background() {
31		t.Fatal("contexts don't match")
32	}
33}
34
35func TestEnabled(t *testing.T) {
36	mt := mockTracer{}
37	Register(&mt)
38	if !IsEnabled() {
39		t.Fatal("unexpected disabled tracing")
40	}
41	if tr := NewTransport(&http.Transport{}); tr != http.DefaultTransport {
42		t.Fatal("didn't receive expected transport")
43	}
44	ctx := StartSpan(context.Background(), "foo")
45	v := ctx.Value(mockTracer{})
46	if val, ok := v.(string); !ok {
47		t.Fatal("unexpected value type")
48	} else if val != "foo" {
49		t.Fatal("unexpected value")
50	}
51	EndSpan(ctx, http.StatusOK, nil)
52	if !mt.ended {
53		t.Fatal("EndSpan didn't forward call to registered tracer")
54	}
55}
56
57type mockTracer struct {
58	ended bool
59}
60
61func (m mockTracer) NewTransport(base *http.Transport) http.RoundTripper {
62	return http.DefaultTransport
63}
64
65func (m mockTracer) StartSpan(ctx context.Context, name string) context.Context {
66	return context.WithValue(ctx, mockTracer{}, name)
67}
68
69func (m *mockTracer) EndSpan(ctx context.Context, httpStatusCode int, err error) {
70	m.ended = true
71}
72