GitLabgitlab-org
cli
main
1//go:build !integration
3package main
5import (
6 "bytes"
7 "errors"
8 "log"
9 "os"
10 "testing"
12 "github.com/spf13/cobra"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15 "github.com/zalando/go-keyring"
16 "go.uber.org/goleak"
18 "gitlab.com/gitlab-org/cli/internal/config"
19 "gitlab.com/gitlab-org/cli/internal/iostreams"
20 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
21)
23// Test started when the test binary is started
24// and calls the main function
25func TestGlab(t *testing.T) {
26 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
27 keyring.MockInit()
28 t.Cleanup(keyring.MockInit)
29 main()
30}
32func TestMain(m *testing.M) {
33 goleak.VerifyTestMain(m,
34 goleak.IgnoreTopFunction("internal/poll.runtime_pollWait"), // HTTP keep-alive connections
35 )
36}
38func TestMain_isUpdateCheckEnabled(t *testing.T) {
39 tests := []struct {
40 name string
41 envValue string
42 config config.Config
43 expectedResult bool
44 description string
45 }{
46 {
47 name: "env var enabled true",
48 envValue: "true",
49 config: config.NewFromString(""),
50 expectedResult: true,
51 description: "GLAB_CHECK_UPDATE=true should return true",
52 },
53 {
54 name: "env var enabled 1",
55 envValue: "1",
56 config: config.NewFromString(""),
57 expectedResult: true,
58 description: "GLAB_CHECK_UPDATE=1 should return true",
59 },
60 {
61 name: "env var disabled false",
62 envValue: "false",
63 config: config.NewFromString(""),
64 expectedResult: false,
65 description: "GLAB_CHECK_UPDATE=false should return false",
66 },
67 {
68 name: "env var disabled 0",
69 envValue: "0",
70 config: config.NewFromString(""),
71 expectedResult: false,
72 description: "GLAB_CHECK_UPDATE=0 should return false",
73 },
74 {
75 name: "config enabled true",
76 envValue: "",
77 config: config.NewFromString("check_update: true"),
78 expectedResult: true,
79 description: "check_update=true in config should return true",
80 },
81 {
82 name: "config enabled 1",
83 envValue: "",
84 config: config.NewFromString("check_update: 1"),
85 expectedResult: true,
86 description: "check_update=1 in config should return true",
87 },
88 {
89 name: "config disabled false",
90 envValue: "",
91 config: config.NewFromString("check_update: false"),
92 expectedResult: false,
93 description: "check_update=false in config should return false",
94 },
95 {
96 name: "config disabled 0",
97 envValue: "",
98 config: config.NewFromString("check_update: 0"),
99 expectedResult: false,
100 description: "check_update=0 in config should return false",
101 },
102 {
103 name: "env var overrides config",
104 envValue: "false",
105 config: config.NewFromString("check_update: true"),
106 expectedResult: false,
107 description: "Environment variable should take precedence over config",
108 },
109 {
110 name: "default when no config",
111 envValue: "",
112 config: config.NewFromString(""),
113 expectedResult: true,
114 description: "Should default to true when no config is set",
115 },
116 {
117 name: "invalid config value returns false",
118 envValue: "",
119 config: config.NewFromString("check_update: invalid"),
120 expectedResult: false,
121 description: "Invalid config value should return false (strconv.ParseBool zero value)",
122 },
123 }
125 for _, tt := range tests {
126 t.Run(tt.name, func(t *testing.T) {
127 // Set environment variable if specified
128 if tt.envValue != "" {
129 t.Setenv("GLAB_CHECK_UPDATE", tt.envValue)
130 }
132 ios, _, _, _ := cmdtest.TestIOStreams()
133 factory := cmdtest.NewTestFactory(ios, cmdtest.WithConfig(tt.config))
135 result := isUpdateCheckEnabled(factory)
137 assert.Equal(t, tt.expectedResult, result, tt.description)
138 })
139 }
140}
142func TestMain_configureHyperlinks(t *testing.T) {
143 tests := []struct {
144 name string
145 envValue string
146 envName string
147 config config.Config
148 expected string
149 description string
150 }{
151 {
152 name: "config unset, no env",
153 config: config.NewFromString(""),
154 expected: "never",
155 description: "configureHyperlinks should not override the IOStreams default when config and env are unset",
156 },
157 {
158 name: "config=true, no env",
159 config: config.NewFromString("display_hyperlinks: true"),
160 expected: "auto",
161 description: "display_hyperlinks=true should map to auto (TTY-only)",
162 },
163 {
164 name: "config=false, no env",
165 config: config.NewFromString("display_hyperlinks: false"),
166 expected: "never",
167 description: "display_hyperlinks=false should map to never",
168 },
169 {
170 name: "FORCE_HYPERLINKS=1, config unset",
171 envName: "FORCE_HYPERLINKS",
172 envValue: "1",
173 config: config.NewFromString(""),
174 expected: "always",
175 description: "FORCE_HYPERLINKS=1 should force always when config is unset",
176 },
177 {
178 name: "FORCE_HYPERLINKS=1, config=false",
179 envName: "FORCE_HYPERLINKS",
180 envValue: "1",
181 config: config.NewFromString("display_hyperlinks: false"),
182 expected: "always",
183 description: "FORCE_HYPERLINKS=1 should override display_hyperlinks=false",
184 },
185 {
186 name: "FORCE_HYPERLINKS=0, config unset",
187 envName: "FORCE_HYPERLINKS",
188 envValue: "0",
189 config: config.NewFromString(""),
190 expected: "never",
191 description: "a falsy FORCE_HYPERLINKS should fall through to the config check, leaving the IOStreams default in place",
192 },
193 {
194 name: "FORCE_HYPERLINKS=0, config=false",
195 envName: "FORCE_HYPERLINKS",
196 envValue: "0",
197 config: config.NewFromString("display_hyperlinks: false"),
198 expected: "never",
199 description: "a falsy FORCE_HYPERLINKS should fall through and let display_hyperlinks=false win",
200 },
201 {
202 name: "GLAB_FORCE_HYPERLINKS=1, config=false",
203 envName: "GLAB_FORCE_HYPERLINKS",
204 envValue: "1",
205 config: config.NewFromString("display_hyperlinks: false"),
206 expected: "always",
207 description: "GLAB_FORCE_HYPERLINKS=1 should override display_hyperlinks=false",
208 },
209 {
210 name: "GLAB_FORCE_HYPERLINKS=0, config=false",
211 envName: "GLAB_FORCE_HYPERLINKS",
212 envValue: "0",
213 config: config.NewFromString("display_hyperlinks: false"),
214 expected: "never",
215 description: "a falsy GLAB_FORCE_HYPERLINKS should fall through and let display_hyperlinks=false win",
216 },
217 }
219 for _, tt := range tests {
220 t.Run(tt.name, func(t *testing.T) {
221 // Clear both env vars first so each subtest is hermetic regardless
222 // of the surrounding shell environment.
223 t.Setenv("FORCE_HYPERLINKS", "")
224 t.Setenv("GLAB_FORCE_HYPERLINKS", "")
225 os.Unsetenv("FORCE_HYPERLINKS")
226 os.Unsetenv("GLAB_FORCE_HYPERLINKS")
228 if tt.envName != "" {
229 t.Setenv(tt.envName, tt.envValue)
230 }
232 ios, _, _, _ := cmdtest.TestIOStreams()
233 configureHyperlinks(ios, tt.config)
235 assert.Equal(t, tt.expected, ios.DisplayHyperlinks(), tt.description)
236 })
237 }
238}
240func TestMain_configureColorMode(t *testing.T) {
241 tests := []struct {
242 name string
243 envValue string
244 config config.Config
245 expected iostreams.ColorMode
246 description string
247 }{
248 {
249 name: "config unset, no env",
250 config: config.NewFromString(""),
251 expected: iostreams.ColorModeAuto,
252 description: "the color key's schema default (auto) applies when nothing is set",
253 },
254 {
255 name: "config=never",
256 config: config.NewFromString("color: never"),
257 expected: iostreams.ColorModeNever,
258 description: "color: never should force color off",
259 },
260 {
261 name: "config=always",
262 config: config.NewFromString("color: always"),
263 expected: iostreams.ColorModeAlways,
264 description: "color: always should force color on",
265 },
266 {
267 name: "GLAB_COLOR=never, config=always",
268 envValue: "never",
269 config: config.NewFromString("color: always"),
270 expected: iostreams.ColorModeNever,
271 description: "GLAB_COLOR should take precedence over the config file, per the color key's declared EnvVars",
272 },
273 {
274 name: "config=bogus falls back to auto",
275 config: config.NewFromString("color: bogus"),
276 expected: iostreams.ColorModeAuto,
277 description: "an unrecognized color value should fall back to auto rather than failing the command",
278 },
279 {
280 name: "config=truecolor (a removed depth value) falls back to auto",
281 config: config.NewFromString("color: truecolor"),
282 expected: iostreams.ColorModeAuto,
283 description: "color only takes whether values; color: truecolor falls back to auto",
284 },
285 }
287 for _, tt := range tests {
288 t.Run(tt.name, func(t *testing.T) {
289 t.Setenv("GLAB_COLOR", "")
290 os.Unsetenv("GLAB_COLOR")
291 if tt.envValue != "" {
292 t.Setenv("GLAB_COLOR", tt.envValue)
293 }
295 ios, _, _, _ := cmdtest.TestIOStreams()
296 configureColorMode(ios, tt.config)
298 assert.Equal(t, tt.expected, ios.ColorMode(), tt.description)
299 })
300 }
301}
303// An unrecognized color value falls back to auto and is logged under
304// GLAB_DEBUG; an unset value logs nothing.
305func TestMain_configureColorMode_LogsUnrecognizedValue(t *testing.T) {
306 t.Setenv("GLAB_DEBUG", "true")
307 t.Setenv("GLAB_COLOR", "")
308 os.Unsetenv("GLAB_COLOR")
310 var logOutput bytes.Buffer
311 log.SetOutput(&logOutput)
312 t.Cleanup(func() { log.SetOutput(os.Stderr) })
314 ios, _, _, _ := cmdtest.TestIOStreams()
315 configureColorMode(ios, config.NewFromString("color: bogus"))
317 assert.Contains(t, logOutput.String(), "bogus", "an unrecognized color value should be logged via internal/dbg, not eaten silently")
319 logOutput.Reset()
320 ios2, _, _, _ := cmdtest.TestIOStreams()
321 configureColorMode(ios2, config.NewFromString(""))
322 assert.Empty(t, logOutput.String(), "an unset color value is not an error and must not log anything")
323}
325func TestFangColorEnv_Apply(t *testing.T) {
326 tests := []struct {
327 name string
328 mode iostreams.ColorMode
329 noColor string
330 cliForce string
331 wantNoColor string
332 wantCLIForce string
333 }{
334 {name: "never disables color for fang", mode: iostreams.ColorModeNever, wantNoColor: "1"},
335 {name: "never drops CLICOLOR_FORCE, which wins on a non-TTY", mode: iostreams.ColorModeNever, cliForce: "1", wantNoColor: "1"},
336 {name: "always forces color for fang", mode: iostreams.ColorModeAlways, wantCLIForce: "1"},
337 {name: "always overrides NO_COLOR", mode: iostreams.ColorModeAlways, noColor: "1", wantCLIForce: "1"},
338 {name: "auto leaves the environment alone", mode: iostreams.ColorModeAuto, noColor: "1", cliForce: "0", wantNoColor: "1", wantCLIForce: "0"},
339 }
341 for _, tt := range tests {
342 t.Run(tt.name, func(t *testing.T) {
343 setColorEnv(t, tt.noColor, tt.cliForce)
345 newFangColorEnv(tt.mode).apply()
347 gotNoColor, hasNoColor := os.LookupEnv("NO_COLOR")
348 gotForce, hasForce := os.LookupEnv("CLICOLOR_FORCE")
349 assert.Equal(t, tt.wantNoColor != "", hasNoColor)
350 assert.Equal(t, tt.wantNoColor, gotNoColor)
351 assert.Equal(t, tt.wantCLIForce != "", hasForce)
352 assert.Equal(t, tt.wantCLIForce, gotForce)
353 })
354 }
355}
357func TestFangColorEnv_RestoreBringsBackTheOriginalEnvironment(t *testing.T) {
358 setColorEnv(t, "yes", "")
360 e := newFangColorEnv(iostreams.ColorModeAlways)
361 e.apply()
362 e.restore()
364 got, ok := os.LookupEnv("NO_COLOR")
365 assert.True(t, ok)
366 assert.Equal(t, "yes", got)
367 _, ok = os.LookupEnv("CLICOLOR_FORCE")
368 assert.False(t, ok, "a variable that was unset stays unset")
369}
371// Children that glab starts (git, pagers, editors, alias shells) must not
372// inherit the variables meant for fang's rendering.
373func TestScopeColorEnvToFang_CommandsRunWithTheOriginalEnvironment(t *testing.T) {
374 setColorEnv(t, "", "")
376 var duringRun, duringRunE []string
377 root := &cobra.Command{Use: "glab"}
378 root.AddCommand(&cobra.Command{Use: "run", Run: func(*cobra.Command, []string) { duringRun = colorEnvSnapshot() }})
379 nested := &cobra.Command{Use: "group"}
380 nested.AddCommand(&cobra.Command{Use: "rune", RunE: func(*cobra.Command, []string) error {
381 duringRunE = colorEnvSnapshot()
382 return errors.New("boom")
383 }})
384 root.AddCommand(nested)
386 e := newFangColorEnv(iostreams.ColorModeAlways)
387 e.apply()
388 scopeColorEnvToFang(root, e)
390 root.SetArgs([]string{"run"})
391 require.NoError(t, root.Execute())
392 assert.Empty(t, duringRun, "Run sees the original environment")
393 assert.Equal(t, []string{"CLICOLOR_FORCE=1"}, colorEnvSnapshot(), "fang's error rendering sees the exported value again afterwards")
395 root.SetArgs([]string{"group", "rune"})
396 root.SilenceErrors, root.SilenceUsage = true, true
397 require.Error(t, root.Execute())
398 assert.Empty(t, duringRunE, "nested RunE sees the original environment")
399 assert.Equal(t, []string{"CLICOLOR_FORCE=1"}, colorEnvSnapshot(), "re-applied even when the command fails")
400}
402func setColorEnv(t *testing.T, noColor, cliForce string) {
403 t.Helper()
404 t.Setenv("NO_COLOR", noColor)
405 t.Setenv("CLICOLOR_FORCE", cliForce)
406 if noColor == "" {
407 os.Unsetenv("NO_COLOR")
408 }
409 if cliForce == "" {
410 os.Unsetenv("CLICOLOR_FORCE")
411 }
412}
414func colorEnvSnapshot() []string {
415 var out []string
416 for _, k := range []string{"NO_COLOR", "CLICOLOR_FORCE"} {
417 if v, ok := os.LookupEnv(k); ok {
418 out = append(out, k+"="+v)
419 }
420 }
421 return out
422}
Diagnostics6 git calls · 46 ms
CallStatusSizeTime046 ms
discover200185 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=4 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB9 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=9 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchtree:0200195 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=195 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=62ad6b84b990e694d7e6e68667ba67fcbef93a08 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=195 git.pkt.payload.max=168 git.sideband.band1.bytes=168 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=168 git.pack.trailer=946df40edc15e3ab53d2f74cc477577e7e3fbcdcOpen pack map
fetch2003.0 KiB · hit32 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=32 git.response.bytes=3058 git.response.cache=HIT git.response.duration_ms=32 git.fetch.wants=620e860cb6249672da31b2d92a6b22dfe76e360d git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=3058 git.pkt.payload.max=3031 git.sideband.band1.bytes=3031 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://gitlab.com/gitlab-org/cli
- Ref
- refs/heads/main
- Commit
- 0dd7574dce9e385c5c30540e6c15657adc6bdce9
- cf-ray
- a5e2348f1ad9a594
- Request
- 9711d19d…
- Protocol
- v2 · sha1
- Agent
- git/2.56.g1891de4-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format