-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat_test.go
More file actions
512 lines (438 loc) · 11.8 KB
/
format_test.go
File metadata and controls
512 lines (438 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package gop_test
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"text/template"
"time"
"unsafe"
"github.com/ysmood/gop"
)
func eq(t *testing.T, a, b interface{}) {
t.Helper()
if a == b {
return
}
t.Log(a, "[should equal]", b)
t.Fail()
}
// RandStr generates a random string with the specified length
func randStr(l int) string {
b := make([]byte, (l+1)/2)
_, _ = rand.Read(b)
return hex.EncodeToString(b)[:l]
}
func render(value string, data interface{}) string {
out := bytes.NewBuffer(nil)
t := template.New("")
t, err := t.Parse(value)
if err != nil {
panic(err)
}
err = t.Execute(out, data)
if err != nil {
panic(err)
}
return out.String()
}
func assertPanic(t *testing.T, fn func()) (val interface{}) {
t.Helper()
defer func() {
t.Helper()
val = recover()
if val == nil {
t.Error("should panic")
}
}()
fn()
return
}
func TestStyle(t *testing.T) {
s := gop.Style{Set: "<s>", Unset: "</s>"}
eq(t, gop.S("test", s), "<s>test</s>")
eq(t, gop.S("", s), "<s></s>")
eq(t, gop.S("", gop.None), "")
}
func TestTokenize(t *testing.T) {
ref := "test"
timeStamp, _ := time.Parse(time.RFC3339Nano, "2021-08-28T08:36:36.807908+08:00")
fn := func(string) int { return 10 }
ch1 := make(chan int)
ch2 := make(chan string, 3)
ch3 := make(chan struct{})
v := []interface{}{
nil,
[]int{},
[]interface{}{true, false, uintptr(0x17), float32(100.121111133)},
true, 10, int8(2), int32(100),
float64(100.121111133),
complex64(1 + 2i), complex128(1 + 2i),
[3]int{1, 2},
ch1,
ch2,
ch3,
fn,
map[interface{}]interface{}{
`"test"`: 10,
"a": 1,
&ref: 1,
},
unsafe.Pointer(&ref),
struct {
Int int
str string
M map[int]int
}{10, "ok", map[int]int{1: 0x20}},
[]byte("aa\xe2"),
[]byte("bytes\n\tbytes"),
[]byte("long long long long string"),
byte('a'),
byte(1),
'天',
"long long long long string",
"\ntest",
"\t\n`",
&ref,
(*struct{ Int int })(nil),
&struct{ Int int }{},
&map[int]int{1: 2, 3: 4},
&[]int{1, 2},
&[2]int{1, 2},
&[]byte{1, 2},
timeStamp,
time.Hour,
`{"a": 1}`,
[]byte(`{"a": 1}`),
}
check := func(out string, file string) {
t.Helper()
tpl, err := os.ReadFile(file)
if err != nil {
t.Fatal(err)
}
expected := render(string(tpl), map[string]interface{}{
"ch1": fmt.Sprintf("0x%x", reflect.ValueOf(ch1).Pointer()),
"ch2": fmt.Sprintf("0x%x", reflect.ValueOf(ch2).Pointer()),
"ch3": fmt.Sprintf("0x%x", reflect.ValueOf(ch3).Pointer()),
"fn": fmt.Sprintf("0x%x", reflect.ValueOf(fn).Pointer()),
"ptr": fmt.Sprintf("%v", &ref),
"ref": fmt.Sprintf("0x%x", reflect.ValueOf(&ref).Pointer()),
})
if out != expected {
t.Log("check failed")
writeFile(t, "tmp/expected.txt", expected)
writeFile(t, "tmp/out.txt", out)
t.Fail()
}
}
out := gop.StripANSI(gop.F(v))
{
b, err := os.ReadFile(filepath.Join("fixtures", "compile_check.go.tmpl"))
if err != nil {
t.Fatal(err)
}
code := fmt.Sprintf(string(b), out)
f := filepath.Join("tmp", randStr(8), "main.go")
err = os.MkdirAll(filepath.Dir(f), 0755)
if err != nil {
t.Fatal(err)
}
writeFile(t, f, code)
b, err = exec.Command("go", "run", f).CombinedOutput()
if err != nil {
t.Fatal(string(b))
}
}
check(out, filepath.Join("fixtures", "expected.tmpl"))
out = gop.VisualizeANSI(gop.F(v))
check(out, filepath.Join("fixtures", "expected_with_color.tmpl"))
}
func TestRef(t *testing.T) {
a := [2][]int{{1}}
a[1] = a[0]
eq(t, gop.Plain(a), `[2][]int{
[]int{
1,
},
[]int{
1,
},
}`)
}
type A struct {
Int int
B *B
}
type B struct {
s string
a *A
}
func TestCircularRef(t *testing.T) {
a := A{Int: 10}
b := B{"test", &a}
a.B = &b
eq(t, gop.StripANSI(gop.F(a)), `gop_test.A{
Int: 10,
B: &gop_test.B{
s: "test",
a: &gop_test.A{
Int: 10,
B: gop.Circular("B").(*gop_test.B),
},
},
}`)
}
func TestCircularNilRef(t *testing.T) {
arr := []A{{}, {}}
eq(t, gop.StripANSI(gop.F(arr)), `[]gop_test.A{
gop_test.A{
Int: 0,
B: (*gop_test.B)(nil),
},
gop_test.A{
Int: 0,
B: (*gop_test.B)(nil),
},
}`)
}
func TestCircularMap(t *testing.T) {
a := map[int]interface{}{}
a[0] = a
ts := gop.Tokenize(a)
eq(t, gop.Format(ts, gop.ThemeNone), `map[int]interface {}{
0: gop.Circular().(map[int]interface {}),
}`)
}
func TestCircularSlice(t *testing.T) {
a := [][]interface{}{{nil}, {nil}}
a[0][0] = a[1]
a[1][0] = a[0][0]
ts := gop.Tokenize(a)
eq(t, gop.Format(ts, gop.ThemeNone), `[][]interface {}{
[]interface {}{
[]interface {}{
gop.Circular(0, 0).([]interface {}),
},
},
[]interface {}{
gop.Circular(1).([]interface {}),
},
}`)
}
func TestCircularMapKey(t *testing.T) {
a := map[interface{}]interface{}{}
b := map[interface{}]interface{}{}
a[&b] = b
b[&a] = a
ts := gop.Tokenize(b)
eq(t, gop.Format(ts, gop.ThemeNone), render(`map[interface {}]interface {}{
(interface {})(nil)/* {{.a}} */: map[interface {}]interface {}{
(interface {})(nil)/* {{.b}} */: gop.Circular().(map[interface {}]interface {}),
},
}`, map[string]interface{}{
"a": fmt.Sprintf("0x%x", reflect.ValueOf(&a).Pointer()),
"b": fmt.Sprintf("0x%x", reflect.ValueOf(&b).Pointer()),
}))
}
func TestPlain(t *testing.T) {
eq(t, gop.Plain(10), "10")
}
func TestPlainMinify(t *testing.T) {
a := map[int]interface{}{
1: "a",
}
b := map[int]interface{}{}
pa := gop.Plain(a)
pb := gop.Plain(b)
eq(t, pa, "map[int]interface {}{\n 1: \"a\",\n}")
eq(t, pb, "map[int]interface {}{}")
}
func TestP(t *testing.T) {
gop.Stdout = io.Discard
_ = gop.P("test")
gop.Stdout = os.Stdout
}
func TestConvertors(t *testing.T) {
eq(t, gop.Circular(""), nil)
s := randStr(8)
eq(t, *gop.Ptr(s).(*string), s)
bs := base64.StdEncoding.EncodeToString([]byte(s))
eq(t, string(gop.Base64(bs)), string([]byte(s)))
now := time.Now()
eq(t, gop.Time(now.Format(time.RFC3339Nano), 1234).Unix(), now.Unix())
eq(t, gop.Duration("10m"), 10*time.Minute)
eq(t, gop.JSONStr(nil, "[1, 2]"), "[1, 2]")
eq(t, string(gop.JSONBytes(nil, "[1, 2]")), string([]byte("[1, 2]")))
eq(t, gop.GopError("test").Error(), "test")
}
func TestGetPrivateFieldErr(t *testing.T) {
assertPanic(t, func() {
gop.GetPrivateField(reflect.ValueOf(1), 0)
})
assertPanic(t, func() {
gop.GetPrivateFieldByName(reflect.ValueOf(1), "test")
})
}
func TestTypeName(t *testing.T) {
type f float64
type i int
type c complex128
type b byte
eq(t, gop.Plain(f(1)), "gop_test.f(1.0)")
eq(t, gop.Plain(i(1)), "gop_test.i(1)")
eq(t, gop.Plain(c(1)), "gop_test.c(1+0i)")
eq(t, gop.Plain(b('a')), "gop_test.b(97)")
}
func TestFixNestedStyle(t *testing.T) {
s := gop.S(" 0 "+gop.S(" 1 "+
gop.S(" 2 "+
gop.S(" 3 ", gop.Cyan)+
" 4 ", gop.Blue)+
" 5 ", gop.Red)+" 6 ", gop.BgRed)
out := gop.VisualizeANSI(gop.FixNestedStyle(s))
eq(t, out, `<41> 0 <31> 1 <39><34> 2 <39><36> 3 <39><34> 4 <39><31> 5 <39> 6 <49>`)
gop.FixNestedStyle("test")
}
func TestStripANSI(t *testing.T) {
eq(t, gop.StripANSI(gop.S("test", gop.Red)), "test")
}
func TestTheme(t *testing.T) {
eq(t, gop.ThemeDefault(gop.Error)[0], gop.Underline)
}
func TestNil(t *testing.T) {
eq(t, gop.Plain(map[string]string(nil)), "map[string]string(nil)")
eq(t, gop.Plain(chan int(nil)), "(chan int)(nil)")
eq(t, gop.Plain([]string(nil)), "[]string(nil)")
eq(t, gop.Plain((func())(nil)), "(func())(nil)")
eq(t, gop.Plain((*struct{})(nil)), "(*struct {})(nil)")
}
func TestJSONArrayBug(t *testing.T) {
// Test for the bug fix where JSON arrays were incorrectly checked as objects
// The bug was: _, isArr := jv.(map[string]interface{}) instead of jv.([]interface{})
// This caused JSON arrays to never be recognized, so they weren't properly formatted
jsonArrayStr := `[1, 2, 3]`
result := gop.Plain(jsonArrayStr)
// With the fix, JSON arrays should be detected and formatted with gop.JSONStr()
// The result should contain "gop.JSONStr(" indicating proper JSON array detection
if !strings.Contains(result, "gop.JSONStr(") {
t.Errorf("JSON array not properly detected as JSON. Got: %s", result)
}
// Test with byte array too
jsonArrayBytes := []byte(`[{"key": "value"}, 123]`)
result2 := gop.Plain(jsonArrayBytes)
// With the fix, JSON byte arrays should be detected and formatted with gop.JSONBytes()
if !strings.Contains(result2, "gop.JSONBytes(") {
t.Errorf("JSON byte array not properly detected as JSON. Got: %s", result2)
}
// Test that the tokenized version contains the actual parsed array structure
if !strings.Contains(result, "[]interface {}") {
t.Errorf("JSON array structure not properly tokenized. Got: %s", result)
}
}
func TestMaxDepth(t *testing.T) {
// Create a deeply nested structure
type Node struct {
Value int
Next *Node
}
// Create a chain of 20 nodes
var root *Node
current := &Node{Value: 0}
root = current
for i := 1; i < 20; i++ {
current.Next = &Node{Value: i}
current = current.Next
}
// Test with default MaxDepth (15)
result := gop.Plain(root)
if !strings.Contains(result, "gop.GopError(") {
t.Errorf("Expected max depth error with default MaxDepth, got: %s", result)
}
if !strings.Contains(result, "max depth exceeded") {
t.Errorf("Expected 'max depth exceeded' message, got: %s", result)
}
// Test with custom MaxDepth of 5
tokens := gop.TokenizeWithOptions(root, gop.Options{MaxDepth: 5})
result = gop.Format(tokens, gop.ThemeNone)
if !strings.Contains(result, "gop.GopError(") {
t.Errorf("Expected max depth error with MaxDepth=5, got: %s", result)
}
if !strings.Contains(result, "max depth exceeded") {
t.Errorf("Expected 'max depth exceeded' message with MaxDepth=5, got: %s", result)
}
// Test with MaxDepth of 0 (no limit)
tokens = gop.TokenizeWithOptions(root, gop.Options{MaxDepth: 0})
result = gop.Format(tokens, gop.ThemeNone)
if strings.Contains(result, "max depth exceeded") {
t.Errorf("Should not have max depth error with MaxDepth=0, got: %s", result)
}
// Verify all 20 values are present when no limit
for i := 0; i < 20; i++ {
if !strings.Contains(result, fmt.Sprintf("Value: %d", i)) {
t.Errorf("Missing Value: %d in unlimited depth output", i)
}
}
// Test with deeply nested maps
deepMap := map[string]interface{}{
"level1": map[string]interface{}{
"level2": map[string]interface{}{
"level3": map[string]interface{}{
"level4": map[string]interface{}{
"level5": map[string]interface{}{
"level6": "deep value",
},
},
},
},
},
}
// Test with MaxDepth of 3
tokens = gop.TokenizeWithOptions(deepMap, gop.Options{MaxDepth: 3})
result = gop.Format(tokens, gop.ThemeNone)
if !strings.Contains(result, "gop.GopError(") {
t.Errorf("Expected max depth error with nested maps at MaxDepth=3, got: %s", result)
}
// Test with MaxDepth of 10 (should be enough for this structure)
tokens = gop.TokenizeWithOptions(deepMap, gop.Options{MaxDepth: 10})
result = gop.Format(tokens, gop.ThemeNone)
if strings.Contains(result, "max depth exceeded") {
t.Errorf("Should not have max depth error with MaxDepth=10 for this structure, got: %s", result)
}
if !strings.Contains(result, "deep value") {
t.Errorf("Should contain 'deep value' with sufficient MaxDepth, got: %s", result)
}
// Test with deeply nested slices
var deepSlice interface{} = []interface{}{
[]interface{}{
[]interface{}{
[]interface{}{
[]interface{}{
[]interface{}{
"deeply nested",
},
},
},
},
},
}
tokens = gop.TokenizeWithOptions(deepSlice, gop.Options{MaxDepth: 4})
result = gop.Format(tokens, gop.ThemeNone)
if !strings.Contains(result, "gop.GopError(") {
t.Errorf("Expected max depth error with nested slices at MaxDepth=4, got: %s", result)
}
}
func writeFile(t *testing.T, f, code string) {
err := os.WriteFile(f, []byte(code), 0644)
if err != nil {
t.Fatal(err)
}
}