(t *testing.T)
| 12 | ) |
| 13 | |
| 14 | func TestRecordTelemetry(t *testing.T) { |
| 15 | t.Run("records command path and flags", func(t *testing.T) { |
| 16 | recorder := &telemetry.EventRecorderSpy{} |
| 17 | cmd := &cobra.Command{ |
| 18 | Use: "list", |
| 19 | RunE: func(cmd *cobra.Command, args []string) error { return nil }, |
| 20 | } |
| 21 | cmd.Flags().Bool("web", false, "") |
| 22 | cmd.Flags().String("repo", "", "") |
| 23 | |
| 24 | parent := &cobra.Command{Use: "pr"} |
| 25 | root := &cobra.Command{Use: "gh"} |
| 26 | root.AddCommand(parent) |
| 27 | parent.AddCommand(cmd) |
| 28 | |
| 29 | cmdutil.RecordTelemetry(cmd, recorder) |
| 30 | |
| 31 | require.NoError(t, cmd.Flags().Set("web", "true")) |
| 32 | require.NoError(t, cmd.Flags().Set("repo", "cli/cli")) |
| 33 | require.NoError(t, cmd.RunE(cmd, nil)) |
| 34 | |
| 35 | require.Len(t, recorder.Events, 1) |
| 36 | event := recorder.Events[0] |
| 37 | assert.Equal(t, "command_invocation", event.Type) |
| 38 | assert.Equal(t, "gh pr list", event.Dimensions["command"]) |
| 39 | assert.Equal(t, "repo,web", event.Dimensions["flags"]) |
| 40 | }) |
| 41 | |
| 42 | t.Run("is a no-op when original RunE is nil", func(t *testing.T) { |
| 43 | recorder := &telemetry.EventRecorderSpy{} |
| 44 | cmd := &cobra.Command{Use: "test"} |
| 45 | |
| 46 | cmdutil.RecordTelemetry(cmd, recorder) |
| 47 | |
| 48 | assert.Nil(t, cmd.RunE, "RunE should remain nil when it was nil before") |
| 49 | assert.Empty(t, recorder.Events, "no telemetry should be recorded") |
| 50 | }) |
| 51 | |
| 52 | t.Run("propagates error from original RunE", func(t *testing.T) { |
| 53 | recorder := &telemetry.EventRecorderSpy{} |
| 54 | expectedErr := fmt.Errorf("something went wrong") |
| 55 | cmd := &cobra.Command{ |
| 56 | Use: "fail", |
| 57 | RunE: func(cmd *cobra.Command, args []string) error { return expectedErr }, |
| 58 | } |
| 59 | |
| 60 | cmdutil.RecordTelemetry(cmd, recorder) |
| 61 | |
| 62 | err := cmd.RunE(cmd, nil) |
| 63 | assert.ErrorIs(t, err, expectedErr) |
| 64 | // Telemetry is still recorded even on error |
| 65 | require.Len(t, recorder.Events, 1) |
| 66 | assert.Equal(t, "command_invocation", recorder.Events[0].Type) |
| 67 | }) |
| 68 | |
| 69 | t.Run("flags are sorted alphabetically", func(t *testing.T) { |
| 70 | recorder := &telemetry.EventRecorderSpy{} |
| 71 | cmd := &cobra.Command{ |
nothing calls this directly
no test coverage detected