GitLabgitlab-org
cli
main
1//go:build !integration
3package ciutils
5import (
6 "bytes"
7 "net/http"
8 "strings"
9 "testing"
10 "time"
12 "git.sr.ht/~timofurrer/ugh"
13 retryablehttp "github.com/hashicorp/go-retryablehttp"
14 "github.com/stretchr/testify/assert"
15 "github.com/stretchr/testify/require"
16 "go.uber.org/mock/gomock"
18 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
19 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
21 "gitlab.com/gitlab-org/cli/internal/iostreams"
22 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
23)
25func TestDisplayMultiplePipelines_UsesSinglePipelineInfo(t *testing.T) {
26 t.Parallel()
28 pipelines := []*gitlab.PipelineInfo{
29 {
30 ID: 456,
31 IID: 789,
32 Status: "success",
33 Ref: "main",
34 SHA: "abc0def0",
35 WebURL: "https://gitlab.com/project/-/pipelines/123",
36 },
37 }
38 ios, _, _, _ := cmdtest.TestIOStreams()
40 result := DisplayMultiplePipelines(ios, pipelines, "group/project")
42 assert.Contains(t, result, "success")
43 assert.Contains(t, result, "#456")
44 assert.Contains(t, result, "#789")
45 assert.Contains(t, result, "main")
46}
48func TestDisplayMultiplePipelines_UsesMultiplePipelinesInfo(t *testing.T) {
49 t.Parallel()
51 pipelines := []*gitlab.PipelineInfo{
52 {
53 ID: 900,
54 Status: "success",
55 Ref: "main",
56 },
57 {
58 ID: 901,
59 Status: "failed",
60 Ref: "develop",
61 },
62 {
63 ID: 902,
64 Status: "running",
65 Ref: "feat/ure",
66 },
67 }
68 ios, _, _, _ := cmdtest.TestIOStreams()
70 result := DisplayMultiplePipelines(ios, pipelines, "group/project")
72 assert.Contains(t, result, "success")
73 assert.Contains(t, result, "failed")
74 assert.Contains(t, result, "running")
75}
77func TestDisplayMultiplePipelines_HandlesEmptyPipelines(t *testing.T) {
78 t.Parallel()
80 pipelines := []*gitlab.PipelineInfo{}
81 ios, _, _, _ := cmdtest.TestIOStreams()
83 result := DisplayMultiplePipelines(ios, pipelines, "group/project")
85 assert.Equal(t, "No Pipelines available on group/project", result)
86}
88func TestGetJobId(t *testing.T) {
89 t.Parallel()
90 // Response indicating last page
91 lastPageResponse := &gitlab.Response{
92 Response: &http.Response{StatusCode: http.StatusOK},
93 NextPage: 0,
94 }
96 // Response indicating there's a next page
97 nextPageResponse := &gitlab.Response{
98 Response: &http.Response{StatusCode: http.StatusOK},
99 NextPage: 2,
100 }
102 type testCase struct {
103 name string
104 jobName string
105 pipelineId int
106 console func(t *testing.T) *ugh.Console
107 setupMock func(tc *gitlabtesting.TestClient)
108 expectedOut int64
109 expectedError string
110 }
112 tests := []testCase{
113 {
114 name: "when getJobId with integer is requested",
115 jobName: "1122",
116 expectedOut: 1122,
117 setupMock: func(tc *gitlabtesting.TestClient) {},
118 },
119 {
120 name: "when getJobId with name and pipelineId is requested",
121 jobName: "lint",
122 pipelineId: 123,
123 expectedOut: 1122,
124 setupMock: func(tc *gitlabtesting.TestClient) {
125 tc.MockJobs.EXPECT().
126 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
127 Return([]*gitlab.Job{
128 {ID: 1122, Name: "lint", Status: "failed"},
129 {ID: 1124, Name: "publish", Status: "failed"},
130 }, lastPageResponse, nil)
131 },
132 },
133 {
134 name: "when getJobId with name and pipelineId is requested and job is found on page 2",
135 jobName: "deploy",
136 pipelineId: 123,
137 expectedOut: 1144,
138 setupMock: func(tc *gitlabtesting.TestClient) {
139 // First page
140 tc.MockJobs.EXPECT().
141 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
142 Return([]*gitlab.Job{
143 {ID: 1122, Name: "lint", Status: "failed"},
144 {ID: 1124, Name: "publish", Status: "failed"},
145 }, nextPageResponse, nil)
146 // Second page
147 tc.MockJobs.EXPECT().
148 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
149 Return([]*gitlab.Job{
150 {ID: 1133, Name: "test", Status: "failed"},
151 {ID: 1144, Name: "deploy", Status: "failed"},
152 }, lastPageResponse, nil)
153 },
154 },
155 {
156 name: "when job is found on page 1, page 2 is never requested",
157 jobName: "lint",
158 pipelineId: 123,
159 expectedOut: 1122,
160 setupMock: func(tc *gitlabtesting.TestClient) {
161 // Only one call expected: the mock has no second EXPECT(), so a
162 // second ListPipelineJobs call would fail the test.
163 tc.MockJobs.EXPECT().
164 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
165 Return([]*gitlab.Job{
166 {ID: 1122, Name: "lint", Status: "failed"},
167 {ID: 1124, Name: "publish", Status: "failed"},
168 }, nextPageResponse, nil)
169 },
170 },
171 {
172 name: "when job name is not found across multiple pages",
173 jobName: "missing",
174 pipelineId: 123,
175 expectedOut: 0,
176 expectedError: "pipeline 123 contains no jobs with the name missing",
177 setupMock: func(tc *gitlabtesting.TestClient) {
178 tc.MockJobs.EXPECT().
179 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
180 Return([]*gitlab.Job{
181 {ID: 1122, Name: "lint", Status: "failed"},
182 }, nextPageResponse, nil)
183 tc.MockJobs.EXPECT().
184 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
185 Return([]*gitlab.Job{
186 {ID: 1144, Name: "deploy", Status: "failed"},
187 }, lastPageResponse, nil)
188 },
189 },
190 {
191 name: "when pipeline contains no jobs at all",
192 jobName: "lint",
193 pipelineId: 123,
194 expectedOut: 0,
195 expectedError: "pipeline 123 contains no jobs at all",
196 setupMock: func(tc *gitlabtesting.TestClient) {
197 tc.MockJobs.EXPECT().
198 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
199 Return([]*gitlab.Job{}, lastPageResponse, nil)
200 },
201 },
202 {
203 name: "when getJobId with name and pipelineId is requested and listJobs throws error",
204 jobName: "lint",
205 pipelineId: 123,
206 expectedError: "list pipeline jobs:",
207 expectedOut: 0,
208 setupMock: func(tc *gitlabtesting.TestClient) {
209 forbiddenResponse := &gitlab.Response{Response: &http.Response{StatusCode: http.StatusForbidden}}
210 tc.MockJobs.EXPECT().
211 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
212 Return(nil, forbiddenResponse, assert.AnError)
213 },
214 },
215 {
216 name: "when getJobId with name and last pipeline is requested",
217 jobName: "lint",
218 pipelineId: 0,
219 expectedOut: 1122,
220 setupMock: func(tc *gitlabtesting.TestClient) {
221 // GetPipelineWithFallback first tries GetLatestPipeline
222 tc.MockPipelines.EXPECT().
223 GetLatestPipeline("OWNER/REPO", gomock.Any(), gomock.Any()).
224 Return(&gitlab.Pipeline{ID: 123}, nil, nil)
225 // Then checks if pipeline has jobs
226 tc.MockJobs.EXPECT().
227 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any()).
228 Return([]*gitlab.Job{
229 {ID: 1, Name: "test"},
230 }, nil, nil)
231 // Then GetJobId lists all jobs for the pipeline
232 tc.MockJobs.EXPECT().
233 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
234 Return([]*gitlab.Job{
235 {ID: 1122, Name: "lint", Status: "failed"},
236 {ID: 1124, Name: "publish", Status: "failed"},
237 }, lastPageResponse, nil)
238 },
239 },
240 {
241 name: "when getJobId with name and last pipeline is requested and getCommits throws error",
242 jobName: "lint",
243 pipelineId: 0,
244 expectedError: "get pipeline: failed to get pipeline for branch main:",
245 expectedOut: 0,
246 setupMock: func(tc *gitlabtesting.TestClient) {
247 forbiddenResponse := &gitlab.Response{Response: &http.Response{StatusCode: http.StatusForbidden}}
248 // GetPipelineWithFallback tries GetLatestPipeline
249 tc.MockPipelines.EXPECT().
250 GetLatestPipeline("OWNER/REPO", gomock.Any(), gomock.Any()).
251 Return(nil, forbiddenResponse, assert.AnError)
252 // Then tries MR lookup (will also fail)
253 tc.MockMergeRequests.EXPECT().
254 ListProjectMergeRequests("OWNER/REPO", gomock.Any()).
255 Return(nil, forbiddenResponse, assert.AnError)
256 },
257 },
258 {
259 name: "when getJobId with name and last pipeline is requested and getJobs throws error",
260 jobName: "lint",
261 pipelineId: 0,
262 expectedError: "list pipeline jobs:",
263 expectedOut: 0,
264 setupMock: func(tc *gitlabtesting.TestClient) {
265 // GetPipelineWithFallback tries GetLatestPipeline
266 tc.MockPipelines.EXPECT().
267 GetLatestPipeline("OWNER/REPO", gomock.Any(), gomock.Any()).
268 Return(&gitlab.Pipeline{ID: 123}, nil, nil)
269 // Check if pipeline has jobs
270 tc.MockJobs.EXPECT().
271 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any()).
272 Return([]*gitlab.Job{{ID: 1, Name: "test"}}, nil, nil)
273 // Then GetJobId tries to list all jobs (this fails)
274 forbiddenResponse := &gitlab.Response{Response: &http.Response{StatusCode: http.StatusForbidden}}
275 tc.MockJobs.EXPECT().
276 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
277 Return(nil, forbiddenResponse, assert.AnError)
278 },
279 },
280 {
281 name: "when getJobId with pipelineId is requested, ask for job and answer",
282 jobName: "",
283 pipelineId: 123,
284 expectedOut: 1122,
285 console: func(t *testing.T) *ugh.Console {
286 t.Helper()
288 c := ugh.New(t)
289 c.Expect(ugh.Select("Select pipeline job to trace:")).
290 Do(ugh.SelectIndex(0))
291 return c
292 },
293 setupMock: func(tc *gitlabtesting.TestClient) {
294 tc.MockJobs.EXPECT().
295 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
296 Return([]*gitlab.Job{
297 {ID: 1122, Name: "lint", Status: "failed"},
298 {ID: 1124, Name: "publish", Status: "failed"},
299 }, lastPageResponse, nil)
300 },
301 },
302 }
304 for _, tc := range tests {
305 t.Run(tc.name, func(t *testing.T) {
306 t.Parallel()
308 testClient := gitlabtesting.NewTestClient(t)
309 tc.setupMock(testClient)
311 factoryOpts := []cmdtest.FactoryOption{
312 cmdtest.WithGitLabClient(testClient.Client),
313 cmdtest.WithBranch("main"),
314 }
316 var ios *iostreams.IOStreams
317 if tc.console != nil {
318 var cleanup func()
319 ios, cleanup = cmdtest.TestIOStreamsWithConsole(t, tc.console(t))
320 t.Cleanup(cleanup)
321 } else {
322 ios, _, _, _ = cmdtest.TestIOStreams()
323 }
324 f := cmdtest.NewTestFactory(ios, factoryOpts...)
326 client, _ := f.GitLabClient()
327 repo, _ := f.BaseRepo()
329 output, err := GetJobId(t.Context(), &JobInputs{
330 JobName: tc.jobName,
331 PipelineId: tc.pipelineId,
332 Branch: "main",
333 }, &JobOptions{
334 IO: f.IO(),
335 Repo: repo,
336 Client: client,
337 })
339 if tc.expectedError == "" {
340 require.NoError(t, err)
341 } else {
342 require.Error(t, err)
343 assert.Contains(t, err.Error(), tc.expectedError)
344 }
345 assert.Equal(t, tc.expectedOut, output)
346 })
347 }
348}
350func TestGetJobIdInteractivePaginates(t *testing.T) {
351 t.Parallel()
353 testClient := gitlabtesting.NewTestClient(t)
354 nextPageResponse := &gitlab.Response{
355 Response: &http.Response{StatusCode: http.StatusOK},
356 NextPage: 2,
357 }
358 lastPageResponse := &gitlab.Response{
359 Response: &http.Response{StatusCode: http.StatusOK},
360 }
361 var requestedPages []string
362 testClient.MockJobs.EXPECT().
363 ListPipelineJobs("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
364 Times(2).
365 DoAndReturn(func(_ any, _ int64, _ *gitlab.ListJobsOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Job, *gitlab.Response, error) {
366 req, err := retryablehttp.NewRequest(http.MethodGet, "https://gitlab.com", nil)
367 require.NoError(t, err)
368 for _, option := range options {
369 if option != nil {
370 require.NoError(t, option(req))
371 }
372 }
374 requestedPages = append(requestedPages, req.URL.Query().Get("page"))
375 if len(requestedPages) == 1 {
376 return []*gitlab.Job{{ID: 1122, Name: "lint", Status: "failed"}}, nextPageResponse, nil
377 }
378 return []*gitlab.Job{{ID: 1144, Name: "deploy", Status: "success"}}, lastPageResponse, nil
379 })
381 console := ugh.New(t)
382 console.Expect(ugh.Select("Select pipeline job to trace:")).
383 Do(ugh.SelectIndex(1))
384 ios, cleanup := cmdtest.TestIOStreamsWithConsole(t, console)
385 t.Cleanup(cleanup)
386 f := cmdtest.NewTestFactory(ios,
387 cmdtest.WithGitLabClient(testClient.Client),
388 cmdtest.WithBranch("main"),
389 )
390 client, err := f.GitLabClient()
391 require.NoError(t, err)
392 repo, err := f.BaseRepo()
393 require.NoError(t, err)
395 jobID, err := GetJobId(t.Context(), &JobInputs{
396 PipelineId: 123,
397 Branch: "main",
398 }, &JobOptions{
399 IO: f.IO(),
400 Repo: repo,
401 Client: client,
402 })
404 require.NoError(t, err)
405 assert.Equal(t, int64(1144), jobID)
406 assert.Equal(t, []string{"", "2"}, requestedPages)
407}
409func TestParseCSVToIntSlice(t *testing.T) {
410 t.Parallel()
412 tests := []struct {
413 name string
414 input string
415 expectedOut []int
416 }{
417 {
418 name: "when input is empty",
419 input: "",
420 expectedOut: nil,
421 },
422 {
423 name: "when input is a comma-separated string",
424 input: "111,222,333",
425 expectedOut: []int{111, 222, 333},
426 },
427 {
428 name: "when input is a space-separated string",
429 input: "111 222 333 4444",
430 expectedOut: []int{111, 222, 333, 4444},
431 },
432 {
433 name: "when input is a space-separated and comma-separated string",
434 input: "111, 222, 333, 4444",
435 expectedOut: []int{111, 222, 333, 4444},
436 },
437 }
439 for _, tc := range tests {
440 t.Run(tc.name, func(t *testing.T) {
441 t.Parallel()
443 // Simulate splitting raw input
444 args := strings.Fields(tc.input)
446 output, err := IDsFromArgs(args)
447 if err != nil {
448 require.NoError(t, err)
449 }
451 assert.Equal(t, tc.expectedOut, output)
452 })
453 }
454}
456func TestTraceJob(t *testing.T) {
457 t.Parallel()
458 type testCase struct {
459 name string
460 jobName string
461 pipelineId int
462 setupMock func(tc *gitlabtesting.TestClient)
463 expectedError string
464 }
466 tests := []testCase{
467 {
468 name: "when traceJob is requested",
469 jobName: "1122",
470 setupMock: func(tc *gitlabtesting.TestClient) {
471 tc.MockJobs.EXPECT().
472 GetJob("OWNER/REPO", int64(1122), gomock.Any()).
473 Return(&gitlab.Job{
474 ID: 1122,
475 Name: "lint",
476 Status: "success",
477 }, nil, nil)
479 tc.MockJobs.EXPECT().
480 GetTraceFile("OWNER/REPO", int64(1122), gomock.Any()).
481 Return(bytes.NewReader([]byte("Lorem ipsum")), nil, nil)
482 },
483 },
484 {
485 name: "when the job was canceled",
486 jobName: "1122",
487 setupMock: func(tc *gitlabtesting.TestClient) {
488 // The API reports this state as "canceled". A single GetJob call
489 // is expected: the trace loop has to stop once it sees it.
490 tc.MockJobs.EXPECT().
491 GetJob("OWNER/REPO", int64(1122), gomock.Any()).
492 Return(&gitlab.Job{
493 ID: 1122,
494 Name: "lint",
495 Status: "canceled",
496 }, nil, nil)
498 tc.MockJobs.EXPECT().
499 GetTraceFile("OWNER/REPO", int64(1122), gomock.Any()).
500 Return(bytes.NewReader([]byte("Job canceled")), nil, nil)
501 },
502 },
503 {
504 name: "when traceJob is requested and getJob throws error",
505 jobName: "1122",
506 expectedError: "failed to find job:",
507 setupMock: func(tc *gitlabtesting.TestClient) {
508 forbiddenResponse := &gitlab.Response{Response: &http.Response{StatusCode: http.StatusForbidden}}
509 tc.MockJobs.EXPECT().
510 GetJob("OWNER/REPO", int64(1122), gomock.Any()).
511 Return(nil, forbiddenResponse, assert.AnError)
512 },
513 },
514 {
515 name: "when traceJob is requested and trace job throws error",
516 jobName: "1122",
517 expectedError: "failed to find job:",
518 setupMock: func(tc *gitlabtesting.TestClient) {
519 tc.MockJobs.EXPECT().
520 GetJob("OWNER/REPO", int64(1122), gomock.Any()).
521 Return(&gitlab.Job{
522 ID: 1122,
523 Name: "lint",
524 Status: "success",
525 }, nil, nil)
527 forbiddenResponse := &gitlab.Response{Response: &http.Response{StatusCode: http.StatusForbidden}}
528 tc.MockJobs.EXPECT().
529 GetTraceFile("OWNER/REPO", int64(1122), gomock.Any()).
530 Return(nil, forbiddenResponse, assert.AnError)
531 },
532 },
533 }
535 for _, tc := range tests {
536 t.Run(tc.name, func(t *testing.T) {
537 t.Parallel()
539 testClient := gitlabtesting.NewTestClient(t)
540 tc.setupMock(testClient)
542 ios, _, _, _ := cmdtest.TestIOStreams()
543 f := cmdtest.NewTestFactory(ios,
544 cmdtest.WithGitLabClient(testClient.Client),
545 cmdtest.WithBranch("main"),
546 )
548 client, _ := f.GitLabClient()
549 repo, _ := f.BaseRepo()
551 err := TraceJob(t.Context(), &JobInputs{
552 JobName: tc.jobName,
553 PipelineId: tc.pipelineId,
554 Branch: "main",
555 }, &JobOptions{
556 IO: f.IO(),
557 Repo: repo,
558 Client: client,
559 PollInterval: time.Millisecond,
560 })
562 if tc.expectedError == "" {
563 require.NoError(t, err)
564 } else {
565 require.Error(t, err)
566 assert.Contains(t, err.Error(), tc.expectedError)
567 }
568 })
569 }
570}
572func TestRunTraceJob(t *testing.T) {
573 t.Parallel()
575 t.Run("traces the requested job ID in a string-identified project", func(t *testing.T) {
576 t.Parallel()
578 tc := gitlabtesting.NewTestClient(t)
579 tc.MockJobs.EXPECT().
580 GetJob("OWNER/REPO", int64(4242)).
581 Return(&gitlab.Job{ID: 4242, Name: "lint", Status: "success"}, nil, nil)
582 tc.MockJobs.EXPECT().
583 GetTraceFile("OWNER/REPO", int64(4242), gomock.Any()).
584 Return(bytes.NewReader([]byte("parent trace")), nil, nil)
586 var out bytes.Buffer
587 err := RunTraceJob(t.Context(), tc.Client, &out, "OWNER/REPO", 4242, time.Millisecond)
589 require.NoError(t, err)
590 assert.Contains(t, out.String(), "parent trace")
591 })
593 t.Run("stops after reporting a skipped job once", func(t *testing.T) {
594 t.Parallel()
596 tc := gitlabtesting.NewTestClient(t)
597 tc.MockJobs.EXPECT().
598 GetJob("OWNER/REPO", int64(4243)).
599 Return(&gitlab.Job{ID: 4243, Name: "deploy", Status: "skipped"}, nil, nil)
601 var out bytes.Buffer
602 err := RunTraceJob(t.Context(), tc.Client, &out, "OWNER/REPO", 4243, time.Millisecond)
604 require.NoError(t, err)
605 assert.Equal(t, 1, strings.Count(out.String(), "deploy has been skipped."))
606 assert.NotContains(t, out.String(), "Showing logs for")
607 })
609 t.Run("traces a job in a numerically-identified downstream project", func(t *testing.T) {
610 t.Parallel()
612 // A child pipeline's project arrives as a numeric ID, not "owner/repo".
613 tc := gitlabtesting.NewTestClient(t)
614 tc.MockJobs.EXPECT().
615 GetJob(int64(777), int64(99)).
616 Return(&gitlab.Job{ID: 99, Name: "lint", Status: "success"}, nil, nil)
617 tc.MockJobs.EXPECT().
618 GetTraceFile(int64(777), int64(99), gomock.Any()).
619 Return(bytes.NewReader([]byte("child trace")), nil, nil)
621 var out bytes.Buffer
622 err := RunTraceJob(t.Context(), tc.Client, &out, int64(777), 99, time.Millisecond)
624 require.NoError(t, err)
625 assert.Contains(t, out.String(), "child trace")
626 })
628 t.Run("returns the error when the job cannot be fetched", func(t *testing.T) {
629 t.Parallel()
631 tc := gitlabtesting.NewTestClient(t)
632 notFound := &gitlab.Response{Response: &http.Response{StatusCode: http.StatusNotFound}}
633 tc.MockJobs.EXPECT().
634 GetJob(int64(777), int64(99)).
635 Return(nil, notFound, assert.AnError)
637 var out bytes.Buffer
638 err := RunTraceJob(t.Context(), tc.Client, &out, int64(777), 99, time.Millisecond)
640 require.Error(t, err)
641 assert.Contains(t, err.Error(), "failed to find job:")
642 })
643}
645// TestGetDefaultBranch_HappyPath tests successful scenarios for GetDefaultBranch
646func TestGetDefaultBranch_HappyPath(t *testing.T) {
647 tests := []struct {
648 name string
649 defaultBranch string
650 expectedResult string
651 }{
652 {
653 name: "when API returns default branch",
654 defaultBranch: "develop",
655 expectedResult: "develop",
656 },
657 {
658 name: "when API returns main as default branch",
659 defaultBranch: "main",
660 expectedResult: "main",
661 },
662 {
663 name: "when API returns empty default branch",
664 defaultBranch: "",
665 expectedResult: "main",
666 },
667 }
669 for _, tc := range tests {
670 t.Run(tc.name, func(t *testing.T) {
671 testClient := gitlabtesting.NewTestClient(t)
673 project := &gitlab.Project{
674 DefaultBranch: tc.defaultBranch,
675 }
676 testClient.MockProjects.EXPECT().GetProject("OWNER/REPO", gomock.Any()).Return(project, nil, nil)
678 ios, _, _, _ := cmdtest.TestIOStreams()
679 f := cmdtest.NewTestFactory(ios,
680 cmdtest.WithGitLabClient(testClient.Client),
681 )
683 client, _ := f.GitLabClient()
684 repo, _ := f.BaseRepo()
685 result := GetDefaultBranch(repo, client)
686 require.Equal(t, tc.expectedResult, result)
687 })
688 }
689}
691// TestGetDefaultBranch_ErrorCases tests error scenarios for GetDefaultBranch
692func TestGetDefaultBranch_ErrorCases(t *testing.T) {
693 tests := []struct {
694 name string
695 factoryOptions []cmdtest.FactoryOption
696 expectMain bool
697 }{
698 {
699 name: "when BaseRepo fails",
700 factoryOptions: []cmdtest.FactoryOption{cmdtest.WithBaseRepoError(assert.AnError)},
701 expectMain: true,
702 },
703 {
704 name: "when GitLabClient fails",
705 factoryOptions: []cmdtest.FactoryOption{cmdtest.WithGitLabClientError(assert.AnError)},
706 expectMain: true,
707 },
708 }
710 for _, tc := range tests {
711 t.Run(tc.name, func(t *testing.T) {
712 ios, _, _, _ := cmdtest.TestIOStreams()
713 factory := cmdtest.NewTestFactory(ios, tc.factoryOptions...)
715 client, _ := factory.GitLabClient()
716 repo, _ := factory.BaseRepo()
718 // Run the test with the configured factory
719 result := GetDefaultBranch(repo, client)
720 require.Equal(t, "main", result)
721 })
722 }
723}
725// TestGetDefaultBranch_APIErrorCases tests API failure scenarios for GetDefaultBranch
726func TestGetDefaultBranch_APIErrorCases(t *testing.T) {
727 t.Run("when API call fails", func(t *testing.T) {
728 testClient := gitlabtesting.NewTestClient(t)
730 testClient.MockProjects.EXPECT().GetProject("OWNER/REPO", gomock.Any()).Return(nil, nil, assert.AnError)
732 ios, _, _, _ := cmdtest.TestIOStreams()
733 f := cmdtest.NewTestFactory(ios,
734 cmdtest.WithGitLabClient(testClient.Client),
735 )
737 client, _ := f.GitLabClient()
738 repo, _ := f.BaseRepo()
739 result := GetDefaultBranch(repo, client)
740 require.Equal(t, "main", result)
741 })
742}
744// TestGetBranch_HappyPath tests successful scenarios for GetBranch
745func TestGetBranch_HappyPath(t *testing.T) {
746 tests := []struct {
747 name string
748 specifiedBranch string
749 gitBranch string
750 apiDefaultBranch string
751 expectedResult string
752 }{
753 {
754 name: "when branch is specified",
755 specifiedBranch: "feature-branch",
756 expectedResult: "feature-branch",
757 },
758 {
759 name: "when no branch specified and git works",
760 gitBranch: "current-git-branch",
761 expectedResult: "current-git-branch",
762 },
763 {
764 name: "when no branch specified and git fails, uses API default",
765 apiDefaultBranch: "develop",
766 expectedResult: "develop",
767 },
768 }
770 for _, tc := range tests {
771 t.Run(tc.name, func(t *testing.T) {
772 testClient := gitlabtesting.NewTestClient(t)
774 if tc.apiDefaultBranch != "" {
775 project := &gitlab.Project{
776 DefaultBranch: tc.apiDefaultBranch,
777 }
778 testClient.MockProjects.EXPECT().GetProject("OWNER/REPO", gomock.Any()).Return(project, nil, nil)
779 }
781 ios, _, _, _ := cmdtest.TestIOStreams()
782 f := cmdtest.NewTestFactory(ios,
783 cmdtest.WithGitLabClient(testClient.Client),
784 )
786 if tc.gitBranch != "" {
787 f.BranchStub = func() (string, error) {
788 return tc.gitBranch, nil
789 }
790 } else if tc.apiDefaultBranch != "" {
791 f.BranchStub = func() (string, error) {
792 return "", assert.AnError
793 }
794 }
796 client, _ := f.GitLabClient()
797 repo, _ := f.BaseRepo()
798 result := GetBranch(tc.specifiedBranch, f.BranchStub, repo, client)
799 require.Equal(t, tc.expectedResult, result)
800 })
801 }
802}
804// TestGetBranch_ErrorFallback tests error scenarios that fallback to main
805func TestGetBranch_ErrorFallback(t *testing.T) {
806 t.Run("when no branch specified and git fails, falls back to main", func(t *testing.T) {
807 testClient := gitlabtesting.NewTestClient(t)
809 // Mock API failure
810 testClient.MockProjects.EXPECT().GetProject("OWNER/REPO", gomock.Any()).Return(nil, nil, assert.AnError)
812 ios, _, _, _ := cmdtest.TestIOStreams()
813 f := cmdtest.NewTestFactory(ios,
814 cmdtest.WithGitLabClient(testClient.Client),
815 )
817 f.BranchStub = func() (string, error) {
818 return "", assert.AnError
819 }
821 client, _ := f.GitLabClient()
822 repo, _ := f.BaseRepo()
823 result := GetBranch("", f.BranchStub, repo, client)
824 require.Equal(t, "main", result)
825 })
826}
Diagnostics8 git calls · 298 ms
CallStatusSizeTime0298 ms
discover200185 B3 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 · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=2 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
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
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit5 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=5 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:02001.8 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=1857 git.response.cache=HIT git.response.duration_ms=4 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:0200635 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=635 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=517b073a0d5c32bc4e93f86de74b31d60ff8cf03 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=635 git.pkt.payload.max=608 git.sideband.band1.bytes=608 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=608 git.pack.trailer=178abb9456d874b7fd38fa21ad5cf9ca3ebcccaaOpen pack map
fetchtree:0200137 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=279 git.response.bytes=137 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=4e47711142a3b290b5c9384e7f2ca8e270e94877 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=137 git.pkt.payload.max=110 git.sideband.band1.bytes=110 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=110 git.pack.trailer=4a0dd4754cdea3dd8d79d2ff79ba051fab60cf78Open pack map
fetch2004.1 KiB280 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=4237 git.response.cache=MISS git.response.duration_ms=280 git.fetch.wants=6f4c2c828878eed70f48bb815e1f1dabd8d934ab 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=4237 git.pkt.payload.max=4210 git.sideband.band1.bytes=4210 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
- a5e2ac272c73e6b0
- Request
- 972e1b49…
- 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