master
go 68 lines 1.53 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package discovery
4
5 import (
6 "context"
7 "sort"
8 "testing"
9 "time"
10
11 "github.com/netdata/netdata/go/plugins/plugin/framework/confgroup"
12
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15 )
16
17 type discoverySim struct {
18 mgr *Manager
19 collectDelay time.Duration
20 expectedGroups []*confgroup.Group
21 }
22
23 func (sim discoverySim) run(t *testing.T) {
24 t.Helper()
25 require.NotNil(t, sim.mgr)
26
27 in, out := make(chan []*confgroup.Group), make(chan []*confgroup.Group)
28 go sim.collectGroups(t, in, out)
29
30 ctx, cancel := context.WithCancel(context.Background())
31 defer cancel()
32 go sim.mgr.Run(ctx, in)
33
34 actualGroups := <-out
35
36 sortGroups(sim.expectedGroups)
37 sortGroups(actualGroups)
38
39 assert.Equal(t, sim.expectedGroups, actualGroups)
40 }
41
42 func (sim discoverySim) collectGroups(t *testing.T, in, out chan []*confgroup.Group) {
43 time.Sleep(sim.collectDelay)
44
45 timeout := sim.mgr.sendEvery + time.Second*2
46 var groups []*confgroup.Group
47 loop:
48 for {
49 select {
50 case inGroups := <-in:
51 if groups = append(groups, inGroups...); len(groups) >= len(sim.expectedGroups) {
52 break loop
53 }
54 case <-time.After(timeout):
55 t.Logf("discovery %s timed out after %s, got %d groups, expected %d, some events are skipped",
56 sim.mgr.discoverers, timeout, len(groups), len(sim.expectedGroups))
57 break loop
58 }
59 }
60 out <- groups
61 }
62
63 func sortGroups(groups []*confgroup.Group) {
64 if len(groups) == 0 {
65 return
66 }
67 sort.Slice(groups, func(i, j int) bool { return groups[i].Source < groups[j].Source })
68 }