Skip to content

Commit

Permalink
cli: add unit tests to telemetry
Browse files Browse the repository at this point in the history
  • Loading branch information
davidweisse committed Apr 16, 2024
1 parent 2537c4f commit b65717c
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions cli/telemetry/telemetry_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
}

0 comments on commit b65717c

Please sign in to comment.