...
1 package glog
2
3 import (
4 "context"
5 "flag"
6 "testing"
7
8 "github.com/golang/glog/internal/logsink"
9 )
10
11 type contextKey string
12 type fakeLogSink struct {
13 context context.Context
14 }
15
16 var ctxKey = contextKey("key")
17 var ctxValue = "some-value"
18 var originalSinks = logsink.StructuredSinks
19
20 func (s *fakeLogSink) Printf(meta *logsink.Meta, format string, args ...any) (int, error) {
21 s.context = meta.Context
22 return 0, nil
23 }
24
25
26
27 func TestLogContext(t *testing.T) {
28 fakeLogSink := &fakeLogSink{}
29 logsink.StructuredSinks = append([]logsink.Structured{fakeLogSink}, originalSinks...)
30
31 funcs := map[string]func(ctx context.Context, args ...any){
32 "InfoContext": InfoContext,
33 "InfoContextDepth": func(ctx context.Context, args ...any) { InfoContextDepth(ctx, 2, args) },
34 "ErrorContext": ErrorContext,
35 "WarningContext": WarningContext,
36 }
37
38 ctx := context.WithValue(context.Background(), ctxKey, ctxValue)
39 for name, f := range funcs {
40 f(ctx, "test")
41 want := ctxValue
42 if got := fakeLogSink.context.Value(ctxKey); got != want {
43 t.Errorf("%s: context value unexpectedly missing: got %q, want %q", name, got, want)
44 }
45 }
46 }
47
48
49 func TestVInfoContext(t *testing.T) {
50 fakeLogSink := &fakeLogSink{}
51 logsink.StructuredSinks = append([]logsink.Structured{fakeLogSink}, originalSinks...)
52 if err := flag.Lookup("v").Value.Set("2"); err != nil {
53 t.Fatalf("Failed to set -v=2: %v", err)
54 }
55 defer flag.Lookup("v").Value.Set("0")
56 ctx := context.WithValue(context.Background(), ctxKey, ctxValue)
57 V(2).InfoContext(ctx, "test")
58 want := ctxValue
59 if got := fakeLogSink.context.Value(ctxKey); got != want {
60 t.Errorf("V.InfoContext: context value unexpectedly missing: got %q, want %q", got, want)
61 }
62 }
63
View as plain text