-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool_test.go
More file actions
714 lines (632 loc) · 14.7 KB
/
tool_test.go
File metadata and controls
714 lines (632 loc) · 14.7 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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
package tool
import (
"errors"
"fmt"
"strconv"
"testing"
"github.com/stretchr/testify/suite"
)
type (
ToolTestSuite struct {
suite.Suite
StdLogger
}
testLogger struct {
buf string
}
)
func (t *testLogger) Println(a ...any) {
t.buf += fmt.Sprintln(a...)
}
func (t *testLogger) Panicln(a ...any) {
panic(a)
}
func (t *testLogger) Printf(s string, a ...any) {
t.buf += fmt.Sprintf(s, a...)
}
func (t *testLogger) Print(a ...any) {
t.buf += fmt.Sprint(a...)
}
var testLog = &testLogger{}
func TestSuite(t *testing.T) {
suite.Run(t, new(ToolTestSuite))
}
func (s *ToolTestSuite) SetupSuite() {
SetLogger(testLog)
}
func (s *ToolTestSuite) SetupTest() {
testLog.buf = ""
}
func (s *ToolTestSuite) TestIn() {
s.Run("string", func() {
s.True(In("hi", "oh", "hi", "there"))
s.False(In("hi", "hello", "beautiful"))
})
s.Run("byte", func() {
s.True(In(byte(2), []byte{1, 2, 3}...))
s.Equal(false, In(byte(255), []byte{1, 2, 3}...))
})
}
func (s *ToolTestSuite) TestConsole() {
s.Run("1", func() {
Console("123", "456", "789")
s.Equal("[github.com/iamwavecut/tool:tool_test.go:65]> 123 456 789\n", testLog.buf)
})
s.Run("2", func() {
testLog.buf = ""
Console(struct{ int }{123})
s.Equal("[github.com/iamwavecut/tool:tool_test.go:70]> {int:123}\n", testLog.buf)
})
s.Run("3", func() {
testLog.buf = ""
Console(nil)
s.Equal("[github.com/iamwavecut/tool:tool_test.go:75]> <nil>\n", testLog.buf)
})
}
func (s *ToolTestSuite) TestNonZero() {
s.Run("string", func() {
s.Equal("hi", NonZero("hi", "there"))
s.Equal("there", NonZero("", "there"))
})
s.Run("int", func() {
s.Equal(1, NonZero(1, 2))
s.Equal(2, NonZero(0, 2))
})
type testStruct struct {
i int
}
s.Run("struct", func() {
s.Equal(testStruct{i: 2}, NonZero(testStruct{}, testStruct{i: 2}))
})
}
func (s *ToolTestSuite) TestJsonify() {
s.Run("string", func() {
res := Jsonify([]string{"oh", "hi", "there"})
s.NotEmpty(res.String())
s.Equal(`["oh","hi","there"]`, res.String())
})
s.Run("bytes", func() {
res := Jsonify([]string{"oh", "hi", "there"})
s.NotEmpty(res.Bytes())
s.Equal([]byte(`["oh","hi","there"]`), res.Bytes())
})
s.Run("invalid", func() {
res := Jsonify(func() {})
s.Empty(res)
})
}
func (s *ToolTestSuite) TestObjectify() {
s.Run("string", func() {
out := map[string]string{}
in := `{"key":"value"}`
res := Objectify(in, &out)
s.True(res)
s.Equal(map[string]string{"key": "value"}, out)
})
s.Run("bytestring", func() {
out := map[string]string{}
in := []byte(`{"key":"value"}`)
res := Objectify(in, &out)
s.True(res)
s.Equal(map[string]string{"key": "value"}, out)
})
}
func (s *ToolTestSuite) TestRetryFunc() {
s.Run("failure", func() {
times := 5
errorNum := 7
res := RetryFunc(times, 0, func() error {
if errorNum > 0 {
return errors.New(strconv.Itoa(errorNum))
}
return nil
})
s.Error(res)
})
s.Run("success", func() {
times := 5
errorNum := 3
res := RetryFunc(times, 0, func() error {
if errorNum > 0 {
errorNum--
return errors.New(strconv.Itoa(errorNum))
}
return nil
})
s.NoError(res)
})
}
func (s *ToolTestSuite) TestTry() {
s.Run("failure", func() {
s.False(Try(nil))
})
s.Run("success", func() {
s.True(Try(fmt.Errorf("error")))
})
s.Run("failure verbose", func() {
s.False(Try(nil, true))
s.Empty(testLog.buf)
})
s.Run("success verbose", func() {
s.True(Try(fmt.Errorf("verbose error"), true))
s.Equal("verbose error\n", testLog.buf)
})
}
func (s *ToolTestSuite) TestMust() {
s.Run("failure", func() {
s.NotPanics(func() {
Must(nil)
})
})
s.Run("success", func() {
s.Panics(func() {
Must(fmt.Errorf("error"))
})
})
}
func (s *ToolTestSuite) TestRandInt() {
s.Contains([]int{1, 2, 3, 4, 5}, RandInt(1, 5))
}
func (s *ToolTestSuite) TestPtr() {
intPtr := Ptr(1)
s.IsType(func() *int { i := 0; return &i }(), intPtr)
strPtr := Ptr("test")
s.IsType(func() *string { s := ""; return &s }(), strPtr)
boolPtr := Ptr(true)
s.IsType(func() *bool { s := true; return &s }(), boolPtr)
}
func (s *ToolTestSuite) TestVal() {
s.Run("non-nil pointer", func() {
val := 42
ptr := &val
result := Val(ptr)
s.Equal(val, result)
})
s.Run("nil pointer", func() {
var ptr *int
result := Val(ptr)
s.Equal(0, result)
})
s.Run("string pointer", func() {
val := "hello"
ptr := &val
result := Val(ptr)
s.Equal(val, result)
})
s.Run("nil string pointer", func() {
var ptr *string
result := Val(ptr)
s.Equal("", result)
})
s.Run("struct pointer", func() {
type testStruct struct {
Value int
}
val := testStruct{Value: 100}
ptr := &val
result := Val(ptr)
s.Equal(val, result)
})
}
func (s *ToolTestSuite) TestNilPtr() {
s.Run("non-zero int", func() {
val := 42
ptr := NilPtr(val)
s.NotNil(ptr)
s.Equal(val, *ptr)
})
s.Run("zero int", func() {
val := 0
ptr := NilPtr(val)
s.Nil(ptr)
})
s.Run("non-zero string", func() {
val := "hello"
ptr := NilPtr(val)
s.NotNil(ptr)
s.Equal(val, *ptr)
})
s.Run("zero string", func() {
val := ""
ptr := NilPtr(val)
s.Nil(ptr)
})
s.Run("non-zero bool", func() {
val := true
ptr := NilPtr(val)
s.NotNil(ptr)
s.Equal(val, *ptr)
})
s.Run("zero bool", func() {
val := false
ptr := NilPtr(val)
s.Nil(ptr)
})
s.Run("struct with zero value", func() {
type testStruct struct {
Value int
}
val := testStruct{}
ptr := NilPtr(val)
s.Nil(ptr)
})
s.Run("struct with non-zero value", func() {
type testStruct struct {
Value int
}
val := testStruct{Value: 42}
ptr := NilPtr(val)
s.NotNil(ptr)
s.Equal(val.Value, ptr.Value)
})
}
func (s *ToolTestSuite) TestZeroVal() {
s.Run("int", func() {
result := ZeroVal(42)
s.Equal(0, result)
})
s.Run("string", func() {
result := ZeroVal("hello")
s.Equal("", result)
})
s.Run("bool", func() {
result := ZeroVal(true)
s.Equal(false, result)
})
s.Run("pointer", func() {
val := 42
ptr := &val
result := ZeroVal(ptr)
s.Nil(result)
})
s.Run("nil pointer", func() {
var ptr *int
result := ZeroVal(ptr)
s.Nil(result)
})
s.Run("struct", func() {
type testStruct struct {
Value int
Name string
}
val := testStruct{Value: 100, Name: "test"}
result := ZeroVal(val)
s.Equal(testStruct{}, result)
})
s.Run("slice", func() {
val := []int{1, 2, 3}
result := ZeroVal(val)
s.Nil(result)
})
s.Run("map", func() {
val := map[string]int{"a": 1}
result := ZeroVal(val)
s.Nil(result)
})
}
func (s *ToolTestSuite) TestRecoverer() {
for _, tc := range []struct {
name string
initial int
expected int
maxPanics int
success bool
}{
{name: "valid 0", initial: 0, expected: 1, maxPanics: 0, success: true},
{name: "valid 1", initial: 0, expected: 1, maxPanics: 1, success: true},
{name: "panic 0", maxPanics: 0, success: false},
{name: "panic 10", maxPanics: 10, success: false},
} {
s.Run(tc.name, func() {
recovers := 0
if tc.success {
s.NoError(
Recoverer(tc.maxPanics, func() {
tc.initial = tc.expected
}, tc.name),
)
s.Equal(tc.expected, tc.initial)
} else {
s.Error(
Recoverer(tc.maxPanics, func() {
recovers++
panic("test")
}, tc.name),
)
s.Equal(tc.maxPanics, recovers-1)
}
})
}
s.NoError(
Recoverer(0, func() {}),
)
}
func (s *ToolTestSuite) TestStrtr() {
in := "abcdef"
expected := "rstxyz"
actual := Strtr(in, map[string]string{
"a": "r",
"b": "s",
"c": "t",
"def": "xyz",
})
s.Equal(expected, actual)
s.Equal(in, Strtr(in, map[string]string{}))
s.Equal(in, Strtr(in, map[string]string{"": "b"}))
s.Empty(Strtr("", map[string]string{"a": "b"}))
s.Empty(Strtr("", map[string]string{"": ""}))
s.Equal(in, Strtr(in, map[string]string{"abc": "abc"}))
}
func (s *ToolTestSuite) TestIdentifyPanic() {
s.NotPanics(func() { identifyPanic() })
}
func (s *ToolTestSuite) TestExecTemplate() {
s.Run("simple", func() {
s.Equal("hello world", ExecTemplate("hello {{.}}", "world"))
})
s.Run("complex", func() {
s.Equal("hello world", ExecTemplate("hello {{.name}}", map[string]string{"name": "world"}))
})
s.Run("no map key (partial render)", func() {
s.Equal("hello ", ExecTemplate("hello {{.name}}", map[string]string{}))
})
s.Run("struct", func() {
type Name struct {
Name string
}
s.Equal("hello world", ExecTemplate("hello {{.Name}}", Name{Name: "world"}))
})
s.Run("struct no field (error)", func() {
type Name struct {
Value string
}
s.Equal("", ExecTemplate("hello {{.Name}}", Name{Value: "world"}))
})
s.Run("empty", func() {
s.Equal("", ExecTemplate("", "world"))
})
}
func (s *ToolTestSuite) TestMuteMulti() {
tests := []struct {
name string
in []any
want []any
}{
{
name: "trailing error",
in: []any{1, 2, 3, errors.New("error")},
want: []any{1, 2, 3},
},
{
name: "no error",
in: []any{1, 2, 3},
want: []any{1, 2, 3},
},
{
name: "empty",
in: []any{},
want: nil,
},
{
name: "only error",
in: []any{errors.New("error")},
want: nil,
},
}
for _, tc := range tests {
s.Run(tc.name, func() {
res := MultiMute(tc.in...)
s.Equal(tc.want, res)
})
}
}
func (s *ToolTestSuite) TestReturn() {
tests := []struct {
name string
inputVal int
inputErr error
}{
{
name: "error is nil",
inputVal: 5,
inputErr: nil,
},
{
name: "error is not nil",
inputVal: 7,
inputErr: errors.New("an error"),
},
}
for _, test := range tests {
s.Run(test.name, func() {
result := Return(test.inputVal, test.inputErr)
s.Equal(test.inputVal, result)
})
}
}
func (s *ToolTestSuite) TestMustReturn() {
tests := []struct {
name string
inputVal int
inputErr error
shouldPanic bool
}{
{
name: "When error is nil",
inputVal: 5,
inputErr: nil,
shouldPanic: false,
},
{
name: "When error is not nil",
inputVal: 7,
inputErr: errors.New("an error"),
shouldPanic: true,
},
}
for _, test := range tests {
s.Run(test.name, func() {
if test.shouldPanic {
s.Panics(func() { MustReturn(test.inputVal, test.inputErr) })
} else {
s.NotPanics(func() {
result := MustReturn(test.inputVal, test.inputErr)
s.Equal(test.inputVal, result)
})
}
})
}
}
func (s *ToolTestSuite) TestErr() {
errExpected := errors.New("Some error")
args := []any{"Hello", errExpected}
err := Err(args...)
s.NotNil(err)
s.Equal(errExpected, err)
args = []any{"Hello", "World"}
err = Err(args...)
s.Nil(err)
args = []any{}
err = Err(args...)
s.Nil(err)
}
func (s *ToolTestSuite) TestCatch() {
s.Run("catchable error", func() {
recoveredByTestFramework := false
defer func() {
if r := recover(); r != nil {
recoveredByTestFramework = true
s.Fail("Panic was not properly handled by tool.Catch or was an unexpected re-panic.", fmt.Sprintf("Recovered: %+v", r))
}
}()
errCaughtByHandler := false
var actualCaughtError error
expectedErrText := "catchable error from Must"
funcToTest := func() {
defer Catch(func(caught error) {
errCaughtByHandler = true
actualCaughtError = caught
})
Must(errors.New(expectedErrText))
s.Fail("tool.Must should have panicked, execution should not reach here.")
}
s.Assert().NotPanics(func() {
funcToTest()
}, "funcToTest containing Must and Catch should not panic externally.")
s.Assert().False(recoveredByTestFramework, "Test framework's defer should not have recovered if tool.Catch worked as expected.")
s.Assert().True(errCaughtByHandler, "Error should have been caught by the Catch handler.")
s.Assert().NotNil(actualCaughtError, "Error caught by handler should not be nil")
if actualCaughtError != nil {
s.Assert().Equal(expectedErrText, actualCaughtError.Error(), "Error message mismatch in Catch handler")
}
})
s.Run("uncatchable error", func() {
var catchHandlerCalled bool
uncatchableErr := errors.New("uncatchable error")
fnThatPanicsUncatchably := func() {
defer Catch(func(_ error) {
catchHandlerCalled = true
s.Fail("Catch handler should not be called for uncatchable errors that are re-panicked.")
})
panic(uncatchableErr)
}
s.Assert().PanicsWithValue(uncatchableErr, func() {
fnThatPanicsUncatchably()
}, "Expected to panic with the original uncatchable error.")
s.Assert().False(catchHandlerCalled, "Catch handler should not have been called.")
})
}
func (s *ToolTestSuite) TestConvertSlice() {
type testCase struct {
Name string
Input []int
DestTypeValue float64
ExpectedOutput []float64
ShouldPanic bool
}
testCases := []testCase{
{
Name: "successful conversion",
Input: []int{1, 2, 3},
DestTypeValue: float64(0),
ExpectedOutput: []float64{1.0, 2.0, 3.0},
ShouldPanic: false,
},
{
Name: "empty slice conversion",
Input: []int{},
DestTypeValue: float64(0),
ExpectedOutput: []float64{},
ShouldPanic: false,
},
{
Name: "nil slice conversion",
Input: nil,
DestTypeValue: float64(0),
ExpectedOutput: nil,
ShouldPanic: true,
},
}
for _, tc := range testCases {
s.Run(tc.Name, func() {
if tc.ShouldPanic {
if tc.Name == "nil slice conversion" {
s.PanicsWithError("ConvertSlice failed: srcSlice is nil", func() {
ConvertSlice(tc.Input, tc.DestTypeValue)
})
} else {
s.Panics(func() {
ConvertSlice(tc.Input, tc.DestTypeValue)
})
}
} else {
actualOutput := ConvertSlice(tc.Input, tc.DestTypeValue)
s.Equal(tc.ExpectedOutput, actualOutput)
}
})
}
s.Run("empty_slice_conversion", func() {
emptyIntSlice := []int{}
emptyFloatSlice := []float64{}
actualOutput := ConvertSlice(emptyIntSlice, float64(0))
s.Equal(emptyFloatSlice, actualOutput)
s.NotNil(actualOutput)
})
type SrcStruct struct {
A int
B string
}
type DestStruct struct {
A int
B string
C float32
}
type DestStructPartial struct {
A int
}
s.Run("struct_slice_conversion_identical", func() {
src := []SrcStruct{{A: 1, B: "one"}, {A: 2, B: "two"}}
expected := []SrcStruct{{A: 1, B: "one"}, {A: 2, B: "two"}}
actual := ConvertSlice(src, SrcStruct{})
s.Equal(expected, actual)
})
s.Run("struct_slice_conversion_extra_dest_field", func() {
src := []SrcStruct{{A: 1, B: "one"}, {A: 2, B: "two"}}
expected := []DestStruct{{A: 1, B: "one", C: 0.0}, {A: 2, B: "two", C: 0.0}}
actual := ConvertSlice(src, DestStruct{})
s.Equal(expected, actual)
})
s.Run("struct_slice_conversion_missing_dest_field", func() {
src := []SrcStruct{{A: 1, B: "one"}, {A: 2, B: "two"}}
expected := []DestStructPartial{{A: 1}, {A: 2}}
actual := ConvertSlice(src, DestStructPartial{})
s.Equal(expected, actual)
})
}
func (s *ToolTestSuite) TestIsZero() {
s.True(IsZero(0))
s.True(IsZero(""))
s.True(IsZero(false))
var v *int
s.True(IsZero(v))
}