-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter_test.go
118 lines (105 loc) · 2.38 KB
/
printer_test.go
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
package pretty_test
import (
"bytes"
"fmt"
"io"
"testing"
"github.com/pierrre/assert"
"github.com/pierrre/assert/assertauto"
. "github.com/pierrre/pretty"
)
func newTestPrinter() (*Printer, *CommonValueWriter) {
c := NewConfig()
vw := NewCommonValueWriter()
vw.ConfigureTest()
p := NewPrinter(c, vw)
return p, vw
}
type testCase struct {
name string
value any
configure func(vw *CommonValueWriter)
ignoreResult bool
ignoreAllocs bool
ignoreBenchmark bool
}
func (tc *testCase) newPrinter() *Printer {
p, vw := newTestPrinter()
if tc.configure != nil {
tc.configure(vw)
}
return p
}
var testCases []*testCase
func addTestCases(tcs []*testCase) {
testCases = append(testCases, tcs...)
}
func addTestCasesPrefix(prefix string, tcs []*testCase) {
for _, tc := range tcs {
tc.name = prefix + "/" + tc.name
}
addTestCases(tcs)
}
func Test(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
p := tc.newPrinter()
s := p.String(tc.value)
if !tc.ignoreResult {
assertauto.Equal(t, s, assertauto.Name("result"))
}
t.Log(s)
if !tc.ignoreAllocs {
allocs, _ := assertauto.AllocsPerRun(t, 100, func() {
t.Helper()
p.Write(io.Discard, tc.value)
}, assertauto.Name("allocs"))
t.Logf("allocs: %g", allocs)
}
})
}
}
func Benchmark(b *testing.B) {
for _, tc := range testCases {
if tc.ignoreBenchmark {
continue
}
b.Run(tc.name, func(b *testing.B) {
p := tc.newPrinter()
for range b.N {
p.Write(io.Discard, tc.value)
}
})
}
}
func TestWrite(t *testing.T) {
buf := new(bytes.Buffer)
Write(buf, "test")
s := buf.String()
assertauto.Equal(t, s, assertauto.Name("result"))
assertauto.AllocsPerRun(t, 100, func() {
t.Helper()
Write(io.Discard, "test")
}, assertauto.Name("allocs"))
}
func TestString(t *testing.T) {
s := String("test")
assertauto.Equal(t, s, assertauto.Name("result"))
assertauto.AllocsPerRun(t, 100, func() {
t.Helper()
String("test")
}, assertauto.Name("allocs"))
}
func TestFormatter(t *testing.T) {
buf := new(bytes.Buffer)
f := Formatter("test")
_, err := fmt.Fprintf(buf, "%v", f)
assert.NoError(t, err)
s := buf.String()
assertauto.Equal(t, s, assertauto.Name("result"))
assertauto.AllocsPerRun(t, 100, func() {
t.Helper()
_, err := fmt.Fprintf(io.Discard, "%v", f)
assert.NoError(t, err)
}, assertauto.Name("allocs"))
}