GitLabgitlab-org

cli

main
ply8 git calls255 ms104 KiB6 cachedprotocol v2
1542 lines46 KiBRaw
1//go:build !integration
3package list
5import (
6 "bufio"
7 "fmt"
8 "net/http"
9 "os"
10 "regexp"
11 "slices"
12 "strconv"
13 "strings"
14 "testing"
15 "time"
17 "github.com/MakeNowJust/heredoc/v2"
18 "github.com/spf13/cobra"
19 "github.com/stretchr/testify/assert"
20 "github.com/stretchr/testify/require"
21 "go.uber.org/mock/gomock"
23 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
24 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
26 "gitlab.com/gitlab-org/cli/internal/api"
27 "gitlab.com/gitlab-org/cli/internal/cmdutils"
28 "gitlab.com/gitlab-org/cli/internal/commands/issuable"
29 "gitlab.com/gitlab-org/cli/internal/iostreams"
30 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
33func TestNewCmdList(t *testing.T) {
34 ios, _, _, _ := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(true))
36 // No API calls are made in this test since we provide a custom runFunc
37 factory := cmdtest.NewTestFactory(ios)
38 t.Run("Issue_NewCmdList", func(t *testing.T) {
39 gotOpts := &ListOptions{}
40 err := NewCmdList(factory, func(opts *ListOptions) error {
41 gotOpts = opts
42 return nil
43 }, issuable.TypeIssue).Execute()
45 require.NoError(t, err)
46 assert.Equal(t, factory.IO(), gotOpts.IO)
48 gotBaseRepo, _ := gotOpts.BaseRepo()
49 expectedBaseRepo, _ := factory.BaseRepo()
50 assert.Equal(t, expectedBaseRepo, gotBaseRepo)
51 })
54func TestNewCmdListHelpExamples(t *testing.T) {
55 for _, tc := range []struct {
56 name string
57 issueType issuable.IssueType
58 example string
59 }{
60 {name: "issue", issueType: issuable.TypeIssue, example: "glab issue list --milestone release-2.0.0"},
61 {name: "incident", issueType: issuable.TypeIncident, example: "glab incident list --milestone release-2.0.0"},
62 } {
63 t.Run(tc.name, func(t *testing.T) {
64 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
65 cmd := NewCmdList(f, nil, tc.issueType)
66 cmd.SetOut(f.IO().StdOut)
67 return cmd
68 }, false)
70 output, err := exec("--help")
71 require.NoError(t, err)
72 assert.Contains(t, output.String(), tc.example)
73 assert.NotContains(t, output.String(), "--opened")
74 })
75 }
78func TestMilestoneFlagHelpUsesTitle(t *testing.T) {
79 t.Parallel()
81 testCases := []struct {
82 name string
83 issueType issuable.IssueType
84 }{
85 {name: "issue", issueType: issuable.TypeIssue},
86 {name: "incident", issueType: issuable.TypeIncident},
87 }
89 for _, tc := range testCases {
90 t.Run(tc.name, func(t *testing.T) {
91 t.Parallel()
93 ios, _, stdout, _ := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(false))
94 cmd := NewCmdList(cmdtest.NewTestFactory(ios), nil, tc.issueType)
95 cmd.SetOut(stdout)
97 cmd.SetArgs([]string{"--help"})
98 err := cmd.Execute()
99 require.NoError(t, err)
100 assert.Contains(t, stdout.String(), fmt.Sprintf("Filter %s by milestone <title>.", tc.name))
101 })
102 }
105func TestIssueList_tty(t *testing.T) {
106 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
107 t.Setenv("NO_COLOR", "true")
109 testClient := gitlabtesting.NewTestClient(t)
111 createdAt := time.Date(2016, 1, 4, 15, 31, 51, 0, time.UTC)
112 incidentType := "incident"
114 testClient.MockIssues.EXPECT().
115 ListProjectIssues("OWNER/REPO", gomock.Any()).
116 Return([]*gitlab.Issue{
117 {
118 ID: 76,
119 IID: 6,
120 ProjectID: 1,
121 State: "opened",
122 Title: "Issue one",
123 Description: "a description here",
124 Labels: gitlab.Labels{"foo", "bar"},
125 WebURL: "http://gitlab.com/OWNER/REPO/issues/6",
126 CreatedAt: &createdAt,
127 References: &gitlab.IssueReferences{
128 Full: "OWNER/REPO/issues/6",
129 Relative: "#6",
130 Short: "#6",
131 },
132 },
133 {
134 ID: 77,
135 IID: 7,
136 ProjectID: 1,
137 State: "opened",
138 Title: "Issue two",
139 Description: "description two here",
140 Labels: gitlab.Labels{"fooz", "baz"},
141 WebURL: "http://gitlab.com/OWNER/REPO/issues/7",
142 CreatedAt: &createdAt,
143 References: &gitlab.IssueReferences{
144 Full: "OWNER/REPO/issues/7",
145 Relative: "#7",
146 Short: "#7",
147 },
148 },
149 {
150 ID: 78,
151 IID: 8,
152 ProjectID: 1,
153 State: "opened",
154 Title: "Incident",
155 Description: "description incident here",
156 Labels: gitlab.Labels{"foo", "baz"},
157 WebURL: "http://gitlab.com/OWNER/REPO/issues/8",
158 CreatedAt: &createdAt,
159 IssueType: &incidentType,
160 References: &gitlab.IssueReferences{
161 Full: "OWNER/REPO/issues/8",
162 Relative: "#8",
163 Short: "#8",
164 },
165 },
166 }, nil, nil)
168 // Create an api.Client with the mock GitLab client
169 apiClient, err := api.NewClient(
170 func(*http.Client) (gitlab.AuthSource, error) {
171 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
172 },
173 api.WithGitLabClient(testClient.Client),
174 )
175 require.NoError(t, err)
177 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
178 return NewCmdList(f, nil, issuable.TypeIssue)
179 }, true,
180 cmdtest.WithApiClient(apiClient),
181 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
182 )
184 output, err := exec("")
185 if err != nil {
186 t.Errorf("error running command `issue list`: %v", err)
187 }
189 out := output.String()
190 timeRE := regexp.MustCompile(`\d+ years`)
191 out = timeRE.ReplaceAllString(out, "X years")
193 assert.Equal(t, heredoc.Doc(`
194 Showing 3 open issues in OWNER/REPO that match your search. (Page 1)
196 ID Title Labels Created at
197 #6 Issue one (foo, bar) about X years ago
198 #7 Issue two (fooz, baz) about X years ago
199 #8 Incident (foo, baz) about X years ago
201 `), out)
202 assert.Empty(t, output.Stderr())
205func TestIssueList_ids(t *testing.T) {
206 testClient := gitlabtesting.NewTestClient(t)
208 createdAt := time.Date(2016, 1, 4, 15, 31, 51, 0, time.UTC)
209 incidentType := "incident"
211 testClient.MockIssues.EXPECT().
212 ListProjectIssues("OWNER/REPO", gomock.Any()).
213 Return([]*gitlab.Issue{
214 {
215 ID: 76,
216 IID: 6,
217 ProjectID: 1,
218 State: "opened",
219 Title: "Issue one",
220 Labels: gitlab.Labels{"foo", "bar"},
221 WebURL: "http://gitlab.com/OWNER/REPO/issues/6",
222 CreatedAt: &createdAt,
223 },
224 {
225 ID: 77,
226 IID: 7,
227 ProjectID: 1,
228 State: "opened",
229 Title: "Issue two",
230 Labels: gitlab.Labels{"fooz", "baz"},
231 WebURL: "http://gitlab.com/OWNER/REPO/issues/7",
232 CreatedAt: &createdAt,
233 },
234 {
235 ID: 78,
236 IID: 8,
237 ProjectID: 1,
238 State: "opened",
239 Title: "Incident",
240 Labels: gitlab.Labels{"foo", "baz"},
241 WebURL: "http://gitlab.com/OWNER/REPO/issues/8",
242 CreatedAt: &createdAt,
243 IssueType: &incidentType,
244 },
245 }, nil, nil)
247 // Create an api.Client with the mock GitLab client
248 apiClient, err := api.NewClient(
249 func(*http.Client) (gitlab.AuthSource, error) {
250 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
251 },
252 api.WithGitLabClient(testClient.Client),
253 )
254 require.NoError(t, err)
256 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
257 return NewCmdList(f, nil, issuable.TypeIssue)
258 }, true,
259 cmdtest.WithApiClient(apiClient),
260 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
261 )
263 output, err := exec("-F ids")
264 if err != nil {
265 t.Errorf("error running command `issue list -F ids`: %v", err)
266 }
268 assert.Equal(t, "6\n7\n8\n", output.String())
269 assert.Empty(t, output.Stderr())
272func TestIssueList_urls(t *testing.T) {
273 testClient := gitlabtesting.NewTestClient(t)
275 createdAt := time.Date(2016, 1, 4, 15, 31, 51, 0, time.UTC)
276 incidentType := "incident"
278 testClient.MockIssues.EXPECT().
279 ListProjectIssues("OWNER/REPO", gomock.Any()).
280 Return([]*gitlab.Issue{
281 {
282 ID: 76,
283 IID: 6,
284 ProjectID: 1,
285 State: "opened",
286 Title: "Issue one",
287 Labels: gitlab.Labels{"foo", "bar"},
288 WebURL: "http://gitlab.com/OWNER/REPO/issues/6",
289 CreatedAt: &createdAt,
290 },
291 {
292 ID: 77,
293 IID: 7,
294 ProjectID: 1,
295 State: "opened",
296 Title: "Issue two",
297 Labels: gitlab.Labels{"fooz", "baz"},
298 WebURL: "http://gitlab.com/OWNER/REPO/issues/7",
299 CreatedAt: &createdAt,
300 },
301 {
302 ID: 78,
303 IID: 8,
304 ProjectID: 1,
305 State: "opened",
306 Title: "Incident",
307 Labels: gitlab.Labels{"foo", "baz"},
308 WebURL: "http://gitlab.com/OWNER/REPO/issues/8",
309 CreatedAt: &createdAt,
310 IssueType: &incidentType,
311 },
312 }, nil, nil)
314 // Create an api.Client with the mock GitLab client
315 apiClient, err := api.NewClient(
316 func(*http.Client) (gitlab.AuthSource, error) {
317 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
318 },
319 api.WithGitLabClient(testClient.Client),
320 )
321 require.NoError(t, err)
323 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
324 return NewCmdList(f, nil, issuable.TypeIssue)
325 }, true,
326 cmdtest.WithApiClient(apiClient),
327 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
328 )
330 output, err := exec("-F urls")
331 if err != nil {
332 t.Errorf("error running command `issue list -F urls`: %v", err)
333 }
335 assert.Equal(t, heredoc.Doc(`
336 http://gitlab.com/OWNER/REPO/issues/6
337 http://gitlab.com/OWNER/REPO/issues/7
338 http://gitlab.com/OWNER/REPO/issues/8
339 `), output.String())
340 assert.Empty(t, output.Stderr())
343func TestIssueList_tty_withFlags(t *testing.T) {
344 // NOTE: These subtests cannot run in parallel because they use cmdutils.GroupOverride()
345 // which modifies global viper state (SetEnvPrefix, BindEnv).
346 t.Run("project", func(t *testing.T) {
347 testClient := gitlabtesting.NewTestClient(t)
349 testClient.MockUsers.EXPECT().
350 ListUsers(gomock.Any()).
351 Return([]*gitlab.User{
352 {ID: 100, Username: "someuser"},
353 }, nil, nil)
355 testClient.MockIssues.EXPECT().
356 ListProjectIssues("OWNER/REPO", gomock.Any()).
357 DoAndReturn(func(pid any, opts *gitlab.ListProjectIssuesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
358 // Verify flags are passed correctly
359 // Note: -p is Page, -P is PerPage, so "-P1 -p100" means PerPage=1, Page=100
360 assert.Equal(t, "opened", *opts.State)
361 assert.Equal(t, int64(100), opts.Page)
362 assert.Equal(t, int64(1), opts.PerPage)
363 assert.True(t, *opts.Confidential)
364 assert.NotNil(t, opts.AssigneeID) // User ID 100 from someuser lookup
365 assert.Equal(t, gitlab.LabelOptions{"bug"}, *opts.Labels)
366 assert.Equal(t, "1", *opts.Milestone)
367 return []*gitlab.Issue{}, nil, nil
368 })
370 apiClient, err := api.NewClient(
371 func(*http.Client) (gitlab.AuthSource, error) {
372 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
373 },
374 api.WithGitLabClient(testClient.Client),
375 )
376 require.NoError(t, err)
378 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
379 return NewCmdList(f, nil, issuable.TypeIssue)
380 }, true,
381 cmdtest.WithApiClient(apiClient),
382 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
383 )
385 output, err := exec("--opened -P1 -p100 --confidential -a someuser -l bug -m1")
386 require.NoError(t, err)
388 assert.Empty(t, output.Stderr())
389 assert.Equal(t, `No open issues match your search in OWNER/REPO.
392`, output.String())
393 })
394 t.Run("group", func(t *testing.T) {
395 testClient := gitlabtesting.NewTestClient(t)
397 testClient.MockIssues.EXPECT().
398 ListGroupIssues("GROUP", gomock.Any()).
399 Return([]*gitlab.Issue{}, nil, nil)
401 apiClient, err := api.NewClient(
402 func(*http.Client) (gitlab.AuthSource, error) {
403 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
404 },
405 api.WithGitLabClient(testClient.Client),
406 )
407 require.NoError(t, err)
409 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
410 return NewCmdList(f, nil, issuable.TypeIssue)
411 }, true,
412 cmdtest.WithApiClient(apiClient),
413 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
414 )
416 output, err := exec("--group GROUP")
417 require.NoError(t, err)
419 assert.Empty(t, output.Stderr())
420 assert.Equal(t, `No open issues match your search in GROUP.
423`, output.String())
424 })
427func TestIssueList_headerTotal(t *testing.T) {
428 // NOTE: These subtests cannot run in parallel because the epic case uses cmdutils.GroupOverride()
429 // which modifies global viper state (SetEnvPrefix, BindEnv).
430 t.Setenv("NO_COLOR", "true")
432 issues := []*gitlab.Issue{
433 {IID: 6, State: "opened", Title: "Issue one", WebURL: "http://gitlab.com/OWNER/REPO/issues/6"},
434 {IID: 7, State: "opened", Title: "Issue two", WebURL: "http://gitlab.com/OWNER/REPO/issues/7"},
435 }
437 tests := []struct {
438 name string
439 issueType issuable.IssueType
440 cli string
441 setupMock func(tc *gitlabtesting.TestClient)
442 wantHeader string
443 }{
444 {
445 name: "project shows the total from the API",
446 issueType: issuable.TypeIssue,
447 cli: "",
448 setupMock: func(tc *gitlabtesting.TestClient) {
449 tc.MockIssues.EXPECT().
450 ListProjectIssues("OWNER/REPO", gomock.Any()).
451 Return(issues, &gitlab.Response{CurrentPage: 1, NextPage: 2, TotalPages: 21, TotalItems: 42}, nil)
452 },
453 wantHeader: "Showing 2 of 42 open issues in OWNER/REPO that match your search. (Page 1)\n",
454 },
455 {
456 name: "group shows the total from the API",
457 issueType: issuable.TypeIssue,
458 cli: "--group GROUP --per-page 2 --page 21",
459 setupMock: func(tc *gitlabtesting.TestClient) {
460 tc.MockIssues.EXPECT().
461 ListGroupIssues("GROUP", gomock.Any()).
462 Return(issues, &gitlab.Response{CurrentPage: 21, TotalPages: 21, TotalItems: 42}, nil)
463 },
464 wantHeader: "Showing 2 of 42 open issues in GROUP that match your search. (Page 21)\n",
465 },
466 {
467 name: "incident shows the total from the API",
468 issueType: issuable.TypeIncident,
469 cli: "",
470 setupMock: func(tc *gitlabtesting.TestClient) {
471 tc.MockIssues.EXPECT().
472 ListProjectIssues("OWNER/REPO", gomock.Any()).
473 Return(issues, &gitlab.Response{CurrentPage: 1, NextPage: 2, TotalPages: 3, TotalItems: 5}, nil)
474 },
475 wantHeader: "Showing 2 of 5 open incidents in OWNER/REPO that match your search. (Page 1)\n",
476 },
477 {
478 name: "project without a total from the API",
479 issueType: issuable.TypeIssue,
480 cli: "",
481 setupMock: func(tc *gitlabtesting.TestClient) {
482 tc.MockIssues.EXPECT().
483 ListProjectIssues("OWNER/REPO", gomock.Any()).
484 Return(issues, &gitlab.Response{CurrentPage: 1, NextPage: 2}, nil)
485 },
486 wantHeader: "Showing 2 open issues in OWNER/REPO that match your search. (Page 1)\n",
487 },
488 {
489 name: "epic ignores the total from the API",
490 issueType: issuable.TypeIssue,
491 cli: "--group GROUP --epic 42",
492 setupMock: func(tc *gitlabtesting.TestClient) {
493 tc.MockEpicIssues.EXPECT().
494 ListEpicIssues("GROUP", int64(42), gomock.Any()).
495 Return(issues, &gitlab.Response{CurrentPage: 1, TotalPages: 1, TotalItems: 42}, nil)
496 },
497 wantHeader: "Showing 2 open issues in GROUP&42 that match your search. (Page 1)\n",
498 },
499 }
501 for _, tt := range tests {
502 t.Run(tt.name, func(t *testing.T) {
503 testClient := gitlabtesting.NewTestClient(t)
504 tt.setupMock(testClient)
506 apiClient, err := api.NewClient(
507 func(*http.Client) (gitlab.AuthSource, error) {
508 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
509 },
510 api.WithGitLabClient(testClient.Client),
511 )
512 require.NoError(t, err)
514 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
515 return NewCmdList(f, nil, tt.issueType)
516 }, true,
517 cmdtest.WithApiClient(apiClient),
518 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
519 )
521 output, err := exec(tt.cli)
522 require.NoError(t, err)
524 assert.True(t, strings.HasPrefix(output.String(), tt.wantHeader), "got %q", output.String())
525 assert.Empty(t, output.Stderr())
526 })
527 }
530func TestIssueList_groupPassesConfidentialAndIteration(t *testing.T) {
531 testClient := gitlabtesting.NewTestClient(t)
533 testClient.MockIssues.EXPECT().
534 ListGroupIssues("GROUP", gomock.Any()).
535 DoAndReturn(func(gid any, opts *gitlab.ListGroupIssuesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
536 require.NotNil(t, opts.Confidential, "confidential filter dropped for group listing")
537 assert.True(t, *opts.Confidential)
538 require.NotNil(t, opts.IterationID, "iteration filter dropped for group listing")
539 assert.Equal(t, int64(9), *opts.IterationID)
540 return []*gitlab.Issue{}, nil, nil
541 })
543 apiClient, err := api.NewClient(
544 func(*http.Client) (gitlab.AuthSource, error) {
545 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
546 },
547 api.WithGitLabClient(testClient.Client),
548 )
549 require.NoError(t, err)
551 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
552 return NewCmdList(f, nil, issuable.TypeIssue)
553 }, true,
554 cmdtest.WithApiClient(apiClient),
555 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
556 )
558 output, err := exec("--group GROUP --confidential --iteration 9")
559 require.NoError(t, err)
561 assert.Empty(t, output.Stderr())
564func TestIssueList_filterByIteration(t *testing.T) {
565 testClient := gitlabtesting.NewTestClient(t)
567 testClient.MockIssues.EXPECT().
568 ListProjectIssues("OWNER/REPO", gomock.Any()).
569 DoAndReturn(func(pid any, opts *gitlab.ListProjectIssuesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
570 // Verify iteration_id is passed
571 assert.Equal(t, int64(9), *opts.IterationID)
572 return []*gitlab.Issue{}, nil, nil
573 })
575 apiClient, err := api.NewClient(
576 func(*http.Client) (gitlab.AuthSource, error) {
577 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
578 },
579 api.WithGitLabClient(testClient.Client),
580 )
581 require.NoError(t, err)
583 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
584 return NewCmdList(f, nil, issuable.TypeIssue)
585 }, true,
586 cmdtest.WithApiClient(apiClient),
587 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
588 )
590 output, err := exec("--iteration 9")
591 require.NoError(t, err)
593 assert.Empty(t, output.Stderr())
594 assert.Equal(t, `No open issues match your search in OWNER/REPO.
597`, output.String())
600func TestIssueList_filterByDates(t *testing.T) {
601 // NOTE: These subtests cannot run in parallel because they use cmdutils.GroupOverride()
602 // which modifies global viper state (SetEnvPrefix, BindEnv).
603 t.Run("project", func(t *testing.T) {
604 testClient := gitlabtesting.NewTestClient(t)
606 testClient.MockIssues.EXPECT().
607 ListProjectIssues("OWNER/REPO", gomock.Any()).
608 DoAndReturn(func(pid any, opts *gitlab.ListProjectIssuesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
609 require.NotNil(t, opts.CreatedAfter)
610 require.NotNil(t, opts.CreatedBefore)
611 require.NotNil(t, opts.UpdatedAfter)
612 require.NotNil(t, opts.UpdatedBefore)
613 assert.Equal(t, time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), *opts.CreatedAfter)
614 assert.Equal(t, time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC), *opts.CreatedBefore)
615 assert.Equal(t, time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), *opts.UpdatedAfter)
616 assert.Equal(t, time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC), *opts.UpdatedBefore)
617 return []*gitlab.Issue{}, nil, nil
618 })
620 apiClient, err := api.NewClient(
621 func(*http.Client) (gitlab.AuthSource, error) {
622 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
623 },
624 api.WithGitLabClient(testClient.Client),
625 )
626 require.NoError(t, err)
628 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
629 return NewCmdList(f, nil, issuable.TypeIssue)
630 }, true,
631 cmdtest.WithApiClient(apiClient),
632 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
633 )
635 output, err := exec("--created-after 2026-01-01T00:00:00Z --created-before 2026-02-01T00:00:00Z --updated-after 2026-03-01T00:00:00Z --updated-before 2026-04-01T00:00:00Z")
636 require.NoError(t, err)
638 assert.Empty(t, output.Stderr())
639 assert.Equal(t, `No open issues match your search in OWNER/REPO.
642`, output.String())
643 })
644 t.Run("no date flags", func(t *testing.T) {
645 testClient := gitlabtesting.NewTestClient(t)
647 testClient.MockIssues.EXPECT().
648 ListProjectIssues("OWNER/REPO", gomock.Any()).
649 DoAndReturn(func(pid any, opts *gitlab.ListProjectIssuesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
650 assert.Nil(t, opts.CreatedAfter)
651 assert.Nil(t, opts.CreatedBefore)
652 assert.Nil(t, opts.UpdatedAfter)
653 assert.Nil(t, opts.UpdatedBefore)
654 return []*gitlab.Issue{}, nil, nil
655 })
657 apiClient, err := api.NewClient(
658 func(*http.Client) (gitlab.AuthSource, error) {
659 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
660 },
661 api.WithGitLabClient(testClient.Client),
662 )
663 require.NoError(t, err)
665 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
666 return NewCmdList(f, nil, issuable.TypeIssue)
667 }, true,
668 cmdtest.WithApiClient(apiClient),
669 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
670 )
672 _, err = exec("")
673 require.NoError(t, err)
674 })
675 t.Run("group", func(t *testing.T) {
676 testClient := gitlabtesting.NewTestClient(t)
678 testClient.MockIssues.EXPECT().
679 ListGroupIssues("GROUP", gomock.Any()).
680 DoAndReturn(func(gid any, opts *gitlab.ListGroupIssuesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
681 require.NotNil(t, opts.UpdatedAfter)
682 assert.Equal(t, time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC), *opts.UpdatedAfter)
683 assert.Nil(t, opts.CreatedAfter)
684 return []*gitlab.Issue{}, nil, nil
685 })
687 apiClient, err := api.NewClient(
688 func(*http.Client) (gitlab.AuthSource, error) {
689 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
690 },
691 api.WithGitLabClient(testClient.Client),
692 )
693 require.NoError(t, err)
695 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
696 return NewCmdList(f, nil, issuable.TypeIssue)
697 }, true,
698 cmdtest.WithApiClient(apiClient),
699 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
700 )
702 output, err := exec("--group GROUP --updated-after 2026-10-01T00:00:00Z")
703 require.NoError(t, err)
705 assert.Empty(t, output.Stderr())
706 assert.Equal(t, `No open issues match your search in GROUP.
709`, output.String())
710 })
711 t.Run("invalid format", func(t *testing.T) {
712 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
713 return NewCmdList(f, nil, issuable.TypeIssue)
714 }, true,
715 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
716 )
718 _, err := exec("--created-after 2026-10-01")
719 require.ErrorContains(t, err, "invalid time format")
720 })
723func TestIssueList_tty_withIssueType(t *testing.T) {
724 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
725 t.Setenv("NO_COLOR", "true")
727 testClient := gitlabtesting.NewTestClient(t)
729 createdAt := time.Date(2016, 1, 4, 15, 31, 51, 0, time.UTC)
730 incidentType := "incident"
732 testClient.MockIssues.EXPECT().
733 ListProjectIssues("OWNER/REPO", gomock.Any()).
734 DoAndReturn(func(pid any, opts *gitlab.ListProjectIssuesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
735 // Verify issue_type filter is passed
736 assert.Equal(t, new("incident"), opts.IssueType)
737 return []*gitlab.Issue{
738 {
739 ID: 78,
740 IID: 8,
741 ProjectID: 1,
742 State: "opened",
743 Title: "Incident",
744 Description: "description incident here",
745 Labels: gitlab.Labels{"foo", "baz"},
746 WebURL: "http://gitlab.com/OWNER/REPO/issues/8",
747 CreatedAt: &createdAt,
748 IssueType: &incidentType,
749 References: &gitlab.IssueReferences{
750 Full: "OWNER/REPO/issues/8",
751 Relative: "#8",
752 Short: "#8",
753 },
754 },
755 }, nil, nil
756 })
758 apiClient, err := api.NewClient(
759 func(*http.Client) (gitlab.AuthSource, error) {
760 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
761 },
762 api.WithGitLabClient(testClient.Client),
763 )
764 require.NoError(t, err)
766 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
767 return NewCmdList(f, nil, issuable.TypeIssue)
768 }, true,
769 cmdtest.WithApiClient(apiClient),
770 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
771 )
773 output, err := exec("--issue-type=incident")
774 require.NoError(t, err)
776 out := output.String()
777 timeRE := regexp.MustCompile(`\d+ years`)
778 out = timeRE.ReplaceAllString(out, "X years")
780 assert.Contains(t, out, "Showing 1 open incident in OWNER/REPO that match your search. (Page 1)")
781 assert.Contains(t, out, "#8\tIncident\t(foo, baz)\tabout X years ago")
782 assert.Empty(t, output.Stderr())
785func TestIncidentList_tty_withIssueType(t *testing.T) {
786 // This test doesn't need API mocking - it just tests that --issue-type flag
787 // is not allowed for incident command
788 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
789 return NewCmdList(f, nil, issuable.TypeIncident)
790 }, true,
791 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
792 )
794 output, err := exec("--issue-type=incident")
795 if err == nil {
796 t.Error("expected an `unknown flag: --issue-type` error, but got nothing")
797 }
799 assert.Empty(t, output.String())
800 assert.Empty(t, output.Stderr())
803func TestIssueList_tty_mine(t *testing.T) {
804 t.Run("mine with all flag and user exists", func(t *testing.T) {
805 testClient := gitlabtesting.NewTestClient(t)
807 testClient.MockUsers.EXPECT().
808 CurrentUser(gomock.Any()).
809 Return(&gitlab.User{Username: "john_smith"}, nil, nil)
811 testClient.MockIssues.EXPECT().
812 ListProjectIssues("OWNER/REPO", gomock.Any()).
813 DoAndReturn(func(pid any, opts *gitlab.ListProjectIssuesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
814 // Verify assignee ID is set from current user lookup
815 assert.NotNil(t, opts.AssigneeID)
816 return []*gitlab.Issue{}, nil, nil
817 })
819 apiClient, err := api.NewClient(
820 func(*http.Client) (gitlab.AuthSource, error) {
821 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
822 },
823 api.WithGitLabClient(testClient.Client),
824 )
825 require.NoError(t, err)
827 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
828 return NewCmdList(f, nil, issuable.TypeIssue)
829 }, true,
830 cmdtest.WithApiClient(apiClient),
831 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
832 )
834 output, err := exec("--mine -A")
835 require.NoError(t, err)
837 assert.Empty(t, output.Stderr())
838 assert.Equal(t, `No issues match your search in OWNER/REPO.
841`, output.String())
842 })
843 t.Run("user does not exists", func(t *testing.T) {
844 testClient := gitlabtesting.NewTestClient(t)
846 notFoundResp := &gitlab.Response{
847 Response: &http.Response{StatusCode: http.StatusNotFound},
848 }
849 testClient.MockUsers.EXPECT().
850 CurrentUser(gomock.Any()).
851 Return(nil, notFoundResp, gitlab.ErrNotFound)
853 apiClient, err := api.NewClient(
854 func(*http.Client) (gitlab.AuthSource, error) {
855 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
856 },
857 api.WithGitLabClient(testClient.Client),
858 )
859 require.NoError(t, err)
861 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
862 return NewCmdList(f, nil, issuable.TypeIssue)
863 }, true,
864 cmdtest.WithApiClient(apiClient),
865 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
866 )
868 output, err := exec("--mine -A")
869 require.Error(t, err)
871 assert.Empty(t, output.Stderr())
872 assert.Empty(t, output.String())
873 })
876func makeHyperlink(linkText, targetURL string) string {
877 return fmt.Sprintf("\x1b]8;;%s\x1b\\%s\x1b]8;;\x1b\\", targetURL, linkText)
880func TestIssueList_hyperlinks(t *testing.T) {
881 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
882 t.Setenv("NO_COLOR", "true")
884 noHyperlinkCells := [][]string{
885 {"#6", "Issue one", "(foo, bar)", "about X years ago"},
886 {"#7", "Issue two", "(fooz, baz)", "about X years ago"},
887 {"#8", "Incident", "(foo, baz)", "about X years ago"},
888 }
890 hyperlinkCells := [][]string{
891 {makeHyperlink("#6", "http://gitlab.com/OWNER/REPO/issues/6"), "Issue one", "(foo, bar)", "about X years ago"},
892 {makeHyperlink("#7", "http://gitlab.com/OWNER/REPO/issues/7"), "Issue two", "(fooz, baz)", "about X years ago"},
893 {makeHyperlink("#8", "http://gitlab.com/OWNER/REPO/issues/8"), "Incident", "(foo, baz)", "about X years ago"},
894 }
896 type hyperlinkTest struct {
897 forceHyperlinksEnv string
898 displayHyperlinksConfig string
899 isTTY bool
901 expectedCells [][]string
902 }
904 tests := []hyperlinkTest{
905 // FORCE_HYPERLINKS causes hyperlinks to be output, whether or not we're talking to a TTY
906 {forceHyperlinksEnv: "1", isTTY: true, expectedCells: hyperlinkCells},
907 {forceHyperlinksEnv: "1", isTTY: false, expectedCells: hyperlinkCells},
909 // empty/missing display_hyperlinks in config defaults to *not* outputting hyperlinks
910 {displayHyperlinksConfig: "", isTTY: true, expectedCells: noHyperlinkCells},
911 {displayHyperlinksConfig: "", isTTY: false, expectedCells: noHyperlinkCells},
913 // display_hyperlinks: false in config prevents outputting hyperlinks
914 {displayHyperlinksConfig: "false", isTTY: true, expectedCells: noHyperlinkCells},
915 {displayHyperlinksConfig: "false", isTTY: false, expectedCells: noHyperlinkCells},
917 // display_hyperlinks: true in config only outputs hyperlinks if we're talking to a TTY
918 {displayHyperlinksConfig: "true", isTTY: true, expectedCells: hyperlinkCells},
919 {displayHyperlinksConfig: "true", isTTY: false, expectedCells: noHyperlinkCells},
920 }
922 createdAt1 := time.Date(2016, 1, 4, 15, 31, 51, 0, time.UTC)
923 createdAt2 := time.Date(2016, 1, 4, 16, 31, 51, 0, time.UTC)
924 incidentType := "incident"
926 testIssues := []*gitlab.Issue{
927 {
928 ID: 76,
929 IID: 6,
930 ProjectID: 1,
931 State: "opened",
932 Title: "Issue one",
933 Description: "a description here",
934 Labels: gitlab.Labels{"foo", "bar"},
935 WebURL: "http://gitlab.com/OWNER/REPO/issues/6",
936 CreatedAt: &createdAt1,
937 References: &gitlab.IssueReferences{
938 Full: "OWNER/REPO/issues/6",
939 Relative: "#6",
940 Short: "#6",
941 },
942 },
943 {
944 ID: 77,
945 IID: 7,
946 ProjectID: 1,
947 State: "opened",
948 Title: "Issue two",
949 Description: "description two here",
950 Labels: gitlab.Labels{"fooz", "baz"},
951 WebURL: "http://gitlab.com/OWNER/REPO/issues/7",
952 CreatedAt: &createdAt1,
953 References: &gitlab.IssueReferences{
954 Full: "OWNER/REPO/issues/7",
955 Relative: "#7",
956 Short: "#7",
957 },
958 },
959 {
960 ID: 78,
961 IID: 8,
962 ProjectID: 1,
963 State: "opened",
964 Title: "Incident",
965 Description: "description incident here",
966 Labels: gitlab.Labels{"foo", "baz"},
967 WebURL: "http://gitlab.com/OWNER/REPO/issues/8",
968 CreatedAt: &createdAt2,
969 IssueType: &incidentType,
970 References: &gitlab.IssueReferences{
971 Full: "OWNER/REPO/issues/8",
972 Relative: "#8",
973 Short: "#8",
974 },
975 },
976 }
978 for _, tc := range tests {
979 t.Run("", func(t *testing.T) {
980 testClient := gitlabtesting.NewTestClient(t)
982 testClient.MockIssues.EXPECT().
983 ListProjectIssues("OWNER/REPO", gomock.Any()).
984 Return(testIssues, nil, nil)
986 apiClient, err := api.NewClient(
987 func(*http.Client) (gitlab.AuthSource, error) {
988 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
989 },
990 api.WithGitLabClient(testClient.Client),
991 )
992 require.NoError(t, err)
994 doHyperlinks := "never"
995 if tc.forceHyperlinksEnv == "1" {
996 doHyperlinks = "always"
997 } else if tc.displayHyperlinksConfig == "true" {
998 doHyperlinks = "auto"
999 }
1001 ios, _, _, _ := cmdtest.TestIOStreams(
1002 cmdtest.WithTestIOStreamsAsTTY(tc.isTTY),
1003 iostreams.WithDisplayHyperLinks(doHyperlinks),
1006 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
1007 return NewCmdList(f, nil, issuable.TypeIssue)
1008 }, tc.isTTY,
1009 cmdtest.WithIOStreamsOverride(ios),
1010 cmdtest.WithApiClient(apiClient),
1011 cmdtest.WithGitLabClient(testClient.Client),
1012 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
1015 output, err := exec("")
1016 require.NoError(t, err)
1018 out := output.String()
1019 timeRE := regexp.MustCompile(`\d+ years`)
1020 out = timeRE.ReplaceAllString(out, "X years")
1022 lines := strings.Split(strings.TrimRight(out, "\n"), "\n")
1024 // first two lines have the header and some separating whitespace, so skip those
1025 for lineNum, line := range lines[3:] {
1026 gotCells := strings.Split(line, "\t")
1027 expectedCells := tc.expectedCells[lineNum]
1029 assert.Len(t, gotCells, len(expectedCells))
1031 for cellNum, gotCell := range gotCells {
1032 expectedCell := expectedCells[cellNum]
1034 assert.Equal(t, expectedCell, strings.Trim(gotCell, " "))
1037 })
1041func TestIssueListJSON(t *testing.T) {
1042 testClient := gitlabtesting.NewTestClient(t)
1044 createdAt, _ := time.Parse(time.RFC3339, "2024-01-31T05:37:57.883Z")
1045 updatedAt, _ := time.Parse(time.RFC3339, "2024-02-02T00:54:02.842Z")
1046 issueType := "issue"
1048 testIssue := &gitlab.Issue{
1049 ID: 141525495,
1050 IID: 15,
1051 ProjectID: 37777023,
1052 Title: "tem",
1053 Description: "",
1054 State: "opened",
1055 CreatedAt: &createdAt,
1056 UpdatedAt: &updatedAt,
1057 Labels: gitlab.Labels{},
1058 Assignees: []*gitlab.IssueAssignee{},
1059 Author: &gitlab.IssueAuthor{ID: 11809982, Username: "jay_mccure", Name: "Jay McCure", State: "active", AvatarURL: "https://gitlab.com/uploads/-/system/user/avatar/11809982/avatar.png", WebURL: "https://gitlab.com/jay_mccure"},
1060 Confidential: false,
1061 IssueType: &issueType,
1062 WebURL: "https://gitlab.com/jay_mccure/test2target/-/issues/15",
1063 TimeStats: &gitlab.TimeStats{},
1064 TaskCompletionStatus: &gitlab.TasksCompletionStatus{Count: 0, CompletedCount: 0},
1065 Links: &gitlab.IssueLinks{Self: "https://gitlab.com/api/v4/projects/37777023/issues/15", Notes: "https://gitlab.com/api/v4/projects/37777023/issues/15/notes", AwardEmoji: "https://gitlab.com/api/v4/projects/37777023/issues/15/award_emoji", Project: "https://gitlab.com/api/v4/projects/37777023"},
1066 References: &gitlab.IssueReferences{Short: "#15", Relative: "#15", Full: "jay_mccure/test2target#15"},
1069 testClient.MockIssues.EXPECT().
1070 ListProjectIssues("OWNER/REPO", gomock.Any()).
1071 Return([]*gitlab.Issue{testIssue}, nil, nil)
1073 apiClient, err := api.NewClient(
1074 func(*http.Client) (gitlab.AuthSource, error) {
1075 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
1076 },
1077 api.WithGitLabClient(testClient.Client),
1079 require.NoError(t, err)
1081 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
1082 return NewCmdList(f, nil, issuable.TypeIssue)
1083 }, true,
1084 cmdtest.WithApiClient(apiClient),
1085 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
1088 output, err := exec("--output json")
1089 require.NoError(t, err)
1091 b, err := os.ReadFile("./testdata/issueListFull.json")
1092 require.NoError(t, err)
1094 expectedOut := string(b)
1096 assert.JSONEq(t, expectedOut, output.String())
1097 assert.Empty(t, output.Stderr())
1100func TestIssueListMutualOutputFlags(t *testing.T) {
1101 // This test doesn't need API mocking - it just tests flag validation
1102 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
1103 return NewCmdList(f, nil, issuable.TypeIssue)
1104 }, true,
1105 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
1108 _, err := exec("--output json --output-format ids")
1110 require.Error(t, err)
1111 assert.EqualError(t, err, "if any flags in the group [output output-format] are set none of the others can be; [output output-format] were all set")
1114func TestIssueAndIncidentListRejectInvalidOutputFlags(t *testing.T) {
1115 for _, issueType := range []issuable.IssueType{issuable.TypeIssue, issuable.TypeIncident} {
1116 t.Run(string(issueType), func(t *testing.T) {
1117 for _, flag := range []string{"--output invalid", "--output \"\"", "--output-format invalid", "--output-format \"\""} {
1118 t.Run(flag, func(t *testing.T) {
1119 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
1120 return NewCmdList(f, nil, issueType)
1121 }, true)
1123 _, err := exec(flag)
1124 require.ErrorContains(t, err, "must be one of")
1125 })
1127 })
1131func TestIssueList_epicIssues(t *testing.T) {
1132 // NOTE: This test cannot run in parallel because it uses cmdutils.GroupOverride()
1133 // which modifies global viper state (SetEnvPrefix, BindEnv).
1135 testdata := []*gitlab.Issue{
1137 IID: 1,
1138 State: "opened",
1139 Assignees: []*gitlab.IssueAssignee{
1140 {ID: 101},
1141 },
1142 Author: &gitlab.IssueAuthor{ID: 102},
1143 Labels: gitlab.Labels{"label::one"},
1144 Milestone: &gitlab.Milestone{
1145 Title: "Milestone one",
1146 },
1147 Title: "This is issue one",
1148 Iteration: &gitlab.GroupIteration{
1149 ID: 103,
1150 },
1151 Confidential: false,
1152 CreatedAt: new(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)),
1153 UpdatedAt: new(time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)),
1154 },
1156 IID: 2,
1157 State: "closed",
1158 Assignees: []*gitlab.IssueAssignee{
1159 {ID: 102},
1160 },
1161 Author: &gitlab.IssueAuthor{ID: 202},
1162 Labels: gitlab.Labels{"label::two"},
1163 Milestone: &gitlab.Milestone{
1164 Title: "Milestone two",
1165 },
1166 Title: "That is issue two",
1167 Iteration: &gitlab.GroupIteration{
1168 ID: 203,
1169 },
1170 Confidential: true,
1171 CreatedAt: new(time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC)),
1172 UpdatedAt: new(time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)),
1173 },
1176 tests := []struct {
1177 name string
1178 commandLine string
1179 user *gitlab.User
1180 wantIDs []int
1181 wantErr string
1182 perPage int
1183 }{
1185 name: "group flag",
1186 commandLine: `--group testGroupID --epic 42`,
1187 wantIDs: []int{1},
1188 },
1190 name: "repo flag",
1191 commandLine: `--repo testGroupID/repo --epic 42`,
1192 wantIDs: []int{1},
1193 },
1195 name: "all flag",
1196 commandLine: `--group testGroupID --epic 42 --all`,
1197 wantIDs: []int{1, 2},
1198 },
1200 name: "closed flag",
1201 commandLine: `--group testGroupID --epic 42 --closed`,
1202 wantIDs: []int{2},
1203 },
1205 name: "assignee flag",
1206 user: &gitlab.User{
1207 ID: 101,
1208 Username: "one-oh-one",
1209 },
1210 commandLine: `--group testGroupID --epic 42 --all --assignee one-oh-one`,
1211 wantIDs: []int{1},
1212 },
1214 name: "not-assignee flag",
1215 user: &gitlab.User{
1216 ID: 101,
1217 Username: "one-oh-one",
1218 },
1219 commandLine: `--group testGroupID --epic 42 --all --not-assignee one-oh-one`,
1220 wantIDs: []int{2},
1221 },
1223 name: "author flag",
1224 user: &gitlab.User{
1225 ID: 102,
1226 Username: "one-oh-two",
1227 },
1228 commandLine: `--group testGroupID --epic 42 --all --author one-oh-two`,
1229 wantIDs: []int{1},
1230 },
1232 name: "not-author flag",
1233 user: &gitlab.User{
1234 ID: 102,
1235 Username: "one-oh-two",
1236 },
1237 commandLine: `--group testGroupID --epic 42 --all --not-author one-oh-two`,
1238 wantIDs: []int{2},
1239 },
1241 name: "milestone flag",
1242 commandLine: `--group testGroupID --epic 42 --all --milestone 'milestone one'`,
1243 wantIDs: []int{1},
1244 },
1246 name: "search flag",
1247 commandLine: `--group testGroupID --epic 42 --all --search 'iSsUe OnE'`,
1248 wantIDs: []int{1},
1249 },
1251 name: "iteration flag",
1252 commandLine: `--group testGroupID --epic 42 --all --iteration 103`,
1253 wantIDs: []int{1},
1254 },
1256 name: "confidential flag",
1257 commandLine: `--group testGroupID --epic 42 --all --confidential`,
1258 wantIDs: []int{2},
1259 },
1261 name: "created-after flag",
1262 commandLine: `--group testGroupID --epic 42 --all --created-after 2026-01-15T00:00:00Z`,
1263 wantIDs: []int{2},
1264 },
1266 name: "created-before flag",
1267 commandLine: `--group testGroupID --epic 42 --all --created-before 2026-01-15T00:00:00Z`,
1268 wantIDs: []int{1},
1269 },
1271 name: "updated-after flag",
1272 commandLine: `--group testGroupID --epic 42 --all --updated-after 2026-03-15T00:00:00Z`,
1273 wantIDs: []int{2},
1274 },
1276 name: "updated-before flag",
1277 commandLine: `--group testGroupID --epic 42 --all --updated-before 2026-03-15T00:00:00Z`,
1278 wantIDs: []int{1},
1279 },
1281 name: "date flags include the boundary",
1282 commandLine: `--group testGroupID --epic 42 --all --created-after 2026-02-01T00:00:00Z --created-before 2026-02-01T00:00:00Z`,
1283 wantIDs: []int{2},
1284 },
1286 name: "page flag",
1287 commandLine: `--group testGroupID --epic 42 --all --page=2`,
1288 wantErr: "the --page flag",
1289 },
1291 name: "per-page flag",
1292 commandLine: `--group testGroupID --epic 42 --all --per-page=9999`,
1293 // per-page is clamped to the max supported per_page value
1294 perPage: api.MaxPerPage,
1295 wantIDs: []int{1, 2},
1296 },
1299 for _, tt := range tests {
1300 t.Run(tt.name, func(t *testing.T) {
1301 testClient := gitlabtesting.NewTestClient(t)
1303 if tt.user != nil {
1304 testClient.MockUsers.EXPECT().
1305 ListUsers(gomock.Any()).
1306 Return([]*gitlab.User{tt.user}, nil, nil)
1309 if tt.wantErr == "" {
1310 testClient.MockEpicIssues.EXPECT().
1311 ListEpicIssues("testGroupID", int64(42), gomock.Any()).
1312 DoAndReturn(func(gid any, epic int64, opts *gitlab.ListOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.Issue, *gitlab.Response, error) {
1313 if tt.perPage != 0 {
1314 assert.Equal(t, int64(tt.perPage), opts.PerPage)
1316 return testdata, &gitlab.Response{NextPage: 0}, nil
1317 })
1320 apiClient, err := api.NewClient(
1321 func(*http.Client) (gitlab.AuthSource, error) {
1322 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
1323 },
1324 api.WithGitLabClient(testClient.Client),
1326 require.NoError(t, err)
1328 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
1329 return NewCmdList(f, nil, issuable.TypeIssue)
1330 }, true,
1331 cmdtest.WithApiClient(apiClient),
1332 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
1335 output, err := exec(tt.commandLine + ` --output-format ids`)
1336 if tt.wantErr != "" {
1337 require.ErrorContains(t, err, tt.wantErr)
1339 if err != nil {
1340 return
1343 assert.Empty(t, output.Stderr())
1345 gotIDs, err := strToIntSlice(output.String())
1346 if err != nil {
1347 t.Fatalf("command %q: unexpected output:\n%s", tt.commandLine, output.String())
1350 assert.Equal(t, tt.wantIDs, gotIDs)
1351 })
1355func TestIssueList_filterByLabel(t *testing.T) {
1356 // NOTE: This test cannot run in parallel because it uses cmdutils.GroupOverride()
1357 // which modifies global viper state (SetEnvPrefix, BindEnv).
1359 tests := map[string]struct {
1360 respBody []*gitlab.Issue
1361 args string
1362 expect []int
1363 }{
1364 "with --label": {
1365 respBody: []*gitlab.Issue{
1367 IID: 1,
1368 State: "opened",
1369 Assignees: []*gitlab.IssueAssignee{
1370 {ID: 101},
1371 },
1372 Author: &gitlab.IssueAuthor{ID: 102},
1373 Labels: gitlab.Labels{"label::one"},
1374 Milestone: &gitlab.Milestone{
1375 Title: "Milestone one",
1376 },
1377 Title: "This is issue one",
1378 Iteration: &gitlab.GroupIteration{
1379 ID: 103,
1380 },
1381 Confidential: false,
1382 },
1384 IID: 2,
1385 State: "open",
1386 Assignees: []*gitlab.IssueAssignee{
1387 {ID: 101},
1388 },
1389 Author: &gitlab.IssueAuthor{ID: 102},
1390 Labels: gitlab.Labels{"label::one"},
1391 Milestone: &gitlab.Milestone{
1392 Title: "Milestone two",
1393 },
1394 Title: "That is issue two",
1395 Iteration: &gitlab.GroupIteration{
1396 ID: 203,
1397 },
1398 Confidential: false,
1399 },
1400 },
1401 args: "--group testGroupID --epic 42 --all --label label::one",
1402 expect: []int{1, 2},
1403 },
1404 "with --not-label": {
1405 respBody: []*gitlab.Issue{
1407 IID: 3,
1408 State: "open",
1409 Assignees: []*gitlab.IssueAssignee{
1410 {ID: 101},
1411 },
1412 Author: &gitlab.IssueAuthor{ID: 102},
1413 Labels: gitlab.Labels{"label::two"},
1414 Milestone: &gitlab.Milestone{
1415 Title: "Milestone two",
1416 },
1417 Title: "That is issue three",
1418 Iteration: &gitlab.GroupIteration{
1419 ID: 303,
1420 },
1421 Confidential: false,
1422 },
1423 },
1424 args: "--group testGroupID --epic 42 --all --not-label label::one",
1425 expect: []int{3},
1426 },
1427 "with --label and --not-label": {
1428 respBody: []*gitlab.Issue{
1430 IID: 1,
1431 State: "opened",
1432 Assignees: []*gitlab.IssueAssignee{
1433 {ID: 101},
1434 },
1435 Author: &gitlab.IssueAuthor{ID: 102},
1436 Labels: gitlab.Labels{"label::one"},
1437 Milestone: &gitlab.Milestone{
1438 Title: "Milestone one",
1439 },
1440 Title: "This is issue one",
1441 Iteration: &gitlab.GroupIteration{
1442 ID: 103,
1443 },
1444 Confidential: false,
1445 },
1447 IID: 2,
1448 State: "open",
1449 Assignees: []*gitlab.IssueAssignee{
1450 {ID: 101},
1451 },
1452 Author: &gitlab.IssueAuthor{ID: 102},
1453 Labels: gitlab.Labels{"label::one"},
1454 Milestone: &gitlab.Milestone{
1455 Title: "Milestone two",
1456 },
1457 Title: "That is issue two",
1458 Iteration: &gitlab.GroupIteration{
1459 ID: 203,
1460 },
1461 Confidential: false,
1462 },
1464 IID: 3,
1465 State: "open",
1466 Assignees: []*gitlab.IssueAssignee{
1467 {ID: 101},
1468 },
1469 Author: &gitlab.IssueAuthor{ID: 102},
1470 Labels: gitlab.Labels{"label::two"},
1471 Milestone: &gitlab.Milestone{
1472 Title: "Milestone two",
1473 },
1474 Title: "That is issue three",
1475 Iteration: &gitlab.GroupIteration{
1476 ID: 303,
1477 },
1478 Confidential: false,
1479 },
1480 },
1481 args: "--group testGroupID --epic 42 --all --label label::one --not-label label::three",
1482 expect: []int{1, 2, 3},
1483 },
1486 for name, tt := range tests {
1487 t.Run(name, func(t *testing.T) {
1488 testClient := gitlabtesting.NewTestClient(t)
1490 testClient.MockEpicIssues.EXPECT().
1491 ListEpicIssues("testGroupID", int64(42), gomock.Any()).
1492 Return(tt.respBody, &gitlab.Response{NextPage: 0}, nil)
1494 apiClient, err := api.NewClient(
1495 func(*http.Client) (gitlab.AuthSource, error) {
1496 return gitlab.AccessTokenAuthSource{Token: "test-token"}, nil
1497 },
1498 api.WithGitLabClient(testClient.Client),
1500 require.NoError(t, err)
1502 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
1503 return NewCmdList(f, nil, issuable.TypeIssue)
1504 }, true,
1505 cmdtest.WithApiClient(apiClient),
1506 cmdtest.WithBaseRepo("OWNER", "REPO", ""),
1509 out, err := exec(tt.args + " --output-format ids")
1510 require.NoError(t, err, "command: %s err: %v", tt.args, err)
1511 require.Emptyf(t, out.Stderr(), "command: %s stderr: %s", tt.args, out.Stderr())
1513 got, err := strToIntSlice(out.String())
1514 require.NoErrorf(t, err, "command: %s output:\n%s", tt.args, out)
1516 assert.Equal(t, tt.expect, got)
1517 })
1521func strToIntSlice(s string) ([]int, error) {
1522 var ret []int
1524 scanner := bufio.NewScanner(strings.NewReader(s))
1525 for scanner.Scan() {
1526 line := strings.TrimSpace(scanner.Text())
1527 if line == "" {
1528 continue
1531 i, err := strconv.Atoi(line)
1532 if err != nil {
1533 return nil, err
1536 ret = append(ret, i)
1539 slices.Sort(ret)
1541 return ret, nil
Diagnostics8 git calls · 255 ms
CallStatusSizeTime0255 ms
discover200185 B4 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=4
git.response.bytes=185
git.server.agent=git/2.56.g1891de4-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=185
git.pkt.payload.max=35
ls-refs20058 KiB · hit4 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=4
git.response.bytes=59849
git.response.cache=HIT
git.response.duration_ms=4
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 · 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=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=2
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:0200347 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=347
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=73f6a798386c4a4df64da0b5349881ded38885ca
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=347
git.pkt.payload.max=320
git.sideband.band1.bytes=320
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=320
git.pack.trailer=93ed36ed1884d41429801c50b3bb5d32ef1307a5
Open pack map
fetchtree:0200209 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=209
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=135b8c60872264a89b3665cc28cad86b62fd614c
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=209
git.pkt.payload.max=182
git.sideband.band1.bytes=182
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=182
git.pack.trailer=73ae1ae228d92d2d7cfa420b9d05651ed87abc5b
Open pack map
fetch2007.1 KiB242 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=242
git.response.bytes=7252
git.response.cache=MISS
git.response.duration_ms=242
git.fetch.wants=f98dfc63c82e923131f3f023f1e7773ddcb578e2
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=7252
git.pkt.payload.max=7225
git.sideband.band1.bytes=7225
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
a5e2fd64e90bcf81
Request
9be7c27d…
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