-
Notifications
You must be signed in to change notification settings - Fork 0
/
gofiledb_test.go
645 lines (536 loc) · 14.5 KB
/
gofiledb_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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// gofiledb package provides an interface between Go applications and the linux-based file system
// so that the filesystem can be used as a database or a caching layer.
package gofiledb
import (
"fmt"
"github.com/teejays/clog"
"github.com/teejays/gofiledb/util"
"log"
"os/user"
"reflect"
"testing"
)
const REMOVE_COLLECTION = false
const DESTROY = false
var documentRoot string
func init() {
// Set this to 0 for full logging, and 7 to no logging.
clog.LogLevel = 0
usr, err := user.Current()
if err != nil {
log.Fatalf("[Init] %v", err)
}
documentRoot = util.JoinPath(usr.HomeDir, "gofiledb_test")
}
/********************************************************************************
* M O C K D A T A *
*********************************************************************************/
type (
User struct {
UserId int
Name string
Address string
Age int
Org OrgData
}
OrgData struct {
OrgId int64
}
)
type Org struct {
OrgId int
Name string
Employees int
}
var mockClients []ClientInitOptions = []ClientInitOptions{
// 0
{OverwritePreviousData: true},
// 1
{OverwritePreviousData: true},
}
var mockCollections map[string]CollectionProps = map[string]CollectionProps{
"User": CollectionProps{
Name: "User",
EncodingType: ENCODING_JSON,
EnableGzipCompression: false,
NumPartitions: 3,
},
"Org": CollectionProps{
Name: "Org",
EncodingType: ENCODING_JSON,
EnableGzipCompression: true,
NumPartitions: 3,
},
}
var mockUsers map[string]User = map[string]User{
// Mock 0 A
"1": User{
UserId: 1,
Name: "John Doe",
Address: "123 Main Street, ME 12345",
Age: 25,
Org: OrgData{OrgId: 1},
},
// Mock 1a
"1a": User{
UserId: 1,
Name: "John Doe B",
Address: "123 Main Street, ME 12345",
Age: 30,
Org: OrgData{OrgId: 1},
},
// Mock 1 A
"2": User{
UserId: 2,
Name: "Jane Does",
Address: "123 Main Street, ME 12345",
Age: 25,
Org: OrgData{OrgId: 261},
},
// Mock 2 A
"3": User{
UserId: 3,
Name: "Joe Dies",
Address: "123 Main Street, ME 12345",
Age: 26,
Org: OrgData{OrgId: 1},
},
}
var mockOrgs []Org = []Org{
Org{
OrgId: 1,
Name: "Company A",
Employees: 100,
},
Org{
OrgId: 2,
Name: "Company B",
Employees: 500,
},
}
/********************************************************************************
* T E S T S *
*********************************************************************************/
/*
* Client Tests
*/
// TestGetClientPreInit: Makes sure we get a ClientNotInitialized Error when getting a client which has not been initialized
func TestGetClientPreInit(t *testing.T) {
clog.Infof("Running: TestGetClientPreInit")
defer func() {
// it should panic
if r := recover(); r == nil {
t.Error("Expected Panic with ErrClientNotInitialized error but got nil")
return
} else if r.(string) != ErrClientNotInitialized.Error() {
t.Errorf("Expected Panic with ErrClientNotInitialized error but got: %s", r)
}
}()
_ = GetClient()
}
// TestInitializeClient: Makes sure we can initialize a fresh copy of a client at documentRoot
func TestInitializeClient(t *testing.T) {
clog.Infof("Running: TestInitializeClient")
mockClients[0].DocumentRoot = documentRoot
err := Initialize(mockClients[0])
if err != nil {
log.Fatalf("[TestInitClient] %v", err)
}
_ = GetClient() // ensure that this doesn't panic
}
// TestInitializeClient: Makes sure we can initialize a fresh copy of a client at documentRoot
func TestInitializeClientAgain(t *testing.T) {
clog.Infof("Running: TestInitializeClientTwo")
mockClients[1].DocumentRoot = documentRoot
err := Initialize(mockClients[1])
if err != nil && err != ErrClientAlreadyInitialized {
log.Fatalf("[TestInitClient] %v", err)
}
if err == nil {
t.Error("Expected ErrClientAlreadyInitialized error but got nil")
}
_ = GetClient() // Ensure that this doesn't panic
}
// TestGetClient: Makes sure we can get the initialized client
func TestGetClient(t *testing.T) {
clog.Infof("Running: TestGetClient")
_ = GetClient() // Ensure that this doesn't panic
}
/*
* Collection Tests
*/
func TestIsCollectionExistFail(t *testing.T) {
clog.Infof("Running: TestIsCollectionExistFail")
client := GetClient()
exists, err := client.IsCollectionExist(mockCollections["User"].Name)
if err != nil {
t.Error(err)
}
if exists {
t.Error("Expected collection to not exist, but it exists")
}
}
func TestAddCollection(t *testing.T) {
clog.Infof("Running: TestAddCollectionUser")
client := GetClient()
err := client.AddCollection(mockCollections["User"])
if err != nil {
t.Error(err)
}
}
func TestIsCollectionExist(t *testing.T) {
clog.Infof("Running: TestIsCollectionExist")
client := GetClient()
exists, err := client.IsCollectionExist(mockCollections["User"].Name)
if err != nil {
t.Error(err)
}
if !exists {
t.Errorf("Expected collections %s to exist but received false for IsCollectionExist method", mockCollections["User"].Name)
}
}
/*
* Index Tests
*/
func TestAddIndex(t *testing.T) {
clog.Infof("Running: TestAddIndex")
client := GetClient()
err := client.AddIndex(mockCollections["User"].Name, "Age")
if err != nil {
t.Error(err)
}
err = client.AddIndex(mockCollections["User"].Name, "Org.OrgId")
if err != nil {
t.Error(err)
}
}
/*
* Data Write
*/
func TestSetStructFirst(t *testing.T) {
clog.Infof("Running: TestSetStructFirst")
collectionName := "User"
ref := "1"
data := mockUsers[ref]
key := Key(data.UserId)
client := GetClient()
err := client.SetStruct(mockCollections[collectionName].Name, key, data)
if err != nil {
t.Error(err)
}
var newData User
err = fetchAndAssertData(collectionName, key, newData, data, "UserId")
if err != nil {
t.Error(err)
}
}
func TestSetStructSecond(t *testing.T) {
clog.Infof("Running: TestSetStructSecond")
collectionName := "User"
ref := "2"
data := mockUsers[ref]
key := Key(data.UserId)
client := GetClient()
err := client.SetStruct(mockCollections[collectionName].Name, key, data)
if err != nil {
t.Error(err)
}
var newData User
err = fetchAndAssertData(collectionName, key, newData, data, "UserId")
if err != nil {
t.Error(err)
}
}
func TestSetStructThird(t *testing.T) {
clog.Infof("Running: TestSetStructThird")
collectionName := "User"
ref := "3"
data := mockUsers[ref]
key := Key(data.UserId)
client := GetClient()
err := client.SetStruct(mockCollections[collectionName].Name, key, data)
if err != nil {
t.Error(err)
}
var newData User
err = fetchAndAssertData(collectionName, key, newData, data, "UserId")
if err != nil {
t.Error(err)
}
}
func TestSetSructOverwrite(t *testing.T) {
clog.Infof("Running: TestSetStructOverWrite")
collectionName := "User"
ref := "1a"
data := mockUsers[ref]
key := Key(data.UserId)
client := GetClient()
err := client.SetStruct(mockCollections[collectionName].Name, key, data)
if err != nil {
t.Error(err)
}
var newData User
err = fetchAndAssertData(collectionName, key, newData, data, "UserId")
if err != nil {
t.Error(err)
}
}
/*
* Data Read
*/
func TestGetStruct(t *testing.T) {
clog.Infof("Running: TestGetStruct")
collectionName := "User"
ref := "1a"
data := mockUsers[ref]
key := Key(data.UserId)
var newData User
err := fetchAndAssertData(collectionName, key, newData, data, "UserId")
if err != nil {
t.Error(err)
}
}
/*
* Data Search
*/
func TestSearch(t *testing.T) {
collectionName := "User"
keyField := "UserId"
c := GetClient()
resp, err := c.Search(collectionName, "Age:25")
if err != nil {
t.Error(err)
}
err = assertSearchResponse(resp, 1, []User{mockUsers["2"]}, keyField)
if err != nil {
fmt.Println(resp)
t.Error(err)
}
resp, err = c.Search(collectionName, "Org.OrgId:1")
if err != nil {
t.Error(err)
}
err = assertSearchResponse(resp, 2, []User{mockUsers["1a"], mockUsers["3"]}, keyField)
if err != nil {
fmt.Println(resp)
t.Error(err)
}
resp, err = c.Search(collectionName, "Org.OrgId:1+Age:26")
if err != nil {
t.Error(err)
}
err = assertSearchResponse(resp, 1, []User{mockUsers["3"]}, keyField)
if err != nil {
fmt.Println(resp)
t.Error(err)
}
resp, err = c.Search(collectionName, "Org.OrgId:1+Age:26+Name:Tom")
if err != nil && err != ErrIndexNotImplemented {
t.Error(err)
}
if err != ErrIndexNotImplemented {
t.Error(fmt.Errorf("Expected ErrIndexNotImplemented got: %v, %s", resp, err))
}
}
func TestGzipCollection(t *testing.T) {
collectionName := "Org"
collectionProps := mockCollections[collectionName]
keyField := "OrgId"
// Create a new collection
client := GetClient()
err := client.AddCollection(collectionProps)
if err != nil {
t.Error(err)
}
// Add Document 1
ref := 0
data := mockOrgs[ref]
key := data.OrgId
err = client.SetStruct(collectionName, Key(key), data)
if err != nil {
t.Error(err)
}
// Add Index
err = client.AddIndex(collectionName, "Employees")
if err != nil {
t.Error(err)
}
// Add Document 2
ref = 1
data = mockOrgs[ref]
key = data.OrgId
err = client.SetStruct(collectionName, Key(key), data)
if err != nil {
t.Error(err)
}
// Fetch Document 1
ref = 0
data = mockOrgs[ref]
key = data.OrgId
var data1 Org
err = fetchAndAssertData(collectionName, Key(key), data1, data, keyField)
if err != nil {
t.Error(err)
}
// Fetch Document 2
ref = 1
data = mockOrgs[ref]
key = data.OrgId
var data2 Org
err = fetchAndAssertData(collectionName, Key(key), data2, data, keyField)
if err != nil {
t.Error(err)
}
// Search
resp, err := client.Search(collectionName, "Employees:500")
if err != nil {
t.Error(err)
}
err = assertSearchResponse(resp, 1, []Org{mockOrgs[1]}, keyField)
if err != nil {
t.Error(err)
}
}
func TestRemoveCollection(t *testing.T) {
if !REMOVE_COLLECTION {
log.Println("REMOVE_COLLECTION flag set to false. Leaving collection data as it is.")
return
}
client := GetClient()
err := client.RemoveCollection(mockCollections["User"].Name)
if err != nil {
t.Error(err)
}
err = client.RemoveCollection(mockCollections["Org"].Name)
if err != nil {
t.Error(err)
}
}
func TestDestroy(t *testing.T) {
if !DESTROY {
log.Println("DESTROY flag set to false. Not destorying the db.")
return
}
client := GetClient()
err := client.Destroy()
if err != nil {
t.Error(err)
}
}
/********************************************************************************
* H E L P E R S
*********************************************************************************/
// func assertUserDataByKey(key Key, expectedData interface{}) error {
// client := GetClient()
// var data User
// err := client.GetStruct(userCollectionName, key, &data)
// if err != nil {
// return err
// }
// if data != expectedData {
// return fmt.Errorf("Fectched data did not match expected data: \n Fetched: %v \n Expected: %v", data, expectedData)
// }
// return nil
// }
func fetchAndAssertData(collectionName string, key Key, newData interface{}, expectedData interface{}, keyFieldName string) error {
client := GetClient()
err := client.GetStruct(collectionName, key, &newData)
if err != nil {
return err
}
clog.Debugf("Fetched with Key: %d \n%+v", key, newData)
clog.Debugf("Expected with Key: %d \n%+v", key, expectedData)
err = assertEquality(expectedData, newData, keyFieldName)
if err != nil {
return fmt.Errorf("Fectched data did not match expected data: \n Fetched: %v \n Expected: %v \n Error: %s", newData, expectedData, err)
}
return nil
}
func assertSearchResponse(resp SearchResponse, expectedLength int, expectedResult interface{}, keyFieldName string) error {
if resp.NumDocuments != expectedLength {
return fmt.Errorf("number of results returned %d do not match the expected number %d", resp.NumDocuments, expectedLength)
}
var seen map[Key]bool = make(map[Key]bool)
switch reflect.TypeOf(expectedResult).Kind() {
case reflect.Slice:
expectedResultV := reflect.ValueOf(expectedResult)
for i := 0; i < expectedResultV.Len(); i++ {
dv := expectedResultV.Index(i)
dkv := dv.FieldByName(keyFieldName)
var dk Key = Key(dkv.Int())
if seen[dk] == true {
return fmt.Errorf("Same document can not be used twice in the expected results: %v", dv.Interface())
}
seen[dk] = false
for _, _r := range resp.Result {
r, ok := _r.(map[string]interface{})
if !ok {
return fmt.Errorf("Could not assert a result item as a map. It should be a map...")
}
__rk, ok := r[keyFieldName].(float64)
if !ok {
return fmt.Errorf("Could not assert the key field '%s' in a result item as a float. It is of type %s. \n%+v", keyFieldName, reflect.TypeOf(r[keyFieldName]), r)
}
_rk := int(__rk)
rk := Key(_rk)
if dk == rk {
if seen[dk] == true {
return fmt.Errorf("Same document seen twice in the results: %v", dk)
}
seen[rk] = true
break
}
}
}
break
default:
return fmt.Errorf("The expected results passed as param is not a slice. It should be a slice.")
}
for d, s := range seen {
if !s {
return fmt.Errorf("Expected document not found in the results: %v", d)
}
}
return nil
}
func assertEquality(expectedData interface{}, data interface{}, keyFieldName string) error {
// We get the key field value in both structs and compare them
dv := reflect.ValueOf(expectedData)
dkv := dv.FieldByName(keyFieldName)
var dk Key = Key(dkv.Int()) // dkv should be of type int
r, ok := data.(map[string]interface{})
if !ok {
return fmt.Errorf("Could not assert data param as a map. It should be a map...")
}
__rk, ok := r[keyFieldName].(float64)
if !ok {
return fmt.Errorf("Could not assert the key field '%s' in a result item as a float. It is of type %s. \n%+v", keyFieldName, reflect.TypeOf(r[keyFieldName]), r)
}
_rk := int(__rk)
rk := Key(_rk)
if dk != rk {
return fmt.Errorf("The key fields did not match for the two structs: expected %d got %d", dk, rk)
}
return nil
}
func assertSearchResult(resp SearchResponse, expectedLength int, names []string) error {
if resp.NumDocuments != expectedLength {
return fmt.Errorf("number of results returned %d do not match the expected number %d", resp.NumDocuments, expectedLength)
}
for _, n := range names {
var exists bool
for i, _r := range resp.Result {
r, ok := _r.(map[string]interface{})
if !ok {
return fmt.Errorf("error asserting the row %d of results as a map[string]interface{}", i+1)
}
if n == r["Name"] {
exists = true
}
}
if !exists {
return fmt.Errorf("Expected a document with name %s but did not find it in result.", n)
}
}
return nil
}