-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2537c4f
commit b65717c
Showing
1 changed file
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
} | ||
} |