GitLabgitlab-org

cli

main
ply8 git calls249 ms100 KiB6 cachedprotocol v2
405 lines12 KiBRaw
1//go:build !integration
3package list
5import (
6 "encoding/json"
7 "errors"
8 "fmt"
9 "testing"
10 "time"
12 "github.com/MakeNowJust/heredoc/v2"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15 "go.uber.org/mock/gomock"
17 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
18 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
20 timelogapi "gitlab.com/gitlab-org/cli/internal/commands/timelog/api"
21 "gitlab.com/gitlab-org/cli/internal/glinstance"
22 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
25// GroupOverride reads the package-level viper in cmdutils, so these tests do
26// not call t.Parallel.
28func setupCmd(t *testing.T, tc *gitlabtesting.TestClient) cmdtest.CmdExecFunc {
29 t.Helper()
30 return cmdtest.SetupCmdForTest(
31 t,
32 NewCmd,
33 false,
34 cmdtest.WithGitLabClient(tc.Client),
35 cmdtest.WithBaseRepo("OWNER", "REPO", glinstance.DefaultHostname),
36 )
39// expectPage expects one timelogs query, captures it, and answers with conn
40// under data.project, or under data.group when group is true.
41func expectPage(tc *gitlabtesting.TestClient, group bool, conn *timelogapi.TimelogConnection, captured *gitlab.GraphQLQuery) *gitlabtesting.MockGraphQLInterfaceDoCall {
42 return tc.MockGraphQL.EXPECT().
43 Do(gomock.Any(), gomock.Any(), gomock.Any()).
44 DoAndReturn(func(query gitlab.GraphQLQuery, response any, _ ...gitlab.RequestOptionFunc) (*gitlab.Response, error) {
45 if captured != nil {
46 *captured = query
47 }
48 resp, ok := response.(*timelogapi.TimelogsResponse)
49 if !ok {
50 return nil, fmt.Errorf("unexpected response type %T", response)
51 }
52 if group {
53 resp.Data.Group = &timelogapi.Namespace{Timelogs: conn}
54 } else {
55 resp.Data.Project = &timelogapi.Namespace{Timelogs: conn}
56 }
57 return &gitlab.Response{}, nil
58 })
61func spentAt(day int) time.Time {
62 return time.Date(2026, 10, day, 12, 0, 0, 0, time.UTC)
65func TestListProject(t *testing.T) {
66 tc := gitlabtesting.NewTestClient(t)
67 var query gitlab.GraphQLQuery
68 expectPage(tc, false, &timelogapi.TimelogConnection{
69 Nodes: []timelogapi.Timelog{
70 {
71 SpentAt: spentAt(14),
72 TimeSpent: 5400,
73 Summary: "Report command",
74 User: timelogapi.User{Username: "alice"},
75 Project: timelogapi.Project{FullPath: "OWNER/REPO"},
76 Issue: &timelogapi.Issuable{IID: "969", Title: "Handle time tracking"},
77 },
78 {
79 SpentAt: spentAt(13),
80 TimeSpent: 2700,
81 User: timelogapi.User{Username: "bob"},
82 Project: timelogapi.Project{FullPath: "OWNER/REPO"},
83 MergeRequest: &timelogapi.Issuable{IID: "4092", Title: "feat: time tracking"},
84 },
85 {
86 SpentAt: spentAt(12),
87 TimeSpent: -900,
88 Summary: "Logged twice",
89 User: timelogapi.User{Username: "bob"},
90 Project: timelogapi.Project{FullPath: "OWNER/REPO"},
91 Issue: &timelogapi.Issuable{IID: "969", Title: "Handle time tracking"},
92 },
93 },
94 }, &query)
96 out, err := setupCmd(t, tc)("")
97 require.NoError(t, err)
99 assert.Contains(t, query.Query, "project(fullPath: $fullPath)")
100 assert.Equal(t, map[string]any{"fullPath": "OWNER/REPO"}, query.Variables)
102 expected := heredoc.Doc(`
103 DATE USER TIME ITEM TITLE SUMMARY
104 2026-10-14 alice 1h 30m #969 Handle time tracking Report command
105 2026-10-13 bob 45m !4092 feat: time tracking -
106 2026-10-12 bob -15m #969 Handle time tracking Logged twice
108 Total: 2h (3 time logs)
109 `)
110 assert.Equal(t, expected, out.OutBuf.String())
113func TestListGroup(t *testing.T) {
114 tc := gitlabtesting.NewTestClient(t)
115 var query gitlab.GraphQLQuery
116 expectPage(tc, true, &timelogapi.TimelogConnection{
117 Nodes: []timelogapi.Timelog{
118 {
119 SpentAt: spentAt(14),
120 TimeSpent: 3600,
121 User: timelogapi.User{Username: "alice"},
122 Project: timelogapi.Project{FullPath: "my-group/sub/app"},
123 Issue: &timelogapi.Issuable{IID: "7", Title: "Fix login"},
124 },
125 {
126 SpentAt: spentAt(13),
127 TimeSpent: 8 * 3600,
128 User: timelogapi.User{Username: "bob"},
129 Project: timelogapi.Project{FullPath: "my-group/api"},
130 MergeRequest: &timelogapi.Issuable{IID: "12", Title: "Add endpoint"},
131 },
132 },
133 }, &query)
135 out, err := setupCmd(t, tc)("--group my-group")
136 require.NoError(t, err)
138 assert.Contains(t, query.Query, "group(fullPath: $fullPath)")
139 assert.Equal(t, map[string]any{"fullPath": "my-group"}, query.Variables)
141 expected := heredoc.Doc(`
142 DATE USER TIME ITEM TITLE SUMMARY
143 2026-10-14 alice 1h my-group/sub/app#7 Fix login -
144 2026-10-13 bob 1d my-group/api!12 Add endpoint -
146 Total: 1d 1h (2 time logs)
147 `)
148 assert.Equal(t, expected, out.OutBuf.String())
151func TestListFilters(t *testing.T) {
152 tc := gitlabtesting.NewTestClient(t)
153 var query gitlab.GraphQLQuery
154 expectPage(tc, false, &timelogapi.TimelogConnection{}, &query)
156 _, err := setupCmd(t, tc)("--user alice --start-date 2026-10-01 --end-date 2026-10-14")
157 require.NoError(t, err)
159 assert.Equal(t, map[string]any{
160 "fullPath": "OWNER/REPO",
161 "username": "alice",
162 "startDate": "2026-10-01",
163 "endDate": "2026-10-14",
164 }, query.Variables)
167func TestListUsernameWithLeadingAt(t *testing.T) {
168 tc := gitlabtesting.NewTestClient(t)
169 var query gitlab.GraphQLQuery
170 expectPage(tc, false, &timelogapi.TimelogConnection{}, &query)
172 _, err := setupCmd(t, tc)("--user @alice")
173 require.NoError(t, err)
175 assert.Equal(t, "alice", query.Variables["username"])
178func TestListDatesInUTC(t *testing.T) {
179 local := time.Local
180 time.Local = time.FixedZone("UTC+10", 10*60*60)
181 t.Cleanup(func() { time.Local = local })
183 tc := gitlabtesting.NewTestClient(t)
184 expectPage(tc, false, &timelogapi.TimelogConnection{
185 Nodes: []timelogapi.Timelog{
186 {
187 SpentAt: time.Date(2026, 10, 14, 20, 0, 0, 0, time.UTC),
188 TimeSpent: 3600,
189 User: timelogapi.User{Username: "alice"},
190 Issue: &timelogapi.Issuable{IID: "1", Title: "First"},
191 },
192 },
193 }, nil)
195 out, err := setupCmd(t, tc)("")
196 require.NoError(t, err)
198 assert.Contains(t, out.OutBuf.String(), "2026-10-14\talice")
201func TestListCurrentUser(t *testing.T) {
202 tc := gitlabtesting.NewTestClient(t)
203 var query gitlab.GraphQLQuery
204 gomock.InOrder(
205 tc.MockUsers.EXPECT().CurrentUser(gomock.Any()).Return(&gitlab.User{Username: "alice"}, nil, nil),
206 expectPage(tc, false, &timelogapi.TimelogConnection{}, &query),
207 )
209 _, err := setupCmd(t, tc)("--user @me")
210 require.NoError(t, err)
212 assert.Equal(t, "alice", query.Variables["username"])
215func TestListCurrentUserError(t *testing.T) {
216 tc := gitlabtesting.NewTestClient(t)
217 tc.MockUsers.EXPECT().CurrentUser(gomock.Any()).Return(nil, nil, errors.New("401 Unauthorized"))
219 _, err := setupCmd(t, tc)("--user @me")
220 require.ErrorContains(t, err, "failed to get the current user")
223func TestListPaginates(t *testing.T) {
224 tc := gitlabtesting.NewTestClient(t)
225 var first, second gitlab.GraphQLQuery
226 // GitLab drops timelogs the user cannot see from a page, so a page can be
227 // empty while more pages follow.
228 gomock.InOrder(
229 expectPage(tc, false, &timelogapi.TimelogConnection{
230 PageInfo: timelogapi.PageInfo{HasNextPage: true, EndCursor: "cursor-1"},
231 }, &first),
232 expectPage(tc, false, &timelogapi.TimelogConnection{
233 Nodes: []timelogapi.Timelog{
234 {
235 SpentAt: spentAt(1),
236 TimeSpent: 600,
237 User: timelogapi.User{Username: "alice"},
238 Issue: &timelogapi.Issuable{IID: "1", Title: "First"},
239 },
240 },
241 }, &second),
242 )
244 out, err := setupCmd(t, tc)("")
245 require.NoError(t, err)
247 assert.NotContains(t, first.Variables, "after")
248 assert.Equal(t, "cursor-1", second.Variables["after"])
249 assert.Contains(t, out.OutBuf.String(), "Total: 10m (1 time log)")
252func TestListEmpty(t *testing.T) {
253 tc := gitlabtesting.NewTestClient(t)
254 expectPage(tc, false, &timelogapi.TimelogConnection{}, nil)
256 out, err := setupCmd(t, tc)("")
257 require.NoError(t, err)
259 assert.Equal(t, "No time logged in OWNER/REPO.\n", out.OutBuf.String())
262func TestListJSON(t *testing.T) {
263 tc := gitlabtesting.NewTestClient(t)
264 expectPage(tc, false, &timelogapi.TimelogConnection{
265 Nodes: []timelogapi.Timelog{
266 {
267 SpentAt: spentAt(14),
268 TimeSpent: 5400,
269 Summary: "Report command",
270 User: timelogapi.User{Username: "alice"},
271 Project: timelogapi.Project{FullPath: "OWNER/REPO"},
272 Issue: &timelogapi.Issuable{IID: "969", Title: "Handle time tracking", WebURL: "https://gitlab.com/OWNER/REPO/-/issues/969"},
273 },
274 {
275 SpentAt: spentAt(13),
276 TimeSpent: -900,
277 User: timelogapi.User{Username: "bob"},
278 Project: timelogapi.Project{FullPath: "OWNER/REPO"},
279 MergeRequest: &timelogapi.Issuable{IID: "4092", Title: "feat: time tracking"},
280 },
281 },
282 }, nil)
284 out, err := setupCmd(t, tc)("--output json")
285 require.NoError(t, err)
287 var timelogs []timelogapi.Timelog
288 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &timelogs))
289 require.Len(t, timelogs, 2)
291 assert.Equal(t, spentAt(14), timelogs[0].SpentAt)
292 assert.Equal(t, int64(5400), timelogs[0].TimeSpent)
293 assert.Equal(t, "Report command", timelogs[0].Summary)
294 assert.Equal(t, "alice", timelogs[0].User.Username)
295 require.NotNil(t, timelogs[0].Issue)
296 assert.Equal(t, "https://gitlab.com/OWNER/REPO/-/issues/969", timelogs[0].Issue.WebURL)
297 assert.Nil(t, timelogs[0].MergeRequest)
299 assert.Equal(t, int64(-900), timelogs[1].TimeSpent)
300 require.NotNil(t, timelogs[1].MergeRequest)
301 assert.Equal(t, "4092", timelogs[1].MergeRequest.IID)
302 assert.Nil(t, timelogs[1].Issue)
305func TestListJSONEmpty(t *testing.T) {
306 tc := gitlabtesting.NewTestClient(t)
307 expectPage(tc, false, &timelogapi.TimelogConnection{}, nil)
309 out, err := setupCmd(t, tc)("--output json")
310 require.NoError(t, err)
312 assert.JSONEq(t, "[]", out.OutBuf.String())
315func TestListGraphQLErrors(t *testing.T) {
316 tc := gitlabtesting.NewTestClient(t)
317 tc.MockGraphQL.EXPECT().
318 Do(gomock.Any(), gomock.Any(), gomock.Any()).
319 DoAndReturn(func(_ gitlab.GraphQLQuery, response any, _ ...gitlab.RequestOptionFunc) (*gitlab.Response, error) {
320 resp, ok := response.(*timelogapi.TimelogsResponse)
321 if !ok {
322 return nil, fmt.Errorf("unexpected response type %T", response)
323 }
324 require.NoError(t, json.Unmarshal([]byte(`{
325 "errors": [{"message": "Start argument must be before End argument"}],
326 "data": {"project": {"timelogs": null}}
327 }`), resp))
328 return &gitlab.Response{}, nil
329 })
331 _, err := setupCmd(t, tc)("")
332 require.EqualError(t, err, "failed to list timelogs: Start argument must be before End argument")
335func TestListNotFound(t *testing.T) {
336 tc := gitlabtesting.NewTestClient(t)
337 tc.MockGraphQL.EXPECT().
338 Do(gomock.Any(), gomock.Any(), gomock.Any()).
339 Return(&gitlab.Response{}, nil)
341 _, err := setupCmd(t, tc)("--group missing")
342 require.EqualError(t, err, "group not found: missing")
345func TestListRequestError(t *testing.T) {
346 tc := gitlabtesting.NewTestClient(t)
347 tc.MockGraphQL.EXPECT().
348 Do(gomock.Any(), gomock.Any(), gomock.Any()).
349 Return(nil, errors.New("connection refused"))
351 _, err := setupCmd(t, tc)("")
352 require.EqualError(t, err, "failed to list timelogs: connection refused")
355func TestListNoRepository(t *testing.T) {
356 tc := gitlabtesting.NewTestClient(t)
357 exec := cmdtest.SetupCmdForTest(
358 t,
359 NewCmd,
360 false,
361 cmdtest.WithGitLabClient(tc.Client),
362 cmdtest.WithBaseRepoError(errors.New("not a git repository")),
363 )
365 _, err := exec("")
366 require.EqualError(t, err, "not a git repository")
369func TestListFlagValidation(t *testing.T) {
370 tests := []struct {
371 name string
372 args string
373 wantErr string
374 }{
375 {
376 name: "end date before start date",
377 args: "--start-date 2026-10-14 --end-date 2026-10-01",
378 wantErr: "invalid date range: --end-date is before --start-date",
379 },
380 {
381 name: "date not in YYYY-MM-DD format",
382 args: "--start-date 14/10/2026",
383 wantErr: "invalid argument \"14/10/2026\" for \"--start-date\" flag",
384 },
385 {
386 name: "group and repo together",
387 args: "--group my-group --repo OWNER/REPO",
388 wantErr: "if any flags in the group [group repo] are set none of the others can be",
389 },
390 {
391 name: "positional argument",
392 args: "extra",
393 wantErr: "unknown command \"extra\"",
394 },
395 }
397 for _, tt := range tests {
398 t.Run(tt.name, func(t *testing.T) {
399 tc := gitlabtesting.NewTestClient(t)
401 _, err := setupCmd(t, tc)(tt.args)
402 require.ErrorContains(t, err, tt.wantErr)
403 })
404 }
Diagnostics8 git calls · 249 ms
CallStatusSizeTime0249 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 · 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
fetchcombine:blob:none+tree:2 · deepen 12004.2 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=4273
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
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=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:0200166 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=166
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=dc4c26b053ce2f4849dff66c00cba032cb3cfda1
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=166
git.pkt.payload.max=139
git.sideband.band1.bytes=139
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=139
git.pack.trailer=1e354378f0db79627a255e16548c215c78a4f110
Open pack map
fetchtree:0200135 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=135
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=05e890f0025d40f27397e3c42c53d2b815f880e2
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=135
git.pkt.payload.max=108
git.sideband.band1.bytes=108
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=108
git.pack.trailer=b7af15d6bdffabfaf03a420343008bd896eb646f
Open pack map
fetch2002.9 KiB237 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=237
git.response.bytes=3011
git.response.cache=MISS
git.response.duration_ms=237
git.fetch.wants=84f63bae5bebc1cdf637aaccbcbed13034fea8b0
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=3011
git.pkt.payload.max=2984
git.sideband.band1.bytes=2984
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
a5e2e6d2c9dbecfa
Request
fc59438f…
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