GitLabgitlab-org
cli
main
1package iostreams
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "testing"
9 "github.com/stretchr/testify/assert"
10 "github.com/stretchr/testify/require"
11)
13// newIOWithJQ returns an IOStreams suitable for tests, with a fresh JQFilter
14// already attached so callers can drive it via io.JQ.Set without nil checks.
15func newIOWithJQ(buf *bytes.Buffer) *IOStreams {
16 return &IOStreams{StdOut: buf, JQ: &JQFilter{}}
17}
19func TestPrintJSON_TopLevelNilSliceBecomesEmptyArray(t *testing.T) {
20 // Test that top-level nil slices (like from gitlab.ScanAndCollect) are
21 // normalized to [] instead of null
22 type Token struct {
23 ID int `json:"id"`
24 Name string `json:"name"`
25 }
27 buf := &bytes.Buffer{}
28 io := newIOWithJQ(buf)
30 // Simulate what gitlab.ScanAndCollect returns for empty results
31 var tokens []Token // nil slice
33 err := io.PrintJSON(tokens)
34 require.NoError(t, err)
36 // Verify the actual JSON output is []
37 assert.Equal(t, "[]\n", buf.String())
38}
40func TestPrintJSON_TopLevelSliceWithData(t *testing.T) {
41 // Test that top-level slices with data are preserved correctly
42 type Token struct {
43 ID int `json:"id"`
44 Name string `json:"name"`
45 }
47 buf := &bytes.Buffer{}
48 io := newIOWithJQ(buf)
50 tokens := []Token{
51 {ID: 1, Name: "token1"},
52 {ID: 2, Name: "token2"},
53 }
55 err := io.PrintJSON(tokens)
56 require.NoError(t, err)
58 // Parse the output
59 var result []Token
60 jsonBytes := bytes.TrimSpace(buf.Bytes())
61 err = json.Unmarshal(jsonBytes, &result)
62 require.NoError(t, err)
64 assert.Len(t, result, 2)
65 assert.Equal(t, tokens[0].ID, result[0].ID)
66 assert.Equal(t, tokens[0].Name, result[0].Name)
67 assert.Equal(t, tokens[1].ID, result[1].ID)
68 assert.Equal(t, tokens[1].Name, result[1].Name)
69}
71func TestPrintJSON_NestedNilSlicesPreserved(t *testing.T) {
72 // Test that nested nil slices (from API responses) are preserved as null
73 // to maintain the semantic difference between absent and empty
74 type Token struct {
75 ID int `json:"id"`
76 Scopes []string `json:"scopes"` // nil should stay null in JSON
77 }
79 buf := &bytes.Buffer{}
80 io := newIOWithJQ(buf)
82 tokens := []Token{
83 {ID: 1, Scopes: nil}, // This nil should remain null in the JSON output
84 }
86 err := io.PrintJSON(tokens)
87 require.NoError(t, err)
89 // Verify the nested nil slice is preserved as null
90 jsonBytes := bytes.TrimSpace(buf.Bytes())
91 var result []map[string]any
92 err = json.Unmarshal(jsonBytes, &result)
93 require.NoError(t, err)
95 require.Len(t, result, 1)
97 // The scopes field should be null (present but nil)
98 scopes, exists := result[0]["scopes"]
99 assert.True(t, exists, "expected scopes field to exist")
100 assert.Nil(t, scopes, "expected scopes to be null")
101}
103func TestPrintJSON_PassthroughWhenJQNil(t *testing.T) {
104 // IOStreams instances constructed without a JQFilter should still work;
105 // PrintJSON should bypass the filter and emit raw JSON.
106 buf := &bytes.Buffer{}
107 io := &IOStreams{StdOut: buf} // no JQ
109 require.NoError(t, io.PrintJSON(map[string]int{"a": 1}))
110 assert.Equal(t, "{\"a\":1}\n", buf.String())
111}
113func TestPrintJSON_JQFilterSelectsField(t *testing.T) {
114 buf := &bytes.Buffer{}
115 io := newIOWithJQ(buf)
116 require.NoError(t, io.JQ.Set(".name"))
118 require.NoError(t, io.PrintJSON(map[string]string{"name": "alpha"}))
120 // jq -r style: bare string output.
121 assert.Equal(t, "alpha\n", buf.String())
122}
124func TestPrintJSON_JQFilterEmitsObject(t *testing.T) {
125 buf := &bytes.Buffer{}
126 io := newIOWithJQ(buf)
127 require.NoError(t, io.JQ.Set(".user"))
129 require.NoError(t, io.PrintJSON(map[string]any{
130 "user": map[string]any{"id": 1, "name": "alpha"},
131 }))
133 // Non-string results stay JSON-encoded (compact).
134 var result map[string]any
135 err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &result)
136 require.NoError(t, err)
137 assert.Equal(t, "alpha", result["name"])
138 assert.EqualValues(t, 1, result["id"])
139}
141func TestPrintJSON_JQFilterIteratesArray(t *testing.T) {
142 buf := &bytes.Buffer{}
143 io := newIOWithJQ(buf)
144 require.NoError(t, io.JQ.Set(".[].name"))
146 input := []map[string]string{
147 {"name": "alpha"},
148 {"name": "beta"},
149 }
150 require.NoError(t, io.PrintJSON(input))
152 assert.Equal(t, "alpha\nbeta\n", buf.String())
153}
155func TestPrintJSON_JQFilterMissingFieldEmitsNull(t *testing.T) {
156 // Edge case: jq selecting a missing field emits "null", matching jq semantics.
157 buf := &bytes.Buffer{}
158 io := newIOWithJQ(buf)
159 require.NoError(t, io.JQ.Set(".nonexistent"))
161 require.NoError(t, io.PrintJSON(map[string]string{"name": "alpha"}))
163 assert.Equal(t, "null\n", buf.String())
164}
166func TestPrintJSON_JQFilterEmptyProducesNoOutput(t *testing.T) {
167 // Edge case: `empty` consumes the input and yields no results.
168 buf := &bytes.Buffer{}
169 io := newIOWithJQ(buf)
170 require.NoError(t, io.JQ.Set("empty"))
172 require.NoError(t, io.PrintJSON(map[string]string{"name": "alpha"}))
174 assert.Empty(t, buf.String())
175}
177func TestPrintJSON_JQFilterRuntimeErrorIsWrapped(t *testing.T) {
178 // Edge case: a runtime error from gojq (e.g. tonumber on a non-numeric
179 // string) is surfaced as a wrapped error with the --jq prefix.
180 buf := &bytes.Buffer{}
181 io := newIOWithJQ(buf)
182 require.NoError(t, io.JQ.Set(".foo | tonumber"))
184 err := io.PrintJSON(map[string]string{"foo": "bar"})
185 require.Error(t, err)
186 assert.Contains(t, err.Error(), "--jq error")
187}
189func TestPrintJSONError_WritesEnvelopeToStdout(t *testing.T) {
190 buf := &bytes.Buffer{}
191 io := newIOWithJQ(buf)
193 require.NoError(t, io.PrintJSONError(errors.New("404 Not Found")))
195 var got struct {
196 Error struct {
197 Message string `json:"message"`
198 } `json:"error"`
199 }
200 require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
201 assert.Equal(t, "404 Not Found", got.Error.Message)
202}
204func TestPrintJSONError_IgnoresJQFilter(t *testing.T) {
205 // The --jq expression targets the command's success output, so applying it
206 // to an error object would replace the failure with a filter error.
207 buf := &bytes.Buffer{}
208 io := newIOWithJQ(buf)
209 require.NoError(t, io.JQ.Set(".[].id"))
211 require.NoError(t, io.PrintJSONError(errors.New("404 Not Found")))
213 var got struct {
214 Error struct {
215 Message string `json:"message"`
216 } `json:"error"`
217 }
218 require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
219 assert.Equal(t, "404 Not Found", got.Error.Message)
220}
222func TestPrintJSONError_PassthroughWhenJQNil(t *testing.T) {
223 buf := &bytes.Buffer{}
224 io := &IOStreams{StdOut: buf} // no JQ
226 require.NoError(t, io.PrintJSONError(errors.New("boom")))
227 assert.JSONEq(t, `{"error":{"message":"boom"}}`, buf.String())
228}
Diagnostics6 git calls · 225 ms
CallStatusSizeTime0225 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=0 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
fetchtree:0200432 B · hit0 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=220 git.response.bytes=432 git.response.cache=HIT git.response.duration_ms=0 git.fetch.filter=tree:0 git.fetch.wants=a79e8e89fbedf0d57724da455f6326f6e79de3b5 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=432 git.pkt.payload.max=405 git.sideband.band1.bytes=405 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=405 git.pack.trailer=6b5f558fa7a37603ce66aafb676f53aedcb02370Open pack map
fetch2001.9 KiB220 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=1908 git.response.cache=MISS git.response.duration_ms=220 git.fetch.wants=f804a0b50fabd4f3e9127e93c36a4bb239815615 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=1908 git.pkt.payload.max=1881 git.sideband.band1.bytes=1881 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
- a5e2c32ee84eaedd
- Request
- f69ae02a…
- 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