-
Notifications
You must be signed in to change notification settings - Fork 16
/
query_mappers_test.go
107 lines (92 loc) · 2.42 KB
/
query_mappers_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
package proteus
import (
"database/sql"
"fmt"
"testing"
"github.com/jonbodner/stackerr"
)
type NoErrType string
func (NoErrType) Error() string {
return "NOERR"
}
type DummyDB struct {
pos int
Queries []string
Args [][]interface{}
}
func (dd *DummyDB) Query(query string, args ...interface{}) (*sql.Rows, error) {
return nil, dd.checkExpectedData(query, args...)
}
func (dd *DummyDB) Exec(query string, args ...interface{}) (sql.Result, error) {
return nil, dd.checkExpectedData(query, args...)
}
func (dd *DummyDB) checkExpectedData(query string, args ...interface{}) error {
if dd.pos >= len(dd.Queries) || dd.pos >= len(dd.Args) {
return stackerr.Errorf("Expected at least %d queries and args, only have %d queries and %d args", dd.pos, len(dd.Queries), len(dd.Args))
}
var msg string
if dd.Queries[dd.pos] != query {
msg = fmt.Sprintf("Expected query %s, got query %s", dd.Queries[dd.pos], query)
}
for k, v := range dd.Args[dd.pos] {
if k >= len(args) {
msg = msg + fmt.Sprintf(" Expected at least %d args to be passed in, got %d", k, len(args))
break
}
if v != args[k] {
msg = msg + fmt.Sprintf(" Expected arg %v at pos %d, got %v", v, k, args[k])
}
}
dd.pos = dd.pos + 1
if len(msg) == 0 {
return NoErrType("")
}
return stackerr.New(msg)
}
func TestMapMapper(t *testing.T) {
m := MapMapper{
"q1": "select * from foo where id = :id:",
"q2": "update foo set x=:x: where id = :id:",
}
runMapper(m, t)
}
func TestPropMapper(t *testing.T) {
m, err := PropFileToQueryMapper("test.properties")
if err != nil {
t.Fatal(err)
}
runMapper(m, t)
}
func runMapper(m QueryMapper, t *testing.T) {
type f struct {
Id string
X string
}
type s struct {
GetF func(e Querier, id string) (f, error) `proq:"q:q1" prop:"id"`
Update func(e Executor, id string, x string) (int64, error) `proq:"q:q2" prop:"id,x"`
}
sImpl := s{}
err := Build(&sImpl, Postgres, m)
if err != nil {
t.Error("error while building", err)
}
dummyDB := &DummyDB{
Queries: []string{
"select * from foo where id = $1",
"update foo set x=$1 where id = $2",
},
Args: [][]interface{}{
[]interface{}{"1"},
[]interface{}{"Hello", "2"},
},
}
_, err = sImpl.GetF(dummyDB, "1")
if _, ok := err.(NoErrType); !ok {
t.Errorf("Expected no error, got %v", err)
}
_, err = sImpl.Update(dummyDB, "2", "Hello")
if _, ok := err.(NoErrType); !ok {
t.Errorf("Expected no error, got %v", err)
}
}