github.com/crowdsecurity/crowdsec@v1.6.1/pkg/apiserver/apic_metrics_test.go (about) 1 package apiserver 2 3 import ( 4 "context" 5 "fmt" 6 "net/url" 7 "testing" 8 "time" 9 10 "github.com/jarcoal/httpmock" 11 "github.com/stretchr/testify/assert" 12 "github.com/stretchr/testify/require" 13 14 "github.com/crowdsecurity/go-cs-lib/version" 15 16 "github.com/crowdsecurity/crowdsec/pkg/apiclient" 17 ) 18 19 func TestAPICSendMetrics(t *testing.T) { 20 tests := []struct { 21 name string 22 duration time.Duration 23 expectedCalls int 24 setUp func(*apic) 25 metricsInterval time.Duration 26 }{ 27 { 28 name: "basic", 29 duration: time.Millisecond * 120, 30 metricsInterval: time.Millisecond * 20, 31 expectedCalls: 5, 32 setUp: func(api *apic) {}, 33 }, 34 { 35 name: "with some metrics", 36 duration: time.Millisecond * 120, 37 metricsInterval: time.Millisecond * 20, 38 expectedCalls: 5, 39 setUp: func(api *apic) { 40 api.dbClient.Ent.Machine.Delete().ExecX(context.Background()) 41 api.dbClient.Ent.Machine.Create(). 42 SetMachineId("1234"). 43 SetPassword(testPassword.String()). 44 SetIpAddress("1.2.3.4"). 45 SetScenarios("crowdsecurity/test"). 46 SetLastPush(time.Time{}). 47 SetUpdatedAt(time.Time{}). 48 ExecX(context.Background()) 49 50 api.dbClient.Ent.Bouncer.Delete().ExecX(context.Background()) 51 api.dbClient.Ent.Bouncer.Create(). 52 SetIPAddress("1.2.3.6"). 53 SetName("someBouncer"). 54 SetAPIKey("foobar"). 55 SetRevoked(false). 56 SetLastPull(time.Time{}). 57 ExecX(context.Background()) 58 }, 59 }, 60 } 61 62 httpmock.RegisterResponder("POST", "http://api.crowdsec.net/api/metrics/", httpmock.NewBytesResponder(200, []byte{})) 63 httpmock.Activate() 64 65 defer httpmock.Deactivate() 66 67 for _, tc := range tests { 68 tc := tc 69 t.Run(tc.name, func(t *testing.T) { 70 url, err := url.ParseRequestURI("http://api.crowdsec.net/") 71 require.NoError(t, err) 72 73 apiClient, err := apiclient.NewDefaultClient( 74 url, 75 "/api", 76 fmt.Sprintf("crowdsec/%s", version.String()), 77 nil, 78 ) 79 require.NoError(t, err) 80 81 api := getAPIC(t) 82 api.pushInterval = time.Millisecond 83 api.pushIntervalFirst = time.Millisecond 84 api.apiClient = apiClient 85 api.metricsInterval = tc.metricsInterval 86 api.metricsIntervalFirst = tc.metricsInterval 87 tc.setUp(api) 88 89 stop := make(chan bool) 90 httpmock.ZeroCallCounters() 91 go api.SendMetrics(stop) 92 time.Sleep(tc.duration) 93 stop <- true 94 95 info := httpmock.GetCallCountInfo() 96 noResponderCalls := info["NO_RESPONDER"] 97 responderCalls := info["POST http://api.crowdsec.net/api/metrics/"] 98 assert.LessOrEqual(t, absDiff(tc.expectedCalls, responderCalls), 2) 99 assert.Zero(t, noResponderCalls) 100 }) 101 } 102 }