-
Notifications
You must be signed in to change notification settings - Fork 37
/
utils.go
119 lines (101 loc) · 2.5 KB
/
utils.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
119
package testutils
import (
"fmt"
"regexp"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/stephenafamo/bob"
)
type Testcases map[string]Testcase
// Also used to generate documentation
type Testcase struct {
Query bob.Query
ExpectedSQL string
ExpectedArgs []any
Doc string
}
var (
oneOrMoreSpace = regexp.MustCompile(`\s+`)
spaceAroundBrackets = regexp.MustCompile(`\s*([\(|\)])\s*`)
)
func Clean(s string) string {
s = strings.TrimSpace(s)
s = oneOrMoreSpace.ReplaceAllLiteralString(s, " ")
s = spaceAroundBrackets.ReplaceAllString(s, " $1 ")
return s
}
type FormatFunc = func(string) (string, error)
func QueryDiff(a, b string, clean FormatFunc) (string, error) {
if clean == nil {
clean = func(s string) (string, error) { return Clean(s), nil }
}
cleanA, err := clean(a)
if err != nil {
return "", fmt.Errorf("%s\n%w", a, err)
}
cleanB, err := clean(b)
if err != nil {
return "", fmt.Errorf("%s\n%w", b, err)
}
return cmp.Diff(cleanA, cleanB), nil
}
func ArgsDiff(a, b []any) string {
return cmp.Diff(a, b)
}
func ErrDiff(a, b error) string {
return cmp.Diff(a, b)
}
func RunTests(t *testing.T, cases Testcases, format FormatFunc) {
t.Helper()
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
sql, args, err := bob.Build(tc.Query)
if err != nil {
t.Fatalf("error: %v", err)
}
diff, err := QueryDiff(tc.ExpectedSQL, sql, format)
if err != nil {
t.Fatalf("error: %v", err)
}
if diff != "" {
fmt.Println(sql)
fmt.Println(args)
t.Fatalf("diff: %s", diff)
}
if diff := ArgsDiff(tc.ExpectedArgs, args); diff != "" {
t.Fatalf("diff: %s", diff)
}
})
}
}
type ExpressionTestcases map[string]ExpressionTestcase
// Also used to generate documentation
type ExpressionTestcase struct {
Expression bob.Expression
ExpectedSQL string
ExpectedArgs []any
ExpectedError error
Doc string
}
func RunExpressionTests(t *testing.T, d bob.Dialect, cases ExpressionTestcases) {
t.Helper()
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
b := &strings.Builder{}
args, err := bob.Express(b, d, 1, tc.Expression)
sql := b.String()
if diff := ErrDiff(tc.ExpectedError, err); diff != "" {
t.Fatalf("diff: %s", diff)
}
if diff, _ := QueryDiff(tc.ExpectedSQL, sql, nil); diff != "" {
fmt.Println(sql)
fmt.Println(args)
t.Fatalf("diff: %s", diff)
}
if diff := ArgsDiff(tc.ExpectedArgs, args); diff != "" {
t.Fatalf("diff: %s", diff)
}
})
}
}