-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore_test.go
1555 lines (1219 loc) · 46.9 KB
/
store_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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright Scoir Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package mongodb_test
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/cenkalti/backoff"
"github.com/google/uuid"
"github.com/hyperledger/aries-framework-go/spi/storage"
commontest "github.com/hyperledger/aries-framework-go/test/component/storage"
dctest "github.com/ory/dockertest/v3"
dc "github.com/ory/dockertest/v3/docker"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/hyperledger/aries-framework-go-ext/component/storage/mongodb"
)
const (
mongoDBConnString = "mongodb://localhost:27017"
dockerMongoDBImage = "mongo"
dockerMongoDBTagV400 = "4.0.0"
dockerMongoDBTagV428 = "4.2.8"
dockerMongoDBTagV500 = "5.0.0"
)
// This should function the same as the default logger in the mongodb package.
// This is here just to increase code coverage by allowing us to exercise the WithLogger option.
type testLogger struct {
logger *log.Logger
}
func (d *testLogger) Infof(msg string, args ...interface{}) {
d.logger.Printf(msg, args...)
}
func TestMongoDB_V4_0_0(t *testing.T) {
startContainerAndDoAllTests(t, dockerMongoDBTagV400)
}
func TestMongoDB_V4_2_8(t *testing.T) {
startContainerAndDoAllTests(t, dockerMongoDBTagV428)
}
func TestMongoDB_V5_0_0(t *testing.T) {
startContainerAndDoAllTests(t, dockerMongoDBTagV500)
}
func TestProvider_New_Failure(t *testing.T) {
provider, err := mongodb.NewProvider("BadConnString")
require.EqualError(t, err, `failed to create a new MongoDB client: error parsing uri: `+
`scheme must be "mongodb" or "mongodb+srv"`)
require.Nil(t, provider)
}
func TestProvider_SetStoreConfig_Failure(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://BadURL", mongodb.WithTimeout(1))
require.NoError(t, err)
_, err = provider.OpenStore("StoreName")
require.NoError(t, err)
err = provider.SetStoreConfig("StoreName", storage.StoreConfiguration{TagNames: []string{"tagName1"}})
require.EqualError(t, err, "failed to set indexes: failed to get existing indexed tag names: "+
"failed to get list of indexes from MongoDB: server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: badurl:27017, Type: Unknown }, ] }") //nolint:lll
}
func TestProvider_GetStoreConfig_Failure(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://BadURL", mongodb.WithTimeout(1))
require.NoError(t, err)
_, err = provider.OpenStore("TestStoreName")
require.NoError(t, err)
config, err := provider.GetStoreConfig("TestStoreName")
require.EqualError(t, err, "failed to determine if the underlying database exists for teststorename: "+
"server selection error: context deadline exceeded, current topology: { Type: Unknown, "+
"Servers: [{ Addr: badurl:27017, Type: Unknown }, ] }")
require.Empty(t, config)
}
func TestStore_Put_Failure(t *testing.T) {
t.Run("Deadline exceeded (server not reachable)", func(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://BadURL", mongodb.WithTimeout(1))
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
err = store.Put("key", []byte("value"))
require.EqualError(t, err, "failed to run UpdateOne command in MongoDB: server selection error: context "+
"deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: badurl:27017, Type: Unknown }, ] }")
})
t.Run("Invalid tags", func(t *testing.T) {
// We only test for < and > here since the : case is handled in the common unit tests (commontest.TestAll)
t.Run("Tag name contains <", func(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://test")
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
err = store.Put("key", []byte("value"), storage.Tag{Name: "<"})
require.EqualError(t, err, `"<" is an invalid tag name since it contains one or more of the`+
` following substrings: ":", "<=", "<", ">=", ">"`)
})
t.Run("Tag value contains <", func(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://test")
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
err = store.Put("key", []byte("value"), storage.Tag{Value: "<"})
require.EqualError(t, err, `"<" is an invalid tag value since it contains one or more of the`+
` following substrings: ":", "<=", "<", ">=", ">"`)
})
t.Run("Tag name contains >", func(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://test")
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
err = store.Put("key", []byte("value"), storage.Tag{Name: ">"})
require.EqualError(t, err, `">" is an invalid tag name since it contains one or more of the`+
` following substrings: ":", "<=", "<", ">=", ">"`)
})
t.Run("Tag value contains >", func(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://test")
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
err = store.Put("key", []byte("value"), storage.Tag{Value: ">"})
require.EqualError(t, err, `">" is an invalid tag value since it contains one or more of the`+
` following substrings: ":", "<=", "<", ">=", ">"`)
})
})
}
func TestStore_Get_Failure(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://BadURL", mongodb.WithTimeout(1))
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
value, err := store.Get("key")
require.EqualError(t, err, "failed to run FindOne command in MongoDB: server selection error: context "+
"deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: badurl:27017, Type: Unknown }, ] }")
require.Nil(t, value)
}
func TestStore_GetTags_Failure(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://BadURL", mongodb.WithTimeout(1))
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
tags, err := store.GetTags("key")
require.EqualError(t, err, "failed to run FindOne command in MongoDB: server selection error: "+
"context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: badurl:27017, "+
"Type: Unknown }, ] }")
require.Nil(t, tags)
}
func TestStore_GetBulk_Failure(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://BadURL", mongodb.WithTimeout(1))
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
values, err := store.GetBulk("key1", "key2")
require.EqualError(t, err, "failed to run Find command in MongoDB: server selection error: context "+
"deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: badurl:27017, Type: Unknown }, ] }")
require.Nil(t, values)
}
func TestStore_Delete_Failure(t *testing.T) {
provider, err := mongodb.NewProvider("mongodb://BadURL", mongodb.WithTimeout(1))
require.NoError(t, err)
store, err := provider.OpenStore("StoreName")
require.NoError(t, err)
err = store.Delete("key1")
require.EqualError(t, err, "failed to run DeleteOne command in MongoDB: server selection error: context "+
"deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: badurl:27017, Type: Unknown }, ] }")
}
func TestStore_Batch_TimeoutFailure(t *testing.T) {
storeName := randomStoreName()
provider, err := mongodb.NewProvider("mongodb://BadURL", mongodb.WithTimeout(1))
require.NoError(t, err)
store, err := provider.OpenStore(storeName)
require.NoError(t, err)
err = store.Batch([]storage.Operation{{Key: "key"}})
require.EqualError(t, err, "failed to run BulkWrite command in MongoDB: server selection error: context "+
"deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: badurl:27017, Type: Unknown }, ] }")
}
func startContainerAndDoAllTests(t *testing.T, dockerMongoDBTag string) {
t.Helper()
pool, mongoDBResource := startMongoDBContainer(t, dockerMongoDBTag)
defer func() {
require.NoError(t, pool.Purge(mongoDBResource), "failed to purge MongoDB resource")
}()
doAllTests(t, mongoDBConnString)
}
func doAllTests(t *testing.T, connString string) {
t.Helper()
provider, err := mongodb.NewProvider(connString, mongodb.WithDBPrefix("dbPrefixTest_"),
mongodb.WithLogger(&testLogger{
logger: log.New(os.Stdout, "MongoDB-Provider ", log.Ldate|log.Ltime|log.LUTC),
}))
require.NoError(t, err)
commontest.TestAll(t, provider)
testGetStoreConfigUnderlyingDatabaseCheck(t, connString)
testMultipleProvidersSettingSameStoreConfigurationAtTheSameTime(t, connString)
testMultipleProvidersStoringSameDataAtTheSameTime(t, connString)
testMultipleProvidersStoringSameBulkDataAtTheSameTime(t, connString)
testCloseProviderTwice(t, connString)
testQueryWithMultipleTags(t, connString)
testQueryWithLessThanGreaterThanOperators(t, connString)
testStoreJSONNeedingEscaping(t, connString)
testBatchIsNewKeyError(t, connString)
}
func testGetStoreConfigUnderlyingDatabaseCheck(t *testing.T, connString string) {
t.Helper()
provider, err := mongodb.NewProvider(connString)
require.NoError(t, err)
defer func() {
require.NoError(t, provider.Close())
}()
storeName := randomStoreName()
// The MongoDB database shouldn't exist yet.
config, err := provider.GetStoreConfig(storeName)
require.Equal(t, true, errors.Is(storage.ErrStoreNotFound, err),
"unexpected error or no error")
require.Empty(t, config)
_, err = provider.OpenStore(storeName)
require.NoError(t, err)
// MongoDB defers creating the database until data is put in it or indexes are created.
// The call above to OpenStore shouldn't have created the database yet.
config, err = provider.GetStoreConfig(storeName)
require.Equal(t, true, errors.Is(storage.ErrStoreNotFound, err),
"unexpected error or no error")
require.Empty(t, config)
// This will create the database.
err = provider.SetStoreConfig(storeName, storage.StoreConfiguration{TagNames: []string{"TagName1"}})
require.NoError(t, err)
// Now the underlying database should be found.
config, err = provider.GetStoreConfig(storeName)
require.NoError(t, err)
require.Equal(t, "TagName1", config.TagNames[0])
err = provider.Close()
require.NoError(t, err)
// Create a new Provider object.
provider2, err := mongodb.NewProvider(connString)
require.NoError(t, err)
defer func() {
require.NoError(t, provider2.Close())
}()
// This method tells you how many store objects are open in this Provider.
// Since it's a new Provider, there shouldn't be any.
openStores := provider2.GetOpenStores()
require.Len(t, openStores, 0)
// This will succeed since GetStoreConfig checks the underlying databases instead of the
// in-memory store objects.
config, err = provider2.GetStoreConfig(storeName)
require.NoError(t, err)
require.Equal(t, "TagName1", config.TagNames[0])
// The call above should not have created a new store object.
openStores = provider2.GetOpenStores()
require.Len(t, openStores, 0)
// As mentioned above, MongoDB defers creating databases until there is data put in or indexes are set.
// The code above triggered database creationg by creating indexes. Below we will do the same type of test, but this
// time we create the database by storing data.
storeName2 := randomStoreName()
store, err := provider2.OpenStore(storeName2)
require.NoError(t, err)
// Underlying database shouldn't exist yet.
config, err = provider2.GetStoreConfig(storeName2)
require.Equal(t, true, errors.Is(storage.ErrStoreNotFound, err),
"unexpected error or no error")
require.Empty(t, config)
err = store.Put("key", []byte("value"))
require.NoError(t, err)
// Now the underlying database should be found.
// The config will be empty since it was never set
config, err = provider2.GetStoreConfig(storeName2)
require.NoError(t, err)
require.Empty(t, config.TagNames)
}
func testMultipleProvidersSettingSameStoreConfigurationAtTheSameTime(t *testing.T, connString string) {
t.Helper()
const numberOfProviders = 100
storeName := randomStoreName()
providers := make([]*mongodb.Provider, numberOfProviders)
openStores := make([]storage.Store, numberOfProviders)
for i := 0; i < numberOfProviders; i++ {
provider, err := mongodb.NewProvider(connString, mongodb.WithTimeout(time.Second*5),
mongodb.WithMaxRetries(10),
mongodb.WithTimeBetweenRetries(time.Second))
require.NoError(t, err)
// If you see a warning in your IDE about having a defer statement in a loop, it can be ignored in this case.
// The goal is to close all the stores as soon as there's a failure anywhere in this test in order to free
// up resources for other tests, which may still pass. We don't want them to close at the end of this loop,
// so there's no issue having this here.
defer func() {
require.NoError(t, provider.Close())
}()
providers[i] = provider
openStore, err := providers[i].OpenStore(storeName)
require.NoError(t, err)
openStores[i] = openStore
}
var waitGroup sync.WaitGroup
for i := 0; i < numberOfProviders; i++ {
i := i
waitGroup.Add(1)
setStoreConfig := func() {
defer waitGroup.Done()
errSetStoreConfig := providers[i].SetStoreConfig(storeName,
storage.StoreConfiguration{TagNames: []string{
"TagName1", "TagName2", "TagName3", "TagName4",
"TagName5", "TagName6", "TagName7", "TagName8",
"TagName9", "TagName10", "TagName11", "TagName12",
"TagName13", "TagName14", "TagName15", "TagName16",
"TagName17", "TagName18", "TagName19", "TagName20",
"TagName21", "TagName22", "TagName23", "TagName24",
"TagName25", "TagName26", "TagName27", "TagName28",
"TagName29", "TagName30", "TagName31", "TagName32",
}})
require.NoError(t, errSetStoreConfig)
// Close the store as soon as possible in order to free up resources for other threads.
require.NoError(t, openStores[i].Close())
}
go setStoreConfig()
}
waitGroup.Wait()
storeConfig, err := providers[0].GetStoreConfig(storeName)
require.NoError(t, err)
require.Len(t, storeConfig.TagNames, 32)
for i := 0; i < len(storeConfig.TagNames); i++ {
require.Equal(t, fmt.Sprintf("TagName%d", i+1), storeConfig.TagNames[i])
}
}
func testMultipleProvidersStoringSameDataAtTheSameTime(t *testing.T, connString string) {
t.Helper()
const numberOfProviders = 100
storeName := randomStoreName()
providers := make([]*mongodb.Provider, numberOfProviders)
openStores := make([]storage.Store, numberOfProviders)
for i := 0; i < numberOfProviders; i++ {
provider, err := mongodb.NewProvider(connString, mongodb.WithTimeout(time.Second*10),
mongodb.WithMaxRetries(10),
mongodb.WithTimeBetweenRetries(time.Second))
require.NoError(t, err)
// If you see a warning in your IDE about having a defer statement in a loop, it can be ignored in this case.
// The goal is to close all the stores as soon as there's a failure anywhere in this test in order to free
// up resources for other tests, which may still pass. We don't want them to close at the end of this loop,
// so there's no issue having this here.
defer func() {
require.NoError(t, provider.Close())
}()
providers[i] = provider
openStore, err := providers[i].OpenStore(storeName)
require.NoError(t, err)
openStores[i] = openStore
}
type sampleStruct struct {
Entry1 string `json:"entry1"`
Entry2 string `json:"entry2"`
Entry3 string `json:"entry3"`
}
sampleData := sampleStruct{
Entry1: "value1",
Entry2: "value2",
Entry3: "value3",
}
sampleDataBytes, err := json.Marshal(sampleData)
require.NoError(t, err)
var waitGroup sync.WaitGroup
for i := 0; i < numberOfProviders; i++ {
i := i
waitGroup.Add(1)
setStoreConfig := func() {
defer waitGroup.Done()
errPut := openStores[i].Put("key", sampleDataBytes)
require.NoError(t, errPut)
}
go setStoreConfig()
}
waitGroup.Wait()
value, err := openStores[0].Get("key")
require.NoError(t, err)
var retrievedData sampleStruct
err = json.Unmarshal(value, &retrievedData)
require.NoError(t, err)
require.Equal(t, sampleData.Entry1, retrievedData.Entry1)
require.Equal(t, sampleData.Entry2, retrievedData.Entry2)
require.Equal(t, sampleData.Entry3, retrievedData.Entry3)
}
func testMultipleProvidersStoringSameBulkDataAtTheSameTime(t *testing.T, connString string) {
t.Helper()
const numberOfProviders = 100
storeName := randomStoreName()
providers := make([]*mongodb.Provider, numberOfProviders)
openStores := make([]storage.Store, numberOfProviders)
for i := 0; i < numberOfProviders; i++ {
provider, err := mongodb.NewProvider(connString, mongodb.WithTimeout(time.Second*5),
mongodb.WithMaxRetries(10),
mongodb.WithTimeBetweenRetries(time.Second))
require.NoError(t, err)
// If you see a warning in your IDE about having a defer statement in a loop, it can be ignored in this case.
// The goal is to close all the stores as soon as there's a failure anywhere in this test in order to free
// up resources for other tests, which may still pass. We don't want them to close at the end of this loop,
// so there's no issue having this here.
defer func() {
require.NoError(t, provider.Close())
}()
providers[i] = provider
openStore, err := providers[i].OpenStore(storeName)
require.NoError(t, err)
openStores[i] = openStore
}
type sampleStruct struct {
Entry1 string `json:"entry1"`
Entry2 string `json:"entry2"`
Entry3 string `json:"entry3"`
}
sampleData1 := sampleStruct{
Entry1: "value1",
Entry2: "value2",
Entry3: "value3",
}
sampleData1Bytes, err := json.Marshal(sampleData1)
require.NoError(t, err)
sampleData2 := sampleStruct{
Entry1: "value4",
Entry2: "value5",
Entry3: "value6",
}
sampleData2Bytes, err := json.Marshal(sampleData2)
require.NoError(t, err)
sampleData3 := sampleStruct{
Entry1: "value7",
Entry2: "value8",
Entry3: "value9",
}
sampleData3Bytes, err := json.Marshal(sampleData3)
require.NoError(t, err)
operations := []storage.Operation{
{Key: "key1", Value: sampleData1Bytes},
{Key: "key2", Value: sampleData2Bytes},
{Key: "key3", Value: sampleData3Bytes},
}
var waitGroup sync.WaitGroup
for i := 0; i < numberOfProviders; i++ {
i := i
waitGroup.Add(1)
setStoreConfig := func() {
defer waitGroup.Done()
errBatch := openStores[i].Batch(operations)
require.NoError(t, errBatch)
// Close the store as soon as possible in order to free up resources for other threads.
require.NoError(t, openStores[i].Close())
}
go setStoreConfig()
}
waitGroup.Wait()
values, err := openStores[0].GetBulk("key1", "key2", "key3")
require.NoError(t, err)
require.Len(t, values, 3)
var retrievedData1 sampleStruct
err = json.Unmarshal(values[0], &retrievedData1)
require.NoError(t, err)
require.Equal(t, sampleData1.Entry1, retrievedData1.Entry1)
require.Equal(t, sampleData1.Entry2, retrievedData1.Entry2)
require.Equal(t, sampleData1.Entry3, retrievedData1.Entry3)
var retrievedData2 sampleStruct
err = json.Unmarshal(values[1], &retrievedData2)
require.NoError(t, err)
require.Equal(t, sampleData2.Entry1, retrievedData2.Entry1)
require.Equal(t, sampleData2.Entry2, retrievedData2.Entry2)
require.Equal(t, sampleData2.Entry3, retrievedData2.Entry3)
var retrievedData3 sampleStruct
err = json.Unmarshal(values[2], &retrievedData3)
require.NoError(t, err)
require.Equal(t, sampleData3.Entry1, retrievedData3.Entry1)
require.Equal(t, sampleData3.Entry2, retrievedData3.Entry2)
require.Equal(t, sampleData3.Entry3, retrievedData3.Entry3)
}
func testCloseProviderTwice(t *testing.T, connString string) {
t.Helper()
provider, err := mongodb.NewProvider(connString)
require.NoError(t, err)
_, err = provider.OpenStore("TestStore1")
require.NoError(t, err)
_, err = provider.OpenStore("TestStore2")
require.NoError(t, err)
require.NoError(t, provider.Close())
require.NoError(t, provider.Close()) // Should succeed, even if called repeatedly.
}
func testQueryWithMultipleTags(t *testing.T, connString string) { //nolint: gocyclo // test file
t.Helper()
provider, err := mongodb.NewProvider(connString)
require.NoError(t, err)
defer func() {
require.NoError(t, provider.Close())
}()
keysToPut, valuesToPut, tagsToPut := getTestData()
storeName := randomStoreName()
store, err := provider.OpenStore(storeName)
require.NoError(t, err)
err = provider.SetStoreConfig(storeName,
storage.StoreConfiguration{TagNames: []string{
tagsToPut[0][0].Name,
tagsToPut[0][1].Name,
tagsToPut[0][2].Name,
tagsToPut[0][3].Name,
tagsToPut[0][4].Name,
}})
require.NoError(t, err)
defer func() {
require.NoError(t, store.Close())
}()
putData(t, store, keysToPut, valuesToPut, tagsToPut)
t.Run("Both pairs are tag names + values - 3 values found", func(t *testing.T) {
queryExpressionsToTest := []string{
"Breed:GoldenRetriever&&NumLegs:4&&EarType:Floppy",
"NumLegs:4&&EarType:Floppy&&Breed:GoldenRetriever", // Should be equivalent to the above expression
}
expectedKeys := []string{keysToPut[0], keysToPut[3], keysToPut[4]}
expectedValues := [][]byte{valuesToPut[0], valuesToPut[3], valuesToPut[4]}
expectedTags := [][]storage.Tag{tagsToPut[0], tagsToPut[3], tagsToPut[4]}
expectedTotalItemsCount := 3
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryExpressionToTest := range queryExpressionsToTest {
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpressionToTest, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, expectedKeys, expectedValues, expectedTags, expectedTotalItemsCount)
}
}
})
t.Run("Both pairs are tag names + values - 2 values found", func(t *testing.T) {
queryExpressionsToTest := []string{
"Breed:GoldenRetriever&&Personality:Calm",
"Personality:Calm&&Breed:GoldenRetriever", // Should be equivalent to the above expression
}
expectedKeys := []string{keysToPut[3], keysToPut[4]}
expectedValues := [][]byte{valuesToPut[3], valuesToPut[4]}
expectedTags := [][]storage.Tag{tagsToPut[3], tagsToPut[4]}
expectedTotalItemsCount := 2
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryExpressionToTest := range queryExpressionsToTest {
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpressionToTest, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, expectedKeys, expectedValues, expectedTags, expectedTotalItemsCount)
}
}
})
t.Run("Both pairs are tag names + values - 1 value found", func(t *testing.T) {
queryExpressionsToTest := []string{
"Personality:Shy&&EarType:Pointy",
"EarType:Pointy&&Personality:Shy", // Should be equivalent to the above expression
}
expectedKeys := []string{keysToPut[1]}
expectedValues := [][]byte{valuesToPut[1]}
expectedTags := [][]storage.Tag{tagsToPut[1]}
expectedTotalItemsCount := 1
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryExpressionToTest := range queryExpressionsToTest {
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpressionToTest, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, expectedKeys, expectedValues, expectedTags, expectedTotalItemsCount)
}
}
})
t.Run("Both pairs are tag names + values - 0 values found", func(t *testing.T) {
queryExpressionsToTest := []string{
"Personality:Crazy&&EarType:Pointy",
"EarType:Pointy&&Personality:Crazy", // Should be equivalent to the above expression
}
expectedTotalItemsCount := 0
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryExpressionToTest := range queryExpressionsToTest {
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpressionToTest, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, nil, nil, nil, expectedTotalItemsCount)
}
}
})
t.Run("First pair is a tag name + value, second is a tag name only - 1 value found", func(t *testing.T) {
queryExpressionsToTest := []string{
"EarType:Pointy&&Nickname",
"Nickname&&EarType:Pointy", // Should be equivalent to the above expression
}
expectedKeys := []string{keysToPut[2]}
expectedValues := [][]byte{valuesToPut[2]}
expectedTags := [][]storage.Tag{tagsToPut[2]}
expectedTotalItemsCount := 1
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryExpressionToTest := range queryExpressionsToTest {
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpressionToTest, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, expectedKeys, expectedValues, expectedTags, expectedTotalItemsCount)
}
}
})
t.Run("First pair is a tag name + value, second is a tag name only - 0 values found", func(t *testing.T) {
queryExpressionsToTest := []string{
"EarType:Pointy&&CoatType",
"CoatType&&EarType:Pointy", // Should be equivalent to the above expression
}
expectedTotalItemsCount := 0
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryExpressionToTest := range queryExpressionsToTest {
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpressionToTest, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, nil, nil, nil, expectedTotalItemsCount)
}
}
})
}
func testQueryWithLessThanGreaterThanOperators(t *testing.T, connString string) {
t.Helper()
provider, err := mongodb.NewProvider(connString)
require.NoError(t, err)
defer func() {
require.NoError(t, provider.Close())
}()
keysToPut, valuesToPut, tagsToPut := getTestData()
storeName := randomStoreName()
store, err := provider.OpenStore(storeName)
require.NoError(t, err)
err = provider.SetStoreConfig(storeName,
storage.StoreConfiguration{TagNames: []string{
tagsToPut[0][0].Name,
tagsToPut[0][1].Name,
tagsToPut[0][2].Name,
tagsToPut[0][3].Name,
tagsToPut[0][4].Name,
tagsToPut[0][5].Name,
}})
require.NoError(t, err)
defer func() {
require.NoError(t, store.Close())
}()
putData(t, store, keysToPut, valuesToPut, tagsToPut)
t.Run("Less than or equal to", func(t *testing.T) {
queryExpression := "Age<=2"
expectedKeys := []string{keysToPut[0], keysToPut[1], keysToPut[2]}
expectedValues := [][]byte{valuesToPut[0], valuesToPut[1], valuesToPut[2]}
expectedTags := [][]storage.Tag{tagsToPut[0], tagsToPut[1], tagsToPut[2]}
expectedTotalItemsCount := 3
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpression, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, expectedKeys, expectedValues, expectedTags, expectedTotalItemsCount)
}
})
t.Run("Less than", func(t *testing.T) {
queryExpression := "Age<2"
expectedKeys := []string{keysToPut[1], keysToPut[2]}
expectedValues := [][]byte{valuesToPut[1], valuesToPut[2]}
expectedTags := [][]storage.Tag{tagsToPut[1], tagsToPut[2]}
expectedTotalItemsCount := 2
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpression, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, expectedKeys, expectedValues, expectedTags, expectedTotalItemsCount)
}
})
t.Run("Greater than or equal to", func(t *testing.T) {
queryExpression := "Age>=2"
expectedKeys := []string{keysToPut[0], keysToPut[3]}
expectedValues := [][]byte{valuesToPut[0], valuesToPut[3]}
expectedTags := [][]storage.Tag{tagsToPut[0], tagsToPut[3]}
expectedTotalItemsCount := 2
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpression, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, expectedKeys, expectedValues, expectedTags, expectedTotalItemsCount)
}
})
t.Run("Greater than", func(t *testing.T) {
queryExpression := "Age>2"
expectedKeys := []string{keysToPut[3]}
expectedValues := [][]byte{valuesToPut[3]}
expectedTags := [][]storage.Tag{tagsToPut[3]}
expectedTotalItemsCount := 1
queryOptionsToTest := []storage.QueryOption{
nil,
storage.WithPageSize(2),
storage.WithPageSize(1),
storage.WithPageSize(100),
}
for _, queryOptionToTest := range queryOptionsToTest {
iterator, err := store.Query(queryExpression, queryOptionToTest)
require.NoError(t, err)
verifyExpectedIterator(t, iterator, expectedKeys, expectedValues, expectedTags, expectedTotalItemsCount)
}
})
t.Run("Tag value is not a valid integer", func(t *testing.T) {
iterator, err := store.Query("TagName>ThisIsNotAnInteger")
require.EqualError(t, err, "invalid query format. when using any one of the <=, <, >=, > operators, "+
"the immediate value on the right side side must be a valid integer: strconv.Atoi: parsing "+
`"ThisIsNotAnInteger": invalid syntax`)
require.Nil(t, iterator)
})
}
func testStoreJSONNeedingEscaping(t *testing.T, connString string) {
t.Helper()
provider, err := mongodb.NewProvider(connString)
require.NoError(t, err)
defer func() {
require.NoError(t, provider.Close())
}()
store, err := provider.OpenStore(randomStoreName())
require.NoError(t, err)
t.Run("Success", func(t *testing.T) {
t.Run("One simple key-value pair", func(t *testing.T) {
type simpleType struct {
OneDotHere string `json:"oneDotHere.,omitempty"`
}
testValue := simpleType{OneDotHere: "SomeValue"}
testValueBytes, err := json.Marshal(testValue)
require.NoError(t, err)
testKey := "TestKey1"
err = store.Put(testKey, testValueBytes)
require.NoError(t, err)
testValueBytesRetrieved, err := store.Get(testKey)
require.NoError(t, err)
var testValueRetrieved simpleType
err = json.Unmarshal(testValueBytesRetrieved, &testValueRetrieved)
require.NoError(t, err)