github.com/netdata/go.d.plugin@v0.58.1/agent/discovery/sim_test.go (about)

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