Debian Codegraph @

fmt_test.go

raw
1 package tblfmt
2
3 import (
4 "bytes"
5 "database/sql"
6 "database/sql/driver"
7 "encoding/csv"
8 "encoding/json/jsontext"
9 json "encoding/json/v2"
10 "errors"
11 "math"
12 "reflect"
13 "regexp"
14 "slices"
15 "strconv"
16 "strings"
17 "testing"
18 "time"
19
20 runewidth "github.com/mattn/go-runewidth"
21 "github.com/xo/tblfmt/internal"
22 )
23
24 func TestTabwidthCalc(t *testing.T) {
25 tests := []struct {
26 s string
27 offset int
28 tab int
29 exp int
30 }{
31 {"", 0, 8, 0},
32 {" ", 0, 8, 1},
33 {" ", 0, 8, 4},
34 {"\u8888", 0, 8, 2},
35 {"\t", 0, 8, 8},
36 {"\t\t", 0, 8, 16}, // 5
37 {"\t\t ", 0, 8, 17},
38 {" \t\t ", 0, 8, 17},
39 {" \t\t\t ", 0, 8, 25},
40 {"foo\tbar\t", 0, 8, 16},
41 {"\t\t\u8888", 0, 8, 18}, // 10
42 {"\u8888\t\u8888", 0, 8, 10},
43 {"\u8888\t\u8888\t", 0, 8, 16},
44 {"", 1, 8, 0}, // 13
45 {"\t", 1, 4, 3},
46 {" \t", 1, 4, 3},
47 {" \t ", 1, 4, 4},
48 {"\u8888\t\u8888\t", 1, 4, 7},
49 /*
50 ---xxxxxxxxx (width == 9)
51 | 袈 袈 |
52 */
53 {"\u8888\t\t\u8888\t", 3, 2, 9}, // 18
54 /*
55 --------------xxxxxxxxxxxxxxxxxxxxxxxxxxxx (width == 28)
56 | 袈 袈 袈|
57 */
58 {"\u8888\t\u8888\t\t\u8888", 14, 8, 28}, // 19
59 {"袈 袈 袈", 14, 8, 28},
60 }
61 for i, test := range tests {
62 tabs, w := tabpositions(test.s)
63 w += tabwidth(tabs, test.offset, test.tab)
64 if test.exp != w {
65 t.Errorf("test %d %q expected tabwidth(%v, %d, %d) = %d, got: %d", i, test.s, tabs, test.offset, test.tab, test.exp, w)
66 }
67 }
68 }
69
70 var tabRE = regexp.MustCompile("\t")
71
72 // tabpositions returns a list of tab positions in s.
73 func tabpositions(s string) ([][2]int, int) {
74 var tabs [][2]int
75 var last int
76 for _, m := range tabRE.FindAllStringIndex(s, -1) {
77 tabs = append(tabs, [2]int{m[0], runewidth.StringWidth(s[last:m[0]])})
78 last = m[0] + 1
79 }
80 return tabs, runewidth.StringWidth(s[last:])
81 }
82
83 func TestFormatBytesTabs(t *testing.T) {
84 tests := []escTest{
85 v("", 0),
86 v("\u8888\t\u8888", 4),
87 v(" \u8888 \t \u8888 ", 8),
88 }
89 for i, test := range tests {
90 v := FormatBytes([]byte(test.s), nil, 0, false, false, 0, 0)
91 if !reflect.DeepEqual(v, test.exp) {
92 t.Errorf("test %d %q expected %v, got: %v", i, test.s, test.exp, v)
93 width := runewidth.StringWidth(string(v.Buf))
94 if v.Width != width {
95 t.Errorf("test %d %q expected width %d, got: %d", i, test.s, width, v.Width)
96 }
97 if width != test.check {
98 t.Errorf("test %d %q expected check width %d, got: %d", i, test.s, test.check, width)
99 }
100 }
101 }
102 }
103
104 func TestFormatBytesComplex(t *testing.T) {
105 s := `{
106 "2011": "Team Garmin - Cervelo",
107 "2012": "AA Drink - Leontien.nl",
108 "2013": "Boels-Dolmans Cycling Team",
109 "2015": "Boels-Dolmans"
110 }`
111 v := FormatBytes([]byte(s), nil, 0, false, false, 0, 0)
112 if w := v.MaxWidth(0, 8); w != 39 {
113 t.Errorf("expected width of 39, got: %d", w)
114 }
115 }
116
117 func TestFormatJSON(t *testing.T) {
118 s := strings.Join(
119 []string{
120 "\a",
121 "\b",
122 "\f",
123 "\n",
124 "\r",
125 "\t",
126 "\x1a",
127 "\x2b",
128 "\x3f",
129 "\\",
130 " ",
131 "\x9f",
132 "\xaf",
133 "\xff",
134 "\u1998",
135 "\U0001f440",
136 "\U0001f930",
137 "foo",
138 "15\u00f8C",
139 },
140 ";",
141 )
142 // note: compared by what the encodings decode to and not byte for byte,
143 // as more than one escaping of the same string is valid JSON, and
144 // FormatBytes and encoding/json legitimately differ: an invalid UTF-8
145 // byte becomes a \ufffd escape here, where encoding/json writes the
146 // U+FFFD replacement rune itself.
147 exp, err := json.Marshal(s, jsontext.AllowInvalidUTF8(true))
148 if err != nil {
149 t.Fatalf("expected no error, got: %v", err)
150 }
151 t.Logf("exp: %s", string(exp))
152 v := FormatBytes([]byte(s), nil, 0, true, false, 0, 0)
153 buf := []byte(`"` + v.String() + `"`)
154 t.Logf("v : %s", string(buf))
155 var expStr string
156 if err := json.Unmarshal(exp, &expStr); err != nil {
157 t.Fatalf("expected no error, got: %v", err)
158 }
159 var s2 string
160 if err := json.Unmarshal(buf, &s2); err != nil {
161 t.Fatalf("expected %s to be valid json, got: %v", string(buf), err)
162 }
163 if s2 != expStr {
164 t.Errorf("\nexpected:\n%q\ngot:\n%q", expStr, s2)
165 }
166 }
167
168 func TestFormatBytesRaw(t *testing.T) {
169 tests := []struct {
170 s string
171 exp string
172 }{
173 {"", ""},
174 {"a", "a"},
175 {" ", `" "`},
176 {" ", `" "`},
177 {" ", `" "`},
178 {"\n", "\"\n\""},
179 {"\t", "\"\t\""},
180 {",", "\",\""},
181 {",\t", "\",\t\""},
182 {",\t\"", "\",\t\"\"\""},
183 }
184 for i, test := range tests {
185 v := FormatBytes([]byte(test.s), nil, 0, false, true, ',', '"')
186 buf := v.Buf
187 if v.Quoted {
188 buf = append([]byte{'"'}, append(buf, '"')...)
189 }
190 if string(buf) != test.exp {
191 t.Errorf("test %d %q expected %q == %q", i, test.s, string(buf), test.exp)
192 }
193 }
194 }
195
196 type escTest struct {
197 s string
198 exp *Value
199 check int
200 }
201
202 func quote(s string) string {
203 s = strconv.Quote(s)
204 s = s[1 : len(s)-1]
205 s = strings.ReplaceAll(s, `\t`, "\t")
206 s = strings.ReplaceAll(s, `\n`, "\n")
207 return s
208 }
209
210 func v(s string, check int) escTest {
211 c := quote(s)
212 tabs, width := tabpositions(c)
213 var buf []byte
214 if len(c) != 0 {
215 buf = []byte(c)
216 }
217 v := &Value{
218 Buf: buf,
219 Tabs: [][][2]int{tabs},
220 Width: width,
221 }
222 return escTest{s, v, check}
223 }
224
225 // TestFormatNull checks that the generic database/sql Null type and other
226 // driver.Valuer implementations format as their contained value, and that a
227 // null value formats as the empty value.
228 //
229 // MySQL's ColumnType.ScanType reports sql.Null[uint64] for a nullable BIGINT
230 // UNSIGNED, and the value is above math.MaxInt64, so it cannot round trip
231 // through the Null's own Value method.
232 func TestFormatNull(t *testing.T) {
233 t.Parallel()
234 loc, err := time.LoadLocation("UTC")
235 if err != nil {
236 t.Fatalf("expected no error, got: %v", err)
237 }
238 tm := time.Date(2026, 1, 2, 3, 4, 5, 0, loc)
239 maxUint64 := sql.Null[uint64]{V: math.MaxUint64, Valid: true}
240 tests := []struct {
241 v any
242 exp string
243 align Align
244 }{
245 {sql.Null[uint64]{V: math.MaxUint64, Valid: true}, "18446744073709551615", AlignRight},
246 {&maxUint64, "18446744073709551615", AlignRight},
247 {sql.Null[uint64]{V: 42, Valid: true}, "42", AlignRight},
248 {sql.Null[uint64]{}, "", AlignLeft},
249 {&sql.Null[uint64]{}, "", AlignLeft},
250 {sql.Null[int64]{V: -5, Valid: true}, "-5", AlignRight},
251 {sql.Null[float64]{V: 3.25, Valid: true}, "3.25", AlignRight},
252 {sql.Null[bool]{V: true, Valid: true}, "true", AlignLeft},
253 {sql.Null[string]{V: "hello", Valid: true}, "hello", AlignLeft},
254 {sql.Null[string]{}, "", AlignLeft},
255 {sql.Null[time.Time]{V: tm, Valid: true}, "2026-01-02T03:04:05Z", AlignLeft},
256 {sql.Null[[]byte]{V: []byte("bytes"), Valid: true}, "bytes", AlignLeft},
257 {valuer{}, "", AlignLeft},
258 {valuer{v: "from valuer"}, "from valuer", AlignLeft},
259 {errValuer{}, "{}", AlignLeft},
260 {(*sql.Null[uint64])(nil), "", AlignLeft},
261 {nil, "", AlignLeft},
262 }
263 f := NewEscapeFormatter(WithTimeLocation(loc))
264 for i, test := range tests {
265 vals, err := f.Format([]any{test.v})
266 switch {
267 case err != nil:
268 t.Errorf("test %d expected no error, got: %v", i, err)
269 continue
270 case len(vals) != 1:
271 t.Errorf("test %d expected 1 value, got: %d", i, len(vals))
272 continue
273 }
274 var s string
275 var align Align
276 if vals[0] != nil {
277 s, align = string(vals[0].Buf), vals[0].Align
278 }
279 if s != test.exp {
280 t.Errorf("test %d %#v expected %q, got: %q", i, test.v, test.exp, s)
281 }
282 if test.exp != "" && align != test.align {
283 t.Errorf("test %d %#v expected align %d, got: %d", i, test.v, test.align, align)
284 }
285 }
286 }
287
288 // TestEncodeJSONNull checks that the generic database/sql Null type encodes as
289 // a bare JSON value, and as JSON null when not valid.
290 func TestEncodeJSONNull(t *testing.T) {
291 t.Parallel()
292 resultSet := internal.New([]string{"b"}, [][]any{
293 {&sql.Null[uint64]{V: math.MaxUint64, Valid: true}},
294 {&sql.Null[uint64]{}},
295 })
296 buf := new(bytes.Buffer)
297 if err := EncodeJSONAll(buf, resultSet); err != nil {
298 t.Fatalf("expected no error, got: %v", err)
299 }
300 // note: compared by what it decodes to rather than by its text, as the
301 // encoder's layout is covered by the golden tests. b is a JSON string
302 // because it is a uint64; see TestEncodeJSONNumber.
303 var v []map[string]jsontext.Value
304 if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &v); err != nil {
305 t.Fatalf("expected %s to be valid json, got: %v", buf.String(), err)
306 }
307 if len(v) != 2 {
308 t.Fatalf("expected 2 json rows, got: %d", len(v))
309 }
310 if s, exp := string(v[0]["b"]), `"18446744073709551615"`; s != exp {
311 t.Errorf("expected %s, got: %s", exp, s)
312 }
313 if s := string(v[1]["b"]); s != "null" {
314 t.Errorf("expected null, got: %s", s)
315 }
316 }
317
318 // valuer is a driver.Valuer returning a string.
319 type valuer struct {
320 v string
321 }
322
323 func (v valuer) Value() (driver.Value, error) {
324 if v.v == "" {
325 return nil, nil
326 }
327 return v.v, nil
328 }
329
330 // errValuer is a driver.Valuer always returning an error.
331 type errValuer struct{}
332
333 func (errValuer) Value() (driver.Value, error) {
334 return nil, errors.New("invalid value")
335 }
336
337 // TestEncodeNumericLocale checks that a locale formatted number does not break
338 // the csv and JSON encodings, where its grouping separator would otherwise be
339 // read as a field separator, or as an invalid JSON number.
340 func TestEncodeNumericLocale(t *testing.T) {
341 t.Parallel()
342 // note: the locales cover the three ways a grouping separator meets csv --
343 // a comma, which is the separator itself; a period paired with a decimal
344 // comma, where only the float needs quoting; and a non-breaking space,
345 // which is quoted as whitespace.
346 tests := []struct {
347 locale string
348 n string
349 f string
350 b string
351 }{
352 {"en-US", "1,234,567", "1,234,567.25", "18,446,744,073,709,551,615"},
353 {"en-IN", "12,34,567", "12,34,567.25", "1,84,46,74,40,73,70,95,51,615"},
354 {"de-DE", "1.234.567", "1.234.567,25", "18.446.744.073.709.551.615"},
355 {"fr-FR", "1\u00a0234\u00a0567", "1\u00a0234\u00a0567,25", "18\u00a0446\u00a0744\u00a0073\u00a0709\u00a0551\u00a0615"},
356 }
357 for _, test := range tests {
358 resultSet := func() ResultSet {
359 return internal.New([]string{"n", "f", "b"}, [][]any{
360 {1234567, 1234567.25, &sql.Null[uint64]{V: math.MaxUint64, Valid: true}},
361 {nil, nil, &sql.Null[uint64]{}},
362 })
363 }
364 buf := new(bytes.Buffer)
365 if err := EncodeCSVAll(buf, resultSet(), WithFormatter(NewEscapeFormatter(
366 WithNumericLocale(true, test.locale),
367 WithIsRaw(true, ',', '"'),
368 ))); err != nil {
369 t.Fatalf("%s expected no error, got: %v", test.locale, err)
370 }
371 t.Logf("%s csv:\n%s", test.locale, buf.String())
372 records, err := csv.NewReader(bytes.NewReader(buf.Bytes())).ReadAll()
373 if err != nil {
374 t.Errorf("%s expected no error, got: %v", test.locale, err)
375 continue
376 }
377 if len(records) != 3 {
378 t.Errorf("%s expected 3 csv records, got: %d", test.locale, len(records))
379 continue
380 }
381 for i, record := range records {
382 if len(record) != 3 {
383 t.Errorf("%s csv record %d expected 3 fields, got: %d (%q)", test.locale, i, len(record), record)
384 }
385 }
386 if exp := []string{test.n, test.f, test.b}; !slices.Equal(records[1], exp) {
387 t.Errorf("%s expected csv %q, got: %q", test.locale, exp, records[1])
388 }
389 buf.Reset()
390 if err := EncodeJSONAll(buf, resultSet(), WithFormatter(NewEscapeFormatter(
391 WithNumericLocale(true, test.locale),
392 WithIsJSON(true),
393 ))); err != nil {
394 t.Fatalf("%s expected no error, got: %v", test.locale, err)
395 }
396 t.Logf("%s json: %s", test.locale, buf.String())
397 // note: json ignores the numeric locale, so the numbers stay numbers
398 // rather than becoming strings; they are compared as their raw text so
399 // that a uint64 above 2^53 is not rounded by decoding it to a float.
400 var v []map[string]jsontext.Value
401 if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &v); err != nil {
402 t.Errorf("%s expected %s to be valid json, got: %v", test.locale, buf.String(), err)
403 continue
404 }
405 // note: b is above the int64 a JSON number is read as, so it is a
406 // JSON string -- of its exact digits, never locale formatted.
407 exp := map[string]string{
408 "n": "1234567",
409 "f": "1.23456725e+06",
410 "b": `"18446744073709551615"`,
411 }
412 if len(v) != 2 {
413 t.Errorf("%s expected 2 json rows, got: %d", test.locale, len(v))
414 continue
415 }
416 for _, col := range []string{"n", "f", "b"} {
417 if s := string(v[0][col]); s != exp[col] {
418 t.Errorf("%s expected json %s to be %s, got: %s", test.locale, col, exp[col], s)
419 }
420 }
421 if s := string(v[1]["b"]); s != "null" {
422 t.Errorf("%s expected null, got: %s", test.locale, s)
423 }
424 }
425 }
426
427 // TestEncodeJSONNumber checks that a number JSON cannot write as a number --
428 // one above the int64 a JSON number is read as, and the values that are not
429 // finite numbers at all -- is written as a string of the same text the other
430 // formats show.
431 func TestEncodeJSONNumber(t *testing.T) {
432 t.Parallel()
433 resultSet := internal.New(
434 []string{"u64max", "u64min", "i64max", "u64ok", "nan", "inf", "ninf", "f"},
435 [][]any{{
436 uint64(math.MaxUint64),
437 uint64(math.MaxInt64) + 1,
438 int64(math.MaxInt64),
439 uint64(42),
440 math.NaN(),
441 math.Inf(1),
442 math.Inf(-1),
443 1.5,
444 }},
445 )
446 buf := new(bytes.Buffer)
447 if err := EncodeJSONAll(buf, resultSet); err != nil {
448 t.Fatalf("expected no error, got: %v", err)
449 }
450 t.Logf("json: %s", buf.String())
451 var v []map[string]jsontext.Value
452 if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &v); err != nil {
453 t.Fatalf("expected %s to be valid json, got: %v", buf.String(), err)
454 }
455 if len(v) != 1 {
456 t.Fatalf("expected 1 json row, got: %d", len(v))
457 }
458 // note: compared as raw text, as decoding would round the large values it
459 // is the point of the quoting to keep exact.
460 for _, test := range []struct {
461 col string
462 exp string
463 }{
464 {"u64max", `"18446744073709551615"`},
465 {"u64min", `"9223372036854775808"`},
466 {"i64max", `9223372036854775807`},
467 // note: quoted although it fits, as the decision is by type so that a
468 // column is one JSON type for all of its rows
469 {"u64ok", `"42"`},
470 {"nan", `"NaN"`},
471 {"inf", `"Infinity"`},
472 {"ninf", `"-Infinity"`},
473 {"f", `1.5`},
474 } {
475 if s := string(v[0][test.col]); s != test.exp {
476 t.Errorf("expected %s to be %s, got: %s", test.col, test.exp, s)
477 }
478 }
479 }
480
481 // TestFormatNotANumber checks that the values that are not finite numbers use
482 // PostgreSQL's spellings, which are what psql displays, in every format.
483 func TestFormatNotANumber(t *testing.T) {
484 t.Parallel()
485 f := NewEscapeFormatter()
486 for i, test := range []struct {
487 v any
488 exp string
489 }{
490 {math.NaN(), "NaN"},
491 {math.Inf(1), "Infinity"},
492 {math.Inf(-1), "-Infinity"},
493 {float32(math.Inf(1)), "Infinity"},
494 {sql.NullFloat64{Float64: math.NaN(), Valid: true}, "NaN"},
495 {sql.Null[float64]{V: math.Inf(-1), Valid: true}, "-Infinity"},
496 } {
497 vals, err := f.Format([]any{test.v})
498 if err != nil {
499 t.Errorf("test %d expected no error, got: %v", i, err)
500 continue
501 }
502 if s := string(vals[0].Buf); s != test.exp {
503 t.Errorf("test %d expected %q, got: %q", i, test.exp, s)
504 }
505 if vals[0].Align != AlignRight {
506 t.Errorf("test %d expected right align, got: %d", i, vals[0].Align)
507 }
508 }
509 }