GitLabgitlab-org

cli

main
ply8 git calls250 ms100 KiB6 cachedprotocol v2
453 lines13 KiBRaw
1//go:build !integration
3package create
5import (
6 "encoding/json"
7 "testing"
8 "time"
10 "github.com/spf13/cobra"
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 "go.uber.org/mock/gomock"
15 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
16 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
18 "gitlab.com/gitlab-org/cli/internal/api"
19 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
22// noMorePages creates a response that indicates no more pages are available
23func noMorePages() *gitlab.Response {
24 return &gitlab.Response{NextPage: 0}
27func parseTime(s string) *time.Time {
28 t, _ := time.Parse(time.RFC3339, s)
29 return &t
32func TestCreateOwnPersonalAccessToken(t *testing.T) {
33 type testCase struct {
34 name string
35 cli string
36 expectedOut string
37 wantJSON bool
38 wantErr bool
39 wantStderr string
40 setupMock func(tc *gitlabtesting.TestClient)
41 }
43 testUser := &gitlab.User{
44 ID: 1,
45 Username: "johndoe",
46 Name: "John Doe",
47 Email: "john.doe@acme.com",
48 }
50 testPAT := &gitlab.PersonalAccessToken{
51 ID: 10183862,
52 Name: "my-pat",
53 Revoked: false,
54 CreatedAt: parseTime("2024-07-08T01:23:04.311Z"),
55 Scopes: []string{"k8s_proxy"},
56 UserID: 926857,
57 Active: true,
58 ExpiresAt: new(gitlab.ISOTime(*parseTime("2024-08-07T00:00:00Z"))),
59 Token: "sometoken",
60 }
62 testCases := []testCase{
63 {
64 name: "create own PAT as text",
65 cli: "--user @me --scope k8s_proxy my-pat",
66 expectedOut: "sometoken\n",
67 setupMock: func(tc *gitlabtesting.TestClient) {
68 tc.MockUsers.EXPECT().
69 CurrentUser(gomock.Any()).
70 Return(testUser, nil, nil)
71 tc.MockPersonalAccessTokens.EXPECT().
72 ListPersonalAccessTokens(gomock.Any(), gomock.Any()).
73 Return([]*gitlab.PersonalAccessToken{}, noMorePages(), nil)
74 tc.MockUsers.EXPECT().
75 CreatePersonalAccessTokenForCurrentUser(gomock.Any()).
76 Return(testPAT, nil, nil)
77 },
78 },
79 {
80 name: "create own PAT as json",
81 cli: "--user @me --scope k8s_proxy --output json my-pat",
82 wantJSON: true,
83 setupMock: func(tc *gitlabtesting.TestClient) {
84 tc.MockUsers.EXPECT().
85 CurrentUser(gomock.Any()).
86 Return(testUser, nil, nil)
87 tc.MockPersonalAccessTokens.EXPECT().
88 ListPersonalAccessTokens(gomock.Any(), gomock.Any()).
89 Return([]*gitlab.PersonalAccessToken{}, noMorePages(), nil)
90 tc.MockUsers.EXPECT().
91 CreatePersonalAccessTokenForCurrentUser(gomock.Any()).
92 Return(testPAT, nil, nil)
93 },
94 },
95 }
97 for _, tc := range testCases {
98 t.Run(tc.name, func(t *testing.T) {
99 // GIVEN
100 testClient := gitlabtesting.NewTestClient(t)
101 tc.setupMock(testClient)
102 exec := cmdtest.SetupCmdForTest(
103 t,
104 NewCmdCreate,
105 true,
106 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
107 )
109 // WHEN
110 out, err := exec(tc.cli)
112 // THEN
113 if tc.wantErr {
114 require.Error(t, err)
115 assert.Contains(t, err.Error(), tc.wantStderr)
116 return
117 }
118 require.NoError(t, err)
119 if tc.wantJSON {
120 var result map[string]any
121 err := json.Unmarshal(out.OutBuf.Bytes(), &result)
122 require.NoError(t, err)
123 assert.Equal(t, "my-pat", result["name"])
124 } else if tc.expectedOut != "" {
125 assert.Equal(t, tc.expectedOut, out.OutBuf.String())
126 }
127 assert.Empty(t, out.ErrBuf.String())
128 })
129 }
132func TestCreateOtherUserPersonalAccessToken(t *testing.T) {
133 type testCase struct {
134 name string
135 cli string
136 expectedOut string
137 wantJSON bool
138 wantErr bool
139 wantStderr string
140 setupMock func(tc *gitlabtesting.TestClient)
141 }
143 otherUser := &gitlab.User{
144 ID: 2,
145 Username: "janedoe",
146 Name: "Jane Doe",
147 Email: "jane.doe@acme.com",
148 }
150 testPAT := &gitlab.PersonalAccessToken{
151 ID: 10183862,
152 Name: "your-pat",
153 Revoked: false,
154 CreatedAt: parseTime("2024-07-08T01:23:04.311Z"),
155 Scopes: []string{"read_registry"},
156 UserID: 2,
157 Active: true,
158 ExpiresAt: new(gitlab.ISOTime(*parseTime("2024-08-07T00:00:00Z"))),
159 Token: "sometoken",
160 }
162 testCases := []testCase{
163 {
164 name: "create other user PAT as text",
165 cli: "--user janedoe --scope read_registry your-pat",
166 expectedOut: "sometoken\n",
167 setupMock: func(tc *gitlabtesting.TestClient) {
168 tc.MockUsers.EXPECT().
169 ListUsers(gomock.Any()).
170 Return([]*gitlab.User{otherUser}, nil, nil)
171 tc.MockPersonalAccessTokens.EXPECT().
172 ListPersonalAccessTokens(gomock.Any(), gomock.Any()).
173 Return([]*gitlab.PersonalAccessToken{}, noMorePages(), nil)
174 tc.MockUsers.EXPECT().
175 CreatePersonalAccessToken(int64(2), gomock.Any()).
176 Return(testPAT, nil, nil)
177 },
178 },
179 {
180 name: "create other user PAT as json",
181 cli: "--user janedoe --scope read_registry --output json your-pat",
182 wantJSON: true,
183 setupMock: func(tc *gitlabtesting.TestClient) {
184 tc.MockUsers.EXPECT().
185 ListUsers(gomock.Any()).
186 Return([]*gitlab.User{otherUser}, nil, nil)
187 tc.MockPersonalAccessTokens.EXPECT().
188 ListPersonalAccessTokens(gomock.Any(), gomock.Any()).
189 Return([]*gitlab.PersonalAccessToken{}, noMorePages(), nil)
190 tc.MockUsers.EXPECT().
191 CreatePersonalAccessToken(int64(2), gomock.Any()).
192 Return(testPAT, nil, nil)
193 },
194 },
195 }
197 for _, tc := range testCases {
198 t.Run(tc.name, func(t *testing.T) {
199 // GIVEN
200 testClient := gitlabtesting.NewTestClient(t)
201 tc.setupMock(testClient)
202 exec := cmdtest.SetupCmdForTest(
203 t,
204 NewCmdCreate,
205 true,
206 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
207 )
209 // WHEN
210 out, err := exec(tc.cli)
212 // THEN
213 if tc.wantErr {
214 require.Error(t, err)
215 assert.Contains(t, err.Error(), tc.wantStderr)
216 return
217 }
218 require.NoError(t, err)
219 if tc.wantJSON {
220 var result map[string]any
221 err := json.Unmarshal(out.OutBuf.Bytes(), &result)
222 require.NoError(t, err)
223 assert.Equal(t, "your-pat", result["name"])
224 } else if tc.expectedOut != "" {
225 assert.Equal(t, tc.expectedOut, out.OutBuf.String())
226 }
227 assert.Empty(t, out.ErrBuf.String())
228 })
229 }
232func TestCreateGroupAccessToken(t *testing.T) {
233 type testCase struct {
234 name string
235 cli string
236 expectedOut string
237 wantJSON bool
238 wantErr bool
239 wantStderr string
240 setupMock func(tc *gitlabtesting.TestClient)
241 }
243 testGroupToken := &gitlab.GroupAccessToken{
244 PersonalAccessToken: gitlab.PersonalAccessToken{
245 ID: 10190772,
246 UserID: 21989300,
247 Name: "my-group-token",
248 Scopes: []string{"read_registry", "read_repository"},
249 CreatedAt: parseTime("2024-07-08T17:33:34.829Z"),
250 ExpiresAt: new(gitlab.ISOTime(*parseTime("2024-08-07T00:00:00Z"))),
251 Active: true,
252 Revoked: false,
253 Token: "glpat-yz2791KMU-xxxxxxxxx",
254 },
255 AccessLevel: gitlab.DeveloperPermissions,
256 }
258 testCases := []testCase{
259 {
260 name: "create group token as text",
261 cli: "--group GROUP --output text --access-level developer --scope read_registry --scope read_repository my-group-token",
262 expectedOut: "glpat-yz2791KMU-xxxxxxxxx\n",
263 setupMock: func(tc *gitlabtesting.TestClient) {
264 tc.MockGroupAccessTokens.EXPECT().
265 ListGroupAccessTokens("GROUP", gomock.Any(), gomock.Any()).
266 Return([]*gitlab.GroupAccessToken{}, noMorePages(), nil)
267 tc.MockGroupAccessTokens.EXPECT().
268 CreateGroupAccessToken("GROUP", gomock.Any()).
269 Return(testGroupToken, nil, nil)
270 },
271 },
272 {
273 name: "create group token as json",
274 cli: "--group GROUP --output json --access-level developer --scope read_registry --scope read_repository my-group-token",
275 wantJSON: true,
276 setupMock: func(tc *gitlabtesting.TestClient) {
277 tc.MockGroupAccessTokens.EXPECT().
278 ListGroupAccessTokens("GROUP", gomock.Any(), gomock.Any()).
279 Return([]*gitlab.GroupAccessToken{}, noMorePages(), nil)
280 tc.MockGroupAccessTokens.EXPECT().
281 CreateGroupAccessToken("GROUP", gomock.Any()).
282 Return(testGroupToken, nil, nil)
283 },
284 },
285 }
287 for _, tc := range testCases {
288 t.Run(tc.name, func(t *testing.T) {
289 // GIVEN
290 testClient := gitlabtesting.NewTestClient(t)
291 tc.setupMock(testClient)
292 exec := cmdtest.SetupCmdForTest(
293 t,
294 NewCmdCreate,
295 true,
296 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
297 )
299 // WHEN
300 out, err := exec(tc.cli)
302 // THEN
303 if tc.wantErr {
304 require.Error(t, err)
305 assert.Contains(t, err.Error(), tc.wantStderr)
306 return
307 }
308 require.NoError(t, err)
309 if tc.wantJSON {
310 var result map[string]any
311 err := json.Unmarshal(out.OutBuf.Bytes(), &result)
312 require.NoError(t, err)
313 assert.Equal(t, "my-group-token", result["name"])
314 } else if tc.expectedOut != "" {
315 assert.Equal(t, tc.expectedOut, out.OutBuf.String())
316 }
317 assert.Empty(t, out.ErrBuf.String())
318 })
319 }
322func TestCreateProjectAccessToken(t *testing.T) {
323 type testCase struct {
324 name string
325 cli string
326 expectedOut string
327 wantJSON bool
328 wantErr bool
329 wantStderr string
330 setupMock func(tc *gitlabtesting.TestClient)
331 }
333 testProjectToken := &gitlab.ProjectAccessToken{
334 PersonalAccessToken: gitlab.PersonalAccessToken{
335 ID: 10191548,
336 UserID: 21990679,
337 Name: "my-project-token",
338 Scopes: []string{"api", "read_repository"},
339 CreatedAt: parseTime("2024-07-08T19:47:14.727Z"),
340 ExpiresAt: new(gitlab.ISOTime(*parseTime("2024-08-07T00:00:00Z"))),
341 Active: true,
342 Revoked: false,
343 Token: "glpat-dfsdfjksjdfslkdfjsd",
344 },
345 AccessLevel: gitlab.DeveloperPermissions,
346 }
348 testCases := []testCase{
349 {
350 name: "create project token as text",
351 cli: "--output text --access-level developer --scope read_repository --scope api my-project-token",
352 expectedOut: "glpat-dfsdfjksjdfslkdfjsd\n",
353 setupMock: func(tc *gitlabtesting.TestClient) {
354 tc.MockProjectAccessTokens.EXPECT().
355 ListProjectAccessTokens("OWNER/REPO", gomock.Any(), gomock.Any()).
356 Return([]*gitlab.ProjectAccessToken{}, noMorePages(), nil)
357 tc.MockProjectAccessTokens.EXPECT().
358 CreateProjectAccessToken("OWNER/REPO", gomock.Any()).
359 Return(testProjectToken, nil, nil)
360 },
361 },
362 {
363 name: "create project token as json",
364 cli: "--output json --access-level developer --scope read_repository --scope api my-project-token",
365 wantJSON: true,
366 setupMock: func(tc *gitlabtesting.TestClient) {
367 tc.MockProjectAccessTokens.EXPECT().
368 ListProjectAccessTokens("OWNER/REPO", gomock.Any(), gomock.Any()).
369 Return([]*gitlab.ProjectAccessToken{}, noMorePages(), nil)
370 tc.MockProjectAccessTokens.EXPECT().
371 CreateProjectAccessToken("OWNER/REPO", gomock.Any()).
372 Return(testProjectToken, nil, nil)
373 },
374 },
375 }
377 for _, tc := range testCases {
378 t.Run(tc.name, func(t *testing.T) {
379 // GIVEN
380 testClient := gitlabtesting.NewTestClient(t)
381 tc.setupMock(testClient)
382 exec := cmdtest.SetupCmdForTest(
383 t,
384 NewCmdCreate,
385 true,
386 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
387 )
389 // WHEN
390 out, err := exec(tc.cli)
392 // THEN
393 if tc.wantErr {
394 require.Error(t, err)
395 assert.Contains(t, err.Error(), tc.wantStderr)
396 return
397 }
398 require.NoError(t, err)
399 if tc.wantJSON {
400 var result map[string]any
401 err := json.Unmarshal(out.OutBuf.Bytes(), &result)
402 require.NoError(t, err)
403 assert.Equal(t, "my-project-token", result["name"])
404 } else if tc.expectedOut != "" {
405 assert.Equal(t, tc.expectedOut, out.OutBuf.String())
406 }
407 assert.Empty(t, out.ErrBuf.String())
408 })
409 }
412func TestCreate_Completions(t *testing.T) {
413 testClient := gitlabtesting.NewTestClient(t)
414 // No mock expectations: completions must not call the API.
415 f := cmdtest.NewTestFactory(nil,
416 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
417 )
419 cmd := NewCmdCreate(f)
420 cmd.SetContext(t.Context())
422 // The <name> argument never takes file completions.
423 comps, directive := cmd.ValidArgsFunction(cmd, nil, "")
424 assert.Empty(t, comps)
425 assert.Equal(t, cobra.ShellCompDirectiveNoFileComp, directive)
427 testCases := map[string]struct {
428 wantComps []cobra.Completion
429 wantDirective cobra.ShellCompDirective
430 }{
431 "group": {wantDirective: cobra.ShellCompDirectiveNoFileComp},
432 "user": {wantComps: []cobra.Completion{cobra.CompletionWithDesc("@me", "Current user")}, wantDirective: cobra.ShellCompDirectiveNoFileComp},
433 "description": {wantDirective: cobra.ShellCompDirectiveNoFileComp},
434 "duration": {wantDirective: cobra.ShellCompDirectiveNoFileComp},
435 "expires-at": {wantDirective: cobra.ShellCompDirectiveNoFileComp},
436 "scope": {wantDirective: cobra.ShellCompDirectiveNoFileComp},
437 "access-level": {
438 wantComps: []cobra.Completion{"guest", "reporter", "developer", "maintainer", "owner"},
439 wantDirective: cobra.ShellCompDirectiveNoFileComp,
440 },
441 }
443 for flag, tc := range testCases {
444 t.Run(flag, func(t *testing.T) {
445 compFn, ok := cmd.GetFlagCompletionFunc(flag)
446 require.True(t, ok, "--%s should have a completion function registered", flag)
448 comps, directive := compFn(cmd, nil, "")
449 assert.Equal(t, tc.wantComps, comps)
450 assert.Equal(t, tc.wantDirective, directive)
451 })
452 }
Diagnostics8 git calls · 250 ms
CallStatusSizeTime0250 ms
discover200185 B7 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
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 · hit6 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=6
git.response.bytes=59849
git.response.cache=HIT
git.response.duration_ms=6
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 · hit4 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=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=44
Open pack map
fetchtree:02001.8 KiB · hit2 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=2
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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200358 B · hit3 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=358
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=218b543e075f31e84c52193d193103408c52cb34
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=358
git.pkt.payload.max=331
git.sideband.band1.bytes=331
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=331
git.pack.trailer=fbb77d44047cd3e1ee682eb9483227c59489e50f
Open pack map
fetchtree:0200138 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=233
git.response.bytes=138
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=f924ab3692a685efef99065da41019864d999ac9
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=138
git.pkt.payload.max=111
git.sideband.band1.bytes=111
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=111
git.pack.trailer=9ac4c7f75d8462b5054c2962ca1c06c51d22edb2
Open pack map
fetch2002.3 KiB233 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=2358
git.response.cache=MISS
git.response.duration_ms=233
git.fetch.wants=28f035dce6de2731c3404db474e49133cdd4063c
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=2358
git.pkt.payload.max=2331
git.sideband.band1.bytes=2331
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
a5e2829afe696483
Request
d9614ee2…
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