-
Notifications
You must be signed in to change notification settings - Fork 0
/
datastore_test.go
490 lines (448 loc) · 11.4 KB
/
datastore_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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package elasticorm_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"testing"
"github.com/fvosberg/elasticorm"
"gopkg.in/olivere/elastic.v5"
)
func TestDatastoreEnsureIndexExists(t *testing.T) {
type User struct {
Name string `json:"name"`
DateOfBirth string `json:"date" elasticorm:"type=date"`
}
client := elasticClient(t)
deleteAllIndices(t, client)
ds, err := elasticorm.NewDatastore(
client,
elasticorm.ForStruct(&User{}),
)
ok(t, err)
err = ds.EnsureIndexExists()
ok(t, err)
indexExists(t, client, `users`)
actMapping, err := client.GetMapping().Do(context.Background())
ok(t, err)
actMappingJSON, err := json.Marshal(actMapping)
ok(t, err)
equals(
t,
`{"users":{"mappings":{"user":{"properties":{"date":{"type":"date"},"name":{"type":"text"}}}}}}`,
string(actMappingJSON),
)
}
func TestDatastoreCreateAUser(t *testing.T) {
type User struct {
ID string `json:"id" elasticorm:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
elasticClient, ds := initDatastore(t, &User{})
user := &User{
// TODO test error on setted ID
FirstName: `Foobar`,
LastName: `Barfoo`,
}
err := ds.Create(user)
ok(t, err)
if user.ID == `` {
t.Error(`The ID of the user should be set after persisting`)
t.FailNow()
}
_, err = elasticClient.Refresh().Do(context.Background())
ok(t, err)
gotUser := &User{}
err = ds.Find(user.ID, gotUser)
ok(t, err)
equals(t, *user, *gotUser)
}
func TestDatastoreUpdateAUser(t *testing.T) {
type User struct {
ID string `json:"id" elasticorm:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
_, ds := initDatastore(t, &User{})
u := &User{
FirstName: `Pre Firstname`,
LastName: `Lastname`,
}
err := ds.Create(u)
ok(t, err)
u.FirstName = `Post Firstname`
err = ds.Update(u)
ok(t, err)
if u.ID == `` {
t.Error(`The ID of the user should not be empty`)
t.FailNow()
}
gotUser := User{}
err = ds.Find(u.ID, &gotUser)
ok(t, err)
equals(t, `Post Firstname`, gotUser.FirstName)
}
func TestDatastoreFindOneBy(t *testing.T) {
type User struct {
ID string `json:"id" elasticorm:"id"`
FirstName string `json:"first_name" elasticorm:"sortable"`
Email string `json:"email" elasticorm:"type=keyword"`
}
tests := []struct {
title string
users []User
searchField string
searchValue string
shouldFind User
expectedError error
SortBy string
Ordering string
}{
{
title: `Find a user by email`,
users: []User{
User{FirstName: `Wrong user`, Email: `[email protected]`},
User{FirstName: `The first name`, Email: `[email protected]`},
User{FirstName: `Wrong user`, Email: `[email protected]`},
},
searchField: `Email`,
searchValue: `[email protected]`,
shouldFind: User{FirstName: `The first name`, Email: `[email protected]`},
},
{
title: `Don't find a user by wrong email`,
users: []User{User{FirstName: `The first name`, Email: `[email protected]`}},
searchField: `Email`,
searchValue: `[email protected]`,
shouldFind: User{},
expectedError: elasticorm.ErrNotFound,
},
{
title: `Search for a field which doesn't exist`,
users: []User{User{FirstName: `The first name`, Email: `[email protected]`}},
searchField: `email`,
searchValue: `[email protected]`,
shouldFind: User{},
expectedError: errors.New(`Mapping configuration has no mapping for struct field`),
},
{
title: `Search with sort - asc`,
users: []User{
User{FirstName: `ABC`, Email: `[email protected]`},
User{FirstName: `DEF`, Email: `[email protected]`},
User{FirstName: `GHI`, Email: `[email protected]`},
},
searchField: `Email`,
searchValue: `[email protected]`,
shouldFind: User{FirstName: `ABC`, Email: `[email protected]`},
SortBy: `FirstName`,
Ordering: `asc`,
},
{
title: `Search with sort - desc`,
users: []User{
User{FirstName: `ABC`, Email: `[email protected]`},
User{FirstName: `DEF`, Email: `[email protected]`},
User{FirstName: `GHI`, Email: `[email protected]`},
},
searchField: `Email`,
searchValue: `[email protected]`,
shouldFind: User{FirstName: `GHI`, Email: `[email protected]`},
SortBy: `FirstName`,
Ordering: `desc`,
},
}
for _, tt := range tests {
t.Run(tt.title, func(t *testing.T) {
elasticClient, ds := initDatastore(t, &User{})
for _, user := range tt.users {
err := ds.Create(&user)
ok(t, err)
elasticClient.Refresh().Do(context.Background())
}
found := User{}
opts := []elasticorm.QueryOptFunc{}
if tt.SortBy != `` || tt.Ordering != `` {
opts = append(opts, ds.SetSorting(tt.SortBy, tt.Ordering))
}
err := ds.FindOneBy(tt.searchField, tt.searchValue, &found, opts...)
if tt.expectedError != nil {
equals(t, tt.expectedError.Error(), err.Error())
} else {
ok(t, err)
}
tt.shouldFind.ID = found.ID
equals(t, tt.shouldFind, found)
})
}
}
func TestFindByGeoBoundingBox(t *testing.T) {
// TODO support deeper nested location structs like User.Home.Location
// TODO check search on non geopoint
type Location struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
type User struct {
ID string `json:"id" elasticorm:"id"`
Name string `json:"name"`
Location *Location `json:"loc" elasticorm:"type=geo_point"`
}
_, ds := initDatastore(t, &User{})
err := ds.Create(&User{Name: "Juister", Location: &Location{Lat: 53.679598, Lon: 6.994391}})
ok(t, err)
err = ds.Create(&User{Name: "Swimmer", Location: &Location{Lat: 53.693986, Lon: 6.992063}})
ok(t, err)
ds.Refresh()
bottomLeft := Location{
Lat: 53.672103,
Lon: 6.962326,
}
topRight := Location{
Lat: 53.685006,
Lon: 7.017360,
}
found := []User{}
err = ds.FindByGeoBoundingBox(
`Location`,
elasticorm.NewBoundingBox(topRight.Lat, topRight.Lon, bottomLeft.Lat, bottomLeft.Lon),
&found,
)
ok(t, err)
equals(t, 1, len(found))
equals(t, "Juister", found[0].Name)
}
func TestFindByGeoDistance(t *testing.T) {
type Location struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
type Isle struct {
ID string `json:"id" elasticorm:"id"`
Name string `json:"name"`
Location *Location `json:"loc" elasticorm:"type=geo_point"`
}
_, ds := initDatastore(t, &Isle{})
err := ds.Create(&Isle{Name: "Memmert", Location: &Location{Lat: 53.640652, Lon: 6.887995}})
ok(t, err)
err = ds.Create(&Isle{Name: "Juist", Location: &Location{Lat: 53.681747, Lon: 7.008158}})
ok(t, err)
err = ds.Create(&Isle{Name: "Borkum", Location: &Location{Lat: 53.600230, Lon: 6.711053}})
ok(t, err)
err = ds.Create(&Isle{Name: "Langeoog", Location: &Location{Lat: 53.743725, Lon: 7.481725}})
ok(t, err)
ds.Refresh()
found := []Isle{}
err = ds.FindByGeoDistance(
`Location`,
53.666499,
7.050261,
`11.1km`,
&found,
)
ok(t, err)
equals(t, 2, len(found))
equals(t, "Juist", found[0].Name)
equals(t, "Memmert", found[1].Name)
}
func TestFindAll(t *testing.T) {
assertions := []struct {
Offset int
Limit int
Order string
ExpectedNames []string
}{
{
Offset: 0,
Limit: 10,
Order: `asc`,
ExpectedNames: []string{
`Unknown No. 0`,
`Unknown No. 1`,
`Unknown No. 2`,
`Unknown No. 3`,
`Unknown No. 4`,
`Unknown No. 5`,
`Unknown No. 6`,
`Unknown No. 7`,
`Unknown No. 8`,
`Unknown No. 9`,
},
},
{
Offset: 0,
Limit: 3,
Order: `asc`,
ExpectedNames: []string{
`Unknown No. 0`,
`Unknown No. 1`,
`Unknown No. 2`,
},
},
{
Offset: 3,
Limit: 3,
Order: `asc`,
ExpectedNames: []string{
`Unknown No. 3`,
`Unknown No. 4`,
`Unknown No. 5`,
},
},
{
Offset: 3,
Limit: 3,
Order: `desc`,
ExpectedNames: []string{
`Unknown No. 6`,
`Unknown No. 5`,
`Unknown No. 4`,
},
},
}
type User struct {
ID string `json:"id" elasticorm:"id"`
Name string `json:"name" elasticorm:"type=text,sortable"` // TODO error on not sorted | test with keyword
}
_, ds := initDatastore(t, &User{})
err := ds.CleanUp()
ok(t, err)
for i := 0; i < 10; i++ {
err := ds.Create(&User{
Name: fmt.Sprintf("Unknown No. %d", i),
})
ok(t, err)
// refresh after each creation to get the desired sorting
ds.Refresh()
}
for _, a := range assertions {
found := []User{}
err = ds.FindAll(
&found,
ds.Offset(a.Offset),
ds.Limit(a.Limit),
ds.SetSorting(`Name`, a.Order),
)
ok(t, err)
equals(t, len(found), len(a.ExpectedNames))
for i, name := range a.ExpectedNames {
equals(t, name, found[i].Name)
}
}
}
func TestFilterFindAll(t *testing.T) {
type Beverage struct {
Type string `json:"type" elasticorm:"type=keyword"`
}
type User struct {
ID string `json:"id" elasticorm:"id"`
Name string `json:"name" elasticorm:"sortable"`
Gender string `json:"gender" elasticorm:"type=keyword"` // TODO what are the edge cases
Beverage Beverage `json:"beverage"`
}
_, ds := initDatastore(t, &User{})
tests := []struct {
FilterFunc elasticorm.QueryOptFunc
FoundNames []string
}{
{
FilterFunc: ds.FilterByField(`Gender`, `female`),
FoundNames: []string{`Unknown No. 1`, `Unknown No. 3`},
},
{
FilterFunc: ds.FilterByField(`Beverage.Type`, `beer`),
FoundNames: []string{`Unknown No. 1`, `Unknown No. 2`},
},
}
for _, test := range tests {
err := ds.CleanUp()
ok(t, err)
err = ds.Create(&User{
Name: "Unknown No. 1",
Gender: `female`,
Beverage: Beverage{
Type: `beer`,
},
})
ok(t, err)
err = ds.Create(&User{
Name: "Unknown No. 2",
Gender: `male`,
Beverage: Beverage{
Type: `beer`,
},
})
ok(t, err)
err = ds.Create(&User{
Name: "Unknown No. 3",
Gender: `female`,
Beverage: Beverage{
Type: `coffee`,
},
})
ok(t, err)
ds.Refresh()
found := []User{}
err = ds.FindAll(
&found,
test.FilterFunc,
ds.SetSorting(`Name`, `asc`),
)
ok(t, err)
equals(t, len(test.FoundNames), len(found))
for k, name := range test.FoundNames {
equals(t, name, found[k].Name)
}
}
}
func initDatastore(t *testing.T, i interface{}) (*elastic.Client, *elasticorm.Datastore) {
client := elasticClient(t)
deleteAllIndices(t, client)
ds, err := elasticorm.NewDatastore(
client,
elasticorm.ForStruct(i),
)
ok(t, err)
err = ds.EnsureIndexExists()
ok(t, err)
return client, ds
}
func elasticClient(t *testing.T) *elastic.Client {
client, err := elastic.NewClient(
elastic.SetURL(elasticSearchURL),
elastic.SetTraceLog(fileLogger(`elastic-trace.log`)),
)
if err != nil {
t.Logf(
"Using %s as elasticsearch URL - please provide a running elasticsearch instance under this URL, or configure it with the env variable EDS_ES_URL. Be carefull, all data will be erased.",
elasticSearchURL,
)
t.Error(`Could not start elasticsearch` + err.Error())
t.FailNow()
}
return client
}
func fileLogger(name string) *log.Logger {
f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0755)
if err != nil {
panic(err)
}
logger := log.New(f, ``, log.LstdFlags)
return logger
}
func deleteAllIndices(t *testing.T, c *elastic.Client) {
_, err := c.DeleteIndex(`_all`).Do(context.Background())
ok(t, err)
_, err = c.Refresh().Do(context.Background())
ok(t, err)
}
func indexExists(t *testing.T, c *elastic.Client, indexName string) {
_, err := c.Refresh().Do(context.Background())
ok(t, err)
exists, err := c.IndexExists(indexName).Do(context.Background())
ok(t, err)
assert(t, exists, `The index `+indexName+` should exist`)
}