|
| 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 | + |
| 15 | +package stackdriver |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "io/ioutil" |
| 20 | + "net/http" |
| 21 | + "net/http/httptest" |
| 22 | + "os" |
| 23 | + "testing" |
| 24 | + "time" |
| 25 | + |
| 26 | + "go.opencensus.io/plugin/ochttp" |
| 27 | + "go.opencensus.io/stats/view" |
| 28 | + "go.opencensus.io/trace" |
| 29 | + "golang.org/x/net/context/ctxhttp" |
| 30 | +) |
| 31 | + |
| 32 | +func TestExport(t *testing.T) { |
| 33 | + projectID, ok := os.LookupEnv("STACKDRIVER_TEST_PROJECT_ID") |
| 34 | + if !ok { |
| 35 | + t.Skip("STACKDRIVER_TEST_PROJECT_ID not set") |
| 36 | + } |
| 37 | + |
| 38 | + exporter, err := NewExporter(Options{ProjectID: projectID}) |
| 39 | + if err != nil { |
| 40 | + t.Fatal(err) |
| 41 | + } |
| 42 | + defer exporter.Flush() |
| 43 | + |
| 44 | + trace.RegisterExporter(exporter) |
| 45 | + defer trace.UnregisterExporter(exporter) |
| 46 | + view.RegisterExporter(exporter) |
| 47 | + defer view.UnregisterExporter(exporter) |
| 48 | + |
| 49 | + trace.SetDefaultSampler(trace.AlwaysSample()) |
| 50 | + |
| 51 | + span := trace.NewSpan("custom-span", nil, trace.StartOptions{}) |
| 52 | + time.Sleep(10 * time.Millisecond) |
| 53 | + span.End() |
| 54 | + |
| 55 | + // Test HTTP spans |
| 56 | + |
| 57 | + handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { |
| 58 | + time.Sleep(150 * time.Millisecond) // do work |
| 59 | + rw.Write([]byte("Hello, world!")) |
| 60 | + }) |
| 61 | + server := httptest.NewServer(&ochttp.Handler{Handler: handler}) |
| 62 | + defer server.Close() |
| 63 | + |
| 64 | + ctx := context.Background() |
| 65 | + client := &http.Client{ |
| 66 | + Transport: &ochttp.Transport{}, |
| 67 | + } |
| 68 | + resp, err := ctxhttp.Get(ctx, client, server.URL+"/test/123?abc=xyz") |
| 69 | + if err != nil { |
| 70 | + t.Fatal(err) |
| 71 | + } |
| 72 | + body, err := ioutil.ReadAll(resp.Body) |
| 73 | + if err != nil { |
| 74 | + t.Fatal(err) |
| 75 | + } |
| 76 | + if want, got := "Hello, world!", string(body); want != got { |
| 77 | + t.Fatalf("resp.Body = %q; want %q", want, got) |
| 78 | + } |
| 79 | +} |
0 commit comments