From e8e2fe29efdfb2096abcaa81a6a6d4a5c24f8b9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Wei=C3=9Fe?= Date: Tue, 16 Apr 2024 09:39:35 +0200 Subject: [PATCH] cli: add unit tests to telemetry --- cli/telemetry/telemetry_test.go | 85 +++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 cli/telemetry/telemetry_test.go diff --git a/cli/telemetry/telemetry_test.go b/cli/telemetry/telemetry_test.go new file mode 100644 index 0000000000..cc98ca6659 --- /dev/null +++ b/cli/telemetry/telemetry_test.go @@ -0,0 +1,85 @@ +package telemetry + +import ( + "context" + "fmt" + "net/http" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" +) + +type roundTripFunc func(req *http.Request) *http.Response + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req), nil +} + +func newTestClient(fn roundTripFunc) *http.Client { + return &http.Client{ + Transport: fn, + } +} + +func TestSendTelemetry(t *testing.T) { + rootTestCmd := &cobra.Command{Version: "0.0.0-dev"} + goodTestCmd := &cobra.Command{} + rootTestCmd.AddCommand(goodTestCmd) + + badTestCmd := &cobra.Command{} + + testCases := map[string]struct { + cmd *cobra.Command + cmdErr error + serverResponseCode int + wantError bool + }{ + "success no cmdError": { + cmd: goodTestCmd, + cmdErr: nil, + serverResponseCode: http.StatusOK, + wantError: false, + }, + "success with cmdError": { + cmd: goodTestCmd, + cmdErr: fmt.Errorf("test error"), + serverResponseCode: http.StatusOK, + wantError: false, + }, + "bad command": { + cmd: badTestCmd, + cmdErr: nil, + serverResponseCode: http.StatusOK, + wantError: true, + }, + "bad http response": { + cmd: goodTestCmd, + cmdErr: nil, + serverResponseCode: http.StatusInternalServerError, + wantError: true, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + assert := assert.New(t) + + client := &Client{ + httpClient: newTestClient(func(_ *http.Request) *http.Response { + return &http.Response{ + StatusCode: tc.serverResponseCode, + } + }), + } + + err := client.SendTelemetry(context.Background(), tc.cmd, tc.cmdErr) + + if tc.wantError { + assert.Error(err) + return + } + assert.NoError(err) + }) + } +}