File: switch_test.go

package info (click to toggle)
gh 2.46.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,548 kB
  • sloc: sh: 227; makefile: 117
file content (439 lines) | stat: -rw-r--r-- 12,886 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package authswitch

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"testing"

	"github.com/cli/cli/v2/internal/config"
	"github.com/cli/cli/v2/internal/keyring"
	"github.com/cli/cli/v2/internal/prompter"
	"github.com/cli/cli/v2/pkg/cmdutil"
	"github.com/cli/cli/v2/pkg/iostreams"
	"github.com/google/shlex"
	"github.com/stretchr/testify/require"
)

func TestNewCmdSwitch(t *testing.T) {
	tests := []struct {
		name           string
		input          string
		expectedOpts   SwitchOptions
		expectedErrMsg string
	}{
		{
			name:         "no flags",
			input:        "",
			expectedOpts: SwitchOptions{},
		},
		{
			name:  "hostname flag",
			input: "--hostname github.com",
			expectedOpts: SwitchOptions{
				Hostname: "github.com",
			},
		},
		{
			name:  "user flag",
			input: "--user monalisa",
			expectedOpts: SwitchOptions{
				Username: "monalisa",
			},
		},
		{
			name:           "positional args is an error",
			input:          "some-positional-arg",
			expectedErrMsg: "accepts 0 arg(s), received 1",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			f := &cmdutil.Factory{}
			argv, err := shlex.Split(tt.input)
			require.NoError(t, err)

			var gotOpts *SwitchOptions
			cmd := NewCmdSwitch(f, func(opts *SwitchOptions) error {
				gotOpts = opts
				return nil
			})
			// Override the help flag as happens in production to allow -h flag
			// to be used for hostname.
			cmd.Flags().BoolP("help", "x", false, "")

			cmd.SetArgs(argv)
			cmd.SetIn(&bytes.Buffer{})
			cmd.SetOut(&bytes.Buffer{})
			cmd.SetErr(&bytes.Buffer{})

			_, err = cmd.ExecuteC()
			if tt.expectedErrMsg != "" {
				require.ErrorContains(t, err, tt.expectedErrMsg)
				return
			}

			require.NoError(t, err)
			require.Equal(t, &tt.expectedOpts, gotOpts)
		})
	}

}

