File: trace_test.go

package info (click to toggle)
golang-github-chainguard-dev-clog 1.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 424 kB
  • sloc: makefile: 4
file content (70 lines) | stat: -rw-r--r-- 1,886 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package gcp

import (
	"log/slog"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/chainguard-dev/clog"
)

func TestTrace(t *testing.T) {
	// This ensures the metadata server is not called at all during tests.
	md := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t.Fatalf("metadata server called")
	}))
	defer md.Close()
	t.Setenv("GCE_METADATA_HOST", md.URL)

	slog.SetDefault(slog.New(NewHandler(slog.LevelDebug)))
	for _, c := range []struct {
		name      string
		env       string
		wantTrace string
	}{
		{"no env set", "", ""},
		{"env set", "my-project", "projects/my-project/traces/traceid"},
	} {
		t.Run(c.name, func(t *testing.T) {
			t.Setenv("GOOGLE_CLOUD_PROJECT", c.env)

			// Set up a server that logs a message with trace context added.
			slog.SetDefault(slog.New(NewHandler(slog.LevelDebug)))
			h := WithCloudTraceContext(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				ctx := r.Context()
				clog.InfoContext(ctx, "hello world")

				// TODO: This doesn't propagate the trace context to the logger.
				//clog.FromContext(ctx).Info("hello world")

				if r.Header.Get("traceparent") == "" {
					t.Error("got empty trace context header, want non-empty")
				}

				traceCtx := ctx.Value("trace")
				if traceCtx == nil {
					if c.wantTrace != "" {
						t.Fatalf("want %s, not found", c.wantTrace)
					}
				} else {
					if traceCtx != c.wantTrace {
						t.Fatalf("got %s, want %s", traceCtx, c.wantTrace)
					}
				}
			}))
			srv := httptest.NewServer(h)
			defer srv.Close()

			// Send a request to the server with a trace context header.
			req, err := http.NewRequest(http.MethodGet, srv.URL, nil)
			if err != nil {
				t.Fatal(err)
			}
			req.Header.Set("traceparent", "00-traceid-spanid-01")
			if _, err := http.DefaultClient.Do(req); err != nil {
				t.Fatal(err)
			}
		})
	}
}