GitLabgitlab-org
cli
main
1//go:build !integration
3package serviceaccountutils
5import (
6 "errors"
7 "testing"
9 "github.com/stretchr/testify/assert"
10 "github.com/stretchr/testify/require"
11 "go.uber.org/mock/gomock"
13 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
14 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
16 "gitlab.com/gitlab-org/cli/internal/api"
17 "gitlab.com/gitlab-org/cli/internal/glrepo"
18 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
19)
21func noMorePages() *gitlab.Response {
22 return &gitlab.Response{NextPage: 0}
23}
25func TestNewClient(t *testing.T) {
26 t.Parallel()
28 repo := func() (glrepo.Interface, error) {
29 return glrepo.NewWithHost("OWNER", "REPO", "gitlab.example.com"), nil
30 }
31 noRepo := func() (glrepo.Interface, error) {
32 return nil, errors.New("not a git repository")
33 }
35 t.Run("project scope uses the base repository and its host", func(t *testing.T) {
36 t.Parallel()
38 var gotHost string
39 apiClient := func(host string) (*api.Client, error) {
40 gotHost = host
41 return cmdtest.NewTestApiClient(t, nil, "", ""), nil
42 }
44 _, scope, err := NewClient(repo, apiClient, "")
45 require.NoError(t, err)
47 assert.Equal(t, Scope{Project: "OWNER/REPO"}, scope)
48 assert.Equal(t, "project OWNER/REPO", scope.String())
49 assert.Equal(t, "gitlab.example.com", gotHost)
50 })
52 t.Run("group scope works outside a repository", func(t *testing.T) {
53 t.Parallel()
55 var gotHost string
56 apiClient := func(host string) (*api.Client, error) {
57 gotHost = host
58 return cmdtest.NewTestApiClient(t, nil, "", ""), nil
59 }
61 _, scope, err := NewClient(noRepo, apiClient, "my-group")
62 require.NoError(t, err)
64 assert.Equal(t, Scope{Group: "my-group"}, scope)
65 assert.Equal(t, "group my-group", scope.String())
66 assert.Empty(t, gotHost)
67 })
69 t.Run("project scope outside a repository fails before building a client", func(t *testing.T) {
70 t.Parallel()
72 apiClient := func(string) (*api.Client, error) {
73 t.Fatal("the API client must not be built")
74 return nil, nil
75 }
77 _, _, err := NewClient(noRepo, apiClient, "")
78 require.EqualError(t, err, "not a git repository")
79 })
80}
82func TestParseID(t *testing.T) {
83 t.Parallel()
85 tests := []struct {
86 ref string
87 wantID int64
88 wantOK bool
89 wantErr string
90 }{
91 {ref: "42", wantID: 42, wantOK: true},
92 {ref: "service_account_group_1_aaa"},
93 {ref: "0", wantErr: `invalid service account ID "0"`},
94 {ref: "-1", wantErr: `invalid service account ID "-1"`},
95 {ref: "99999999999999999999", wantErr: `invalid service account ID "99999999999999999999"`},
96 }
98 for _, tt := range tests {
99 t.Run(tt.ref, func(t *testing.T) {
100 t.Parallel()
102 id, ok, err := ParseID(tt.ref)
103 if tt.wantErr != "" {
104 require.EqualError(t, err, tt.wantErr)
105 return
106 }
107 require.NoError(t, err)
108 assert.Equal(t, tt.wantID, id)
109 assert.Equal(t, tt.wantOK, ok)
110 })
111 }
112}
114func TestFindByUsername(t *testing.T) {
115 t.Parallel()
117 groupAccounts := []*gitlab.GroupServiceAccount{
118 {ID: 41, UserName: "service_account_group_1_aaa", Name: "Deployer", PublicEmail: "public@example.com"},
119 {ID: 42, UserName: "service_account_group_1_bbb", Name: "Releaser"},
120 }
121 projectAccounts := []*gitlab.ProjectServiceAccount{
122 {ID: 51, Username: "service_account_project_2_aaa", Name: "Deployer"},
123 {ID: 52, Username: "service_account_project_2_bbb", Name: "Releaser"},
124 }
126 t.Run("returns the listed group account", func(t *testing.T) {
127 t.Parallel()
129 tc := gitlabtesting.NewTestClient(t)
130 tc.MockGroups.EXPECT().
131 ListServiceAccounts("my-group", gomock.Any(), gomock.Any(), gomock.Any()).
132 Return(groupAccounts, noMorePages(), nil)
134 raw, account, err := FindByUsername(t.Context(), tc.Client, Scope{Group: "my-group"}, "service_account_group_1_bbb")
135 require.NoError(t, err)
136 assert.Same(t, groupAccounts[1], raw)
137 assert.Equal(t, int64(42), account.ID)
138 })
140 t.Run("returns the listed project account", func(t *testing.T) {
141 t.Parallel()
143 tc := gitlabtesting.NewTestClient(t)
144 tc.MockProjects.EXPECT().
145 ListProjectServiceAccounts("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
146 Return(projectAccounts, noMorePages(), nil)
148 raw, account, err := FindByUsername(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, "service_account_project_2_bbb")
149 require.NoError(t, err)
150 assert.Same(t, projectAccounts[1], raw)
151 assert.Equal(t, int64(52), account.ID)
152 })
154 t.Run("a group lookup requests 100 accounts per page", func(t *testing.T) {
155 t.Parallel()
157 tc := gitlabtesting.NewTestClient(t)
158 tc.MockGroups.EXPECT().
159 ListServiceAccounts("my-group", gomock.Cond(func(o *gitlab.ListServiceAccountsOptions) bool { return o.PerPage == 100 }), gomock.Any(), gomock.Any()).
160 Return(groupAccounts, noMorePages(), nil)
162 _, _, err := FindByUsername(t.Context(), tc.Client, Scope{Group: "my-group"}, "service_account_group_1_bbb")
163 require.NoError(t, err)
164 })
166 t.Run("a project lookup requests 100 accounts per page", func(t *testing.T) {
167 t.Parallel()
169 tc := gitlabtesting.NewTestClient(t)
170 tc.MockProjects.EXPECT().
171 ListProjectServiceAccounts("OWNER/REPO", gomock.Cond(func(o *gitlab.ListProjectServiceAccountsOptions) bool { return o.PerPage == 100 }), gomock.Any(), gomock.Any()).
172 Return(projectAccounts, noMorePages(), nil)
174 _, _, err := FindByUsername(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, "service_account_project_2_bbb")
175 require.NoError(t, err)
176 })
178 // The first page announces a next page, so fetching it fails the Times(1)
179 // expectation.
180 t.Run("the lookup stops at the first page with a match", func(t *testing.T) {
181 t.Parallel()
183 tc := gitlabtesting.NewTestClient(t)
184 tc.MockGroups.EXPECT().
185 ListServiceAccounts("my-group", gomock.Any(), gomock.Any(), gomock.Any()).
186 Return(groupAccounts, &gitlab.Response{NextPage: 2}, nil).
187 Times(1)
189 _, account, err := FindByUsername(t.Context(), tc.Client, Scope{Group: "my-group"}, "service_account_group_1_aaa")
190 require.NoError(t, err)
191 assert.Equal(t, int64(41), account.ID)
192 })
194 t.Run("a username matches regardless of case", func(t *testing.T) {
195 t.Parallel()
197 tc := gitlabtesting.NewTestClient(t)
198 tc.MockGroups.EXPECT().
199 ListServiceAccounts("my-group", gomock.Any(), gomock.Any(), gomock.Any()).
200 Return(groupAccounts, noMorePages(), nil)
202 _, account, err := FindByUsername(t.Context(), tc.Client, Scope{Group: "my-group"}, "SERVICE_ACCOUNT_GROUP_1_BBB")
203 require.NoError(t, err)
204 assert.Equal(t, int64(42), account.ID)
205 })
207 t.Run("a username that is not found returns no account", func(t *testing.T) {
208 t.Parallel()
210 tc := gitlabtesting.NewTestClient(t)
211 tc.MockGroups.EXPECT().
212 ListServiceAccounts("my-group", gomock.Any(), gomock.Any(), gomock.Any()).
213 Return(groupAccounts, noMorePages(), nil)
215 raw, _, err := FindByUsername(t.Context(), tc.Client, Scope{Group: "my-group"}, "missing")
216 require.EqualError(t, err, `no service account with username "missing" in group my-group`)
217 assert.Nil(t, raw)
218 })
220 t.Run("a list error is returned", func(t *testing.T) {
221 t.Parallel()
223 tc := gitlabtesting.NewTestClient(t)
224 tc.MockProjects.EXPECT().
225 ListProjectServiceAccounts("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
226 Return(nil, nil, errors.New("403 Forbidden"))
228 _, _, err := FindByUsername(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, "service_account_project_2_bbb")
229 require.EqualError(t, err, "403 Forbidden")
230 })
231}
233func TestResolveID(t *testing.T) {
234 t.Parallel()
236 // No expectation is set, so any API call fails the test.
237 t.Run("numeric ID makes no request", func(t *testing.T) {
238 t.Parallel()
240 tc := gitlabtesting.NewTestClient(t)
242 id, err := ResolveID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, "52")
243 require.NoError(t, err)
244 assert.Equal(t, int64(52), id)
245 })
247 t.Run("username found in a group", func(t *testing.T) {
248 t.Parallel()
250 tc := gitlabtesting.NewTestClient(t)
251 tc.MockGroups.EXPECT().
252 ListServiceAccounts("my-group", gomock.Any(), gomock.Any(), gomock.Any()).
253 Return([]*gitlab.GroupServiceAccount{
254 {ID: 41, UserName: "service_account_group_1_aaa"},
255 {ID: 42, UserName: "service_account_group_1_bbb"},
256 }, noMorePages(), nil)
258 id, err := ResolveID(t.Context(), tc.Client, Scope{Group: "my-group"}, "service_account_group_1_bbb")
259 require.NoError(t, err)
260 assert.Equal(t, int64(42), id)
261 })
263 t.Run("username found in a project", func(t *testing.T) {
264 t.Parallel()
266 tc := gitlabtesting.NewTestClient(t)
267 tc.MockProjects.EXPECT().
268 ListProjectServiceAccounts("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
269 Return([]*gitlab.ProjectServiceAccount{
270 {ID: 51, Username: "service_account_project_2_aaa"},
271 }, noMorePages(), nil)
273 id, err := ResolveID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, "service_account_project_2_aaa")
274 require.NoError(t, err)
275 assert.Equal(t, int64(51), id)
276 })
278 t.Run("username not found", func(t *testing.T) {
279 t.Parallel()
281 tc := gitlabtesting.NewTestClient(t)
282 tc.MockProjects.EXPECT().
283 ListProjectServiceAccounts("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
284 Return([]*gitlab.ProjectServiceAccount{}, noMorePages(), nil)
286 id, err := ResolveID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, "missing")
287 require.EqualError(t, err, `no service account with username "missing" in project OWNER/REPO`)
288 assert.Zero(t, id)
289 })
291 t.Run("invalid ID", func(t *testing.T) {
292 t.Parallel()
294 tc := gitlabtesting.NewTestClient(t)
296 _, err := ResolveID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, "0")
297 require.EqualError(t, err, `invalid service account ID "0"`)
298 })
299}
301func TestPrintDetails(t *testing.T) {
302 t.Parallel()
304 t.Run("without a pending email", func(t *testing.T) {
305 t.Parallel()
307 io, _, stdout, _ := cmdtest.TestIOStreams()
308 PrintDetails(io, Account{ID: 41, Username: "service_account_group_1_aaa"})
310 assert.Equal(t, "ID\t41\nUsername\tservice_account_group_1_aaa\nName\t-\nEmail\t-\n", stdout.String())
311 })
313 t.Run("with a pending email", func(t *testing.T) {
314 t.Parallel()
316 io, _, stdout, _ := cmdtest.TestIOStreams()
317 PrintDetails(io, Account{
318 ID: 41,
319 Username: "release-bot",
320 Name: "Release bot",
321 Email: "service_account_group_1_aaa@noreply.gitlab.example.com",
322 UnconfirmedEmail: "release-bot@example.com",
323 })
325 assert.Equal(t, "ID\t41\nUsername\trelease-bot\nName\tRelease bot\nEmail\tservice_account_group_1_aaa@noreply.gitlab.example.com\nUnconfirmed Email\trelease-bot@example.com\n", stdout.String())
326 })
327}
329func TestFromGroupAndFromProject(t *testing.T) {
330 t.Parallel()
332 assert.Equal(t,
333 Account{ID: 41, Username: "release-bot", Name: "Release bot", Email: "a@example.com", UnconfirmedEmail: "b@example.com"},
334 FromGroup(&gitlab.GroupServiceAccount{ID: 41, UserName: "release-bot", Name: "Release bot", Email: "a@example.com", UnconfirmedEmail: "b@example.com"}),
335 )
336 assert.Equal(t,
337 Account{ID: 51, Username: "release-bot", Name: "Release bot", Email: "a@example.com", UnconfirmedEmail: "b@example.com"},
338 FromProject(&gitlab.ProjectServiceAccount{ID: 51, Username: "release-bot", Name: "Release bot", Email: "a@example.com", UnconfirmedEmail: "b@example.com"}),
339 )
340}
342func TestOrDash(t *testing.T) {
343 t.Parallel()
345 assert.Equal(t, "-", OrDash(""))
346 assert.Equal(t, "Deployer", OrDash("Deployer"))
347}
Diagnostics8 git calls · 303 ms
CallStatusSizeTime0303 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 · hit40 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=36 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=40 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 · hit4 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=4 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit5 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=5 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=5 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:02001.8 KiB · 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: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=2 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:0200207 B · hit5 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=5 git.response.bytes=207 git.response.cache=HIT git.response.duration_ms=5 git.fetch.filter=tree:0 git.fetch.wants=46257722a5d9837ad7305a4a6942623f79e26348 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=207 git.pkt.payload.max=180 git.sideband.band1.bytes=180 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=180 git.pack.trailer=49c3336eecdc11d5831924e911d2e17735206333Open pack map
fetch2002.2 KiB248 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=248 git.response.bytes=2214 git.response.cache=MISS git.response.duration_ms=248 git.fetch.wants=7d66254ff57ec93be52eeccf8c7cbabb9a0cb84e 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=2214 git.pkt.payload.max=2187 git.sideband.band1.bytes=2187 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
- a5e356568c71994c
- Request
- 48147e48…
- 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