Debian Codegraph @

attribute/set_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package attribute_test
5
6 import (
7 "reflect"
8 "regexp"
9 "strings"
10 "testing"
11
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14
15 "go.opentelemetry.io/otel/attribute"
16 )
17
18 type testCase struct {
19 kvs []attribute.KeyValue
20
21 keyRe *regexp.Regexp
22
23 encoding string
24 fullEnc string
25 }
26
27 func expect(enc string, kvs ...attribute.KeyValue) testCase {
28 return testCase{
29 kvs: kvs,
30 encoding: enc,
31 }
32 }
33
34 func expectFiltered(enc, filter, fullEnc string, kvs ...attribute.KeyValue) testCase {
35 return testCase{
36 kvs: kvs,
37 keyRe: regexp.MustCompile(filter),
38 encoding: enc,
39 fullEnc: fullEnc,
40 }
41 }
42
43 func TestSetDedup(t *testing.T) {
44 cases := []testCase{
45 expect("A=B", attribute.String("A", "2"), attribute.String("A", "B")),
46 expect("A=B", attribute.String("A", "2"), attribute.Int("A", 1), attribute.String("A", "B")),
47 expect(
48 "A=B",
49 attribute.String("A", "B"),
50 attribute.String("A", "C"),
51 attribute.String("A", "D"),
52 attribute.String("A", "B"),
53 ),
54
55 expect("A=B,C=D", attribute.String("A", "1"), attribute.String("C", "D"), attribute.String("A", "B")),
56 expect("A=B,C=D", attribute.String("A", "2"), attribute.String("A", "B"), attribute.String("C", "D")),
57 expect(
58 "A=B,C=D",
59 attribute.Float64("C", 1.2),
60 attribute.String("A", "2"),
61 attribute.String("A", "B"),
62 attribute.String("C", "D"),
63 ),
64 expect(
65 "A=B,C=D",
66 attribute.String("C", "D"),
67 attribute.String("A", "B"),
68 attribute.String("A", "C"),
69 attribute.String("A", "D"),
70 attribute.String("A", "B"),
71 ),
72 expect(
73 "A=B,C=D",
74 attribute.String("A", "B"),
75 attribute.String("C", "D"),
76 attribute.String("A", "C"),
77 attribute.String("A", "D"),
78 attribute.String("A", "B"),
79 ),
80 expect(
81 "A=B,C=D",
82 attribute.String("A", "B"),
83 attribute.String("A", "C"),
84 attribute.String("A", "D"),
85 attribute.String("A", "B"),
86 attribute.String("C", "D"),
87 ),
88 }
89 enc := attribute.DefaultEncoder()
90
91 s2d := map[string][]attribute.Distinct{}
92 d2s := map[attribute.Distinct][]string{}
93
94 for _, tc := range cases {
95 cpy := make([]attribute.KeyValue, len(tc.kvs))
96 copy(cpy, tc.kvs)
97 sl := attribute.NewSet(cpy...)
98
99 // Ensure that the input was reordered but no elements went missing.
100 require.ElementsMatch(t, tc.kvs, cpy)
101
102 str := sl.Encoded(enc)
103 equ := sl.Equivalent()
104
105 s2d[str] = append(s2d[str], equ)
106 d2s[equ] = append(d2s[equ], str)
107
108 require.Equal(t, tc.encoding, str)
109 }
110
111 for s, d := range s2d {
112 // No other Distinct values are equal to this.
113 for s2, d2 := range s2d {
114 if s2 == s {
115 continue
116 }
117 for _, elt := range d {
118 for _, otherDistinct := range d2 {
119 require.NotEqual(t, otherDistinct, elt)
120 }
121 }
122 }
123 for _, strs := range d2s {
124 if strs[0] == s {
125 continue
126 }
127 for _, otherString := range strs {
128 require.NotEqual(t, otherString, s)
129 }
130 }
131 }
132
133 for d, s := range d2s {
134 // No other Distinct values are equal to this.
135 for d2, s2 := range d2s {
136 if d2 == d {
137 continue
138 }
139 for _, elt := range s {
140 for _, otherDistinct := range s2 {
141 require.NotEqual(t, otherDistinct, elt)
142 }
143 }
144 }
145 for _, distincts := range s2d {
146 if distincts[0] == d {
147 continue
148 }
149 for _, otherDistinct := range distincts {
150 require.NotEqual(t, otherDistinct, d)
151 }
152 }
153 }
154 }
155
156 func TestFiltering(t *testing.T) {
157 a := attribute.String("A", "a")
158 b := attribute.String("B", "b")
159 c := attribute.String("C", "c")
160
161 tests := []struct {
162 name string
163 in []attribute.KeyValue
164 filter attribute.Filter
165 kept, drop []attribute.KeyValue
166 }{
167 {
168 name: "A",
169 in: []attribute.KeyValue{a, b, c},
170 filter: func(kv attribute.KeyValue) bool { return kv.Key == "A" },
171 kept: []attribute.KeyValue{a},
172 drop: []attribute.KeyValue{b, c},
173 },
174 {
175 name: "B",
176 in: []attribute.KeyValue{a, b, c},
177 filter: func(kv attribute.KeyValue) bool { return kv.Key == "B" },
178 kept: []attribute.KeyValue{b},
179 drop: []attribute.KeyValue{a, c},
180 },
181 {
182 name: "C",
183 in: []attribute.KeyValue{a, b, c},
184 filter: func(kv attribute.KeyValue) bool { return kv.Key == "C" },
185 kept: []attribute.KeyValue{c},
186 drop: []attribute.KeyValue{a, b},
187 },
188 {
189 name: "A||B",
190 in: []attribute.KeyValue{a, b, c},
191 filter: func(kv attribute.KeyValue) bool {
192 return kv.Key == "A" || kv.Key == "B"
193 },
194 kept: []attribute.KeyValue{a, b},
195 drop: []attribute.KeyValue{c},
196 },
197 {
198 name: "B||C",
199 in: []attribute.KeyValue{a, b, c},
200 filter: func(kv attribute.KeyValue) bool {
201 return kv.Key == "B" || kv.Key == "C"
202 },
203 kept: []attribute.KeyValue{b, c},
204 drop: []attribute.KeyValue{a},
205 },
206 {
207 name: "A||C",
208 in: []attribute.KeyValue{a, b, c},
209 filter: func(kv attribute.KeyValue) bool {
210 return kv.Key == "A" || kv.Key == "C"
211 },
212 kept: []attribute.KeyValue{a, c},
213 drop: []attribute.KeyValue{b},
214 },
215 {
216 name: "None",
217 in: []attribute.KeyValue{a, b, c},
218 filter: func(attribute.KeyValue) bool { return false },
219 kept: nil,
220 drop: []attribute.KeyValue{a, b, c},
221 },
222 {
223 name: "All",
224 in: []attribute.KeyValue{a, b, c},
225 filter: func(attribute.KeyValue) bool { return true },
226 kept: []attribute.KeyValue{a, b, c},
227 drop: nil,
228 },
229 {
230 name: "Empty",
231 in: []attribute.KeyValue{},
232 filter: func(attribute.KeyValue) bool { return true },
233 kept: nil,
234 drop: nil,
235 },
236 }
237
238 for _, test := range tests {
239 t.Run(test.name, func(t *testing.T) {
240 t.Run("NewSetWithFiltered", func(t *testing.T) {
241 fltr, drop := attribute.NewSetWithFiltered(test.in, test.filter)
242 assert.Equal(t, test.kept, fltr.ToSlice(), "filtered")
243 assert.ElementsMatch(t, test.drop, drop, "dropped")
244 })
245
246 t.Run("Set.Filter", func(t *testing.T) {
247 s := attribute.NewSet(test.in...)
248 fltr, drop := s.Filter(test.filter)
249 assert.Equal(t, test.kept, fltr.ToSlice(), "filtered")
250 assert.ElementsMatch(t, test.drop, drop, "dropped")
251 })
252 })
253 }
254 }
255
256 func TestUniqueness(t *testing.T) {
257 short := []attribute.KeyValue{
258 attribute.String("A", "0"),
259 attribute.String("B", "2"),
260 attribute.String("A", "1"),
261 }
262 long := []attribute.KeyValue{
263 attribute.String("B", "2"),
264 attribute.String("C", "5"),
265 attribute.String("B", "2"),
266 attribute.String("C", "1"),
267 attribute.String("A", "4"),
268 attribute.String("C", "3"),
269 attribute.String("A", "1"),
270 }
271 cases := []testCase{
272 expectFiltered("A=1", "^A$", "B=2", short...),
273 expectFiltered("B=2", "^B$", "A=1", short...),
274 expectFiltered("A=1,B=2", "^A|B$", "", short...),
275 expectFiltered("", "^C", "A=1,B=2", short...),
276
277 expectFiltered("A=1,C=3", "A|C", "B=2", long...),
278 expectFiltered("B=2,C=3", "C|B", "A=1", long...),
279 expectFiltered("C=3", "C", "A=1,B=2", long...),
280 expectFiltered("", "D", "A=1,B=2,C=3", long...),
281 }
282 enc := attribute.DefaultEncoder()
283
284 for _, tc := range cases {
285 cpy := make([]attribute.KeyValue, len(tc.kvs))
286 copy(cpy, tc.kvs)
287 distinct, uniq := attribute.NewSetWithFiltered(cpy, func(attr attribute.KeyValue) bool {
288 return tc.keyRe.MatchString(string(attr.Key))
289 })
290
291 full := attribute.NewSet(uniq...)
292
293 require.Equal(t, tc.encoding, distinct.Encoded(enc))
294 require.Equal(t, tc.fullEnc, full.Encoded(enc))
295 }
296 }
297
298 func TestLookup(t *testing.T) {
299 set := attribute.NewSet(attribute.Int("C", 3), attribute.Int("A", 1), attribute.Int("B", 2))
300
301 value, has := set.Value("C")
302 require.True(t, has)
303 require.Equal(t, int64(3), value.AsInt64())
304
305 value, has = set.Value("B")
306 require.True(t, has)
307 require.Equal(t, int64(2), value.AsInt64())
308
309 value, has = set.Value("A")
310 require.True(t, has)
311 require.Equal(t, int64(1), value.AsInt64())
312
313 _, has = set.Value("D")
314 require.False(t, has)
315 }
316
317 func TestZeroSetExportedMethodsNoPanic(t *testing.T) {
318 rType := reflect.TypeFor[*attribute.Set]()
319 rVal := reflect.ValueOf(&attribute.Set{})
320 for n := 0; n < rType.NumMethod(); n++ {
321 mType := rType.Method(n)
322 if !mType.IsExported() {
323 t.Logf("ignoring unexported %s", mType.Name)
324 continue
325 }
326 t.Run(mType.Name, func(t *testing.T) {
327 m := rVal.MethodByName(mType.Name)
328 if !m.IsValid() {
329 t.Errorf("unknown method: %s", mType.Name)
330 }
331 assert.NotPanics(t, func() { _ = m.Call(args(mType)) })
332 })
333 }
334 }
335
336 func args(m reflect.Method) []reflect.Value {
337 numIn := m.Type.NumIn() - 1 // Do not include the receiver arg.
338 if numIn <= 0 {
339 return nil
340 }
341 if m.Type.IsVariadic() {
342 numIn--
343 }
344 out := make([]reflect.Value, numIn)
345 for i := range out {
346 aType := m.Type.In(i + 1) // Skip receiver arg.
347 out[i] = reflect.New(aType).Elem()
348 }
349 return out
350 }
351
352 func TestMarshalJSON(t *testing.T) {
353 for _, tc := range []struct {
354 desc string
355 kvs []attribute.KeyValue
356 wantJSON string
357 }{
358 {
359 desc: "empty",
360 kvs: []attribute.KeyValue{},
361 wantJSON: `[]`,
362 },
363 {
364 desc: "single string attribute",
365 kvs: []attribute.KeyValue{attribute.String("A", "a")},
366 wantJSON: `[{"Key":"A","Value":{"Type":"STRING","Value":"a"}}]`,
367 },
368 {
369 desc: "many mixed attributes",
370 kvs: []attribute.KeyValue{
371 attribute.Bool("A", true),
372 attribute.BoolSlice("B", []bool{true, false}),
373 attribute.Int("C", 1),
374 attribute.IntSlice("D", []int{2, 3}),
375 attribute.Int64("E", 22),
376 attribute.Int64Slice("F", []int64{33, 44}),
377 attribute.Float64("G", 1.1),
378 attribute.Float64Slice("H", []float64{2.2, 3.3}),
379 attribute.String("I", "Z"),
380 attribute.StringSlice("J", []string{"X", "Y"}),
381 attribute.Stringer("K", &simpleStringer{val: "foo"}),
382 },
383 wantJSON: `[
384 {
385 "Key": "A",
386 "Value": {
387 "Type": "BOOL",
388 "Value": true
389 }
390 },
391 {
392 "Key": "B",
393 "Value": {
394 "Type": "BOOLSLICE",
395 "Value": [true, false]
396 }
397 },
398 {
399 "Key": "C",
400 "Value": {
401 "Type": "INT64",
402 "Value": 1
403 }
404 },
405 {
406 "Key": "D",
407 "Value": {
408 "Type": "INT64SLICE",
409 "Value": [2, 3]
410 }
411 },
412 {
413 "Key": "E",
414 "Value": {
415 "Type": "INT64",
416 "Value": 22
417 }
418 },
419 {
420 "Key": "F",
421 "Value": {
422 "Type": "INT64SLICE",
423 "Value": [33, 44]
424 }
425 },
426 {
427 "Key": "G",
428 "Value": {
429 "Type": "FLOAT64",
430 "Value": 1.1
431 }
432 },
433 {
434 "Key": "H",
435 "Value": {
436 "Type": "FLOAT64SLICE",
437 "Value": [2.2, 3.3]
438 }
439 },
440 {
441 "Key": "I",
442 "Value": {
443 "Type": "STRING",
444 "Value": "Z"
445 }
446 },
447 {
448 "Key": "J",
449 "Value": {
450 "Type": "STRINGSLICE",
451 "Value": ["X", "Y"]
452 }
453 },
454 {
455 "Key": "K",
456 "Value": {
457 "Type": "STRING",
458 "Value": "foo"
459 }
460 }
461 ]`,
462 },
463 } {
464 t.Run(tc.desc, func(t *testing.T) {
465 set := attribute.NewSet(tc.kvs...)
466 by, err := set.MarshalJSON()
467 require.NoError(t, err)
468 assert.JSONEq(t, tc.wantJSON, string(by))
469 })
470 }
471 }
472
473 func TestSetEqualsEmpty(t *testing.T) {
474 e := attribute.EmptySet()
475 empty := *e
476
477 alt := attribute.NewSet(attribute.String("A", "B"))
478 *e = alt
479
480 var s attribute.Set
481 assert.Truef(t, s.Equals(&empty), "expected %v to equal empty set %v", s, attribute.EmptySet())
482 }
483
484 type simpleStringer struct {
485 val string
486 }
487
488 func (s *simpleStringer) String() string { return s.val }
489
490 func BenchmarkFiltering(b *testing.B) {
491 var kvs [26]attribute.KeyValue
492 buf := [1]byte{'A' - 1}
493 for i := range kvs {
494 buf[0]++ // A, B, C ... Z
495 kvs[i] = attribute.String(string(buf[:]), "")
496 }
497
498 var result struct {
499 set attribute.Set
500 dropped []attribute.KeyValue
501 }
502
503 benchFn := func(fltr attribute.Filter) func(*testing.B) {
504 return func(b *testing.B) {
505 b.Helper()
506 b.Run("Set.Filter", func(b *testing.B) {
507 s := attribute.NewSet(kvs[:]...)
508 b.ResetTimer()
509 b.ReportAllocs()
510 for n := 0; n < b.N; n++ {
511 result.set, result.dropped = s.Filter(fltr)
512 }
513 })
514
515 b.Run("NewSetWithFiltered", func(b *testing.B) {
516 attrs := kvs[:]
517 b.ResetTimer()
518 b.ReportAllocs()
519 for n := 0; n < b.N; n++ {
520 result.set, result.dropped = attribute.NewSetWithFiltered(attrs, fltr)
521 }
522 })
523 }
524 }
525
526 b.Run("NoFilter", benchFn(nil))
527 b.Run("NoFiltered", benchFn(func(attribute.KeyValue) bool { return true }))
528 b.Run("Filtered", benchFn(func(kv attribute.KeyValue) bool { return kv.Key == "A" }))
529 b.Run("AllDropped", benchFn(func(attribute.KeyValue) bool { return false }))
530 }
531
532 func BenchmarkNewSet(b *testing.B) {
533 attrs := []attribute.KeyValue{
534 attribute.String("B1", "2"),
535 attribute.String("C2", "5"),
536 attribute.String("B3", "2"),
537 attribute.String("C4", "1"),
538 attribute.String("A5", "4"),
539 attribute.String("C6", "3"),
540 attribute.String("A7", "1"),
541 }
542 b.ReportAllocs()
543 b.ResetTimer()
544 for b.Loop() {
545 attribute.NewSet(attrs...)
546 }
547 }
548
549 // generateStringAttrsWithSize creates 5 string attributes with specified key and value lengths.
550 func generateStringAttrsWithSize(keyLen, valueLen int) []attribute.KeyValue {
551 // Generate base strings of specified lengths
552 var keyBase strings.Builder
553
554 // Build key base string
555 for i := range keyLen {
556 _, _ = keyBase.WriteString(string(rune('a' + i%26)))
557 }
558
559 // Build value base string
560 var sb strings.Builder
561 for i := range valueLen {
562 _ = sb.WriteByte(byte('0' + i%10))
563 }
564 valueBase := sb.String()
565
566 // Create 5 attributes with different suffixes to ensure uniqueness
567 attrs := []attribute.KeyValue{
568 attribute.String(keyBase.String()+"1", valueBase+"x"),
569 attribute.String(keyBase.String()+"2", valueBase+"y"),
570 attribute.String(keyBase.String()+"3", valueBase+"z"),
571 attribute.String(keyBase.String()+"4", valueBase+"w"),
572 attribute.String(keyBase.String()+"5", valueBase+"v"),
573 }
574 return attrs
575 }
576
577 func BenchmarkNewSetStringAttrs(b *testing.B) {
578 testCases := []struct {
579 name string
580 keyLen int
581 valueLen int
582 }{
583 {"SmallStrings", 2, 1}, // B1="2"
584 {"MediumStrings", 10, 10}, // realistic service names, etc.
585 {"LargeStrings", 25, 25}, // longer service names, URLs, etc.
586 {"VeryLargeStrings", 50, 100}, // very long values like URLs, descriptions
587 {"HugeStrings", 100, 500}, // extremely large like full URLs, JSON, etc.
588 }
589
590 for _, tc := range testCases {
591 b.Run(tc.name, func(b *testing.B) {
592 attrs := generateStringAttrsWithSize(tc.keyLen, tc.valueLen)
593 b.ReportAllocs()
594 b.ResetTimer()
595 for b.Loop() {
596 attribute.NewSet(attrs...)
597 }
598 })
599 }
600 }