GitLabgitlab-org
cli
main
1//go:build !integration
3package init
5import (
6 "context"
7 "fmt"
8 "io/fs"
9 "os/exec"
10 "slices"
11 "strings"
12 "syscall"
13 "testing"
15 "github.com/MakeNowJust/heredoc/v2"
16 "github.com/stretchr/testify/assert"
17 "github.com/stretchr/testify/require"
18 "go.uber.org/mock/gomock"
20 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
21 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
23 "gitlab.com/gitlab-org/cli/internal/api"
24 "gitlab.com/gitlab-org/cli/internal/config"
25 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
26)
28func TestInit_CommandConstruction(t *testing.T) {
29 t.Parallel()
31 // GIVEN
32 ctrl := gomock.NewController(t)
33 tc := gitlabtesting.NewTestClientWithCtrl(ctrl, gitlab.WithBaseURL("https://gitlab.example.com"))
34 execMock := cmdtest.NewMockExecutor(ctrl)
35 exec := cmdtest.SetupCmdForTest(
36 t,
37 NewCmd,
38 false,
39 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "testtoken", "gitlab.example.com", api.WithGitLabClient(tc.Client))),
40 cmdtest.WithBaseRepo("OWNER", "REPO", "gitlab.example.com"),
41 cmdtest.WithExecutor(execMock),
42 )
44 execMock.EXPECT().Exec(gomock.Any(), "my-tofu", []string{
45 "-chdir=infra",
46 "init",
47 "-backend-config=address=https://gitlab.example.com/api/v4/projects/OWNER%2FREPO/terraform/state/production",
48 "-backend-config=lock_address=https://gitlab.example.com/api/v4/projects/OWNER%2FREPO/terraform/state/production/lock",
49 "-backend-config=unlock_address=https://gitlab.example.com/api/v4/projects/OWNER%2FREPO/terraform/state/production/lock",
50 "-backend-config=lock_method=POST",
51 "-backend-config=unlock_method=DELETE",
52 "-backend-config=retry_wait_min=5",
53 "-backend-config=headers={\"Authorization\" = \"Bearer testtoken\"}",
54 }, nil)
56 // WHEN
57 _, err := exec("production -d infra -b my-tofu")
58 require.NoError(t, err)
59}
61func TestInit_CommandConstruction_InitArgs(t *testing.T) {
62 t.Parallel()
64 tests := []struct {
65 stateName string
66 expectedStateTFURLPart string
67 }{
68 {
69 stateName: "production",
70 expectedStateTFURLPart: "terraform/state/production",
71 },
72 {
73 stateName: "production/iac",
74 expectedStateTFURLPart: "terraform/state/production%2Fiac",
75 },
76 }
78 for _, tt := range tests {
79 t.Run(tt.stateName, func(t *testing.T) {
80 t.Parallel()
82 // GIVEN
83 ctrl := gomock.NewController(t)
84 tc := gitlabtesting.NewTestClientWithCtrl(ctrl, gitlab.WithBaseURL("https://gitlab.example.com"))
85 execMock := cmdtest.NewMockExecutor(ctrl)
86 exec := cmdtest.SetupCmdForTest(
87 t,
88 NewCmd,
89 false,
90 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "testtoken", "gitlab.example.com", api.WithGitLabClient(tc.Client))),
91 cmdtest.WithBaseRepo("OWNER", "REPO", "gitlab.example.com"),
92 cmdtest.WithExecutor(execMock),
93 )
95 execMock.EXPECT().Exec(gomock.Any(), "my-tofu", []string{
96 "-chdir=infra",
97 "init",
98 fmt.Sprintf("-backend-config=address=https://gitlab.example.com/api/v4/projects/OWNER%%2FREPO/%s", tt.expectedStateTFURLPart),
99 fmt.Sprintf("-backend-config=lock_address=https://gitlab.example.com/api/v4/projects/OWNER%%2FREPO/%s/lock", tt.expectedStateTFURLPart),
100 fmt.Sprintf("-backend-config=unlock_address=https://gitlab.example.com/api/v4/projects/OWNER%%2FREPO/%s/lock", tt.expectedStateTFURLPart),
101 "-backend-config=lock_method=POST",
102 "-backend-config=unlock_method=DELETE",
103 "-backend-config=retry_wait_min=5",
104 "-backend-config=headers={\"Authorization\" = \"Bearer testtoken\"}",
105 "-reconfigure",
106 }, nil)
108 // WHEN
109 _, err := exec(fmt.Sprintf("%s -d infra -b my-tofu -- -reconfigure", tt.stateName))
110 require.NoError(t, err)
111 })
112 }
113}
115// An OAuth2 host whose refresh token is missing resolves to an access-token-only
116// auth source, which init used to reject outright.
117func TestInit_CommandConstruction_OAuth2AccessTokenOnly(t *testing.T) {
118 for _, k := range []string{"GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN", "GLAB_IS_OAUTH2"} {
119 t.Setenv(k, "")
120 }
122 ctrl := gomock.NewController(t)
123 execMock := cmdtest.NewMockExecutor(ctrl)
124 cfg := config.NewFromString(heredoc.Doc(`
125 hosts:
126 gitlab.example.com:
127 is_oauth2: "true"
128 token: an-access-token
129 api_protocol: https
130 api_host: gitlab.example.com
131 `))
133 apiClient, err := api.NewClientFromConfig("gitlab.example.com", cfg, false, "glab test client")
134 require.NoError(t, err)
136 exec := cmdtest.SetupCmdForTest(
137 t,
138 NewCmd,
139 false,
140 cmdtest.WithApiClient(apiClient),
141 cmdtest.WithConfig(cfg),
142 cmdtest.WithBaseRepo("OWNER", "REPO", "gitlab.example.com"),
143 cmdtest.WithExecutor(execMock),
144 )
146 execMock.EXPECT().Exec(gomock.Any(), "my-tofu", gomock.Cond(func(args []string) bool {
147 return slices.Contains(args, `-backend-config=headers={"Authorization" = "Bearer an-access-token"}`)
148 }), nil)
150 _, err = exec("production -d infra -b my-tofu")
151 require.NoError(t, err)
152}
154// unclassifiableAuthSource is not something NewClientFromConfig can produce, so
155// this only guards the contract for whoever adds the next auth source.
156type unclassifiableAuthSource struct{}
158func (unclassifiableAuthSource) Init(context.Context, *gitlab.Client) error { return nil }
160func (unclassifiableAuthSource) Header(context.Context) (string, string, error) {
161 return "X-Custom", "a-value", nil
162}
164func TestInit_CommandConstruction_credentialErrors(t *testing.T) {
165 tests := []struct {
166 name string
167 authSource gitlab.AuthSource
168 expectedErr string
169 refutedErr string
170 }{
171 {
172 name: "an unclassifiable auth source names the requirement, not the Go type",
173 authSource: unclassifiableAuthSource{},
174 expectedErr: "init command does not support this authentication method",
175 refutedErr: "unclassifiableAuthSource",
176 },
177 {
178 name: "an unauthenticated host is reported once, not wrapped",
179 authSource: gitlab.Unauthenticated{},
180 expectedErr: "glab is not authenticated",
181 refutedErr: "unable to retrieve an access token",
182 },
183 }
185 for _, tt := range tests {
186 t.Run(tt.name, func(t *testing.T) {
187 exec := cmdtest.SetupCmdForTest(
188 t,
189 NewCmd,
190 false,
191 cmdtest.WithApiClient(cmdtest.NewTestAuthSourceApiClient(t, nil, tt.authSource, "gitlab.example.com")),
192 cmdtest.WithBaseRepo("OWNER", "REPO", "gitlab.example.com"),
193 )
195 _, err := exec("production")
197 require.Error(t, err)
198 require.ErrorContains(t, err, tt.expectedErr)
199 assert.NotContains(t, err.Error(), tt.refutedErr)
200 })
201 }
202}
204func TestInit_BinaryNotFound(t *testing.T) {
205 tests := []struct {
206 name string
207 snapName string
208 binary string
209 wantSnapHint bool
210 wantExample string
211 }{
212 {name: "confined snap suggests --binary", snapName: "glab", binary: "tofu", wantSnapHint: true, wantExample: "--binary ~/tofu"},
213 {name: "absolute binary path uses its base name", snapName: "glab", binary: "/usr/bin/tofu", wantSnapHint: true, wantExample: "--binary ~/tofu"},
214 {name: "home-relative binary path uses its base name", snapName: "glab", binary: "~/bin/tofu", wantSnapHint: true, wantExample: "--binary ~/tofu"},
215 {name: "outside the snap returns the plain error", snapName: "", binary: "tofu", wantSnapHint: false},
216 }
218 for _, tt := range tests {
219 t.Run(tt.name, func(t *testing.T) {
220 t.Setenv("SNAP_NAME", tt.snapName)
222 ctrl := gomock.NewController(t)
223 tc := gitlabtesting.NewTestClientWithCtrl(ctrl, gitlab.WithBaseURL("https://gitlab.example.com"))
224 execMock := cmdtest.NewMockExecutor(ctrl)
225 run := cmdtest.SetupCmdForTest(
226 t,
227 NewCmd,
228 false,
229 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "testtoken", "gitlab.example.com", api.WithGitLabClient(tc.Client))),
230 cmdtest.WithBaseRepo("OWNER", "REPO", "gitlab.example.com"),
231 cmdtest.WithExecutor(execMock),
232 )
234 // Match what exec.Command returns: a $PATH lookup error for names, ENOENT for paths.
235 var execErr error = &exec.Error{Name: tt.binary, Err: exec.ErrNotFound}
236 if strings.Contains(tt.binary, "/") {
237 execErr = &fs.PathError{Op: "fork/exec", Path: tt.binary, Err: syscall.ENOENT}
238 }
239 execMock.EXPECT().Exec(gomock.Any(), tt.binary, gomock.Any(), nil).Return(execErr)
241 _, err := run("production --binary " + tt.binary)
243 require.ErrorIs(t, err, execErr)
244 if tt.wantSnapHint {
245 require.ErrorContains(t, err, "snap confinement")
246 require.ErrorContains(t, err, "glab opentofu init production "+tt.wantExample)
247 } else {
248 assert.NotContains(t, err.Error(), "snap confinement")
249 }
250 })
251 }
252}
254func TestShellQuote(t *testing.T) {
255 assert.Equal(t, "production", shellQuote("production"))
256 assert.Equal(t, "'my state'", shellQuote("my state"))
257 assert.Equal(t, `'a;rm -rf ~'`, shellQuote("a;rm -rf ~"))
258 assert.Equal(t, `'it'\''s'`, shellQuote("it's"))
259}
Diagnostics8 git calls · 233 ms
CallStatusSizeTime0233 ms
discover200185 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 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 KiB · hit3 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=HIT git.response.duration_ms=3 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 · 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=4273 git.response.cache=HIT git.response.duration_ms=2 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 · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=5 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=3 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:02001.8 KiB · hit5 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=1857 git.response.cache=HIT git.response.duration_ms=5 git.fetch.filter=tree:0 git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592 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=1857 git.pkt.payload.max=1830 git.sideband.band1.bytes=1830 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1830 git.pack.trailer=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200171 B · hit3 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=171 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=2855fba468423062dfdcf0df3b48b51ba83b86fc 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=171 git.pkt.payload.max=144 git.sideband.band1.bytes=144 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=144 git.pack.trailer=9cf2753898214ee7a00e442cff7d52bb582cde2eOpen pack map
fetchtree:0200135 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=217 git.response.bytes=135 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=d696f1306cf5765e7ec77a88e29ce68d08b51093 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=135 git.pkt.payload.max=108 git.sideband.band1.bytes=108 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=108 git.pack.trailer=0efd523d8b97287959a6006de564aff42f32db4bOpen pack map
fetch2002.3 KiB217 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2405 git.response.cache=MISS git.response.duration_ms=217 git.fetch.wants=fe5f9c8f15bd7158ae4acab445b8d420b40fa8fb 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=2405 git.pkt.payload.max=2378 git.sideband.band1.bytes=2378 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
- a5e2d330a9bbcf3a
- Request
- 00653fad…
- 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