GitLabgitlab-org

cli

main
ply6 git calls57 ms98 KiB5 cachedprotocol v2
249 lines7.8 KiBRaw
1package cmdutils
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "testing"
11 "charm.land/fang/v2"
12 "github.com/spf13/cobra"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
16 "gitlab.com/gitlab-org/cli/internal/iostreams"
19// errorHandlerHarness returns IOStreams with a capturable stdout, the stdout
20// buffer itself, and fangOut — the writer fang hands the error handler
21// directly for the human-readable box, standing in for fang's own
22// colorprofile-wrapped stderr in the real binary.
23func errorHandlerHarness(t *testing.T) (*iostreams.IOStreams, *bytes.Buffer, *bytes.Buffer) {
24 t.Helper()
25 stdout := &bytes.Buffer{}
26 fangOut := &bytes.Buffer{}
27 ios := &iostreams.IOStreams{StdOut: stdout, JQ: &iostreams.JQFilter{}}
28 return ios, stdout, fangOut
31// jsonErrorOf decodes the machine-readable error object written to stdout.
32func jsonErrorOf(t *testing.T, stdout *bytes.Buffer) string {
33 t.Helper()
34 var got struct {
35 Error struct {
36 Message string `json:"message"`
37 } `json:"error"`
38 }
39 require.NoError(t, json.Unmarshal(stdout.Bytes(), &got))
40 return got.Error.Message
43func TestNewGitLabErrorHandler_TextOutput_StdoutStaysEmpty(t *testing.T) {
44 ios, stdout, fangOut := errorHandlerHarness(t)
46 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, errors.New("404 Not Found"))
48 assert.Empty(t, stdout.String(), "text output must not put anything on stdout")
49 assert.Contains(t, fangOut.String(), "404 Not Found")
52func TestNewGitLabErrorHandler_JSONOutput_WritesObjectToStdout(t *testing.T) {
53 ios, stdout, fangOut := errorHandlerHarness(t)
54 ios.SetOutputFormat("json")
56 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, errors.New("404 Not Found"))
58 assert.Equal(t, "404 Not Found", jsonErrorOf(t, stdout))
59 assert.Contains(t, fangOut.String(), "404 Not Found", "human-readable error still goes to stderr")
62// ExitError.Error() returns only the wrapped error's message; the "log"
63// string passed to WrapError is not part of it. This pins that the JSON
64// envelope follows the same contract rather than trying to surface the log
65// text too.
66func TestNewGitLabErrorHandler_JSONOutput_ExitErrorOmitsLogDetail(t *testing.T) {
67 ios, stdout, fangOut := errorHandlerHarness(t)
68 ios.SetOutputFormat("json")
70 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, WrapError(errors.New("403 Forbidden"), "cannot read variable"))
72 assert.Equal(t, "403 Forbidden", jsonErrorOf(t, stdout))
75func TestNewGitLabErrorHandler_JSONOutput_ContextCanceled(t *testing.T) {
76 ios, stdout, fangOut := errorHandlerHarness(t)
77 ios.SetOutputFormat("json")
79 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, fmt.Errorf("aborted: %w", context.Canceled))
81 assert.Equal(t, errCommandInterrupted.Error(), jsonErrorOf(t, stdout))
82 assert.Contains(t, fangOut.String(), errCommandInterrupted.Error())
85func TestNewGitLabErrorHandler_TextOutput_ContextCanceled(t *testing.T) {
86 ios, stdout, fangOut := errorHandlerHarness(t)
88 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, fmt.Errorf("aborted: %w", context.Canceled))
90 assert.Empty(t, stdout.String())
91 assert.Contains(t, fangOut.String(), errCommandInterrupted.Error())
94func TestNewGitLabErrorHandler_SilentError_WritesNothing(t *testing.T) {
95 ios, stdout, fangOut := errorHandlerHarness(t)
97 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, SilentError)
98 assert.Empty(t, stdout.String())
99 assert.Empty(t, fangOut.String())
101 ios.SetOutputFormat("json")
102 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, SilentError)
103 assert.Empty(t, stdout.String(), "SilentError must stay silent in JSON output too")
104 assert.Empty(t, fangOut.String())
107func TestNewGitLabErrorHandler_JSONOutput_IgnoresJQFilter(t *testing.T) {
108 // --jq is written against the command's success output, so applying it to
109 // the error object would hide the failure behind a filter error.
110 ios, stdout, fangOut := errorHandlerHarness(t)
111 ios.SetOutputFormat("json")
112 require.NoError(t, ios.JQ.Set(".[].id"))
114 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, errors.New("404 Not Found"))
116 assert.Equal(t, "404 Not Found", jsonErrorOf(t, stdout))
119// TestGitLabErrorHandler_EndToEnd drives the whole path the issue describes: a
120// command registers --output through EnableJSONOutput, fails before printing
121// anything, and fang hands the resulting error to our handler.
122func TestGitLabErrorHandler_EndToEnd(t *testing.T) {
123 tests := []struct {
124 name string
125 args []string
126 wantJSONStdout bool
127 wantMessage string
128 }{
129 {
130 name: "failure inside RunE with --output=json",
131 args: []string{"KEY", "--output", "json"},
132 wantJSONStdout: true,
133 wantMessage: "404 Not Found",
134 },
135 {
136 name: "failure during argument validation with -F json",
137 args: []string{"-F", "json"},
138 wantJSONStdout: true,
139 wantMessage: "accepts 1 arg(s), received 0",
140 },
141 {
142 name: "failure inside RunE without an output flag",
143 args: []string{"KEY"},
144 wantJSONStdout: false,
145 wantMessage: "404 Not Found",
146 },
147 {
148 name: "failure inside RunE with an explicit text output flag",
149 args: []string{"KEY", "-F", "text"},
150 wantJSONStdout: false,
151 wantMessage: "404 Not Found",
152 },
153 }
155 for _, tc := range tests {
156 t.Run(tc.name, func(t *testing.T) {
157 ios, stdout, fangOut := errorHandlerHarness(t)
158 cmd := &cobra.Command{
159 Use: "test <key>",
160 Args: cobra.ExactArgs(1),
161 SilenceUsage: true,
162 SilenceErrors: true,
163 RunE: func(*cobra.Command, []string) error { return errors.New("404 Not Found") },
164 }
165 var outputFormat string
166 EnableJSONOutput(cmd, ios, &outputFormat)
167 cmd.SetArgs(tc.args)
169 err := cmd.Execute()
170 require.Error(t, err)
172 NewGitLabErrorHandler(ios)(fangOut, fang.Styles{}, err)
174 assert.Contains(t, fangOut.String(), tc.wantMessage)
175 if !tc.wantJSONStdout {
176 assert.Empty(t, stdout.String())
177 return
178 }
179 assert.Equal(t, tc.wantMessage, jsonErrorOf(t, stdout))
180 })
181 }
184func TestNewGitLabErrorHandler_KeepsErrorTextAsWritten(t *testing.T) {
185 tests := []struct {
186 name string
187 errMsg string
188 wantText string
189 }{
190 {
191 name: "long flag",
192 errMsg: "--title required for snippets",
193 wantText: "--title required for snippets.",
194 },
195 {
196 name: "hyphenated long flag",
197 errMsg: "--source-branch is required",
198 wantText: "--source-branch is required.",
199 },
200 {
201 name: "short flag",
202 errMsg: "-t is required",
203 wantText: "-t is required.",
204 },
205 {
206 name: "single-quoted flag list",
207 errMsg: "'--stdin', '--token', '--job-token', '--web', or '--device' required when not running interactively",
208 wantText: "'--stdin', '--token', '--job-token', '--web', or '--device' required when not running interactively.",
209 },
210 {
211 name: "backtick-quoted flag",
212 errMsg: "`--token` parameter can be omitted only if `CI_JOB_TOKEN` environment variable is set",
213 wantText: "`--token` parameter can be omitted only if `CI_JOB_TOKEN` environment variable is set.",
214 },
215 {
216 name: "uppercase acronym",
217 errMsg: "JSON marshal: boom",
218 wantText: "JSON marshal: boom.",
219 },
220 {
221 name: "prose error keeps lowercase first word",
222 errMsg: "flag needs an argument: -t",
223 wantText: "flag needs an argument: -t.",
224 },
225 }
227 for _, tc := range tests {
228 t.Run(tc.name, func(t *testing.T) {
229 ios, _, fangOut := errorHandlerHarness(t)
230 cmd := &cobra.Command{
231 Use: "test",
232 RunE: func(*cobra.Command, []string) error { return errors.New(tc.errMsg) },
233 }
234 cmd.SetErr(fangOut)
235 cmd.SetArgs([]string{})
237 err := fang.Execute(
238 t.Context(),
239 cmd,
240 fang.WithoutCompletions(),
241 fang.WithoutManpage(),
242 fang.WithoutVersion(),
243 fang.WithErrorHandler(NewGitLabErrorHandler(ios)),
244 )
245 require.EqualError(t, err, tc.errMsg)
246 assert.Contains(t, fangOut.String(), tc.wantText)
247 })
248 }
Diagnostics6 git calls · 57 ms
CallStatusSizeTime057 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 KiB · hit2 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=HIT
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
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.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=50
git.response.bytes=1238
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=c10f4b8b760c3fec7ed8ca85e428d5bc523f8e17
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=1238
git.pkt.payload.max=1211
git.sideband.band1.bytes=1211
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=1211
git.pack.trailer=7373aa350f2a611db7d4116eb1450c92f18a27ca
Open pack map
fetch2002.2 KiB · hit50 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=2287
git.response.cache=HIT
git.response.duration_ms=50
git.fetch.wants=f5f1eddde424e81425eb7cba9282cf59a4ed9e61
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=2287
git.pkt.payload.max=2260
git.sideband.band1.bytes=2260
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
a5e18b6d7cd75e37
Request
6824d619…
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