GitLabgitlab-org
cli
main
1//go:build !integration
3package view
5import (
6 "bytes"
7 "context"
8 "encoding/json"
9 "fmt"
10 "os/exec"
11 "regexp"
12 "testing"
13 "time"
15 "github.com/MakeNowJust/heredoc/v2"
16 "github.com/acarl005/stripansi"
17 "github.com/spf13/cobra"
18 "github.com/stretchr/testify/assert"
19 "github.com/stretchr/testify/require"
21 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
22 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
24 "gitlab.com/gitlab-org/cli/internal/api"
25 "gitlab.com/gitlab-org/cli/internal/cmdutils"
26 "gitlab.com/gitlab-org/cli/internal/commands/mr/mrutils"
27 "gitlab.com/gitlab-org/cli/internal/config"
28 "gitlab.com/gitlab-org/cli/internal/iostreams"
29 "gitlab.com/gitlab-org/cli/internal/run"
30 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
31 "gitlab.com/gitlab-org/cli/internal/utils"
32 "gitlab.com/gitlab-org/cli/test"
33)
35var (
36 f cmdutils.Factory
37 stdout *bytes.Buffer
38 stderr *bytes.Buffer
39 ioStreams *iostreams.IOStreams
40)
42var testConfig = config.NewFromString(heredoc.Doc(`
43 hosts:
44 gitlab.com:
45 username: monalisa
46 token: OTOKEN
47`))
49func TestMain(m *testing.M) {
50 ioStreams, _, stdout, stderr = cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(true))
51 client, _ := gitlab.NewClient("")
52 f = cmdtest.NewTestFactory(
53 ioStreams,
54 cmdtest.WithConfig(config.NewFromString(heredoc.Doc(`
55 hosts:
56 gitlab.com:
57 username: monalisa
58 token: OTOKEN
59 `))),
60 cmdtest.WithGitLabClient(client),
61 )
63 timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
64 api.GetMR = func(client *gitlab.Client, projectID any, mrID int64, opts *gitlab.GetMergeRequestsOptions) (*gitlab.MergeRequest, error) {
65 if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" {
66 return nil, fmt.Errorf("error expected")
67 }
69 // Use projectID directly instead of f.BaseRepo() to support per-test factories
70 repoPath, ok := projectID.(string)
71 if !ok {
72 return nil, fmt.Errorf("unexpected projectID type: %T", projectID)
73 }
75 return &gitlab.MergeRequest{
76 BasicMergeRequest: gitlab.BasicMergeRequest{
77 ID: mrID,
78 IID: mrID,
79 Title: "mrTitle",
80 Labels: gitlab.Labels{"test", "bug"},
81 State: "opened",
82 Description: "mrBody",
83 Author: &gitlab.BasicUser{
84 ID: mrID,
85 Name: "John Dev Wick",
86 Username: "jdwick",
87 },
88 Assignees: []*gitlab.BasicUser{
89 {
90 Username: "mona",
91 },
92 {
93 Username: "lisa",
94 },
95 },
96 Reviewers: []*gitlab.BasicUser{
97 {
98 Username: "lisa",
99 },
100 {
101 Username: "mona",
102 },
103 },
104 WebURL: fmt.Sprintf("https://gitlab.com/%s/-/merge_requests/%d", repoPath, mrID),
105 CreatedAt: &timer,
106 UserNotesCount: 2,
107 SourceBranch: "feature-branch",
108 TargetBranch: "main",
109 Milestone: &gitlab.Milestone{
110 Title: "MilestoneTitle",
111 },
112 },
113 }, nil
114 }
115 cmdtest.InitTest(m, "mr_view_test")
116}
118func TestMRView(t *testing.T) {
119 oldListAllDiscussions := mrutils.ListAllDiscussions
120 timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
121 mrutils.ListAllDiscussions = func(_ context.Context, client *gitlab.Client, projectID any, mrID int64, opts *gitlab.ListMergeRequestDiscussionsOptions) ([]*gitlab.Discussion, error) {
122 if projectID == "PROJECT_MR_WITH_EMPTY_NOTE" {
123 return []*gitlab.Discussion{}, nil
124 }
125 return []*gitlab.Discussion{
126 {
127 ID: "disc1",
128 IndividualNote: true,
129 Notes: []*gitlab.Note{
130 {
131 ID: 1,
132 Body: "Note Body",
133 Title: "Note Title",
134 Author: gitlab.NoteAuthor{
135 ID: 1,
136 Username: "johnwick",
137 Name: "John Wick",
138 },
139 System: false,
140 CreatedAt: &timer,
141 NoteableID: 0,
142 },
143 },
144 },
145 {
146 ID: "disc2",
147 IndividualNote: true,
148 Notes: []*gitlab.Note{
149 {
150 ID: 2,
151 Body: "Marked MR as ready",
152 Title: "",
153 Author: gitlab.NoteAuthor{
154 ID: 1,
155 Username: "johnwick",
156 Name: "John Wick",
157 },
158 System: true,
159 CreatedAt: &timer,
160 NoteableID: 0,
161 },
162 },
163 },
164 }, nil
165 }
167 t.Run("show", func(t *testing.T) {
168 client, _ := gitlab.NewClient("")
169 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
170 cmd := NewCmdView(f)
171 cmdutils.EnableRepoOverride(cmd, f)
172 return cmd
173 }, true,
174 cmdtest.WithConfig(testConfig),
175 cmdtest.WithGitLabClient(client),
176 )
178 result, err := exec("13 -c -s -R cli-automated-testing/test")
179 require.NoError(t, err)
181 out := stripansi.Strip(result.String())
182 outErr := stripansi.Strip(result.Stderr())
184 require.Contains(t, out, "mrTitle !13")
185 require.Contains(t, out, "@jdwick opened")
186 require.Contains(t, out, "merge: feature-branch → main")
187 require.Empty(t, outErr)
188 assert.Contains(t, out, "https://gitlab.com/cli-automated-testing/test/-/merge_requests/13")
189 assert.Contains(t, out, "johnwick Marked MR as ready")
190 assert.NotContains(t, out, "[discussion:")
191 })
193 t.Run("no_tty", func(t *testing.T) {
194 client, _ := gitlab.NewClient("")
195 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
196 cmd := NewCmdView(f)
197 cmdutils.EnableRepoOverride(cmd, f)
198 return cmd
199 }, false, // non-TTY
200 cmdtest.WithConfig(testConfig),
201 cmdtest.WithGitLabClient(client),
202 )
204 result, err := exec("13 -c -s -R cli-automated-testing/test")
205 require.NoError(t, err)
207 out := stripansi.Strip(result.String())
208 outErr := stripansi.Strip(result.Stderr())
210 expectedOutputs := []string{
211 `title:\tmrTitle`,
212 `assignees:\tmona, lisa`,
213 `reviewers:\tlisa, mona`,
214 `author:\tjdwick`,
215 `state:\topen`,
216 `comments:\t2`,
217 `labels:\ttest, bug`,
218 `milestone:\tMilestoneTitle\n`,
219 `source_branch:\tfeature-branch`,
220 `target_branch:\tmain`,
221 `--`,
222 `mrBody`,
223 }
225 assert.Empty(t, outErr)
226 t.Helper()
227 var r *regexp.Regexp
228 for _, l := range expectedOutputs {
229 r = regexp.MustCompile(l)
230 if !r.MatchString(out) {
231 t.Errorf("output did not match regexp /%s/\n> output\n%s\n", r, out)
232 return
233 }
234 }
235 })
236 mrutils.ListAllDiscussions = oldListAllDiscussions
237}
239func Test_rawMRPreview(t *testing.T) {
240 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
241 t.Setenv("NO_COLOR", "true")
243 fakeNote1 := &gitlab.Note{}
244 fakeNote1.Author.Username = "bob"
245 fakeNote2 := &gitlab.Note{}
246 fakeNote2.Author.Username = "alice"
248 time1, _ := time.Parse(time.RFC3339, "2023-03-09T16:50:20.111Z")
249 time2, _ := time.Parse(time.RFC3339, "2023-03-09T16:52:30.222Z")
251 mr := &gitlab.MergeRequest{
252 BasicMergeRequest: gitlab.BasicMergeRequest{
253 IID: 503,
254 Title: "MR title",
255 Description: "MR description",
256 State: "merged",
257 Author: &gitlab.BasicUser{Username: "alice"},
258 Labels: gitlab.Labels{"label1", "label2"},
259 Assignees: []*gitlab.BasicUser{{Username: "alice"}, {Username: "bob"}},
260 Reviewers: []*gitlab.BasicUser{{Username: "john"}, {Username: "paul"}},
261 UserNotesCount: 2,
262 Milestone: &gitlab.Milestone{Title: "Some milestone"},
263 SourceBranch: "topic",
264 TargetBranch: "main",
265 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/503",
266 },
267 }
269 discussions := []*gitlab.Discussion{
270 {
271 ID: "disc1",
272 IndividualNote: true,
273 Notes: []*gitlab.Note{
274 {
275 System: true,
276 Author: fakeNote1.Author,
277 Body: "assigned to @alice",
278 CreatedAt: &time1,
279 },
280 },
281 },
282 {
283 ID: "disc2",
284 IndividualNote: true,
285 Notes: []*gitlab.Note{
286 {
287 ID: 100,
288 System: false,
289 Author: fakeNote1.Author,
290 Body: "Some comment",
291 CreatedAt: &time1,
292 },
293 },
294 },
295 {
296 ID: "disc3",
297 IndividualNote: true,
298 Notes: []*gitlab.Note{
299 {
300 ID: 200,
301 System: false,
302 Author: fakeNote2.Author,
303 Body: "Another comment",
304 CreatedAt: &time2,
305 },
306 },
307 },
308 }
310 conflictingMR := *mr
311 conflictingMR.HasConflicts = true
313 // The raw preview is only produced for non-TTY output, so render bodies verbatim.
314 ioStreams, _, _, _ = cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(false))
316 tests := []struct {
317 name string
318 opts *options
319 mr *gitlab.MergeRequest
320 discussions []*gitlab.Discussion
321 want []string
322 notWant []string
323 }{
324 {
325 "mr_default",
326 &options{
327 io: ioStreams,
328 },
329 mr,
330 discussions,
331 []string{
332 "title:\tMR title",
333 "state:\tmerged",
334 "author:\talice",
335 "labels:\tlabel1, label2",
336 "assignees:\talice, bob",
337 "reviewers:\tjohn, paul",
338 "source_branch:\ttopic",
339 "target_branch:\tmain",
340 "conflicts:\tfalse",
341 "comments:\t2",
342 "milestone:\tSome milestone",
343 "number:\t503",
344 "url:\thttps://gitlab.com/OWNER/REPO/-/merge_requests/503",
345 "--",
346 "MR description",
347 },
348 nil,
349 },
350 {
351 "mr_with_conflicts",
352 &options{io: ioStreams},
353 &conflictingMR,
354 nil,
355 []string{"conflicts:\ttrue"},
356 nil,
357 },
358 {
359 "mr_show_comments_no_comments",
360 &options{
361 io: ioStreams,
362 showComments: true,
363 showSystemLogs: true,
364 },
365 mr,
366 []*gitlab.Discussion{},
367 []string{
368 "title:\tMR title",
369 "state:\tmerged",
370 "author:\talice",
371 "labels:\tlabel1, label2",
372 "assignees:\talice, bob",
373 "reviewers:\tjohn, paul",
374 "source_branch:\ttopic",
375 "target_branch:\tmain",
376 "comments:\t2",
377 "milestone:\tSome milestone",
378 "number:\t503",
379 "url:\thttps://gitlab.com/OWNER/REPO/-/merge_requests/503",
380 "--",
381 "MR description",
382 "This merge request has no comments.",
383 },
384 nil,
385 },
386 {
387 "mr_with_comments_and_notes",
388 &options{
389 io: ioStreams,
390 showComments: true,
391 showSystemLogs: true,
392 },
393 mr,
394 discussions,
395 []string{
396 "title:\tMR title",
397 "state:\tmerged",
398 "author:\talice",
399 "labels:\tlabel1, label2",
400 "assignees:\talice, bob",
401 "reviewers:\tjohn, paul",
402 "source_branch:\ttopic",
403 "target_branch:\tmain",
404 "comments:\t2",
405 "milestone:\tSome milestone",
406 "number:\t503",
407 "url:\thttps://gitlab.com/OWNER/REPO/-/merge_requests/503",
408 "--",
409 "MR description",
410 "@bob assigned to @alice",
411 "@bob commented",
412 "[note #100]",
413 "Some comment",
414 "@alice commented",
415 "[note #200]",
416 "Another comment",
417 },
418 []string{"[discussion:"},
419 },
420 }
422 for _, tt := range tests {
423 t.Run(tt.name, func(t *testing.T) {
424 got := rawMRPreview(tt.opts, tt.mr, tt.discussions)
425 for _, want := range tt.want {
426 assert.Contains(t, got, want)
427 }
428 for _, notWant := range tt.notWant {
429 assert.NotContains(t, got, notWant)
430 }
431 })
432 }
434 for _, status := range []string{"unchecked", "checking", "preparing"} {
435 t.Run(status, func(t *testing.T) {
436 pendingMR := *mr
437 pendingMR.State = "opened"
438 pendingMR.DetailedMergeStatus = status
440 got := rawMRPreview(&options{io: ioStreams}, &pendingMR, nil)
441 assert.Contains(t, got, "conflicts:\tunknown\n")
442 assert.NotContains(t, got, "conflicts:\tfalse\n")
443 })
444 }
445}
447func Test_labelsList(t *testing.T) {
448 tests := []struct {
449 name string
450 mr *gitlab.MergeRequest
451 want string
452 }{
453 {
454 "no labels",
455 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
456 Labels: gitlab.Labels{},
457 }},
458 "",
459 },
460 {
461 "one label",
462 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
463 Labels: gitlab.Labels{"label1"},
464 }},
465 "label1",
466 },
467 {
468 "two labels",
469 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
470 Labels: gitlab.Labels{"label1", "label2"},
471 }},
472 "label1, label2",
473 },
474 }
476 for _, test := range tests {
477 t.Run(test.name, func(t *testing.T) {
478 got := labelsList(test.mr)
480 if test.want != got {
481 t.Errorf(`want "%s"; got "%s"`, test.want, got)
482 }
483 })
484 }
485}
487func Test_assigneesList(t *testing.T) {
488 tests := []struct {
489 name string
490 mr *gitlab.MergeRequest
491 want string
492 }{
493 {
494 "no assignee",
495 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
496 Assignees: []*gitlab.BasicUser{},
497 }},
498 "",
499 },
500 {
501 "one assignee",
502 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
503 Assignees: []*gitlab.BasicUser{{Username: "Alice"}},
504 }},
505 "Alice",
506 },
507 {
508 "two assignees",
509 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
510 Assignees: []*gitlab.BasicUser{{Username: "Alice"}, {Username: "Bob"}},
511 }},
512 "Alice, Bob",
513 },
514 }
516 for _, test := range tests {
517 t.Run(test.name, func(t *testing.T) {
518 got := assigneesList(test.mr)
520 if test.want != got {
521 t.Errorf(`want "%s"; got "%s"`, test.want, got)
522 }
523 })
524 }
525}
527func Test_reviewersList(t *testing.T) {
528 tests := []struct {
529 name string
530 mr *gitlab.MergeRequest
531 want string
532 }{
533 {
534 "no assignee",
535 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
536 Reviewers: []*gitlab.BasicUser{},
537 }},
538 "",
539 },
540 {
541 "one assignee",
542 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
543 Reviewers: []*gitlab.BasicUser{{Username: "Alice"}},
544 }},
545 "Alice",
546 },
547 {
548 "two assignees",
549 &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{
550 Reviewers: []*gitlab.BasicUser{{Username: "Alice"}, {Username: "Bob"}},
551 }},
552 "Alice, Bob",
553 },
554 }
556 for _, test := range tests {
557 t.Run(test.name, func(t *testing.T) {
558 got := reviewersList(test.mr)
560 if test.want != got {
561 t.Errorf(`want "%s"; got "%s"`, test.want, got)
562 }
563 })
564 }
565}
567func TestMrViewJSON(t *testing.T) {
568 client, _ := gitlab.NewClient("")
569 exec := cmdtest.SetupCmdForTest(t, NewCmdView, false,
570 cmdtest.WithConfig(testConfig),
571 cmdtest.WithGitLabClient(client),
572 )
574 output, err := exec("1 -F json")
575 require.NoError(t, err)
577 assert.True(t, json.Valid([]byte(output.String())))
578 assert.Empty(t, output.Stderr())
579}
581func TestMRView_requestsPerOutputMode(t *testing.T) {
582 tests := []struct {
583 name string
584 cli string
585 isTTY bool
586 wantGetOpts *gitlab.GetMergeRequestsOptions
587 wantApprovalCall bool
588 }{
589 {
590 name: "tty",
591 cli: "13 -R OWNER/REPO",
592 isTTY: true,
593 wantApprovalCall: true,
594 },
595 {
596 name: "raw",
597 cli: "13 -R OWNER/REPO",
598 isTTY: false,
599 },
600 {
601 name: "json in tty",
602 cli: "13 -F json -R OWNER/REPO",
603 isTTY: true,
604 wantGetOpts: &gitlab.GetMergeRequestsOptions{
605 IncludeDivergedCommitsCount: new(true),
606 RenderHTML: new(true),
607 IncludeRebaseInProgress: new(true),
608 },
609 },
610 {
611 name: "json",
612 cli: "13 -F json -R OWNER/REPO",
613 isTTY: false,
614 wantGetOpts: &gitlab.GetMergeRequestsOptions{
615 IncludeDivergedCommitsCount: new(true),
616 RenderHTML: new(true),
617 IncludeRebaseInProgress: new(true),
618 },
619 },
620 }
622 for _, tt := range tests {
623 t.Run(tt.name, func(t *testing.T) {
624 var gotGetOpts *gitlab.GetMergeRequestsOptions
625 oldGetMR := api.GetMR
626 api.GetMR = func(client *gitlab.Client, projectID any, mrID int64, opts *gitlab.GetMergeRequestsOptions) (*gitlab.MergeRequest, error) {
627 gotGetOpts = opts
628 return oldGetMR(client, projectID, mrID, opts)
629 }
630 t.Cleanup(func() { api.GetMR = oldGetMR })
632 tc := gitlabtesting.NewTestClient(t)
633 if tt.wantApprovalCall {
634 tc.MockMergeRequestApprovals.EXPECT().
635 GetApprovalState("OWNER/REPO", int64(13)).
636 Return(&gitlab.MergeRequestApprovalState{}, nil, nil)
637 }
639 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
640 cmd := NewCmdView(f)
641 cmdutils.EnableRepoOverride(cmd, f)
642 return cmd
643 }, tt.isTTY,
644 cmdtest.WithConfig(testConfig),
645 cmdtest.WithGitLabClient(tc.Client),
646 )
648 _, err := exec(tt.cli)
649 require.NoError(t, err)
651 assert.Equal(t, tt.wantGetOpts, gotGetOpts)
652 })
653 }
654}
656func Test_printTTYMRPreview_closedMRWithNilClosedBy(t *testing.T) {
657 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
658 t.Setenv("NO_COLOR", "true")
660 ioStreams, _, stdout, _ := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(true))
662 createdTime, _ := time.Parse(time.RFC3339, "2024-01-01T12:00:00Z")
664 mr := &gitlab.MergeRequest{
665 BasicMergeRequest: gitlab.BasicMergeRequest{
666 IID: 505,
667 Title: "Test closed MR",
668 Description: "Test description",
669 State: "closed", // Now test closed MR with nil ClosedBy
670 Author: &gitlab.BasicUser{Username: "testuser"},
671 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/505",
672 CreatedAt: &createdTime,
673 ClosedBy: nil,
674 },
675 }
677 opts := &options{
678 io: ioStreams,
679 showComments: false,
680 showSystemLogs: false,
681 }
683 // This should not panic - the bug would cause a nil pointer dereference here
684 printTTYMRPreview(opts, mr, nil, []*gitlab.Discussion{})
685 output := stdout.String()
687 // Verify that it contains "Closed" but not "Closed by:" since ClosedBy is nil
688 assert.Contains(t, output, "Closed")
689 assert.NotContains(t, output, "Closed by:")
690}
692func Test_printTTYMRPreview_mergedBy(t *testing.T) {
693 createdAt, err := time.Parse(time.RFC3339, "2024-01-01T12:00:00Z")
694 require.NoError(t, err)
695 mergedAt := createdAt.Add(24 * time.Hour)
697 tests := []struct {
698 name string
699 state string
700 mergeUser *gitlab.BasicUser
701 noMergedAt bool
702 want string
703 }{
704 {
705 name: "merged with a merge user",
706 state: "merged",
707 mergeUser: &gitlab.BasicUser{Name: "Jane Doe", Username: "jdoe"},
708 want: "The changes were merged into main by Jane Doe",
709 },
710 {
711 name: "merged without a merge user",
712 state: "merged",
713 },
714 {
715 name: "merged with a merge user but no merge time",
716 state: "merged",
717 mergeUser: &gitlab.BasicUser{Name: "Jane Doe", Username: "jdoe"},
718 noMergedAt: true,
719 },
720 {
721 name: "open with an auto-merge user",
722 state: "opened",
723 mergeUser: &gitlab.BasicUser{Name: "Jane Doe", Username: "jdoe"},
724 },
725 }
727 for _, tt := range tests {
728 t.Run(tt.name, func(t *testing.T) {
729 ioStreams, _, stdout, _ := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(true))
731 var mergedAtPtr *time.Time
732 if !tt.noMergedAt {
733 mergedAtPtr = &mergedAt
734 }
736 mr := &gitlab.MergeRequest{
737 BasicMergeRequest: gitlab.BasicMergeRequest{
738 IID: 506,
739 Title: "Test merged MR",
740 State: tt.state,
741 Author: &gitlab.BasicUser{Username: "testuser"},
742 TargetBranch: "main",
743 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/506",
744 CreatedAt: &createdAt,
745 MergeUser: tt.mergeUser,
746 MergedAt: mergedAtPtr,
747 },
748 }
750 printTTYMRPreview(&options{io: ioStreams}, mr, nil, []*gitlab.Discussion{})
752 output := stripansi.Strip(stdout.String())
753 if tt.want == "" {
754 assert.NotContains(t, output, "The changes were merged")
755 return
756 }
757 assert.Contains(t, output, tt.want)
758 })
759 }
760}
762func Test_filterDiscussionsByResolution(t *testing.T) {
763 timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
765 tests := []struct {
766 name string
767 discussions []*gitlab.Discussion
768 state string
769 wantCount int
770 wantIDs []string
771 }{
772 {
773 name: "filter resolved discussions",
774 discussions: []*gitlab.Discussion{
775 {
776 ID: "disc1",
777 IndividualNote: false,
778 Notes: []*gitlab.Note{
779 {ID: 1, Resolvable: true, Resolved: true, CreatedAt: &timer},
780 {ID: 2, Resolvable: true, Resolved: true, CreatedAt: &timer},
781 },
782 },
783 {
784 ID: "disc2",
785 IndividualNote: false,
786 Notes: []*gitlab.Note{
787 {ID: 3, Resolvable: true, Resolved: false, CreatedAt: &timer},
788 },
789 },
790 {
791 ID: "disc3",
792 IndividualNote: true,
793 Notes: []*gitlab.Note{
794 {ID: 4, Resolvable: false, Resolved: false, CreatedAt: &timer},
795 },
796 },
797 },
798 state: "resolved",
799 wantCount: 1,
800 wantIDs: []string{"disc1"},
801 },
802 {
803 name: "filter unresolved discussions",
804 discussions: []*gitlab.Discussion{
805 {
806 ID: "disc1",
807 IndividualNote: false,
808 Notes: []*gitlab.Note{
809 {ID: 1, Resolvable: true, Resolved: true, CreatedAt: &timer},
810 {ID: 2, Resolvable: true, Resolved: true, CreatedAt: &timer},
811 },
812 },
813 {
814 ID: "disc2",
815 IndividualNote: false,
816 Notes: []*gitlab.Note{
817 {ID: 3, Resolvable: true, Resolved: false, CreatedAt: &timer},
818 },
819 },
820 {
821 ID: "disc3",
822 IndividualNote: false,
823 Notes: []*gitlab.Note{
824 {ID: 4, Resolvable: true, Resolved: true, CreatedAt: &timer},
825 {ID: 5, Resolvable: true, Resolved: false, CreatedAt: &timer},
826 },
827 },
828 },
829 state: "unresolved",
830 wantCount: 2,
831 wantIDs: []string{"disc2", "disc3"},
832 },
833 {
834 name: "exclude non-resolvable discussions",
835 discussions: []*gitlab.Discussion{
836 {
837 ID: "disc1",
838 IndividualNote: true,
839 Notes: []*gitlab.Note{
840 {ID: 1, Resolvable: false, Resolved: false, CreatedAt: &timer},
841 },
842 },
843 {
844 ID: "disc2",
845 IndividualNote: false,
846 Notes: []*gitlab.Note{
847 {ID: 2, Resolvable: true, Resolved: true, CreatedAt: &timer},
848 },
849 },
850 },
851 state: "resolved",
852 wantCount: 1,
853 wantIDs: []string{"disc2"},
854 },
855 }
857 for _, tt := range tests {
858 t.Run(tt.name, func(t *testing.T) {
859 got := mrutils.FilterDiscussions(tt.discussions, mrutils.FilterOpts{State: tt.state})
860 require.Len(t, got, tt.wantCount)
862 gotIDs := []string{}
863 for _, d := range got {
864 gotIDs = append(gotIDs, d.ID)
865 }
866 assert.Equal(t, tt.wantIDs, gotIDs)
867 })
868 }
869}
871func TestMRViewWeb(t *testing.T) {
872 tests := []struct {
873 name string
874 cli string
875 wantURL string
876 wantGetMRCalls int
877 wantBranchLookups int
878 }{
879 {
880 name: "by branch, resolved from the list response",
881 cli: "-w -R cli-automated-testing/test",
882 // The web URL comes from the branch lookup, so the merge request
883 // itself is never fetched.
884 wantURL: "https://gitlab.com/cli-automated-testing/test/-/merge_requests/42",
885 wantGetMRCalls: 0,
886 wantBranchLookups: 1,
887 },
888 {
889 name: "by ID",
890 cli: "13 -w -R cli-automated-testing/test",
891 wantURL: "https://gitlab.com/cli-automated-testing/test/-/merge_requests/13",
892 wantGetMRCalls: 1,
893 wantBranchLookups: 0,
894 },
895 }
897 for _, tt := range tests {
898 t.Run(tt.name, func(t *testing.T) {
899 var getMRCalls, branchLookups int
901 oldGetMR := api.GetMR
902 api.GetMR = func(client *gitlab.Client, projectID any, mrID int64, opts *gitlab.GetMergeRequestsOptions) (*gitlab.MergeRequest, error) {
903 getMRCalls++
904 return oldGetMR(client, projectID, mrID, opts)
905 }
906 t.Cleanup(func() { api.GetMR = oldGetMR })
908 oldGetMRForBranch := mrutils.GetMRForBranch
909 mrutils.GetMRForBranch = func(_ context.Context, _ *iostreams.IOStreams, _ *gitlab.Client, mrOpts mrutils.MrOptions) (*gitlab.BasicMergeRequest, error) {
910 branchLookups++
911 return &gitlab.BasicMergeRequest{
912 IID: 42,
913 WebURL: fmt.Sprintf("https://gitlab.com/%s/-/merge_requests/42", mrOpts.BaseRepo.FullName()),
914 }, nil
915 }
916 t.Cleanup(func() { mrutils.GetMRForBranch = oldGetMRForBranch })
918 var browsedURL string
919 restoreCmd := run.SetPrepareCmd(func(cmd *exec.Cmd) run.Runnable {
920 browsedURL = cmd.Args[len(cmd.Args)-1]
921 return &test.OutputStub{}
922 })
923 defer restoreCmd()
925 client, _ := gitlab.NewClient("")
926 execCmd := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
927 cmd := NewCmdView(f)
928 cmdutils.EnableRepoOverride(cmd, f)
929 return cmd
930 }, true,
931 cmdtest.WithConfig(testConfig),
932 cmdtest.WithGitLabClient(client),
933 cmdtest.WithBranch("feature-branch"),
934 )
936 result, err := execCmd(tt.cli)
937 require.NoError(t, err)
939 assert.Equal(t, tt.wantURL, browsedURL)
940 assert.Contains(t, stripansi.Strip(result.Stderr()), "Opening "+utils.DisplayURL(tt.wantURL)+" in your browser.")
941 assert.Equal(t, tt.wantGetMRCalls, getMRCalls, "unexpected number of merge request fetches")
942 assert.Equal(t, tt.wantBranchLookups, branchLookups, "unexpected number of branch lookups")
943 })
944 }
945}
947func Test_mrPreview_timeTracking(t *testing.T) {
948 createdAt, _ := time.Parse(time.RFC3339, "2024-01-01T12:00:00Z")
950 tests := []struct {
951 name string
952 timeStats *gitlab.TimeStats
953 wantTTY []string
954 wantRaw []string
955 wantOmits []string
956 }{
957 {
958 name: "no time stats",
959 timeStats: nil,
960 wantOmits: []string{"Time tracking:", "time_estimate:", "time_spent:"},
961 },
962 {
963 name: "nothing tracked",
964 timeStats: &gitlab.TimeStats{},
965 wantOmits: []string{"Time tracking:", "time_estimate:", "time_spent:"},
966 },
967 {
968 name: "estimate only",
969 timeStats: &gitlab.TimeStats{HumanTimeEstimate: "2d", TimeEstimate: 57600},
970 wantTTY: []string{"Time tracking: 2d estimated\n"},
971 wantRaw: []string{"time_estimate:\t2d\n"},
972 wantOmits: []string{"spent", "time_spent:"},
973 },
974 {
975 name: "time spent and estimate",
976 timeStats: &gitlab.TimeStats{
977 HumanTotalTimeSpent: "1h 30m", TotalTimeSpent: 5400,
978 HumanTimeEstimate: "2d", TimeEstimate: 57600,
979 },
980 wantTTY: []string{"Time tracking: 1h 30m spent of 2d estimated\n"},
981 wantRaw: []string{"time_estimate:\t2d\n", "time_spent:\t1h 30m\n"},
982 },
983 }
985 for _, tt := range tests {
986 t.Run(tt.name, func(t *testing.T) {
987 ios, _, stdout, _ := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(true))
988 opts := &options{io: ios}
989 mr := &gitlab.MergeRequest{
990 BasicMergeRequest: gitlab.BasicMergeRequest{
991 IID: 505,
992 Title: "MR title",
993 State: "opened",
994 Author: &gitlab.BasicUser{Username: "alice"},
995 CreatedAt: &createdAt,
996 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/505",
997 TimeStats: tt.timeStats,
998 },
999 }
1001 printTTYMRPreview(opts, mr, nil, nil)
1002 tty := stripansi.Strip(stdout.String())
1003 raw := rawMRPreview(opts, mr, nil)
1005 for _, want := range tt.wantTTY {
1006 assert.Contains(t, tty, want)
1007 }
1008 for _, want := range tt.wantRaw {
1009 assert.Contains(t, raw, want)
1010 }
1011 for _, omit := range tt.wantOmits {
1012 assert.NotContains(t, tty, omit)
1013 assert.NotContains(t, raw, omit)
1014 }
1015 })
1016 }
1017}
Diagnostics8 git calls · 216 ms
CallStatusSizeTime0216 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs 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 · 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
fetchtree:0 · deepen 1020032 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=32926 git.response.cache=HIT git.response.duration_ms=2 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 · 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:02001.8 KiB · 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=1857 git.response.cache=HIT git.response.duration_ms=3 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:0200746 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=746 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=f3d413a22af5a9c2fe9aa49709b1cb36d1351a7f 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=746 git.pkt.payload.max=719 git.sideband.band1.bytes=719 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=719 git.pack.trailer=330baf80c59a4208b55120dff7dd824b7952b790Open pack map
fetchtree:0200138 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=138 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=00952a766b46b28c5923c4b7c7931d90f8e154a5 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=32847c375d27828204f822a8b513dfb0caa8a797Open pack map
fetch2005.7 KiB204 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=204 git.response.bytes=5830 git.response.cache=MISS git.response.duration_ms=204 git.fetch.wants=7167e3ed4971ef2b3e2f6f3e681b2ddebe98feae 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=5830 git.pkt.payload.max=5803 git.sideband.band1.bytes=5803 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
- a5e2e188284c4af4
- Request
- 5d1065c4…
- 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