GitLabgitlab-org
cli
main
1//go:build !integration
3package create
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 createdToken() *gitlab.DeployToken {
38 return &gitlab.DeployToken{
39 ID: 42,
40 Name: "ci-reader",
41 Username: "gitlab+deploy-token-42",
42 Scopes: []string{"read_repository"},
43 Token: "gldt-secret",
44 }
45}
47// expectProjectCreate returns an accessor for the options the command sent, so
48// the tests can assert on the request and not only on what is printed.
49func expectProjectCreate(tc *gitlabtesting.TestClient, token *gitlab.DeployToken) func() *gitlab.CreateProjectDeployTokenOptions {
50 var sent *gitlab.CreateProjectDeployTokenOptions
51 tc.MockDeployTokens.EXPECT().
52 CreateProjectDeployToken("OWNER/REPO", gomock.Any(), gomock.Any()).
53 DoAndReturn(func(_ any, opt *gitlab.CreateProjectDeployTokenOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.DeployToken, *gitlab.Response, error) {
54 sent = opt
55 return token, nil, nil
56 })
58 return func() *gitlab.CreateProjectDeployTokenOptions { return sent }
59}
61func TestCreate_Project(t *testing.T) {
62 t.Parallel()
64 tc := gitlabtesting.NewTestClient(t)
65 sent := expectProjectCreate(tc, createdToken())
67 out, err := setupExec(t, tc)("ci-reader --scope read_repository")
68 require.NoError(t, err)
70 assert.Equal(t, "ci-reader", *sent().Name)
71 assert.Equal(t, []string{"read_repository"}, *sent().Scopes)
72 assert.Nil(t, sent().Username)
73 assert.Nil(t, sent().ExpiresAt)
75 expected := heredoc.Doc(`
76 ID 42
77 Name ci-reader
78 Username gitlab+deploy-token-42
79 Scopes read_repository
80 Expires At -
81 Token gldt-secret
82 `)
83 assert.Equal(t, expected, out.OutBuf.String())
84 assert.Equal(t, "! Created a deploy token for project OWNER/REPO. Store the token value now. It is not shown again.\n", out.ErrBuf.String())
85}
87func TestCreate_Group(t *testing.T) {
88 t.Parallel()
90 var sent *gitlab.CreateGroupDeployTokenOptions
91 tc := gitlabtesting.NewTestClient(t)
92 tc.MockDeployTokens.EXPECT().
93 CreateGroupDeployToken("group/sub-group", gomock.Any(), gomock.Any()).
94 DoAndReturn(func(_ any, opt *gitlab.CreateGroupDeployTokenOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.DeployToken, *gitlab.Response, error) {
95 sent = opt
96 return &gitlab.DeployToken{
97 ID: 7,
98 Name: "group-reader",
99 Username: "gitlab+deploy-token-7",
100 Scopes: []string{"read_registry"},
101 Token: "gldt-group-secret",
102 }, nil, nil
103 })
105 out, err := setupExec(t, tc)("group-reader --scope read_registry --group group/sub-group")
106 require.NoError(t, err)
108 assert.Equal(t, "group-reader", *sent.Name)
109 assert.Equal(t, []string{"read_registry"}, *sent.Scopes)
111 expected := heredoc.Doc(`
112 ID 7
113 Name group-reader
114 Username gitlab+deploy-token-7
115 Scopes read_registry
116 Expires At -
117 Token gldt-group-secret
118 `)
119 assert.Equal(t, expected, out.OutBuf.String())
120 assert.Equal(t, "! Created a deploy token for group group/sub-group. Store the token value now. It is not shown again.\n", out.ErrBuf.String())
121}
123// Unlike list and get, create is the one command whose output carries the token
124// value, because this is the only time GitLab returns it.
125func TestCreate_JSONKeepsTokenValue(t *testing.T) {
126 t.Parallel()
128 tc := gitlabtesting.NewTestClient(t)
129 expectProjectCreate(tc, createdToken())
131 out, err := setupExec(t, tc)("ci-reader --scope read_repository --output json")
132 require.NoError(t, err)
134 var result gitlab.DeployToken
135 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
136 assert.Equal(t, int64(42), result.ID)
137 assert.Equal(t, "ci-reader", result.Name)
138 assert.Equal(t, "gitlab+deploy-token-42", result.Username)
139 assert.Equal(t, "gldt-secret", result.Token)
140 assert.Empty(t, out.ErrBuf.String())
141}
143func TestCreate_Scopes(t *testing.T) {
144 t.Parallel()
146 tests := []struct {
147 name string
148 args string
149 expected []string
150 }{
151 {name: "single", args: "--scope read_repository", expected: []string{"read_repository"}},
152 {name: "repeated flag", args: "--scope read_repository --scope read_registry", expected: []string{"read_repository", "read_registry"}},
153 {name: "comma-delimited", args: "--scope read_repository,read_registry", expected: []string{"read_repository", "read_registry"}},
154 }
156 for _, tt := range tests {
157 t.Run(tt.name, func(t *testing.T) {
158 t.Parallel()
160 tc := gitlabtesting.NewTestClient(t)
161 sent := expectProjectCreate(tc, createdToken())
163 _, err := setupExec(t, tc)("ci-reader " + tt.args)
164 require.NoError(t, err)
166 assert.Equal(t, tt.expected, *sent().Scopes)
167 })
168 }
169}
171func TestCreate_Username(t *testing.T) {
172 t.Parallel()
174 tc := gitlabtesting.NewTestClient(t)
175 sent := expectProjectCreate(tc, createdToken())
177 _, err := setupExec(t, tc)("ci-reader --scope read_repository --username deployer")
178 require.NoError(t, err)
180 assert.Equal(t, "deployer", *sent().Username)
181}
183// GitLab treats a blank username as absent and assigns the generated default,
184// so this guards the Changed-based detection rather than a server rejection:
185// a value test would drop the field instead of sending it.
186func TestCreate_UsernameExplicitlyEmpty(t *testing.T) {
187 t.Parallel()
189 tc := gitlabtesting.NewTestClient(t)
190 sent := expectProjectCreate(tc, createdToken())
192 _, err := setupExec(t, tc)("ci-reader --scope read_repository --username=")
193 require.NoError(t, err)
195 require.NotNil(t, sent().Username)
196 assert.Empty(t, *sent().Username)
197}
199func TestCreate_ExpiresAt(t *testing.T) {
200 t.Parallel()
202 tests := []struct {
203 name string
204 value string
205 expected time.Time
206 }{
207 {name: "date only", value: "2027-12-31", expected: time.Date(2027, 12, 31, 0, 0, 0, 0, time.UTC)},
208 {name: "RFC 3339", value: "2027-12-31T10:30:00Z", expected: time.Date(2027, 12, 31, 10, 30, 0, 0, time.UTC)},
209 // 0001-01-01 parses to the zero time, which a value test would mistake
210 // for an absent flag and send as "never expires".
211 {name: "zero time", value: "0001-01-01", expected: time.Time{}},
212 }
214 for _, tt := range tests {
215 t.Run(tt.name, func(t *testing.T) {
216 t.Parallel()
218 tc := gitlabtesting.NewTestClient(t)
219 sent := expectProjectCreate(tc, createdToken())
221 _, err := setupExec(t, tc)("ci-reader --scope read_repository --expires-at " + tt.value)
222 require.NoError(t, err)
224 require.NotNil(t, sent().ExpiresAt)
225 assert.Equal(t, tt.expected, sent().ExpiresAt.UTC())
226 })
227 }
228}
230func TestCreate_InvalidExpiresAt(t *testing.T) {
231 t.Parallel()
233 tc := gitlabtesting.NewTestClient(t)
235 _, err := setupExec(t, tc)("ci-reader --scope read_repository --expires-at tomorrow")
236 require.Error(t, err)
237 assert.Contains(t, err.Error(), "invalid argument")
238}
240func TestCreate_ScopeIsRequired(t *testing.T) {
241 t.Parallel()
243 tc := gitlabtesting.NewTestClient(t)
245 _, err := setupExec(t, tc)("ci-reader")
246 require.Error(t, err)
247 assert.Contains(t, err.Error(), `required flag(s) "scope" not set`)
248}
250func TestCreate_APIError(t *testing.T) {
251 t.Parallel()
253 tc := gitlabtesting.NewTestClient(t)
254 tc.MockDeployTokens.EXPECT().
255 CreateProjectDeployToken("OWNER/REPO", gomock.Any(), gomock.Any()).
256 Return(nil, nil, errors.New("400 Bad Request"))
258 _, err := setupExec(t, tc)("ci-reader --scope not_a_scope")
259 require.Error(t, err)
261 var exitErr *cmdutils.ExitError
262 require.ErrorAs(t, err, &exitErr)
263 assert.Equal(t, "failed to create deploy token", exitErr.Details)
264 assert.Contains(t, err.Error(), "400 Bad Request")
265}
267func TestCreate_RepoAndGroupAreMutuallyExclusive(t *testing.T) {
268 t.Parallel()
270 tc := gitlabtesting.NewTestClient(t)
272 _, err := setupExec(t, tc)("ci-reader --scope read_repository --repo OWNER/REPO --group group/sub-group")
273 require.Error(t, err)
274 assert.Contains(t, err.Error(), "none of the others can be")
275}
277// The project scope needs a base repository, and says so before any client is built.
278func TestCreate_OutsideRepositoryWithoutGroup(t *testing.T) {
279 t.Parallel()
281 tc := gitlabtesting.NewTestClient(t)
283 _, err := setupExec(t, tc, cmdtest.WithBaseRepoError(errors.New("not a git repository")))("ci-reader --scope read_repository")
284 require.Error(t, err)
285 assert.Contains(t, err.Error(), "not a git repository")
286}
288// The group scope does not need a base repository.
289func TestCreate_OutsideRepositoryWithGroup(t *testing.T) {
290 t.Parallel()
292 tc := gitlabtesting.NewTestClient(t)
293 tc.MockDeployTokens.EXPECT().
294 CreateGroupDeployToken("group/sub-group", gomock.Any(), gomock.Any()).
295 Return(&gitlab.DeployToken{
296 ID: 7,
297 Name: "group-reader",
298 Username: "gitlab+deploy-token-7",
299 Scopes: []string{"read_repository"},
300 Token: "gldt-group-secret",
301 }, nil, nil)
303 out, err := setupExec(t, tc, cmdtest.WithBaseRepoError(errors.New("not a git repository")))("group-reader --scope read_repository --group group/sub-group")
304 require.NoError(t, err)
306 assert.Contains(t, out.OutBuf.String(), "group-reader")
307}
Diagnostics8 git calls · 208 ms
CallStatusSizeTime0208 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 KiB3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
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 · 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=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
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=3 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=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200263 B · 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=263 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=aff3dd5052d75f0afe2383713d669f993c82b2f9 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=263 git.pkt.payload.max=236 git.sideband.band1.bytes=236 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=236 git.pack.trailer=4076aed8a003d312c41b730611843784ab33181fOpen pack map
fetchtree:0200137 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=196 git.response.bytes=137 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=81cde88ec377c1b5b3312ec40e8e294b0fd83139 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=137 git.pkt.payload.max=110 git.sideband.band1.bytes=110 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=110 git.pack.trailer=af3e93156ce1ec31cf719a81df0fc78f52360639Open pack map
fetch2002.4 KiB196 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2417 git.response.cache=MISS git.response.duration_ms=196 git.fetch.wants=892d18db7d8be2860f910f2ed80da7ec6815617c 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=2417 git.pkt.payload.max=2390 git.sideband.band1.bytes=2390 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
- a5e2827bbc2b6483
- Request
- 73404581…
- 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