on main help sign in
fix: use typed context keys in tests to satisfy staticcheck
6e5bbefwanghuaiyu@qiniu.com
internal/agent/tools/context_test.go+23−9
@@ -5,6 +5,20 @@ import (
5 "testing"
5 "testing"
6)
6)
7
7
8+// Test-specific context key types to avoid collisions
9+type (
10+ testStringKey string
11+ testBoolKey string
12+ testIntKey string
13+)
14+
15+const (
16+ testKey testStringKey = "testKey"
17+ missingKey testStringKey = "missingKey"
18+ boolTestKey testBoolKey = "boolKey"
19+ intTestKey testIntKey = "intKey"
20+)
21+
8func TestGetContextValue(t *testing.T) {
22func TestGetContextValue(t *testing.T) {
9 tests := []struct {
23 tests := []struct {
10 name string
24 name string
@@ -16,9 +30,9 @@ func TestGetContextValue(t *testing.T) {
16 {
30 {
17 name: "returns string value",
31 name: "returns string value",
18 setup: func(ctx context.Context) context.Context {
32 setup: func(ctx context.Context) context.Context {
19− return context.WithValue(ctx, "testKey", "testValue")
33+ return context.WithValue(ctx, testKey, "testValue")
20 },
34 },
21− key: "testKey",
35+ key: testKey,
22 defaultValue: "",
36 defaultValue: "",
23 want: "testValue",
37 want: "testValue",
24 },
38 },
@@ -27,34 +41,34 @@ func TestGetContextValue(t *testing.T) {
27 setup: func(ctx context.Context) context.Context {
41 setup: func(ctx context.Context) context.Context {
28 return ctx
42 return ctx
29 },
43 },
30− key: "missingKey",
44+ key: missingKey,
31 defaultValue: "default",
45 defaultValue: "default",
32 want: "default",
46 want: "default",
33 },
47 },
34 {
48 {
35 name: "returns default when type mismatch",
49 name: "returns default when type mismatch",
36 setup: func(ctx context.Context) context.Context {
50 setup: func(ctx context.Context) context.Context {
37− return context.WithValue(ctx, "testKey", 123) // int, not string
51+ return context.WithValue(ctx, testKey, 123) // int, not string
38 },
52 },
39− key: "testKey",
53+ key: testKey,
40 defaultValue: "default",
54 defaultValue: "default",
41 want: "default",
55 want: "default",
42 },
56 },
43 {
57 {
44 name: "returns bool value",
58 name: "returns bool value",
45 setup: func(ctx context.Context) context.Context {
59 setup: func(ctx context.Context) context.Context {
46− return context.WithValue(ctx, "boolKey", true)
60+ return context.WithValue(ctx, boolTestKey, true)
47 },
61 },
48− key: "boolKey",
62+ key: boolTestKey,
49 defaultValue: false,
63 defaultValue: false,
50 want: true,
64 want: true,
51 },
65 },
52 {
66 {
53 name: "returns int value",
67 name: "returns int value",
54 setup: func(ctx context.Context) context.Context {
68 setup: func(ctx context.Context) context.Context {
55− return context.WithValue(ctx, "intKey", 42)
69+ return context.WithValue(ctx, intTestKey, 42)
56 },
70 },
57− key: "intKey",
71+ key: intTestKey,
58 defaultValue: 0,
72 defaultValue: 0,
59 want: 42,
73 want: 42,
60 },
74 },