MCPcopy
hub / github.com/cli/cli / TestRecordTelemetry

Function TestRecordTelemetry

pkg/cmdutil/telemetry_test.go:14–117  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

12)
13
14func 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{

Callers

nothing calls this directly

Calls 8

RecordTelemetryFunction · 0.92
DisableTelemetryFunction · 0.92
EqualMethod · 0.80
RunMethod · 0.65
SetMethod · 0.65
LenMethod · 0.65
ErrorfMethod · 0.65
StringMethod · 0.45

Tested by

no test coverage detected