1
18
19 package attributes_test
20
21 import (
22 "fmt"
23 "testing"
24
25 "google.golang.org/grpc/attributes"
26 )
27
28 type stringVal struct {
29 s string
30 }
31
32 func (s stringVal) Equal(o any) bool {
33 os, ok := o.(stringVal)
34 return ok && s.s == os.s
35 }
36
37 type stringerVal struct {
38 s string
39 }
40
41 func (s stringerVal) String() string {
42 return s.s
43 }
44
45 func ExampleAttributes() {
46 type keyOne struct{}
47 type keyTwo struct{}
48 a := attributes.New(keyOne{}, 1).WithValue(keyTwo{}, stringVal{s: "two"})
49 fmt.Println("Key one:", a.Value(keyOne{}))
50 fmt.Println("Key two:", a.Value(keyTwo{}))
51
52
53
54 }
55
56 func ExampleAttributes_WithValue() {
57 type keyOne struct{}
58 type keyTwo struct{}
59 a := attributes.New(keyOne{}, 1)
60 a = a.WithValue(keyTwo{}, stringVal{s: "two"})
61 fmt.Println("Key one:", a.Value(keyOne{}))
62 fmt.Println("Key two:", a.Value(keyTwo{}))
63
64
65
66 }
67
68 func ExampleAttributes_String() {
69 type key struct{}
70 var typedNil *stringerVal
71 a1 := attributes.New(key{}, typedNil)
72 a2 := attributes.New(key{}, (*stringerVal)(nil))
73 a3 := attributes.New(key{}, (*stringVal)(nil))
74 a4 := attributes.New(key{}, nil)
75 a5 := attributes.New(key{}, 1)
76 a6 := attributes.New(key{}, stringerVal{s: "two"})
77 a7 := attributes.New(key{}, stringVal{s: "two"})
78 a8 := attributes.New(1, true)
79 fmt.Println("a1:", a1.String())
80 fmt.Println("a2:", a2.String())
81 fmt.Println("a3:", a3.String())
82 fmt.Println("a4:", a4.String())
83 fmt.Println("a5:", a5.String())
84 fmt.Println("a6:", a6.String())
85 fmt.Println("a7:", a7.String())
86 fmt.Println("a8:", a8.String())
87
88
89
90
91
92
93
94
95
96 }
97
98
99 func TestEqual(t *testing.T) {
100 type keyOne struct{}
101 type keyTwo struct{}
102 a1 := attributes.New(keyOne{}, 1).WithValue(keyTwo{}, stringVal{s: "two"})
103 a2 := attributes.New(keyOne{}, 1).WithValue(keyTwo{}, stringVal{s: "two"})
104 if !a1.Equal(a2) {
105 t.Fatalf("%+v.Equals(%+v) = false; want true", a1, a2)
106 }
107 if !a2.Equal(a1) {
108 t.Fatalf("%+v.Equals(%+v) = false; want true", a2, a1)
109 }
110 }
111
112
113 func TestNotEqual(t *testing.T) {
114 type keyOne struct{}
115 type keyTwo struct{}
116 a1 := attributes.New(keyOne{}, 1).WithValue(keyTwo{}, stringVal{s: "two"})
117 a2 := attributes.New(keyOne{}, 2).WithValue(keyTwo{}, stringVal{s: "two"})
118 a3 := attributes.New(keyOne{}, 1).WithValue(keyTwo{}, stringVal{s: "one"})
119 if a1.Equal(a2) {
120 t.Fatalf("%+v.Equals(%+v) = true; want false", a1, a2)
121 }
122 if a2.Equal(a1) {
123 t.Fatalf("%+v.Equals(%+v) = true; want false", a2, a1)
124 }
125 if a3.Equal(a1) {
126 t.Fatalf("%+v.Equals(%+v) = true; want false", a3, a1)
127 }
128 }
129
View as plain text