Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/usagestats/reporter_test.go
4094 views
1
package usagestats
2
3
import (
4
"context"
5
"net/http"
6
"net/http/httptest"
7
"os"
8
"sync"
9
"testing"
10
"time"
11
12
"github.com/go-kit/log"
13
jsoniter "github.com/json-iterator/go"
14
"github.com/stretchr/testify/require"
15
)
16
17
func Test_ReportLoop(t *testing.T) {
18
// stub
19
reportCheckInterval = 100 * time.Millisecond
20
reportInterval = time.Second
21
22
var (
23
mut sync.Mutex
24
totalReports int
25
agentIDs []string
26
)
27
28
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
29
mut.Lock()
30
defer mut.Unlock()
31
32
totalReports++
33
34
var received Report
35
require.NoError(t, jsoniter.NewDecoder(r.Body).Decode(&received))
36
agentIDs = append(agentIDs, received.UsageStatsID)
37
38
rw.WriteHeader(http.StatusOK)
39
}))
40
usageStatsURL = server.URL
41
42
r, err := NewReporter(log.NewLogfmtLogger(os.Stdout))
43
require.NoError(t, err)
44
45
ctx, cancel := context.WithCancel(context.Background())
46
47
go func() {
48
<-time.After(6 * time.Second)
49
cancel()
50
}()
51
metricsFunc := func() map[string]interface{} {
52
return map[string]interface{}{}
53
}
54
require.Equal(t, context.Canceled, r.Start(ctx, metricsFunc))
55
56
mut.Lock()
57
defer mut.Unlock()
58
59
require.GreaterOrEqual(t, totalReports, 5)
60
first := agentIDs[0]
61
for _, uid := range agentIDs {
62
require.Equal(t, first, uid)
63
}
64
require.Equal(t, first, r.agentSeed.UID)
65
}
66
67
func Test_NextReport(t *testing.T) {
68
fixtures := map[string]struct {
69
interval time.Duration
70
createdAt time.Time
71
now time.Time
72
73
next time.Time
74
}{
75
"createdAt aligned with interval and now": {
76
interval: 1 * time.Hour,
77
createdAt: time.Unix(0, time.Hour.Nanoseconds()),
78
now: time.Unix(0, 2*time.Hour.Nanoseconds()),
79
next: time.Unix(0, 2*time.Hour.Nanoseconds()),
80
},
81
"createdAt aligned with interval": {
82
interval: 1 * time.Hour,
83
createdAt: time.Unix(0, time.Hour.Nanoseconds()),
84
now: time.Unix(0, 2*time.Hour.Nanoseconds()+1),
85
next: time.Unix(0, 3*time.Hour.Nanoseconds()),
86
},
87
"createdAt not aligned": {
88
interval: 1 * time.Hour,
89
createdAt: time.Unix(0, time.Hour.Nanoseconds()+18*time.Minute.Nanoseconds()+20*time.Millisecond.Nanoseconds()),
90
now: time.Unix(0, 2*time.Hour.Nanoseconds()+1),
91
next: time.Unix(0, 2*time.Hour.Nanoseconds()+18*time.Minute.Nanoseconds()+20*time.Millisecond.Nanoseconds()),
92
},
93
}
94
for name, f := range fixtures {
95
t.Run(name, func(t *testing.T) {
96
next := nextReport(f.interval, f.createdAt, f.now)
97
require.Equal(t, f.next, next)
98
})
99
}
100
}
101
102