func TestSwitchRun(t *testing.T) {
	type user struct {
		name  string
		token string
	}

	type hostUsers struct {
		host  string
		users []user
	}

	type successfulExpectation struct {
		switchedHost string
		activeUser   string
		activeToken  string
		hostsCfg     string
		stderr       string
	}

	type failedExpectation struct {
		err    error
		stderr string
	}

	userWithMissingToken := "user-that-is-broken-by-the-test"

	tests := []struct {
		name     string
		opts     SwitchOptions
		cfgHosts []hostUsers
		env      map[string]string

		expectedSuccess successfulExpectation
		expectedFailure failedExpectation

		prompterStubs func(*prompter.PrompterMock)
	}{
		{
			name: "given one host with two users, switches to the other user",
			opts: SwitchOptions{},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
			},
			expectedSuccess: successfulExpectation{
				switchedHost: "github.com",
				activeUser:   "inactive-user",
				activeToken:  "inactive-user-token",
				hostsCfg:     "github.com:\n    git_protocol: ssh\n    users:\n        inactive-user:\n        active-user:\n    user: inactive-user\n",
				stderr:       "✓ Switched active account for github.com to inactive-user",
			},
		},
		{
			name: "given one host, with three users, switches to the specified user",
			opts: SwitchOptions{
				Username: "inactive-user-2",
			},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user-1", "inactive-user-1-token"},
					{"inactive-user-2", "inactive-user-2-token"},
					{"active-user", "active-user-token"},
				}},
			},
			expectedSuccess: successfulExpectation{
				switchedHost: "github.com",
				activeUser:   "inactive-user-2",
				activeToken:  "inactive-user-2-token",
				hostsCfg:     "github.com:\n    git_protocol: ssh\n    users:\n        inactive-user-1:\n        inactive-user-2:\n        active-user:\n    user: inactive-user-2\n",
				stderr:       "✓ Switched active account for github.com to inactive-user-2",
			},
		},
		{
			name: "given multiple hosts, with multiple users, switches to the specific user on the host",
			opts: SwitchOptions{
				Hostname: "ghe.io",
				Username: "inactive-user",
			},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
				{"ghe.io", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
			},
			expectedSuccess: successfulExpectation{
				switchedHost: "ghe.io",
				activeUser:   "inactive-user",
				activeToken:  "inactive-user-token",
				hostsCfg:     "github.com:\n    git_protocol: ssh\n    users:\n        inactive-user:\n        active-user:\n    user: active-user\nghe.io:\n    git_protocol: ssh\n    users:\n        inactive-user:\n        active-user:\n    user: inactive-user\n",
				stderr:       "✓ Switched active account for ghe.io to inactive-user",
			},
		},
		{
			name:     "given we're not logged into any hosts, provide an informative error",
			opts:     SwitchOptions{},
			cfgHosts: []hostUsers{},
			expectedFailure: failedExpectation{
				err: errors.New("not logged in to any hosts"),
			},
		},
		{
			name: "given we can't disambiguate users across hosts",
			opts: SwitchOptions{
				Username: "inactive-user",
			},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
				{"ghe.io", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
			},
			expectedFailure: failedExpectation{
				err: errors.New("unable to determine which account to switch to, please specify `--hostname` and `--user`"),
			},
		},
		{
			name: "given we can't disambiguate user on a single host",
			opts: SwitchOptions{
				Hostname: "github.com",
			},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user-1", "inactive-user-1-token"},
					{"inactive-user-2", "inactive-user-2-token"},
					{"active-user", "active-user-token"},
				}},
			},
			expectedFailure: failedExpectation{
				err: errors.New("unable to determine which account to switch to, please specify `--hostname` and `--user`"),
			},
		},
		{
			name: "given the auth token isn't writeable (e.g. a token env var is set)",
			opts: SwitchOptions{},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
			},
			env: map[string]string{"GH_TOKEN": "unimportant-test-value"},
			expectedFailure: failedExpectation{
				err:    cmdutil.SilentError,
				stderr: "The value of the GH_TOKEN environment variable is being used for authentication.",
			},
		},
		{
			name: "specified hostname doesn't exist",
			opts: SwitchOptions{
				Hostname: "ghe.io",
			},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
			},
			expectedFailure: failedExpectation{
				err: errors.New("not logged in to ghe.io"),
			},
		},
		{
			name: "specified user doesn't exist on host",
			opts: SwitchOptions{
				Hostname: "github.com",
				Username: "non-existent-user",
			},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
			},
			expectedFailure: failedExpectation{
				err: errors.New("not logged in to github.com account non-existent-user"),
			},
		},
		{
			name: "specified user doesn't exist on any host",
			opts: SwitchOptions{
				Username: "non-existent-user",
			},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"active-user", "active-user-token"},
				}},
				{"ghe.io", []user{
					{"active-user", "active-user-token"},
				}},
			},
			expectedFailure: failedExpectation{
				err: errors.New("no accounts matched that criteria"),
			},
		},
		{
			name: "when options need to be disambiguated, the user is prompted with matrix of options including active users (if possible)",
			opts: SwitchOptions{},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
				{"ghe.io", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
			},
			prompterStubs: func(pm *prompter.PrompterMock) {
				pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
					require.Equal(t, "What account do you want to switch to?", prompt)
					require.Equal(t, []string{
						"inactive-user (github.com)",
						"active-user (github.com) - active",
						"inactive-user (ghe.io)",
						"active-user (ghe.io) - active",
					}, opts)

					return prompter.IndexFor(opts, "inactive-user (ghe.io)")
				}
			},
			expectedSuccess: successfulExpectation{
				switchedHost: "ghe.io",
				activeUser:   "inactive-user",
				activeToken:  "inactive-user-token",
				hostsCfg:     "github.com:\n    git_protocol: ssh\n    users:\n        inactive-user:\n        active-user:\n    user: active-user\nghe.io:\n    git_protocol: ssh\n    users:\n        inactive-user:\n        active-user:\n    user: inactive-user\n",
				stderr:       "✓ Switched active account for ghe.io to inactive-user",
			},
		},
		{
			name: "options need to be disambiguated given two hosts, one with two users",
			opts: SwitchOptions{},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{"inactive-user", "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
				{"ghe.io", []user{
					{"active-user", "active-user-token"},
				}},
			},
			prompterStubs: func(pm *prompter.PrompterMock) {
				pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) {
					require.Equal(t, "What account do you want to switch to?", prompt)
					require.Equal(t, []string{
						"inactive-user (github.com)",
						"active-user (github.com) - active",
						"active-user (ghe.io) - active",
					}, opts)

					return prompter.IndexFor(opts, "inactive-user (github.com)")
				}
			},
			expectedSuccess: successfulExpectation{
				switchedHost: "github.com",
				activeUser:   "inactive-user",
				activeToken:  "inactive-user-token",
				hostsCfg:     "github.com:\n    git_protocol: ssh\n    users:\n        inactive-user:\n        active-user:\n    user: inactive-user\nghe.io:\n    git_protocol: ssh\n    users:\n        active-user:\n    user: active-user\n",
				stderr:       "✓ Switched active account for github.com to inactive-user",
			},
		},
		{
			name: "when switching fails due to something other than user error, an informative message is printed to explain their new state",
			opts: SwitchOptions{
				Username: userWithMissingToken,
			},
			cfgHosts: []hostUsers{
				{"github.com", []user{
					{userWithMissingToken, "inactive-user-token"},
					{"active-user", "active-user-token"},
				}},
			},
			expectedFailure: failedExpectation{
				err:    fmt.Errorf("no token found for %s", userWithMissingToken),
				stderr: fmt.Sprintf("X Failed to switch account for github.com to %s", userWithMissingToken),
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			cfg, readConfigs := config.NewIsolatedTestConfig(t)

			for k, v := range tt.env {
				t.Setenv(k, v)
			}

			isInteractive := tt.prompterStubs != nil
			if isInteractive {
				pm := &prompter.PrompterMock{}
				tt.prompterStubs(pm)
				tt.opts.Prompter = pm
				defer func() {
					require.Len(t, pm.SelectCalls(), 1)
				}()
			}

			for _, hostUsers := range tt.cfgHosts {
				for _, user := range hostUsers.users {
					_, err := cfg.Authentication().Login(
						hostUsers.host,
						user.name,
						user.token, "ssh", true,
					)
					require.NoError(t, err)

					if user.name == userWithMissingToken {
						require.NoError(t, keyring.Delete(fmt.Sprintf("gh:%s", hostUsers.host), userWithMissingToken))
					}
				}
			}

			tt.opts.Config = func() (config.Config, error) {
				return cfg, nil
			}

			ios, _, _, stderr := iostreams.Test()
			ios.SetStdinTTY(isInteractive)
			ios.SetStdoutTTY(isInteractive)
			tt.opts.IO = ios

			err := switchRun(&tt.opts)
			if tt.expectedFailure.err != nil {
				require.Equal(t, tt.expectedFailure.err, err)
				require.Contains(t, stderr.String(), tt.expectedFailure.stderr)
				return
			}

			require.NoError(t, err)

			activeUser, err := cfg.Authentication().ActiveUser(tt.expectedSuccess.switchedHost)
			require.NoError(t, err)
			require.Equal(t, tt.expectedSuccess.activeUser, activeUser)

			activeToken, _ := cfg.Authentication().TokenFromKeyring(tt.expectedSuccess.switchedHost)
			require.Equal(t, tt.expectedSuccess.activeToken, activeToken)

			hostsBuf := bytes.Buffer{}
			readConfigs(io.Discard, &hostsBuf)

			require.Equal(t, tt.expectedSuccess.hostsCfg, hostsBuf.String())

			require.Contains(t, stderr.String(), tt.expectedSuccess.stderr)
		})
	}
}