-
Notifications
You must be signed in to change notification settings - Fork 182
/
monstache_test.go
489 lines (453 loc) · 12.4 KB
/
monstache_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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"math"
"os"
"reflect"
"testing"
"time"
"github.com/olivere/elastic/v7"
"github.com/rwynn/gtm/v2"
"github.com/rwynn/monstache/v6/monstachemap"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
/*
This test requires the following processes to be running on localhost
- elasticsearch v7.0+
- mongodb 4.0+
- monstache
monstache should be run with the following settings to force bulk requests
-elasticsearch-max-docs 1
-elasticsearch-max-seconds 1
WARNING: This test is destructive for the database test in mongodb and
any index prefixed with test in elasticsearch
If the tests are failing you can try increasing the delay between when
an operation in mongodb is checked in elasticsearch by passing the delay
argument (number of seconds; defaults to 5)
go test -v -delay 10
*/
var delay int
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
var mongoURL = getEnv("MONGO_DB_URL", "mongodb://localhost:27017")
var elasticURL = getEnv("ELASTIC_SEARCH_URL", "http://localhost:9200")
var elasticURLConfig = elastic.SetURL(elasticURL)
var elasticNoSniffConfig = elastic.SetSniff(false)
func init() {
testing.Init()
fmt.Printf("MongoDB Url: %v\nElasticsearch Url: %v\n", mongoURL, elasticURL)
flag.IntVar(&delay, "delay", 3, "Delay between operations in seconds")
flag.Parse()
}
func dialMongo() (*mongo.Client, error) {
rb := bson.NewRegistryBuilder()
rb.RegisterTypeMapEntry(bsontype.DateTime, reflect.TypeOf(time.Time{}))
reg := rb.Build()
clientOptions := options.Client()
clientOptions.ApplyURI(mongoURL)
clientOptions.SetAppName("monstache")
clientOptions.SetRegistry(reg)
client, err := mongo.NewClient(clientOptions)
if err != nil {
return nil, err
}
err = client.Connect(context.Background())
if err != nil {
return nil, err
}
return client, nil
}
func DropTestDB(t *testing.T, client *mongo.Client) {
db := client.Database("test")
if err := db.Drop(context.Background()); err != nil {
t.Fatal(err)
}
}
func ValidateDocResponse(t *testing.T, doc bson.M, resp *elastic.GetResult) {
if resp.Id != doc["_id"] {
t.Fatalf("elasticsearch id %s does not match mongo id %s", resp.Id, doc["_id"])
}
var src map[string]interface{}
err := json.Unmarshal(resp.Source, &src)
if err != nil {
t.Fatal(err)
}
if src["data"].(string) != doc["data"] {
t.Fatalf("elasticsearch data %s does not match mongo data %s", src["data"], doc["data"])
}
}
func TestMarshallEmptyArray(t *testing.T) {
var data = map[string]interface{}{
"data": make([]interface{}, 0),
"ints": []interface{}{1, 2, 3},
}
b, err := json.Marshal(monstachemap.ConvertMapForJSON(data))
if err != nil {
t.Fatalf("Unable to marshal object: %s", err)
}
expectedJSON := "{\"data\":[],\"ints\":[1,2,3]}"
actualJSON := string(b)
if actualJSON != expectedJSON {
t.Fatalf("Expected %s but got %s", expectedJSON, actualJSON)
}
}
func TestParseElasticsearchVersion(t *testing.T) {
var err error
c := &configOptions{}
err = c.parseElasticsearchVersion("6.2.4")
if err != nil {
t.Fatal(err)
}
if c.ElasticMajorVersion != 6 {
t.Fatalf("Expect major version 6")
}
if c.ElasticMinorVersion != 2 {
t.Fatalf("Expect minor version 2")
}
err = c.parseElasticsearchVersion("")
if err == nil {
t.Fatalf("Expected error for blank version")
}
err = c.parseElasticsearchVersion("0")
if err == nil {
t.Fatalf("Expected error for invalid version")
}
}
func TestExtractRelateData(t *testing.T) {
data, err := extractData("foo", map[string]interface{}{"foo": 1})
if err != nil {
t.Fatalf("Expected nil error")
}
if data != 1 {
t.Fatalf("Expected extracting foo value of 1")
}
data, err = extractData("foo.bar", map[string]interface{}{"foo": map[string]interface{}{"bar": 1}})
if err != nil {
t.Fatalf("Expected nil error")
}
if data != 1 {
t.Fatalf("Expected extracting foo.bar value of 1")
}
data, err = extractData("foo.bar", map[string]interface{}{"foo": map[string]interface{}{"foo": 1}})
if err == nil {
t.Fatalf("Expected error for missing key")
}
data, err = extractData("foo", map[string]interface{}{"bar": 1})
if err == nil {
t.Fatalf("Expected error for missing key")
}
data, err = extractData("foo.bar", map[string]interface{}{"foo": []string{"a", "b", "c"}})
if err == nil {
t.Fatalf("Expected error for missing key")
}
}
func TestBuildRelateSelector(t *testing.T) {
sel := buildSelector("foo", 1)
if sel == nil {
t.Fatalf("Expected non-nil selector")
}
if len(sel) != 1 {
t.Fatalf("Expected 1 foo key in selector")
}
if sel["foo"] != 1 {
t.Fatalf("Expected matching foo to 1: %v", sel)
}
sel = buildSelector("foo.bar", 1)
if sel == nil {
t.Fatalf("Expected non-nil selector")
}
if len(sel) != 1 {
t.Fatalf("Expected 1 foo key in selector")
}
bar, ok := sel["foo"].(bson.M)
if !ok {
t.Fatalf("Expected nested selector under foo")
}
if bar["bar"] != 1 {
t.Fatalf("Expected matching foo.bar to 1: %v", sel)
}
}
func TestMatchFieldTypeRelatedData(t *testing.T) {
var err error
var objectID, value primitive.ObjectID
data := convertSrcDataToString(123)
if data != "123" {
t.Fatalf("Expected string value")
}
intVal, err := convertSrcDataToInt("123")
if intVal != int64(123) {
t.Fatalf("Expected int value")
}
_, err = convertSrcDataToDecimal(1.23)
if err != nil {
t.Fatalf("Expected decimal value but got %s", err)
}
_, err = convertSrcDataToDecimal(true)
if err == nil || err.Error() != "Failed to convert match field of type bool to decimal" {
t.Fatalf("Expected error converting to decimal but got %s", err)
}
objectID, err = convertSrcDataToObjectID("5fae4b4e4138d2fcf16cfd64")
if err != nil {
t.Fatalf("Expected objectId value: %v", err)
}
if value, err = primitive.ObjectIDFromHex("5fae4b4e4138d2fcf16cfd64"); err == nil {
if objectID != value {
t.Fatalf("Expected matching data to ObjectId: %v", data)
}
}
}
func TestOpIdToString(t *testing.T) {
var result string
var id = 10.0
var id2 int64 = 1
var id3 float32 = 12.0
op := >m.Op{Id: id}
result = opIDToString(op)
if result != "10" {
t.Fatalf("Expected decimal dropped from float64 for ID")
}
op.Id = id2
result = opIDToString(op)
if result != "1" {
t.Fatalf("Expected int64 converted to string")
}
op.Id = id3
result = opIDToString(op)
if result != "12" {
t.Fatalf("Expected int64 converted to string")
}
}
func TestPruneInvalidJSON(t *testing.T) {
ts := time.Date(-1, time.November, 10, 23, 0, 0, 0, time.UTC)
m := make(map[string]interface{})
m["a"] = math.Inf(1)
m["b"] = math.Inf(-1)
m["c"] = math.NaN()
m["d"] = 1
m["e"] = ts
m["f"] = []interface{}{m["a"], m["b"], m["c"], m["d"], m["e"]}
out := fixPruneInvalidJSON("docId-1", m)
if len(out) != 2 {
t.Fatalf("Expected 4 fields to be pruned")
}
if out["d"] != 1 {
t.Fatalf("Expected 1 field to remain intact")
}
if len(out["f"].([]interface{})) != 1 {
t.Fatalf("Expected 4 array fields to be pruned")
}
if out["f"].([]interface{})[0] != 1 {
t.Fatalf("Expected 1 array field to remain intact")
}
}
func TestSetElasticClientScheme(t *testing.T) {
c := &configOptions{
ElasticUrls: []string{"https://example.com:9200"},
}
if c.needsSecureScheme() == false {
t.Fatalf("secure scheme should be required")
}
c = &configOptions{
ElasticUrls: []string{"http://example.com:9200"},
}
if c.needsSecureScheme() {
t.Fatalf("secure scheme should not be required")
}
c = &configOptions{}
if c.needsSecureScheme() {
t.Fatalf("secure scheme should not be required")
}
}
func TestInsert(t *testing.T) {
client, err := elastic.NewClient(elasticURLConfig, elasticNoSniffConfig)
if err != nil {
t.Fatal(err)
}
mongoClient, err := dialMongo()
if err != nil {
t.Fatal(err)
}
defer mongoClient.Disconnect(context.Background())
DropTestDB(t, mongoClient)
col := mongoClient.Database("test").Collection("test")
doc := bson.M{
"_id": "1",
"data": "data",
}
if _, err = col.InsertOne(context.Background(), doc); err == nil {
time.Sleep(time.Duration(delay) * time.Second)
if resp, err := client.Get().Index("test.test").Id("1").Do(context.Background()); err == nil {
ValidateDocResponse(t, doc, resp)
} else {
t.Fatal(err)
}
} else {
t.Fatal(err)
}
}
func TestUpdate(t *testing.T) {
client, err := elastic.NewClient(elasticURLConfig, elasticNoSniffConfig)
if err != nil {
t.Fatal(err)
}
mongoClient, err := dialMongo()
if err != nil {
t.Fatal(err)
}
defer mongoClient.Disconnect(context.Background())
DropTestDB(t, mongoClient)
col := mongoClient.Database("test").Collection("test")
doc := bson.M{
"_id": "1",
"data": "data",
}
if _, err = col.InsertOne(context.Background(), doc); err == nil {
time.Sleep(time.Duration(delay) * time.Second)
if resp, err := client.Get().Index("test.test").Id("1").Do(context.Background()); err == nil {
ValidateDocResponse(t, doc, resp)
} else {
t.Fatal(err)
}
doc["data"] = "updated"
sel := bson.M{
"_id": "1",
}
if _, err = col.ReplaceOne(context.Background(), sel, doc); err != nil {
t.Fatal(err)
}
time.Sleep(time.Duration(delay) * time.Second)
if resp, err := client.Get().Index("test.test").Id("1").Do(context.Background()); err == nil {
ValidateDocResponse(t, doc, resp)
} else {
t.Fatal(err)
}
} else {
t.Fatal(err)
}
}
func TestDelete(t *testing.T) {
client, err := elastic.NewClient(elasticURLConfig, elasticNoSniffConfig)
if err != nil {
t.Fatal(err)
}
mongoClient, err := dialMongo()
if err != nil {
t.Fatal(err)
}
defer mongoClient.Disconnect(context.Background())
DropTestDB(t, mongoClient)
col := mongoClient.Database("test").Collection("test")
doc := bson.M{
"_id": "1",
"data": "data",
}
if _, err = col.InsertOne(context.Background(), doc); err == nil {
time.Sleep(time.Duration(delay) * time.Second)
if resp, err := client.Get().Index("test.test").Id("1").Do(context.Background()); err == nil {
ValidateDocResponse(t, doc, resp)
} else {
t.Fatal(err)
}
sel := bson.M{
"_id": "1",
}
if _, err = col.DeleteOne(context.Background(), sel); err != nil {
t.Fatal(err)
}
time.Sleep(time.Duration(delay) * time.Second)
_, err := client.Get().Index("test.test").Id("1").Do(context.Background())
if !elastic.IsNotFound(err) {
t.Fatal("record not deleted")
}
} else {
t.Fatal(err)
}
}
func TestDropDatabase(t *testing.T) {
client, err := elastic.NewClient(elasticURLConfig, elasticNoSniffConfig)
if err != nil {
t.Fatal(err)
}
mongoClient, err := dialMongo()
if err != nil {
t.Fatal(err)
}
defer mongoClient.Disconnect(context.Background())
DropTestDB(t, mongoClient)
col := mongoClient.Database("test").Collection("test")
doc := bson.M{
"_id": "1",
"data": "data",
}
if _, err = col.InsertOne(context.Background(), doc); err == nil {
time.Sleep(time.Duration(delay) * time.Second)
if resp, err := client.Get().Index("test.test").Id("1").Do(context.Background()); err == nil {
ValidateDocResponse(t, doc, resp)
} else {
t.Fatal(err)
}
db := mongoClient.Database("test")
if err = db.Drop(context.Background()); err != nil {
t.Fatal(err)
}
time.Sleep(time.Duration(delay) * time.Second)
exists, err := client.IndexExists("test.test").Do(context.Background())
if err != nil {
t.Fatal(err)
}
if exists {
t.Fatal("index not deleted")
}
} else {
t.Fatal(err)
}
}
func TestDropCollection(t *testing.T) {
client, err := elastic.NewClient(elasticURLConfig, elasticNoSniffConfig)
if err != nil {
t.Fatal(err)
}
mongoClient, err := dialMongo()
if err != nil {
t.Fatal(err)
}
defer mongoClient.Disconnect(context.Background())
DropTestDB(t, mongoClient)
col := mongoClient.Database("test").Collection("test")
doc := bson.M{
"_id": "1",
"data": "data",
}
if _, err = col.InsertOne(context.Background(), doc); err == nil {
time.Sleep(time.Duration(delay) * time.Second)
if resp, err := client.Get().Index("test.test").Id("1").Do(context.Background()); err == nil {
ValidateDocResponse(t, doc, resp)
} else {
t.Fatal(err)
}
if err = col.Drop(context.Background()); err != nil {
t.Fatal(err)
}
time.Sleep(time.Duration(delay) * time.Second)
exists, err := client.IndexExists("test.test").Do(context.Background())
if err != nil {
t.Fatal(err)
}
if exists {
t.Fatal("index not deleted")
}
} else {
t.Fatal(err)
}
}