GitLabgitlab-org

cli

main
ply8 git calls254 ms101 KiB5 cachedprotocol v2
391 lines11 KiBRaw
1//go:build !integration
3package update
5import (
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10 "testing"
11 "time"
13 "github.com/MakeNowJust/heredoc/v2"
14 "github.com/acarl005/stripansi"
15 "github.com/google/shlex"
16 "github.com/stretchr/testify/assert"
17 "github.com/stretchr/testify/require"
19 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
21 "gitlab.com/gitlab-org/cli/internal/api"
22 "gitlab.com/gitlab-org/cli/internal/cmdutils"
23 "gitlab.com/gitlab-org/cli/internal/config"
24 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
27// TODO: test by mocking the appropriate api function
28func TestMain(m *testing.M) {
29 cmdtest.InitTest(m, "mr_update_test")
32func TestUpdateMergeRequest(t *testing.T) {
33 io, _, stdout, stderr := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(true))
34 f := cmdtest.NewTestFactory(io, cmdtest.WithConfig(config.NewFromString(heredoc.Doc(`
35 hosts:
36 gitlab.com:
37 username: monalisa
38 token: OTOKEN
39 `))))
40 oldUpdateMr := api.UpdateMR
41 oldGetMR, oldListMRs := api.GetMR, api.ListMRs
42 t.Cleanup(func() {
43 api.UpdateMR, api.GetMR, api.ListMRs = oldUpdateMr, oldGetMR, oldListMRs
44 })
45 timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
46 toggle := false
48 api.UpdateMR = func(client *gitlab.Client, projectID any, mrID int64, opts *gitlab.UpdateMergeRequestOptions) (*gitlab.MergeRequest, error) {
49 if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" || mrID == 0 {
50 return nil, fmt.Errorf("error expected")
51 }
52 repo, err := f.BaseRepo()
53 if err != nil {
54 return nil, err
55 }
57 // Use provided title and body from opts if available
58 title := "mrTitle"
59 body := "mrbody"
60 if opts.Title != nil {
61 title = *opts.Title
62 }
63 if opts.Description != nil {
64 body = *opts.Description
65 }
67 mr := &gitlab.MergeRequest{
68 BasicMergeRequest: gitlab.BasicMergeRequest{
69 ID: mrID,
70 IID: mrID,
71 Title: title,
72 Labels: gitlab.Labels{"bug", "test"},
73 State: "opened",
74 Description: body,
75 Author: &gitlab.BasicUser{
76 ID: mrID,
77 Name: "John Dev Wick",
78 Username: "jdwick",
79 },
80 WebURL: "https://" + repo.RepoHost() + "/" + repo.FullName() + "/-/merge_requests/" + fmt.Sprintf("%d", mrID),
81 CreatedAt: &timer,
82 },
83 }
85 if opts.RemoveSourceBranch != nil {
86 toggle = !toggle
87 mr.ForceRemoveSourceBranch = toggle
88 }
90 return mr, nil
91 }
93 api.GetMR = func(client *gitlab.Client, projectID any, mrID int64, opts *gitlab.GetMergeRequestsOptions) (*gitlab.MergeRequest, error) {
94 if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" {
95 return nil, fmt.Errorf("error expected")
96 }
97 repo, err := f.BaseRepo()
98 if err != nil {
99 return nil, err
100 }
101 title := map[int64]string{
102 1: "mrTitle",
103 2: "Draft: mrTitle",
104 3: "Draft: wip: wip: draft: DrAfT: mrTitle",
105 }[mrID]
106 return &gitlab.MergeRequest{
107 BasicMergeRequest: gitlab.BasicMergeRequest{
108 ID: mrID,
109 IID: mrID,
110 Title: title,
111 Labels: gitlab.Labels{"test", "bug"},
112 State: "opened",
113 Description: "mrBody",
114 ForceRemoveSourceBranch: toggle,
115 SourceBranch: "feature/test-branch",
116 TargetBranch: "main",
117 Author: &gitlab.BasicUser{
118 ID: mrID,
119 Name: "John Dev Wick",
120 Username: "jdwick",
121 },
122 WebURL: fmt.Sprintf("https://%s/%s/-/merge_requests/%d", repo.RepoHost(), repo.FullName(), mrID),
123 },
124 }, nil
125 }
127 api.ListMRs = func(client *gitlab.Client, projectID any, opts *gitlab.ListProjectMergeRequestsOptions, listOpts ...api.CliListMROption) ([]*gitlab.BasicMergeRequest, error) {
128 return []*gitlab.BasicMergeRequest{}, nil
129 }
131 testCases := []struct {
132 Name string
133 Args string
134 ExpectedMsg []string
135 wantErr bool
136 }{
137 {
138 Name: "Update works",
139 Args: "1",
140 ExpectedMsg: []string{"- Updating merge request !1"},
141 },
142 {
143 Name: "Remove source branch",
144 Args: "1 --remove-source-branch",
145 ExpectedMsg: []string{
146 "- Updating merge request !1",
147 "✓ enabled removal of source branch on merge",
148 },
149 },
150 {
151 Name: "Restore remove source branch",
152 Args: "1 --remove-source-branch",
153 ExpectedMsg: []string{
154 "- Updating merge request !1",
155 "✓ disabled removal of source branch on merge",
156 },
157 },
158 {
159 Name: "Issue Does Not Exist",
160 Args: "0",
161 ExpectedMsg: []string{"invalid merge request ID provided"},
162 wantErr: true,
163 },
164 {
165 Name: "Set draft",
166 Args: "1 --draft",
167 ExpectedMsg: []string{"marked as Draft", "!1 Draft: mrTitle"},
168 },
169 {
170 Name: "Don't set draft twice",
171 Args: "2 --draft",
172 ExpectedMsg: []string{"✓ already a Draft", "2 Draft: mrTitle"},
173 },
174 {
175 Name: "Set WIP",
176 Args: "1 --wip",
177 ExpectedMsg: []string{"marked as WIP", "!1 WIP: mrTitle"},
178 },
179 {
180 Name: "Set ready",
181 Args: "2 --ready",
182 ExpectedMsg: []string{"✓ marked as ready", "2 mrTitle"},
183 },
184 {
185 Name: "Set ready with multiple draft prefixes",
186 Args: "3 --ready",
187 ExpectedMsg: []string{"✓ marked as ready", "3 mrTitle"},
188 },
189 {
190 Name: "Fill commit body requires fill flag",
191 Args: "1 --fill-commit-body",
192 ExpectedMsg: []string{"--fill-commit-body should be used with --fill"},
193 wantErr: true,
194 },
195 {
196 Name: "Update with fill flag",
197 Args: "1 --fill --yes",
198 ExpectedMsg: []string{"- Updating merge request !1", "updated title with commit info", "updated body with commit info"},
199 },
200 {
201 Name: "Update with fill and fill-commit-body flags",
202 Args: "1 --fill --fill-commit-body --yes",
203 ExpectedMsg: []string{"- Updating merge request !1", "updated title with commit info", "updated body with commit info"},
204 },
205 {
206 Name: "Update with yes flag skips confirmation",
207 Args: "1 --fill --yes",
208 ExpectedMsg: []string{"- Updating merge request !1"},
209 },
210 {
211 Name: "Update with fill flag and explicit title",
212 Args: "1 --fill --title 'Custom Title' --yes",
213 ExpectedMsg: []string{"- Updating merge request !1", "updated body with commit info"},
214 },
215 {
216 Name: "Update with fill flag and explicit body",
217 Args: "1 --fill --description 'Custom Description' --yes",
218 ExpectedMsg: []string{"- Updating merge request !1", "updated title with commit info"},
219 },
220 {
221 Name: "Update with fill flag on non-git directory",
222 Args: "1 --fill --yes",
223 ExpectedMsg: []string{"- Updating merge request !1"},
224 },
225 {
226 Name: "Update without fill flag should not use autofill",
227 Args: "1 --yes",
228 ExpectedMsg: []string{"- Updating merge request !1"},
229 },
230 }
232 cumulativePreviousOutputLen := 0
233 for _, tc := range testCases {
234 cmd := NewCmdUpdate(f)
235 cmdutils.EnableRepoOverride(cmd, f)
236 t.Run(tc.Name, func(t *testing.T) {
237 // Handle regular command tests
238 argv, err := shlex.Split(tc.Args)
239 if err != nil {
240 t.Fatal(err)
241 }
242 cmd.SetArgs(argv)
243 _, err = cmd.ExecuteC()
244 if err != nil {
245 if tc.wantErr {
246 require.Error(t, err)
247 // For error cases, check if the error message contains expected text
248 for _, msg := range tc.ExpectedMsg {
249 assert.Contains(t, err.Error(), msg)
250 }
251 return
252 } else {
253 t.Fatal(err)
254 }
255 }
257 // For success cases, check stdout output
258 out := stripansi.Strip(stdout.String())[cumulativePreviousOutputLen:]
259 cumulativePreviousOutputLen += len(out)
261 for _, msg := range tc.ExpectedMsg {
262 assert.Contains(t, out, msg)
263 assert.Empty(t, stderr.String())
264 }
265 })
266 }
268 api.UpdateMR = oldUpdateMr
271func TestUpdateMergeRequest_DescriptionFile(t *testing.T) {
272 const body = "# Heading\n\nMulti-line body with \"quotes\", $VARS and `backticks`.\n"
274 oldUpdateMR, oldGetMR := api.UpdateMR, api.GetMR
275 t.Cleanup(func() { api.UpdateMR, api.GetMR = oldUpdateMR, oldGetMR })
277 api.GetMR = func(client *gitlab.Client, projectID any, mrID int64, opts *gitlab.GetMergeRequestsOptions) (*gitlab.MergeRequest, error) {
278 return &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{ID: mrID, IID: mrID, Title: "mrTitle", State: "opened"}}, nil
279 }
281 tests := []struct {
282 name string
283 useStdin bool
284 }{
285 {name: "reads the description from a file"},
286 {name: "reads the description from standard input", useStdin: true},
287 }
289 for _, tt := range tests {
290 t.Run(tt.name, func(t *testing.T) {
291 var gotDescription *string
292 api.UpdateMR = func(client *gitlab.Client, projectID any, mrID int64, opts *gitlab.UpdateMergeRequestOptions) (*gitlab.MergeRequest, error) {
293 gotDescription = opts.Description
294 return &gitlab.MergeRequest{BasicMergeRequest: gitlab.BasicMergeRequest{ID: mrID, IID: mrID, Title: "mrTitle", State: "opened"}}, nil
295 }
297 factoryOpts := []cmdtest.FactoryOption{
298 cmdtest.WithConfig(config.NewFromString(heredoc.Doc(`
299 hosts:
300 gitlab.com:
301 username: monalisa
302 token: OTOKEN
303 `))),
304 }
306 path := "-"
307 if tt.useStdin {
308 factoryOpts = append(factoryOpts, cmdtest.WithStdin(body))
309 } else {
310 path = filepath.Join(t.TempDir(), "description.md")
311 require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
312 }
314 exec := cmdtest.SetupCmdForTest(t, NewCmdUpdate, false, factoryOpts...)
316 _, err := exec(fmt.Sprintf("1 --description-file %q", path))
317 require.NoError(t, err)
319 require.NotNil(t, gotDescription)
320 assert.Equal(t, body, *gotDescription)
321 })
322 }
325func TestUpdateMergeRequest_DescriptionFileConflictsWithDescription(t *testing.T) {
326 exec := cmdtest.SetupCmdForTest(t, NewCmdUpdate, false)
328 _, err := exec(`1 --description inline --description-file some.md`)
330 require.Error(t, err)
331 assert.Contains(t, err.Error(), "[description description-file]")
334func TestWriteUpdatePreview(t *testing.T) {
335 t.Parallel()
336 tests := []struct {
337 name string
338 title string
339 description string
340 want string
341 }{
342 {
343 name: "single-line title and description",
344 title: "My title",
345 description: "My description",
346 want: "\nProposed changes:\n Title: My title\n Description: My description\n\n",
347 },
348 {
349 name: "multi-line title indents continuation lines",
350 title: "First line\nSecond line\nThird line",
351 want: "\nProposed changes:\n Title: First line\n Second line\n Third line\n\n",
352 },
353 {
354 name: "multi-line description indents continuation lines",
355 description: "First line\nSecond line",
356 want: "\nProposed changes:\n Description: First line\n Second line\n\n",
357 },
358 {
359 name: "editor mode placeholder",
360 description: "(from editor)",
361 want: "\nProposed changes:\n Description: (from editor)\n\n",
362 },
363 {
364 name: "only title shown when description is empty",
365 title: "Just a title",
366 description: "",
367 want: "\nProposed changes:\n Title: Just a title\n\n",
368 },
369 {
370 name: "only description shown when title is empty",
371 title: "",
372 description: "Just a description",
373 want: "\nProposed changes:\n Description: Just a description\n\n",
374 },
375 {
376 name: "nothing shown when both are empty",
377 title: "",
378 description: "",
379 want: "\nProposed changes:\n\n",
380 },
381 }
383 for _, tc := range tests {
384 t.Run(tc.name, func(t *testing.T) {
385 t.Parallel()
386 var buf strings.Builder
387 writeUpdatePreview(&buf, tc.title, tc.description)
388 assert.Equal(t, tc.want, buf.String())
389 })
390 }
Diagnostics8 git calls · 254 ms
CallStatusSizeTime0254 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=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 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 · 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:0200746 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=746
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=f3d413a22af5a9c2fe9aa49709b1cb36d1351a7f
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=746
git.pkt.payload.max=719
git.sideband.band1.bytes=719
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=719
git.pack.trailer=330baf80c59a4208b55120dff7dd824b7952b790
Open pack map
fetchtree:0200202 B · hit3 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=202
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=fa6643fe030fa248faec6c90791640385205057a
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=202
git.pkt.payload.max=175
git.sideband.band1.bytes=175
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=175
git.pack.trailer=5de59e2c2970b3a7ffbcd12e501883f267881024
Open pack map
fetch2003.2 KiB242 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=3237
git.response.cache=MISS
git.response.duration_ms=242
git.fetch.wants=c0a9a598dde60355d0f53ba9e6c5454f6d155515
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=3237
git.pkt.payload.max=3210
git.sideband.band1.bytes=3210
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
a5e2da276e3d14c2
Request
7abd94e2…
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