GitLabgitlab-org
cli
main
1//go:build !integration
3package create
5import (
6 "context"
7 "errors"
8 "fmt"
9 "io/fs"
10 "os"
11 "path/filepath"
12 "testing"
14 "github.com/spf13/cobra"
15 "github.com/stretchr/testify/assert"
16 "github.com/stretchr/testify/require"
17 "go.uber.org/mock/gomock"
19 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
20 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
22 "gitlab.com/gitlab-org/cli/internal/cmdutils"
23 "gitlab.com/gitlab-org/cli/internal/git"
24 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
25)
27func TestIssueCreate_TemplateDirectoryError(t *testing.T) {
28 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
29 root := t.TempDir()
30 folder := filepath.Join(root, ".gitlab", "issue_templates")
31 require.NoError(t, os.MkdirAll(filepath.Dir(folder), 0o755))
32 require.NoError(t, os.WriteFile(folder, []byte("not a directory"), 0o644))
33 originalToplevelDir := git.ToplevelDir
34 git.ToplevelDir = func() (string, error) { return root, nil }
35 t.Cleanup(func() { git.ToplevelDir = originalToplevelDir })
37 tc := gitlabtesting.NewTestClient(t)
38 tc.MockProjects.EXPECT().GetProject("OWNER/REPO", gomock.Any()).Return(&gitlab.Project{
39 ID: 1, PathWithNamespace: "OWNER/REPO", IssuesEnabled: true,
40 }, nil, nil)
41 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
42 cmd := NewCmdCreate(f)
43 // Select does not check PromptEnabled; cancellation prevents a reverted fix from blocking.
44 ctx, cancel := context.WithCancel(t.Context())
45 cancel()
46 cmd.SetContext(ctx)
47 return cmd
48 }, false,
49 cmdtest.WithGitLabClient(tc.Client),
50 func(f *cmdtest.Factory) { f.IOStub.SetPrompt("true") },
51 )
52 _, err := exec(`--title "Test issue" --description - --yes`)
53 var pathErr *os.PathError
54 require.ErrorAs(t, err, &pathErr)
55 assert.Equal(t, folder, pathErr.Path)
56 assert.Contains(t, err.Error(), "error getting templates")
57}
59func TestGenerateIssueWebURL(t *testing.T) {
60 opts := &options{
61 Labels: []string{"backend", "frontend"},
62 Assignees: []string{"johndoe", "janedoe"},
63 Milestone: 15,
64 Weight: 3,
65 IsConfidential: true,
66 baseProject: &gitlab.Project{
67 ID: 101,
68 WebURL: "https://gitlab.example.com/gitlab-org/gitlab",
69 },
70 Title: "Autofill tests | for this @project",
71 }
73 u, err := generateIssueWebURL(opts)
75 expectedUrl := "https://gitlab.example.com/gitlab-org/gitlab/-/issues/new?" +
76 "issue%5Bdescription%5D=%0A%2Flabel+~%22backend%22+~%22frontend%22%0A%2Fassign+johndoe%2C+janedoe%0A%2Fmilestone+%2515%0A%2Fweight+3%0A%2Fconfidential&" +
77 "issue%5Btitle%5D=Autofill+tests+%7C+for+this+%40project"
79 require.NoError(t, err)
80 assert.Equal(t, expectedUrl, u)
81}
83func TestIssueCreate_WithTemplate(t *testing.T) {
84 // Cannot use t.Parallel(): test mutates git.ToplevelDir, a package-level variable.
85 t.Setenv("NO_COLOR", "true")
87 tmpDir := t.TempDir()
88 templateDir := filepath.Join(tmpDir, ".gitlab", "issue_templates")
89 require.NoError(t, os.MkdirAll(templateDir, 0o755))
90 require.NoError(t, os.WriteFile(filepath.Join(templateDir, "bug.md"), []byte("## Bug Report\n\nDescribe the bug here."), 0o644))
92 origToplevelDir := git.ToplevelDir
93 git.ToplevelDir = func() (string, error) { return tmpDir, nil }
94 t.Cleanup(func() { git.ToplevelDir = origToplevelDir })
96 testClient := gitlabtesting.NewTestClient(t)
97 testClient.MockProjects.EXPECT().
98 GetProject("OWNER/REPO", gomock.Any()).
99 Return(&gitlab.Project{
100 ID: 37777023,
101 PathWithNamespace: "OWNER/REPO",
102 IssuesEnabled: true,
103 }, nil, nil)
104 testClient.MockIssues.EXPECT().
105 CreateIssue("OWNER/REPO", gomock.Any()).
106 DoAndReturn(func(_ any, opts *gitlab.CreateIssueOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.Issue, *gitlab.Response, error) {
107 assert.Equal(t, "## Bug Report\n\nDescribe the bug here.", *opts.Description)
108 return &gitlab.Issue{IID: 1, Title: "Test Issue", WebURL: "https://gitlab.com/OWNER/REPO/-/issues/1"}, nil, nil
109 })
111 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false, cmdtest.WithGitLabClient(testClient.Client))
113 output, err := exec(`--title "Test Issue" --template bug --yes`)
114 require.NoError(t, err)
115 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/issues/1")
116}
118func TestIssueCreate_TemplateWithMdExtension(t *testing.T) {
119 // Cannot use t.Parallel(): test mutates git.ToplevelDir, a package-level variable.
120 t.Setenv("NO_COLOR", "true")
122 tmpDir := t.TempDir()
123 templateDir := filepath.Join(tmpDir, ".gitlab", "issue_templates")
124 require.NoError(t, os.MkdirAll(templateDir, 0o755))
125 require.NoError(t, os.WriteFile(filepath.Join(templateDir, "bug.md"), []byte("## Bug Report\n\nDescribe the bug here."), 0o644))
127 origToplevelDir := git.ToplevelDir
128 git.ToplevelDir = func() (string, error) { return tmpDir, nil }
129 t.Cleanup(func() { git.ToplevelDir = origToplevelDir })
131 testClient := gitlabtesting.NewTestClient(t)
132 testClient.MockProjects.EXPECT().
133 GetProject("OWNER/REPO", gomock.Any()).
134 Return(&gitlab.Project{
135 ID: 37777023,
136 PathWithNamespace: "OWNER/REPO",
137 IssuesEnabled: true,
138 }, nil, nil)
139 testClient.MockIssues.EXPECT().
140 CreateIssue("OWNER/REPO", gomock.Any()).
141 DoAndReturn(func(_ any, opts *gitlab.CreateIssueOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.Issue, *gitlab.Response, error) {
142 assert.Equal(t, "## Bug Report\n\nDescribe the bug here.", *opts.Description)
143 return &gitlab.Issue{IID: 1, Title: "Test Issue", WebURL: "https://gitlab.com/OWNER/REPO/-/issues/1"}, nil, nil
144 })
146 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false, cmdtest.WithGitLabClient(testClient.Client))
148 // Passing "bug.md" should work the same as "bug"
149 output, err := exec(`--title "Test Issue" --template bug.md --yes`)
150 require.NoError(t, err)
151 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/issues/1")
152}
154func TestIssueCreate_TemplateFilePath(t *testing.T) {
155 // Cannot use t.Parallel(): test mutates git.ToplevelDir, a package-level variable.
156 t.Setenv("NO_COLOR", "true")
158 templateFile := filepath.Join(t.TempDir(), "bug.md")
159 require.NoError(t, os.WriteFile(templateFile, []byte("## Team Bug Report"), 0o644))
161 origToplevelDir := git.ToplevelDir
162 git.ToplevelDir = func() (string, error) { return "", errors.New("not a git repository") }
163 t.Cleanup(func() { git.ToplevelDir = origToplevelDir })
165 testClient := gitlabtesting.NewTestClient(t)
166 testClient.MockProjects.EXPECT().
167 GetProject("OWNER/REPO", gomock.Any()).
168 Return(&gitlab.Project{
169 ID: 37777023,
170 PathWithNamespace: "OWNER/REPO",
171 IssuesEnabled: true,
172 }, nil, nil)
173 testClient.MockIssues.EXPECT().
174 CreateIssue("OWNER/REPO", gomock.Any()).
175 DoAndReturn(func(_ any, opts *gitlab.CreateIssueOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.Issue, *gitlab.Response, error) {
176 assert.Equal(t, "## Team Bug Report", *opts.Description)
177 return &gitlab.Issue{IID: 1, Title: "Test Issue", WebURL: "https://gitlab.com/OWNER/REPO/-/issues/1"}, nil, nil
178 })
180 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false, cmdtest.WithGitLabClient(testClient.Client))
182 output, err := exec(fmt.Sprintf(`--title "Test Issue" --template %q --yes`, templateFile))
183 require.NoError(t, err)
184 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/issues/1")
185}
187func TestIssueCreate_TemplateFilePathNotFound(t *testing.T) {
188 t.Parallel()
190 testClient := gitlabtesting.NewTestClient(t)
191 testClient.MockProjects.EXPECT().
192 GetProject("OWNER/REPO", gomock.Any()).
193 Return(&gitlab.Project{
194 ID: 37777023,
195 PathWithNamespace: "OWNER/REPO",
196 IssuesEnabled: true,
197 }, nil, nil)
199 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false, cmdtest.WithGitLabClient(testClient.Client))
201 missing := filepath.Join(t.TempDir(), "missing.md")
202 _, err := exec(fmt.Sprintf(`--title "Test Issue" --template %q --yes`, missing))
203 assert.ErrorIs(t, err, fs.ErrNotExist)
204}
206func TestIssueCreate_TemplateNotFound(t *testing.T) {
207 // Cannot use t.Parallel(): test mutates git.ToplevelDir, a package-level variable.
208 tmpDir := t.TempDir()
209 require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, ".gitlab", "issue_templates"), 0o755))
211 origToplevelDir := git.ToplevelDir
212 git.ToplevelDir = func() (string, error) { return tmpDir, nil }
213 t.Cleanup(func() { git.ToplevelDir = origToplevelDir })
215 testClient := gitlabtesting.NewTestClient(t)
216 testClient.MockProjects.EXPECT().
217 GetProject("OWNER/REPO", gomock.Any()).
218 Return(&gitlab.Project{
219 ID: 37777023,
220 PathWithNamespace: "OWNER/REPO",
221 IssuesEnabled: true,
222 }, nil, nil)
224 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false, cmdtest.WithGitLabClient(testClient.Client))
226 _, err := exec(`--title "Test Issue" --template nonexistent --yes`)
227 assert.ErrorContains(t, err, `template "nonexistent" not found in .gitlab/issue_templates/`)
228}
230func TestIssueCreate_TemplateMutuallyExclusiveWithDescription(t *testing.T) {
231 t.Parallel()
233 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false)
235 _, err := exec(`--title "Test Issue" --template bug --description "my description"`)
236 assert.Error(t, err)
237}
239func TestIssueCreateWhenIssuesDisabled(t *testing.T) {
240 // GIVEN
241 testClient := gitlabtesting.NewTestClient(t)
243 testClient.MockProjects.EXPECT().
244 GetProject("OWNER/REPO", gomock.Any()).
245 Return(&gitlab.Project{
246 ID: 37777023,
247 Description: "this is a test description",
248 Name: "REPO",
249 NameWithNamespace: "Test User / REPO",
250 Path: "REPO",
251 PathWithNamespace: "OWNER/REPO",
252 DefaultBranch: "main",
253 HTTPURLToRepo: "https://gitlab.com/OWNER/REPO.git",
254 WebURL: "https://gitlab.com/OWNER/REPO",
255 ReadmeURL: "https://gitlab.com/OWNER/REPO/-/blob/main/README.md",
256 IssuesEnabled: false,
257 }, nil, nil)
259 exec := cmdtest.SetupCmdForTest(
260 t,
261 NewCmdCreate,
262 false,
263 cmdtest.WithGitLabClient(testClient.Client),
264 )
266 // WHEN
267 cli := `--title "test title" --description "test description"`
268 output, err := exec(cli)
270 // THEN
271 require.Error(t, err)
272 assert.Empty(t, output.String())
273 assert.Equal(t, "Issues are disabled for project \"OWNER/REPO\" or require project membership. "+
274 "Make sure issues are enabled for the \"OWNER/REPO\" project, and if required, you are a member of the project.\n",
275 output.Stderr())
276}
278func TestIssueCreate_DescriptionFile(t *testing.T) {
279 const body = "# Heading\n\nMulti-line body with \"quotes\", $VARS and `backticks`.\n"
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 testClient := gitlabtesting.NewTestClient(t)
292 testClient.MockProjects.EXPECT().
293 GetProject("OWNER/REPO", gomock.Any()).
294 Return(&gitlab.Project{ID: 1, PathWithNamespace: "OWNER/REPO", IssuesEnabled: true}, nil, nil)
296 var gotDescription *string
297 testClient.MockIssues.EXPECT().
298 CreateIssue("OWNER/REPO", gomock.Any()).
299 DoAndReturn(func(_ any, opts *gitlab.CreateIssueOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.Issue, *gitlab.Response, error) {
300 gotDescription = opts.Description
301 return &gitlab.Issue{IID: 1, Title: "Test Issue", WebURL: "https://gitlab.com/OWNER/REPO/-/issues/1"}, nil, nil
302 })
304 factoryOpts := []cmdtest.FactoryOption{cmdtest.WithGitLabClient(testClient.Client)}
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, NewCmdCreate, false, factoryOpts...)
316 _, err := exec(fmt.Sprintf(`--title "Test Issue" --description-file %q --yes`, path))
317 require.NoError(t, err)
319 require.NotNil(t, gotDescription)
320 assert.Equal(t, body, *gotDescription)
321 })
322 }
323}
325func TestIssueCreate_DescriptionFileConflicts(t *testing.T) {
326 tests := []struct {
327 name string
328 cli string
329 want string
330 }{
331 {
332 name: "with --description",
333 cli: `--title "Test Issue" --description inline --description-file some.md`,
334 want: "[description description-file]",
335 },
336 {
337 name: "with --template",
338 cli: `--title "Test Issue" --template bug --description-file some.md`,
339 want: "[template description-file]",
340 },
341 }
343 for _, tt := range tests {
344 t.Run(tt.name, func(t *testing.T) {
345 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false)
347 _, err := exec(tt.cli)
349 require.Error(t, err)
350 assert.Contains(t, err.Error(), tt.want)
351 })
352 }
353}
Diagnostics8 git calls · 186 ms
CallStatusSizeTime0186 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 · hit3 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=HIT 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
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=44Open pack map
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: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:0200492 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=492 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=409e7038e253494f94691a22a250deee77ba03bf 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=492 git.pkt.payload.max=465 git.sideband.band1.bytes=465 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=465 git.pack.trailer=c8a67aa26d573734cf0c8f302f8c1dd08e47d76aOpen pack map
fetchtree:0200241 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=241 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=65456ca49a78f4c6f0b98ffad089d9ea28940f53 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=241 git.pkt.payload.max=214 git.sideband.band1.bytes=214 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=214 git.pack.trailer=3c6055d4ff8dc803acc935ee10d6f6301f2e5c6bOpen pack map
fetch2002.8 KiB171 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=171 git.response.bytes=2870 git.response.cache=MISS git.response.duration_ms=171 git.fetch.wants=5338c45f9964ef3443c58f75dabe050a26f29951 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=2870 git.pkt.payload.max=2843 git.sideband.band1.bytes=2843 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
- a5e294b42b9d224d
- Request
- 494bba7a…
- 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