forked from go-testfixtures/testfixtures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testfixtures.go
210 lines (187 loc) · 5.12 KB
/
testfixtures.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
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
package testfixtures
import (
"database/sql"
"fmt"
"io/ioutil"
"path"
"path/filepath"
"reflect"
"strings"
"gopkg.in/yaml.v2"
)
type fixtureFile struct {
path string
fileName string
content []byte
}
var (
// ErrWrongCastNotAMap is returned when a map is not a map[interface{}]interface{}
ErrWrongCastNotAMap = fmt.Errorf("Could not cast record: not a map[interface{}]interface{}")
// ErrFileIsNotSliceOrMap is returned the the fixture file is not a slice or map.
ErrFileIsNotSliceOrMap = fmt.Errorf("The fixture file is not a slice or map")
// ErrKeyIsNotString is returned when a record is not of type string
ErrKeyIsNotString = fmt.Errorf("Record map key is not string")
)
func (f *fixtureFile) fileNameWithoutExtension() string {
return strings.Replace(f.fileName, filepath.Ext(f.fileName), "", 1)
}
func (f *fixtureFile) delete(tx *sql.Tx, h DataBaseHelper) error {
_, err := tx.Exec(fmt.Sprintf("DELETE FROM %s", h.quoteKeyword(f.fileNameWithoutExtension())))
return err
}
func (f *fixtureFile) buildInsertSQL(h DataBaseHelper, record map[interface{}]interface{}) (sqlStr string, values []interface{}, err error) {
var sqlColumns string
var sqlValues string
i := 1
for key, value := range record {
if len(sqlColumns) > 0 {
sqlColumns += ", "
sqlValues += ", "
}
keyStr, ok := key.(string)
if !ok {
err = ErrKeyIsNotString
return
}
sqlColumns += h.quoteKeyword(keyStr)
switch h.paramType() {
case paramTypeDollar:
sqlValues += fmt.Sprintf("$%d", i)
case paramTypeQuestion:
sqlValues += "?"
case paramTypeColon:
if isDateTime(value) {
sqlValues += fmt.Sprintf("to_date(:%d, 'YYYY-MM-DD HH24:MI:SS')", i)
} else if isDate(value) {
sqlValues += fmt.Sprintf("to_date(:%d, 'YYYY-MM-DD')", i)
} else if isTime(value) {
sqlValues += fmt.Sprintf("to_date(:%d, 'HH24:MI:SS')", i)
} else {
sqlValues += fmt.Sprintf(":%d", i)
}
}
i++
values = append(values, value)
}
sqlStr = fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", h.quoteKeyword(f.fileNameWithoutExtension()), sqlColumns, sqlValues)
return
}
func (f *fixtureFile) insert(tx *sql.Tx, h DataBaseHelper) error {
var rows interface{}
err := yaml.Unmarshal(f.content, &rows)
if err != nil {
return err
}
t := reflect.TypeOf(rows)
v := reflect.ValueOf(rows)
switch t.Kind() {
case reflect.Slice:
length := v.Len()
for i := 0; i < length; i++ {
record, ok := v.Index(i).Interface().(map[interface{}]interface{})
if !ok {
return ErrWrongCastNotAMap
}
sqlStr, values, err := f.buildInsertSQL(h, record)
if err != nil {
return err
}
_, err = tx.Exec(sqlStr, values...)
if err != nil {
return err
}
}
case reflect.Map:
keys := v.MapKeys()
for _, key := range keys {
record, ok := v.MapIndex(key).Interface().(map[interface{}]interface{})
if !ok {
return ErrWrongCastNotAMap
}
sqlStr, values, err := f.buildInsertSQL(h, record)
if err != nil {
return err
}
_, err = tx.Exec(sqlStr, values...)
if err != nil {
return err
}
}
default:
return ErrFileIsNotSliceOrMap
}
return nil
}
func getYmlFiles(foldername string) ([]*fixtureFile, error) {
var files []*fixtureFile
fileinfos, err := ioutil.ReadDir(foldername)
if err != nil {
return nil, err
}
for _, fileinfo := range fileinfos {
if !fileinfo.IsDir() && filepath.Ext(fileinfo.Name()) == ".yml" {
fixture := &fixtureFile{
path: path.Join(foldername, fileinfo.Name()),
fileName: fileinfo.Name(),
}
fixture.content, err = ioutil.ReadFile(fixture.path)
if err != nil {
return nil, err
}
files = append(files, fixture)
}
}
return files, nil
}
// LoadFixtureFiles load all specified fixtures files into database:
// LoadFixtureFiles(db, &PostgreSQLHelper{},
// "fixtures/customers.yml", "fixtures/orders.yml")
// // add as many files you want
func LoadFixtureFiles(db *sql.DB, h DataBaseHelper, files ...string) error {
var fixtureFiles []*fixtureFile
var err error
for _, f := range files {
fixture := &fixtureFile{
path: f,
fileName: filepath.Base(f),
}
fixture.content, err = ioutil.ReadFile(fixture.path)
if err != nil {
return err
}
fixtureFiles = append(fixtureFiles, fixture)
}
return loadFixtures(db, h, fixtureFiles...)
}
// LoadFixtures loads all fixtures in a given folder into the database:
// LoadFixtures("myfixturesfolder", db, &PostgreSQLHelper{})
func LoadFixtures(foldername string, db *sql.DB, h DataBaseHelper) error {
fixturesFiles, err := getYmlFiles(foldername)
if err != nil {
return err
}
return loadFixtures(db, h, fixturesFiles...)
}
func loadFixtures(db *sql.DB, h DataBaseHelper, fixturesFiles ...*fixtureFile) error {
if !skipDatabaseNameCheck {
if !dbnameRegexp.MatchString(h.databaseName(db)) {
return errNotTestDatabase
}
}
err := h.disableReferentialIntegrity(db, func(tx *sql.Tx) error {
for _, file := range fixturesFiles {
err := file.delete(tx, h)
if err != nil {
return err
}
err = h.whileInsertOnTable(tx, file.fileNameWithoutExtension(), func() error {
return file.insert(tx, h)
})
if err != nil {
return err
}
}
return nil
})
return err
}