Debian Codegraph @

debian/go/src/golang.org/x/telemetry/counter/countertest/countertest_test.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build go1.21
6
7 package countertest
8
9 import (
10 "fmt"
11 "slices"
12 "strings"
13 "sync"
14 "testing"
15
16 "golang.org/x/telemetry/counter"
17 "golang.org/x/telemetry/internal/telemetry"
18 "golang.org/x/telemetry/internal/testenv"
19 )
20
21 func TestReadCounter(t *testing.T) {
22 testenv.SkipIfUnsupportedPlatform(t)
23 c := counter.New("foobar")
24
25 got, err := ReadCounter(c)
26 if err != nil {
27 t.Errorf("ReadCounter = (%d, %v), want (0,nil)", got, err)
28 }
29 if got != 0 {
30 t.Fatalf("ReadCounter = %d, want 0", got)
31 }
32
33 var wg sync.WaitGroup
34 wg.Add(100)
35 for i := 0; i < 100; i++ {
36 go func() {
37 c.Inc()
38 wg.Done()
39 }()
40 }
41 wg.Wait()
42 if got, err := ReadCounter(c); err != nil || got != 100 {
43 t.Errorf("ReadCounter = (%v, %v), want (%v, nil)", got, err, 100)
44 }
45 }
46
47 func TestReadStackCounter(t *testing.T) {
48 testenv.SkipIfUnsupportedPlatform(t)
49 c := counter.NewStack("foobar", 8)
50
51 if got, err := ReadStackCounter(c); err != nil || len(got) != 0 {
52 t.Errorf("ReadStackCounter = (%q, %v), want (%v, nil)", got, err, 0)
53 }
54
55 var wg sync.WaitGroup
56 wg.Add(100)
57 for i := 0; i < 100; i++ {
58 go func() {
59 c.Inc() // one stack!
60 wg.Done()
61 }()
62 }
63 wg.Wait()
64
65 got, err := ReadStackCounter(c)
66 if err != nil || len(got) != 1 {
67 t.Fatalf("ReadStackCounter = (%v, %v), want to read one entry", stringify(got), err)
68 }
69 for k, v := range got {
70 if !strings.Contains(k, t.Name()) || v != 100 {
71 t.Fatalf("ReadStackCounter = %v, want a stack counter with value 100", got)
72 }
73 }
74 }
75
76 func TestSupport(t *testing.T) {
77 if SupportedPlatform == telemetry.DisabledOnPlatform {
78 t.Errorf("supported mismatch: us %v, telemetry.internal.Disabled %v",
79 SupportedPlatform, telemetry.DisabledOnPlatform)
80 }
81 }
82
83 func stringify(m map[string]uint64) string {
84 kv := make([]string, 0, len(m))
85 for k, v := range m {
86 kv = append(kv, fmt.Sprintf("%q:%v", k, v))
87 }
88 slices.Sort(kv)
89 return "{" + strings.Join(kv, " ") + "}"
90 }