GitLabgitlab-org
cli
main
1//go:build !integration
3package list
5import (
6 "encoding/json"
7 "errors"
8 "testing"
9 "time"
11 "github.com/MakeNowJust/heredoc/v2"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14 "go.uber.org/mock/gomock"
16 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
17 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
19 "gitlab.com/gitlab-org/cli/internal/api"
20 "gitlab.com/gitlab-org/cli/internal/cmdutils"
21 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
22)
24func setupExec(t *testing.T, tc *gitlabtesting.TestClient, opts ...cmdtest.FactoryOption) cmdtest.CmdExecFunc {
25 t.Helper()
27 opts = append(
28 []cmdtest.FactoryOption{
29 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(tc.Client))),
30 },
31 opts...,
32 )
34 return cmdtest.SetupCmdForTest(t, NewCmd, false, opts...)
35}
37func noMorePages() *gitlab.Response {
38 return &gitlab.Response{NextPage: 0}
39}
41func projectTokens() []*gitlab.PersonalAccessToken {
42 expiresAt := gitlab.ISOTime(time.Date(2027, 1, 31, 0, 0, 0, 0, time.UTC))
43 lastUsedAt := time.Date(2026, 11, 5, 9, 30, 0, 0, time.UTC)
44 return []*gitlab.PersonalAccessToken{
45 {ID: 7, Name: "ci", Scopes: []string{"api", "read_repository"}, Active: true, ExpiresAt: &expiresAt, LastUsedAt: &lastUsedAt},
46 {ID: 8, Name: "old", Scopes: []string{"read_api"}, Active: false, Revoked: true},
47 }
48}
50// No list expectation for accounts is set: an ID goes straight to the tokens.
51func TestTokenList_Project(t *testing.T) {
52 t.Parallel()
54 tc := gitlabtesting.NewTestClient(t)
55 tc.MockProjects.EXPECT().
56 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Cond(func(o *gitlab.ListProjectServiceAccountPersonalAccessTokensOptions) bool {
57 return o.State == nil && o.PerPage == 100
58 }), gomock.Any(), gomock.Any()).
59 Return(projectTokens(), noMorePages(), nil)
61 out, err := setupExec(t, tc)("51")
62 require.NoError(t, err)
64 expected := heredoc.Doc(`
65 ID Name Scopes Active Expires At Last Used At
66 7 ci api, read_repository true 2027-01-31 2026-11-05T09:30:00Z
67 8 old read_api false - -
68 `)
69 assert.Equal(t, expected, out.OutBuf.String())
70 assert.Empty(t, out.ErrBuf.String())
71}
73func TestTokenList_Active(t *testing.T) {
74 t.Parallel()
76 tc := gitlabtesting.NewTestClient(t)
77 tc.MockProjects.EXPECT().
78 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Cond(func(o *gitlab.ListProjectServiceAccountPersonalAccessTokensOptions) bool {
79 return o.State != nil && *o.State == "active"
80 }), gomock.Any(), gomock.Any()).
81 Return(projectTokens()[:1], noMorePages(), nil)
83 out, err := setupExec(t, tc)("51 --active")
84 require.NoError(t, err)
86 assert.Contains(t, out.OutBuf.String(), "ci")
87 assert.NotContains(t, out.OutBuf.String(), "old")
88}
90func TestTokenList_Group(t *testing.T) {
91 t.Parallel()
93 tc := gitlabtesting.NewTestClient(t)
94 tc.MockGroups.EXPECT().
95 ListServiceAccountPersonalAccessTokens("my-group", int64(41), gomock.Cond(func(o *gitlab.ListServiceAccountPersonalAccessTokensOptions) bool {
96 return o.State == nil && o.PerPage == 100
97 }), gomock.Any(), gomock.Any()).
98 Return([]*gitlab.PersonalAccessToken{{ID: 9, Name: "deploy", Scopes: []string{"api"}, Active: true}}, noMorePages(), nil)
100 out, err := setupExec(t, tc)("41 --group my-group")
101 require.NoError(t, err)
103 expected := heredoc.Doc(`
104 ID Name Scopes Active Expires At Last Used At
105 9 deploy api true - -
106 `)
107 assert.Equal(t, expected, out.OutBuf.String())
108}
110func TestTokenList_ByUsername(t *testing.T) {
111 t.Parallel()
113 tc := gitlabtesting.NewTestClient(t)
114 gomock.InOrder(
115 tc.MockProjects.EXPECT().
116 ListProjectServiceAccounts("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
117 Return([]*gitlab.ProjectServiceAccount{{ID: 52, Username: "release-bot"}}, noMorePages(), nil),
118 tc.MockProjects.EXPECT().
119 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(52), gomock.Any(), gomock.Any(), gomock.Any()).
120 Return(projectTokens(), noMorePages(), nil),
121 )
123 out, err := setupExec(t, tc)("release-bot")
124 require.NoError(t, err)
126 assert.Contains(t, out.OutBuf.String(), "api, read_repository")
127}
129func TestTokenList_JSON(t *testing.T) {
130 t.Parallel()
132 tc := gitlabtesting.NewTestClient(t)
133 tc.MockProjects.EXPECT().
134 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Any(), gomock.Any(), gomock.Any()).
135 Return(projectTokens(), noMorePages(), nil)
137 out, err := setupExec(t, tc)("51 --output json")
138 require.NoError(t, err)
140 var result []*gitlab.PersonalAccessToken
141 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
142 require.Len(t, result, 2)
143 assert.Equal(t, int64(7), result[0].ID)
144 assert.Equal(t, "ci", result[0].Name)
145 assert.Equal(t, []string{"api", "read_repository"}, result[0].Scopes)
146 assert.True(t, result[0].Active)
147 assert.Equal(t, int64(8), result[1].ID)
148 assert.True(t, result[1].Revoked)
149 assert.Empty(t, result[0].Token)
150}
152func TestTokenList_Empty(t *testing.T) {
153 t.Parallel()
155 tc := gitlabtesting.NewTestClient(t)
156 tc.MockProjects.EXPECT().
157 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Any(), gomock.Any(), gomock.Any()).
158 Return([]*gitlab.PersonalAccessToken{}, noMorePages(), nil)
160 out, err := setupExec(t, tc)("51")
161 require.NoError(t, err)
163 assert.Equal(t, "No tokens found for service account 51.\n", out.OutBuf.String())
164}
166func TestTokenList_APIError(t *testing.T) {
167 t.Parallel()
169 tc := gitlabtesting.NewTestClient(t)
170 tc.MockProjects.EXPECT().
171 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Any(), gomock.Any(), gomock.Any()).
172 Return(nil, nil, errors.New("404 Not Found"))
174 _, err := setupExec(t, tc)("51")
175 require.Error(t, err)
177 var exitErr *cmdutils.ExitError
178 require.ErrorAs(t, err, &exitErr)
179 assert.Equal(t, "failed to list service account tokens", exitErr.Details)
180 assert.Contains(t, err.Error(), "404 Not Found")
181}
183func TestTokenList_UsernameNotFound(t *testing.T) {
184 t.Parallel()
186 tc := gitlabtesting.NewTestClient(t)
187 tc.MockProjects.EXPECT().
188 ListProjectServiceAccounts("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
189 Return([]*gitlab.ProjectServiceAccount{}, noMorePages(), nil)
191 _, err := setupExec(t, tc)("missing")
192 require.Error(t, err)
193 assert.Contains(t, err.Error(), `no service account with username "missing" in project OWNER/REPO`)
194}
196func TestTokenList_InvalidID(t *testing.T) {
197 t.Parallel()
199 tc := gitlabtesting.NewTestClient(t)
201 _, err := setupExec(t, tc)("0")
202 require.Error(t, err)
203 assert.Contains(t, err.Error(), `invalid service account ID "0"`)
204}
206func TestTokenList_RequiresArgument(t *testing.T) {
207 t.Parallel()
209 tc := gitlabtesting.NewTestClient(t)
211 _, err := setupExec(t, tc)("")
212 require.Error(t, err)
213 assert.Contains(t, err.Error(), "accepts 1 arg(s), received 0")
214}
216func TestTokenList_RepoAndGroupAreMutuallyExclusive(t *testing.T) {
217 t.Parallel()
219 tc := gitlabtesting.NewTestClient(t)
221 _, err := setupExec(t, tc)("51 --repo OWNER/REPO --group my-group")
222 require.Error(t, err)
223 assert.Contains(t, err.Error(), "none of the others can be")
224}
226func TestTokenList_OutsideRepositoryWithoutGroup(t *testing.T) {
227 t.Parallel()
229 tc := gitlabtesting.NewTestClient(t)
231 _, err := setupExec(t, tc, cmdtest.WithBaseRepoError(errors.New("not a git repository")))("51")
232 require.Error(t, err)
233 assert.Contains(t, err.Error(), "not a git repository")
234}
236func TestTokenList_OutsideRepositoryWithGroup(t *testing.T) {
237 t.Parallel()
239 tc := gitlabtesting.NewTestClient(t)
240 tc.MockGroups.EXPECT().
241 ListServiceAccountPersonalAccessTokens("my-group", int64(41), gomock.Any(), gomock.Any(), gomock.Any()).
242 Return([]*gitlab.PersonalAccessToken{{ID: 9, Name: "deploy"}}, noMorePages(), nil)
244 out, err := setupExec(t, tc, cmdtest.WithBaseRepoError(errors.New("not a git repository")))("41 --group my-group")
245 require.NoError(t, err)
247 assert.Contains(t, out.OutBuf.String(), "deploy")
248}
250// GITLAB_GROUP redirects the command with no flag passed. t.Setenv rules out
251// t.Parallel.
252func TestTokenList_GroupFromEnvironment(t *testing.T) {
253 t.Setenv("GITLAB_GROUP", "env-group")
255 tc := gitlabtesting.NewTestClient(t)
256 tc.MockGroups.EXPECT().
257 ListServiceAccountPersonalAccessTokens("env-group", int64(41), gomock.Any(), gomock.Any(), gomock.Any()).
258 Return([]*gitlab.PersonalAccessToken{{ID: 9, Name: "deploy"}}, noMorePages(), nil)
260 out, err := setupExec(t, tc)("41")
261 require.NoError(t, err)
263 assert.Contains(t, out.OutBuf.String(), "deploy")
264}
Diagnostics9 git calls · 203 ms
CallStatusSizeTime0203 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB2 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=UPDATING git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=4 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=2 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:0200322 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=322 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=ba2caccf6c55211c6b29b98f40c2358479d91b1f 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=322 git.pkt.payload.max=295 git.sideband.band1.bytes=295 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=295 git.pack.trailer=3488e558d4708096e879feba968e084c249dbe22Open pack map
fetchtree:0200223 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=223 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=41d72d07155f99e3acc572f8fe5ad26c802e4ddc 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=223 git.pkt.payload.max=196 git.sideband.band1.bytes=196 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=196 git.pack.trailer=d9c58aac50f427eb21501a81fe28c81c7c49ae44Open pack map
fetchtree:0200133 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=185 git.response.bytes=133 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=fef2397ba5f10896709e0e77f067b17e2bde060b 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=133 git.pkt.payload.max=106 git.sideband.band1.bytes=106 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=106 git.pack.trailer=81b37a8b84ced73eebbc562db73f4e42213075adOpen pack map
fetch2002.0 KiB185 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2002 git.response.cache=MISS git.response.duration_ms=185 git.fetch.wants=d81b582560be47394d20d9517fea006dd32b89e4 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=2002 git.pkt.payload.max=1975 git.sideband.band1.bytes=1975 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
- a5e329b178b54628
- Request
- e2c82440…
- 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