-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.go
232 lines (189 loc) · 4.39 KB
/
core.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package fixture
import (
"database/sql"
"fmt"
"log"
"path"
"strings"
)
const (
defaultSchemaName = "schema.sql"
)
type DataFormat int
func (f DataFormat) String() string {
var ext string
for k, v := range extToDataFmtMapping {
if v == f {
ext = k
}
}
return strings.TrimLeft(ext, ".")
}
const (
SQL DataFormat = iota
YAML
JSON
)
var (
// extToDataFmtMapping maps extension to data format
extToDataFmtMapping = map[string]DataFormat{}
)
func LookupDataFormatByExt(ext string) (DataFormat, bool) {
ret, ok := extToDataFmtMapping[ext]
return ret, ok
}
type TestFixture struct {
config *Config
tables []*table
}
func New(opts ...Option) *TestFixture {
defaultConfig := &Config{
FixtureDataDir: ".",
SchemaFilepath: path.Join(".", defaultSchemaName),
}
tf := &TestFixture{
config: defaultConfig,
}
for _, opt := range opts {
opt(tf)
}
panicOnErr(tf.config.Validate())
tf.tables = parseSchemaFile(tf.config.SchemaFilepath)
tf.createTables()
return tf
}
func (tf *TestFixture) String() string {
return fmt.Sprintf("TestFixture(url='%s')", tf.config.DatabaseURL)
}
func (tf *TestFixture) Config() *Config {
return tf.config
}
func (tf *TestFixture) TableNames() []string {
names := make([]string, 0)
for _, tb := range tf.tables {
names = append(names, tb.name)
}
return names
}
func (tf *TestFixture) Use(tableNames ...string) *Scope {
selectedTables := make([]*table, 0)
for _, name := range tableNames {
table := tf.lookupTable(name)
if table == nil {
panic(fmt.Sprintf("table '%s' not found", name))
}
selectedTables = append(selectedTables, table)
}
return newScope(tf, selectedTables)
}
// DropTables drops all the test tables
func (tf *TestFixture) DropTables() {
log.Printf("fixture: drop %d tables", len(tf.tables))
db := getDB(tf)
defer db.Close()
for _, tb := range tf.tables {
_, err := db.Exec("DROP TABLE " + tb.name)
if err != nil {
log.Printf("fixture: failed to drop table '%s': %s", tb.name, err)
}
}
}
func (tf *TestFixture) createTables() {
log.Printf("fixture: create %d tables", len(tf.tables))
db := getDB(tf)
defer db.Close()
tx, err := db.Begin()
panicOnErr(err)
defer func() {
if err := recover(); err != nil {
tx.Rollback()
panic(err)
}
}()
for _, tb := range tf.tables {
_, err := tx.Exec(tb.createSQL)
if err != nil {
if strings.Contains(fmt.Sprintf("%s", err), "already exists") {
log.Printf("fixture: table '%s' already existed, try to clear existing data now", tb.name)
db.Exec("TRUNCATE TABLE " + tb.name)
}
}
}
tx.Commit()
}
func (tf *TestFixture) lookupTable(name string) *table {
for _, item := range tf.tables {
if item.name == name {
return item
}
}
return nil
}
type Scope struct {
tf *TestFixture
selectedTables []*table
}
func newScope(tf *TestFixture, tables []*table) *Scope {
scope := &Scope{tf, tables}
scope.insertFixtureData()
return scope
}
func (s *Scope) Test(testFunc func()) {
defer s.Clear()
testFunc()
}
// Clear just drop the selected tables, simple and clear
func (s *Scope) Clear() {
log.Printf("fixture: clear %d selected tables", len(s.selectedTables))
db := getDB(s.tf)
defer db.Close()
for _, tb := range s.selectedTables {
_, err := db.Exec("TRUNCATE TABLE " + tb.name)
if err != nil {
log.Printf("fixture: failed to clear table '%s': %s", tb.name, err)
}
}
}
func (s *Scope) insertFixtureData() {
db := getDB(s.tf)
defer db.Close()
tx, err := db.Begin()
panicOnErr(err)
defer func() {
if err := recover(); err != nil {
tx.Rollback()
panic(err)
}
}()
for _, tb := range s.selectedTables {
fixtureData := findFixtureData(s.tf.config.FixtureDataDir, tb)
if fixtureData == nil {
log.Printf("failed to find fixture data for table '%s'", tb.name)
continue
}
log.Printf("insert fixture data for table '%s' from file '%s'", tb.name, fixtureData.Path)
loader := LookupLoader(fixtureData.Format)
sqlStr, err := loader.Load(fixtureData.Path)
panicOnErr(err)
if sqlStr != "" {
_, err = tx.Exec(sqlStr)
if err != nil {
log.Panicf("failed to insert fixture data for table '%s': %s", tb.name, err)
}
}
}
tx.Commit()
}
func getDB(tf *TestFixture) *sql.DB {
db, err := sql.Open(tf.config.DatabaseURL.Driver(), tf.config.DatabaseURL.DSN())
panicOnErr(err)
return db
}
type table struct {
name string
createSQL string
}
type fixtureData struct {
Path string
Format DataFormat
}