-
Notifications
You must be signed in to change notification settings - Fork 33
/
mongodm_test.go
416 lines (293 loc) · 9.69 KB
/
mongodm_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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package mongodm
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"testing"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const (
// It must be a container name to connect to mongodb correctly
DBHost string = "mongo"
DBName string = "mongodm_test"
DBUser string = "admin"
DBPass string = "admin"
DBSource string = "admin"
DBTestCollection string = "_testCollection"
DBTestRelCollection string = "_testRelationCollection"
)
type (
TestModel struct {
DocumentBase `json:",inline" bson:",inline"`
Name string `json:"name" bson:"name" required:"true" minLen:"2"`
Number int `json:"number" bson:"number"`
RequiredField string `json:"requiredField" bson:"requiredField" required:"true"`
SomeSlice []string `json:"to" bson:"to"`
Relation21 interface{} `json:"relationTwo" bson:"relationTwo" model:"TestRelationModel" relation:"11"`
Relation11 interface{} `json:"relationOne" bson:"relationOne" model:"TestRelationModel" relation:"11"`
Relation1N interface{} `json:"relationMany" bson:"relationMany" model:"TestRelationModel" relation:"1n"`
TestEmbed *TestEmbedModel `json:"testEmbed" bson:"testEmbed"`
}
TestRelationModel struct {
DocumentBase `json:",inline" bson:",inline"`
RelationName string `json:"relationName" bson:"relationName"`
}
TestEmbedModel struct {
Value string `json:"value" bson:"value"`
}
)
var dbConnection *Connection
var testRequest = []byte(`{"testmodel" : {"Name":"Max","Number":1337}}`)
var testInvalidRequest = []byte(`{"testmodel" : {"Name":"M"}}`)
var localsFile []byte
func init() {
var err error
localsFile, err = ioutil.ReadFile("locals.json")
if err != nil {
fmt.Printf("File error: %v\n", err)
os.Exit(1)
}
}
func TestConnection(t *testing.T) {
var localMap map[string]map[string]string
json.Unmarshal(localsFile, &localMap)
dbConfig := &Config{
DatabaseHosts: []string{DBHost},
DatabaseName: DBName,
DatabaseUser: DBUser,
DatabasePassword: DBPass,
// Source is the database used to establish credentials and privileges
// with a MongoDB server. Defaults to the value of Database, if that is
// set, or "admin" otherwise.
// see https://godoc.org/labix.org/v2/mgo#DialInfo
DatabaseSource: "admin",
Locals: localMap["en-US"],
}
db, err := Connect(dbConfig)
if err != nil {
t.Error("DB: Connection error", err)
} else {
dbConnection = db
dbConnection.Register(&TestModel{}, DBTestCollection)
dbConnection.Register(&TestRelationModel{}, DBTestRelCollection)
Test := dbConnection.Model("testmodel")
TestRelation := dbConnection.Model("testrelationmodel")
//clear other entrys
Test.RemoveAll(nil)
TestRelation.RemoveAll(nil)
}
}
func TestConnectionWithCustomDialInfo(t *testing.T) {
var localMap map[string]map[string]string
json.Unmarshal(localsFile, &localMap)
dbConfig := &Config{
DialInfo: &mgo.DialInfo{
Addrs: []string{DBHost},
Database: DBName,
Username: DBUser,
Password: DBPass,
Source: DBSource,
},
Locals: localMap["en-US"],
}
_, err := Connect(dbConfig)
if err != nil {
t.Error("DB: Connection error", err)
}
}
func TestConnectionWithoutExtendedConfig(t *testing.T) {
dbConfig := &Config{
DatabaseHosts: []string{DBHost},
DatabaseName: DBName,
}
_, err := Connect(dbConfig)
if err != nil {
t.Error("DB: Connection error", err)
}
}
func TestCreate(t *testing.T) {
Test := dbConnection.Model("testmodel")
TestRelation := dbConnection.Model("testrelationmodel")
testModel := &TestModel{}
testRelationModel := &TestRelationModel{}
Test.New(testModel)
TestRelation.New(testRelationModel)
testRelationModel.RelationName = "some relation"
errRelation := testRelationModel.Save()
if errRelation != nil {
t.Error("DB: creation error", errRelation)
}
testModel.RequiredField = "Test"
testModel.Name = "Some test"
testModel.Number = 1337
testModel.Relation11 = testRelationModel
testModel.Relation21 = nil
testModel.Relation1N = []*TestRelationModel{testRelationModel, testRelationModel, testRelationModel, testRelationModel, testRelationModel}
err := testModel.Save()
if err != nil {
t.Error("DB: creation error", err)
}
}
func TestFindPopulate(t *testing.T) {
Test := dbConnection.Model("testmodel")
testModelSlice := []*TestModel{}
err := Test.Find(bson.M{"deleted": false}).Populate("Relation11", "Relation1N").Exec(&testModelSlice)
if len(testModelSlice) == 0 || err != nil {
t.Error("DB: Creation error - previous test did not persist any data or find failed", err)
}
for _, testModel := range testModelSlice {
if testModel.Name != "Some test" || testModel.Number != 1337 {
t.Error("DB: test model was not saved correctly")
}
if _, ok := testModel.Relation11.(*TestRelationModel); !ok {
t.Error("DB: 11 relation was not populated correctly - wrong type")
}
if _, ok := testModel.Relation1N.([]*TestRelationModel); !ok {
t.Error("DB: 1N relation was not populated correctly - wrong type")
}
if testModel.TestEmbed != nil {
t.Error("DB: Expected nil for embedded type")
}
//one loop is enough
break
}
}
func TestFindOneWithoutPopulate(t *testing.T) {
Test := dbConnection.Model("testmodel")
testModel := &TestModel{}
err := Test.FindOne(bson.M{"deleted": false}).Exec(testModel)
if _, ok := err.(*NotFoundError); ok {
t.Error("DB: FindOne failed, minimum one result was expected", err)
} else if err != nil {
t.Error("DB: FindOne failed", err)
}
//nothing populated, so check for bson object id casts
if testModel.Relation21 != nil {
t.Error("DB: expected second relation as nil")
}
if _, ok := testModel.Relation11.(bson.ObjectId); !ok {
t.Error("DB: nothing populated - cast to bson object id failed for relation 11")
}
if _, ok := testModel.Relation1N.([]bson.ObjectId); !ok {
t.Error("DB: nothing populated - cast to bson object id slice failed for relation 1N")
}
}
func TestUpdate(t *testing.T) {
Test := dbConnection.Model("testmodel")
testModel := &TestModel{}
err := Test.FindOne(bson.M{"deleted": false}).Exec(testModel)
if _, ok := err.(*NotFoundError); ok {
t.Error("DB: FindOne failed, minimum one result was expected", err)
} else if err != nil {
t.Error("DB: FindOne failed", err)
}
testModel.Name = "Some other test"
err = testModel.Save()
if err != nil {
t.Error("DB: update on model failed, save error", err)
}
//rollback
testModelUpdate := &TestModel{}
err = Test.FindOne(bson.M{"name": testModel.Name}).Exec(testModelUpdate)
if err != nil {
t.Error("DB: find with updated data failed", err)
}
testModelUpdate.Name = "Some test"
err = testModelUpdate.Save()
if err != nil {
t.Error("DB: rollback on model failed, save error", err)
}
}
func TestSetNewRelationAndPopulate(t *testing.T) {
Test := dbConnection.Model("testmodel")
TestRelation := dbConnection.Model("testrelationmodel")
testModel := &TestModel{}
err := Test.FindOne(bson.M{"deleted": false}).Exec(testModel)
if _, ok := err.(*NotFoundError); ok {
t.Error("DB: FindOne failed, minimum one result was expected", err)
} else if err != nil {
t.Error("DB: FindOne failed", err)
}
newTestModel := &TestRelationModel{}
TestRelation.New(newTestModel)
err = newTestModel.Save()
if err != nil {
t.Error("DB: Save for new 11 relation failed", err)
}
testModel.Relation11 = newTestModel.Id
err = testModel.Save()
if err != nil {
t.Error("DB: Save for new 11 relation failed", err)
}
err = testModel.Populate("Relation11")
if err != nil {
t.Error("DB: Could not populate new relation", err)
}
if _, ok := testModel.Relation11.(*TestRelationModel); !ok {
if err != nil {
t.Error("DB: Population went wrong - could not cast to the new relation type")
}
}
//add object id to old model for testing
if relations, ok := testModel.Relation1N.([]bson.ObjectId); !ok {
if err != nil {
t.Error("DB: Cast for non population went wrong, bson object id slice expected")
}
} else {
relations = append(relations, newTestModel.Id)
testModel.Relation1N = relations
err := testModel.Save()
if err != nil {
t.Error("DB: Could not save new 1n relation", err)
}
}
}
func TestRemove(t *testing.T) {
Test := dbConnection.Model("testmodel")
testModel := &TestModel{}
err := Test.FindOne(bson.M{"deleted": false}).Exec(testModel)
if _, ok := err.(*NotFoundError); ok {
t.Error("DB: FindOne failed, minimum one result was expected", err)
} else if err != nil {
t.Error("DB: FindOne failed", err)
}
err = testModel.Delete()
if err != nil {
t.Error("DB: model could not be deleted", err)
}
err = Test.FindOne(bson.M{"deleted": true}).Exec(testModel)
if _, ok := err.(*NotFoundError); ok {
t.Error("DB: FindOne failed, expected at least one deleted model", err)
} else if err != nil {
t.Error("DB: FindOne failed", err)
}
}
func TestMapping(t *testing.T) {
Test := dbConnection.Model("testmodel")
testModel := &TestModel{}
err, mapped := Test.New(testModel, testRequest)
if err != nil {
t.Error("DB: JSON mapping failed", err)
}
if _, ok := mapped["testmodel"]; !ok {
t.Error("DB: JSON mapping failed, expected also a non empty map result")
}
if testModel.Name != "Max" && testModel.Number != 1337 {
t.Error("DB: JSON mapping failed, attributes where not set")
}
}
func TestValidation(t *testing.T) {
Test := dbConnection.Model("testmodel")
testModel := &TestModel{}
err, _ := Test.New(testModel, testInvalidRequest)
if err != nil {
t.Error("DB: JSON mapping failed", err)
}
if valid, issues := testModel.Validate(); valid {
t.Error("DB: model validation failed, expected invalid request")
} else if len(issues) != 3 {
t.Error("DB: model validation failed, expected two issues", issues)
}
}