-
Notifications
You must be signed in to change notification settings - Fork 141
/
utilities_testing.go
1829 lines (1494 loc) · 58.8 KB
/
utilities_testing.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 2017-Present Couchbase, Inc.
Use of this software is governed by the Business Source License included in
the file licenses/BSL-Couchbase.txt. As of the Change Date specified in that
file, in accordance with the Business Source License, use of this software will
be governed by the Apache License, Version 2.0, included in the file
licenses/APL2.txt.
*/
package rest
import (
"bytes"
"context"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/couchbase/go-blip"
"github.com/couchbase/gocb/v2"
sgbucket "github.com/couchbase/sg-bucket"
"github.com/couchbase/sync_gateway/auth"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/channels"
"github.com/couchbase/sync_gateway/db"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
)
// Testing utilities that have been included in the rest package so that they
// are available to any package that imports rest. (if they were in a _test.go
// file, they wouldn't be publicly exported to other packages)
// RestTesterConfig represents configuration for sync gateway
type RestTesterConfig struct {
guestEnabled bool // If this is true, Admin Party is in full effect
SyncFn string // put the sync() function source in here (optional)
DatabaseConfig *DatabaseConfig // Supports additional config options. BucketConfig, Name, Sync, Unsupported will be ignored (overridden)
InitSyncSeq uint64 // If specified, initializes _sync:seq on bucket creation. Not supported when running against walrus
EnableNoConflictsMode bool // Enable no-conflicts mode. By default, conflicts will be allowed, which is the default behavior
TestBucket *base.TestBucket // If set, use this bucket instead of requesting a new one.
adminInterface string // adminInterface overrides the default admin interface.
sgReplicateEnabled bool // sgReplicateManager disabled by default for RestTester
hideProductInfo bool
adminInterfaceAuthentication bool
metricsInterfaceAuthentication bool
enableAdminAuthPermissionsCheck bool
useTLSServer bool // If true, TLS will be required for communications with CBS. Default: false
persistentConfig bool
groupID *string
createScopesAndCollections bool // If true, will automatically create any defined scopes and collections on startup.
useLeakyTBForDB bool // If true, the leaky test bucket will be used on the database. Useful for using a LeakyBucket on the DB context for integration tests.
}
// RestTester provides a fake server for testing endpoints
type RestTester struct {
*RestTesterConfig
tb testing.TB
testBucket *base.TestBucket
RestTesterServerContext *ServerContext
AdminHandler http.Handler
adminHandlerOnce sync.Once
PublicHandler http.Handler
publicHandlerOnce sync.Once
MetricsHandler http.Handler
metricsHandlerOnce sync.Once
closed bool
}
func NewRestTester(tb testing.TB, restConfig *RestTesterConfig) *RestTester {
var rt RestTester
if tb == nil {
panic("tester parameter cannot be nil")
}
rt.tb = tb
if restConfig != nil {
rt.RestTesterConfig = restConfig
} else {
rt.RestTesterConfig = &RestTesterConfig{}
}
rt.RestTesterConfig.useTLSServer = base.ServerIsTLS(base.UnitTestUrl())
return &rt
}
func (rt *RestTester) Bucket() base.Bucket {
if rt.tb == nil {
panic("RestTester not properly initialized please use NewRestTester function")
} else if rt.closed {
panic("RestTester was closed!")
}
if rt.testBucket != nil {
return rt.testBucket.Bucket
}
// If we have a TestBucket defined on the RestTesterConfig, use that instead of requesting a new one.
testBucket := rt.RestTesterConfig.TestBucket
if testBucket == nil {
testBucket = base.GetTestBucket(rt.tb)
}
rt.testBucket = testBucket
if rt.InitSyncSeq > 0 {
log.Printf("Initializing %s to %d", base.SyncSeqKey, rt.InitSyncSeq)
_, incrErr := testBucket.Incr(base.SyncSeqKey, rt.InitSyncSeq, rt.InitSyncSeq, 0)
if incrErr != nil {
rt.tb.Fatalf("Error initializing %s in test bucket: %v", base.SyncSeqKey, incrErr)
}
}
corsConfig := &CORSConfig{
Origin: []string{"http://example.com", "*", "http://staging.example.com"},
LoginOrigin: []string{"http://example.com"},
Headers: []string{},
MaxAge: 1728000,
}
adminInterface := &DefaultAdminInterface
if rt.RestTesterConfig.adminInterface != "" {
adminInterface = &rt.RestTesterConfig.adminInterface
}
sc := DefaultStartupConfig("")
username, password, _ := testBucket.BucketSpec.Auth.GetCredentials()
// Disable config polling to avoid test flakiness and increase control of timing.
// Rely on on-demand config fetching for consistency.
sc.Bootstrap.ConfigUpdateFrequency = base.NewConfigDuration(0)
sc.Bootstrap.Server = testBucket.BucketSpec.Server
sc.Bootstrap.Username = username
sc.Bootstrap.Password = password
sc.API.AdminInterface = *adminInterface
sc.API.CORS = corsConfig
sc.API.HideProductVersion = base.BoolPtr(rt.RestTesterConfig.hideProductInfo)
sc.DeprecatedConfig = &DeprecatedConfig{Facebook: &FacebookConfigLegacy{}}
sc.API.AdminInterfaceAuthentication = &rt.adminInterfaceAuthentication
sc.API.MetricsInterfaceAuthentication = &rt.metricsInterfaceAuthentication
sc.API.EnableAdminAuthenticationPermissionsCheck = &rt.enableAdminAuthPermissionsCheck
sc.Bootstrap.UseTLSServer = &rt.RestTesterConfig.useTLSServer
sc.Bootstrap.ServerTLSSkipVerify = base.BoolPtr(base.TestTLSSkipVerify())
if rt.RestTesterConfig.groupID != nil {
sc.Bootstrap.ConfigGroupID = *rt.RestTesterConfig.groupID
}
// Allow EE-only config even in CE for testing using group IDs.
if err := sc.validate(true); err != nil {
panic("invalid RestTester StartupConfig: " + err.Error())
}
// Post-validation, we can lower the bcrypt cost beyond SG limits to reduce test runtime.
sc.Auth.BcryptCost = bcrypt.MinCost
rt.RestTesterServerContext = NewServerContext(&sc, rt.RestTesterConfig.persistentConfig)
if !base.ServerIsWalrus(sc.Bootstrap.Server) {
// Copy any testbucket cert info into boostrap server config
// Required as present for X509 tests there is no way to pass this info to the bootstrap server context with a
// RestTester directly - Should hopefully be alleviated by CBG-1460
sc.Bootstrap.CACertPath = testBucket.BucketSpec.CACertPath
sc.Bootstrap.X509CertPath = testBucket.BucketSpec.Certpath
sc.Bootstrap.X509KeyPath = testBucket.BucketSpec.Keypath
rt.testBucket.BucketSpec.TLSSkipVerify = base.TestTLSSkipVerify()
if err := rt.RestTesterServerContext.initializeCouchbaseServerConnections(); err != nil {
panic("Couldn't initialize Couchbase Server connection: " + err.Error())
}
}
// Copy this startup config at this point into initial startup config
err := base.DeepCopyInefficient(&rt.RestTesterServerContext.initialStartupConfig, &sc)
if err != nil {
rt.tb.Fatalf("Unable to copy initial startup config: %v", err)
}
// tests must create their own databases in persistent mode
if !rt.persistentConfig {
useXattrs := base.TestUseXattrs()
if rt.DatabaseConfig == nil {
// If no db config was passed in, create one
rt.DatabaseConfig = &DatabaseConfig{}
}
if rt.DatabaseConfig.UseViews == nil {
rt.DatabaseConfig.UseViews = base.BoolPtr(base.TestsDisableGSI())
}
if rt.createScopesAndCollections {
if err := createTestBucketScopesAndCollections(base.TestCtx(rt.tb), rt.testBucket, rt.DatabaseConfig.Scopes); err != nil {
rt.tb.Fatalf("Error creating test scopes/collections: %v", err)
}
}
// numReplicas set to 0 for test buckets, since it should assume that there may only be one indexing node.
numReplicas := uint(0)
rt.DatabaseConfig.NumIndexReplicas = &numReplicas
rt.DatabaseConfig.Bucket = &testBucket.BucketSpec.BucketName
rt.DatabaseConfig.Username = username
rt.DatabaseConfig.Password = password
rt.DatabaseConfig.CACertPath = testBucket.BucketSpec.CACertPath
rt.DatabaseConfig.CertPath = testBucket.BucketSpec.Certpath
rt.DatabaseConfig.KeyPath = testBucket.BucketSpec.Keypath
rt.DatabaseConfig.Name = "db"
rt.DatabaseConfig.Sync = &rt.SyncFn
rt.DatabaseConfig.EnableXattrs = &useXattrs
if rt.EnableNoConflictsMode {
boolVal := false
rt.DatabaseConfig.AllowConflicts = &boolVal
}
rt.DatabaseConfig.SGReplicateEnabled = base.BoolPtr(rt.RestTesterConfig.sgReplicateEnabled)
if rt.useLeakyTBForDB {
// If using a leaky bucket, make sure it ignores attempted closures to avoid double closures panic
// due to closing both RestTesterServerContext and testBucket in rt.Close()
leakyBucket, isLeaky := base.AsLeakyBucket(testBucket)
if !isLeaky {
rt.tb.Fatalf("Using option useLeakyTBForDB but testBucket is not a leaky bucket")
}
leakyBucket.SetIgnoreClose(true)
_, err = rt.RestTesterServerContext.AddDatabaseFromConfigWithBucket(*rt.DatabaseConfig, testBucket.Bucket)
} else {
_, err = rt.RestTesterServerContext.AddDatabaseFromConfig(*rt.DatabaseConfig)
}
if err != nil {
rt.tb.Fatalf("Error from AddDatabaseFromConfig: %v", err)
}
// Update the testBucket Bucket to the one associated with the database context. The new (dbContext) bucket
// will be closed when the rest tester closes the server context. The original bucket will be closed using the
// testBucket's closeFn
rt.testBucket.Bucket = rt.RestTesterServerContext.Database("db").Bucket
if rt.DatabaseConfig.Guest == nil {
if err := rt.SetAdminParty(rt.guestEnabled); err != nil {
rt.tb.Fatalf("Error from SetAdminParty %v", err)
}
}
}
// PostStartup (without actually waiting 5 seconds)
close(rt.RestTesterServerContext.hasStarted)
return rt.testBucket.Bucket
}
// createTestBucketScopesAndCollections will create the given scopes and collections within the given test bucket.
func createTestBucketScopesAndCollections(ctx context.Context, tb *base.TestBucket, scopesConfig ScopesConfig) error {
atLeastOneScope := false
for _, scopeConfig := range scopesConfig {
for range scopeConfig.Collections {
atLeastOneScope = true
break
}
break
}
if !atLeastOneScope {
// nothing to do here
return nil
}
un, pw, _ := tb.BucketSpec.Auth.GetCredentials()
var rootCAs *x509.CertPool
if tlsConfig := tb.BucketSpec.TLSConfig(); tlsConfig != nil {
rootCAs = tlsConfig.RootCAs
}
cluster, err := gocb.Connect(tb.BucketSpec.Server, gocb.ClusterOptions{
Username: un,
Password: pw,
SecurityConfig: gocb.SecurityConfig{
TLSSkipVerify: tb.BucketSpec.TLSSkipVerify,
TLSRootCAs: rootCAs,
},
})
if err != nil {
return fmt.Errorf("failed to connect to cluster: %w", err)
}
defer func() { _ = cluster.Close(nil) }()
cm := cluster.Bucket(tb.GetName()).Collections()
for scopeName, scopeConfig := range scopesConfig {
if err := cm.CreateScope(scopeName, nil); err != nil && !errors.Is(err, gocb.ErrScopeExists) {
return fmt.Errorf("failed to create scope %s: %w", scopeName, err)
}
base.DebugfCtx(ctx, base.KeySGTest, "Created scope %s", scopeName)
for collectionName := range scopeConfig.Collections {
if err := cm.CreateCollection(
gocb.CollectionSpec{
Name: collectionName,
ScopeName: scopeName,
}, nil); err != nil {
return fmt.Errorf("failed to create collection %s in scope %s: %w", collectionName, scopeName, err)
}
base.DebugfCtx(ctx, base.KeySGTest, "Created collection %s.%s", scopeName, collectionName)
if err := waitUntilScopeAndCollectionExists(cluster.Bucket(tb.GetName()).Scope(scopeName).Collection(collectionName)); err != nil {
return err
}
base.DebugfCtx(ctx, base.KeySGTest, "Collection now exists %s.%s", scopeName, collectionName)
}
}
return nil
}
func waitUntilScopeAndCollectionExists(collection *gocb.Collection) error {
err, _ := base.RetryLoop("wait for scope and collection to exist", func() (shouldRetry bool, err error, value interface{}) {
_, err = collection.Exists("waitUntilScopeAndCollectionExists", nil)
if err != nil {
base.WarnfCtx(context.TODO(), "Error checking if collection exists: %v", err)
return true, err, nil
}
return false, nil, nil
}, base.CreateMaxDoublingSleeperFunc(30, 10, 1000))
return err
}
func (rt *RestTester) ServerContext() *ServerContext {
rt.Bucket()
return rt.RestTesterServerContext
}
// CreateDatabase is a utility function to create a database through the REST API
func (rt *RestTester) CreateDatabase(dbName string, config DbConfig) (*TestResponse, error) {
dbcJSON, err := base.JSONMarshal(config)
if err != nil {
return nil, err
}
resp := rt.SendAdminRequest(http.MethodPut, fmt.Sprintf("/%s/", dbName), string(dbcJSON))
return resp, nil
}
// ReplaceDbConfig is a utility function to replace a database config through the REST API
func (rt *RestTester) ReplaceDbConfig(dbName string, config DbConfig) (*TestResponse, error) {
dbcJSON, err := base.JSONMarshal(config)
if err != nil {
return nil, err
}
resp := rt.SendAdminRequest(http.MethodPut, fmt.Sprintf("/%s/_config", dbName), string(dbcJSON))
return resp, nil
}
// UpsertDbConfig is a utility function to upsert a database through the REST API
func (rt *RestTester) UpsertDbConfig(dbName string, config DbConfig) (*TestResponse, error) {
dbcJSON, err := base.JSONMarshal(config)
if err != nil {
return nil, err
}
resp := rt.SendAdminRequest(http.MethodPost, fmt.Sprintf("/%s/_config", dbName), string(dbcJSON))
return resp, nil
}
// Returns first database found for server context.
func (rt *RestTester) GetDatabase() *db.DatabaseContext {
for _, database := range rt.ServerContext().AllDatabases() {
return database
}
return nil
}
func (rt *RestTester) MustWaitForDoc(docid string, t testing.TB) {
err := rt.WaitForDoc(docid)
assert.NoError(t, err)
}
func (rt *RestTester) WaitForDoc(docid string) (err error) {
seq, err := rt.SequenceForDoc(docid)
if err != nil {
return err
}
return rt.WaitForSequence(seq)
}
func (rt *RestTester) SequenceForDoc(docid string) (seq uint64, err error) {
database := rt.GetDatabase()
if database == nil {
return 0, fmt.Errorf("No database found")
}
doc, err := database.GetDocument(base.TestCtx(rt.tb), docid, db.DocUnmarshalAll)
if err != nil {
return 0, err
}
return doc.Sequence, nil
}
// Wait for sequence to be buffered by the channel cache
func (rt *RestTester) WaitForSequence(seq uint64) error {
database := rt.GetDatabase()
if database == nil {
return fmt.Errorf("No database found")
}
return database.WaitForSequence(base.TestCtx(rt.tb), seq)
}
func (rt *RestTester) WaitForPendingChanges() error {
database := rt.GetDatabase()
if database == nil {
return fmt.Errorf("No database found")
}
return database.WaitForPendingChanges(base.TestCtx(rt.tb))
}
func (rt *RestTester) SetAdminParty(partyTime bool) error {
a := rt.ServerContext().Database("db").Authenticator(base.TestCtx(rt.tb))
guest, err := a.GetUser("")
if err != nil {
return err
}
guest.SetDisabled(!partyTime)
var chans channels.TimedSet
if partyTime {
chans = channels.AtSequence(base.SetOf(channels.UserStarChannel), 1)
}
guest.SetExplicitChannels(chans, 1)
return a.Save(guest)
}
func (rt *RestTester) Close() {
if rt.tb == nil {
panic("RestTester not properly initialized please use NewRestTester function")
}
rt.closed = true
if rt.RestTesterServerContext != nil {
rt.RestTesterServerContext.Close()
}
if rt.testBucket != nil {
rt.testBucket.Close()
rt.testBucket = nil
}
}
func (rt *RestTester) SendRequest(method, resource string, body string) *TestResponse {
return rt.Send(request(method, resource, body))
}
func (rt *RestTester) SendRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse {
req := request(method, resource, body)
for k, v := range headers {
req.Header.Set(k, v)
}
return rt.Send(req)
}
func (rt *RestTester) SendUserRequestWithHeaders(method, resource string, body string, headers map[string]string, username string, password string) *TestResponse {
req := request(method, resource, body)
req.SetBasicAuth(username, password)
for k, v := range headers {
req.Header.Set(k, v)
}
return rt.Send(req)
}
func (rt *RestTester) SendAdminRequestWithAuth(method, resource string, body string, username string, password string) *TestResponse {
input := bytes.NewBufferString(body)
request, err := http.NewRequest(method, "http://localhost"+resource, input)
require.NoError(rt.tb, err)
request.SetBasicAuth(username, password)
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
response.Code = 200 // doesn't seem to be initialized by default; filed Go bug #4188
rt.TestAdminHandler().ServeHTTP(response, request)
return response
}
func (rt *RestTester) Send(request *http.Request) *TestResponse {
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
response.Code = 200 // doesn't seem to be initialized by default; filed Go bug #4188
rt.TestPublicHandler().ServeHTTP(response, request)
return response
}
func (rt *RestTester) TestAdminHandlerNoConflictsMode() http.Handler {
rt.EnableNoConflictsMode = true
return rt.TestAdminHandler()
}
func (rt *RestTester) TestAdminHandler() http.Handler {
rt.adminHandlerOnce.Do(func() {
rt.AdminHandler = CreateAdminHandler(rt.ServerContext())
})
return rt.AdminHandler
}
func (rt *RestTester) TestPublicHandler() http.Handler {
rt.publicHandlerOnce.Do(func() {
rt.PublicHandler = CreatePublicHandler(rt.ServerContext())
})
return rt.PublicHandler
}
func (rt *RestTester) TestMetricsHandler() http.Handler {
rt.metricsHandlerOnce.Do(func() {
rt.MetricsHandler = CreateMetricHandler(rt.ServerContext())
})
return rt.MetricsHandler
}
type changesResults struct {
Results []db.ChangeEntry
Last_Seq interface{}
}
func (cr changesResults) requireDocIDs(t testing.TB, docIDs []string) {
require.Equal(t, len(docIDs), len(cr.Results))
for _, docID := range docIDs {
var found bool
for _, changeEntry := range cr.Results {
if changeEntry.ID == docID {
found = true
break
}
}
require.True(t, found)
}
}
func (rt *RestTester) CreateWaitForChangesRetryWorker(numChangesExpected int, changesURL, username string, useAdminPort bool) (worker base.RetryWorker) {
waitForChangesWorker := func() (shouldRetry bool, err error, value interface{}) {
var changes changesResults
var response *TestResponse
if useAdminPort {
response = rt.SendAdminRequest("GET", changesURL, "")
} else {
response = rt.Send(requestByUser("GET", changesURL, "", username))
}
err = base.JSONUnmarshal(response.Body.Bytes(), &changes)
if err != nil {
return false, err, nil
}
if len(changes.Results) < numChangesExpected {
// not enough results, retry
return true, nil, nil
}
// If it made it this far, there is no errors and it got enough changes
return false, nil, changes
}
return waitForChangesWorker
}
func (rt *RestTester) waitForChanges(numChangesExpected int, changesURL, username string, useAdminPort bool) (
changes changesResults,
err error) {
waitForChangesWorker := rt.CreateWaitForChangesRetryWorker(numChangesExpected, changesURL, username, useAdminPort)
sleeper := base.CreateSleeperFunc(200, 100)
err, changesVal := base.RetryLoop("Wait for changes", waitForChangesWorker, sleeper)
if err != nil {
return changes, err
}
if changesVal == nil {
return changes, fmt.Errorf("Got nil value for changes")
}
if changesVal != nil {
changes = changesVal.(changesResults)
}
return changes, nil
}
// WaitForCondition runs a retry loop that evaluates the provided function, and terminates
// when the function returns true.
func (rt *RestTester) WaitForCondition(successFunc func() bool) error {
return rt.WaitForConditionWithOptions(successFunc, 200, 100)
}
func (rt *RestTester) WaitForConditionWithOptions(successFunc func() bool, maxNumAttempts, timeToSleepMs int) error {
waitForSuccess := func() (shouldRetry bool, err error, value interface{}) {
if successFunc() {
return false, nil, nil
}
return true, nil, nil
}
sleeper := base.CreateSleeperFunc(maxNumAttempts, timeToSleepMs)
err, _ := base.RetryLoop("Wait for condition options", waitForSuccess, sleeper)
if err != nil {
return err
}
return nil
}
func (rt *RestTester) WaitForConditionShouldRetry(conditionFunc func() (shouldRetry bool, err error, value interface{}), maxNumAttempts, timeToSleepMs int) error {
sleeper := base.CreateSleeperFunc(maxNumAttempts, timeToSleepMs)
err, _ := base.RetryLoop("Wait for condition options", conditionFunc, sleeper)
if err != nil {
return err
}
return nil
}
func (rt *RestTester) SendAdminRequest(method, resource string, body string) *TestResponse {
input := bytes.NewBufferString(body)
request, err := http.NewRequest(method, "http://localhost"+resource, input)
require.NoError(rt.tb, err)
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
response.Code = 200 // doesn't seem to be initialized by default; filed Go bug #4188
rt.TestAdminHandler().ServeHTTP(response, request)
return response
}
func (rt *RestTester) WaitForNUserViewResults(numResultsExpected int, viewUrlPath string, user auth.User, password string) (viewResult sgbucket.ViewResult, err error) {
return rt.WaitForNViewResults(numResultsExpected, viewUrlPath, user, password)
}
func (rt *RestTester) WaitForNAdminViewResults(numResultsExpected int, viewUrlPath string) (viewResult sgbucket.ViewResult, err error) {
return rt.WaitForNViewResults(numResultsExpected, viewUrlPath, nil, "")
}
// Wait for a certain number of results to be returned from a view query
// viewUrlPath: is the path to the view, including the db name. Eg: "/db/_design/foo/_view/bar"
func (rt *RestTester) WaitForNViewResults(numResultsExpected int, viewUrlPath string, user auth.User, password string) (viewResult sgbucket.ViewResult, err error) {
worker := func() (shouldRetry bool, err error, value interface{}) {
var response *TestResponse
if user != nil {
request, _ := http.NewRequest("GET", viewUrlPath, nil)
request.SetBasicAuth(user.Name(), password)
response = rt.Send(request)
} else {
response = rt.SendAdminRequest("GET", viewUrlPath, ``)
}
// If the view is undefined, it might be a race condition where the view is still being created
// See https://github.com/couchbase/sync_gateway/issues/3570#issuecomment-390487982
if strings.Contains(response.Body.String(), "view_undefined") {
base.InfofCtx(response.Req.Context(), base.KeyAll, "view_undefined error: %v. Retrying", response.Body.String())
return true, nil, nil
}
if response.Code != 200 {
return false, fmt.Errorf("Got response code: %d from view call. Expected 200", response.Code), sgbucket.ViewResult{}
}
var result sgbucket.ViewResult
_ = base.JSONUnmarshal(response.Body.Bytes(), &result)
if len(result.Rows) >= numResultsExpected {
// Got enough results, break out of retry loop
return false, nil, result
}
// Not enough results, retry
return true, nil, sgbucket.ViewResult{}
}
description := fmt.Sprintf("Wait for %d view results for query to %v", numResultsExpected, viewUrlPath)
sleeper := base.CreateSleeperFunc(200, 100)
err, returnVal := base.RetryLoop(description, worker, sleeper)
if err != nil {
return sgbucket.ViewResult{}, err
}
return returnVal.(sgbucket.ViewResult), nil
}
// Waits for view to be defined on the server. Used to avoid view_undefined errors.
func (rt *RestTester) WaitForViewAvailable(viewURLPath string) (err error) {
worker := func() (shouldRetry bool, err error, value interface{}) {
response := rt.SendAdminRequest("GET", viewURLPath, ``)
if response.Code == 200 {
return false, nil, nil
}
// Views unavailable, retry
if response.Code == 500 {
log.Printf("Error waiting for view to be available....will retry: %s", response.Body.Bytes())
return true, fmt.Errorf("500 error"), nil
}
// Unexpected error, return
return false, fmt.Errorf("Unexpected error response code while waiting for view available: %v", response.Code), nil
}
description := "Wait for view readiness"
sleeper := base.CreateSleeperFunc(200, 100)
err, _ = base.RetryLoop(description, worker, sleeper)
return err
}
func (rt *RestTester) GetDBState() string {
var body db.Body
resp := rt.SendAdminRequest("GET", "/db/", "")
requireStatus(rt.tb, resp, 200)
require.NoError(rt.tb, base.JSONUnmarshal(resp.Body.Bytes(), &body))
return body["state"].(string)
}
func (rt *RestTester) WaitForDBOnline() (err error) {
return rt.waitForDBState("Online")
}
func (rt *RestTester) waitForDBState(stateWant string) (err error) {
var stateCurr string
maxTries := 20
for i := 0; i < maxTries; i++ {
if stateCurr = rt.GetDBState(); stateCurr == stateWant {
return nil
}
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("given up waiting for DB state, want: %s, current: %s, attempts: %d", stateWant, stateCurr, maxTries)
}
func (rt *RestTester) SendAdminRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse {
input := bytes.NewBufferString(body)
request, _ := http.NewRequest(method, "http://localhost"+resource, input)
for k, v := range headers {
request.Header.Set(k, v)
}
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
response.Code = 200 // doesn't seem to be initialized by default; filed Go bug #4188
rt.TestAdminHandler().ServeHTTP(response, request)
return response
}
// PutDocumentWithRevID builds a new_edits=false style put to create a revision with the specified revID.
// If parentRevID is not specified, treated as insert
func (rt *RestTester) PutDocumentWithRevID(docID string, newRevID string, parentRevID string, body db.Body) (response *TestResponse, err error) {
requestBody := body.ShallowCopy()
newRevGeneration, newRevDigest := db.ParseRevID(newRevID)
revisions := make(map[string]interface{})
revisions["start"] = newRevGeneration
ids := []string{newRevDigest}
if parentRevID != "" {
_, parentDigest := db.ParseRevID(parentRevID)
ids = append(ids, parentDigest)
}
revisions["ids"] = ids
requestBody[db.BodyRevisions] = revisions
requestBytes, err := json.Marshal(requestBody)
if err != nil {
return nil, err
}
resp := rt.SendAdminRequest(http.MethodPut, "/db/"+docID+"?new_edits=false", string(requestBytes))
return resp, nil
}
type SimpleSync struct {
Channels map[string]interface{}
Rev string
Sequence uint64
}
type RawResponse struct {
Sync SimpleSync `json:"_sync"`
}
// GetDocumentSequence looks up the sequence for a document using the _raw endpoint.
// Used by tests that need to validate sequences (for grants, etc)
func (rt *RestTester) GetDocumentSequence(key string) (sequence uint64) {
response := rt.SendAdminRequest("GET", fmt.Sprintf("/db/_raw/%s", key), "")
if response.Code != 200 {
return 0
}
var rawResponse RawResponse
_ = base.JSONUnmarshal(response.BodyBytes(), &rawResponse)
return rawResponse.Sync.Sequence
}
type TestResponse struct {
*httptest.ResponseRecorder
Req *http.Request
bodyCache []byte
}
// BodyBytes takes a copy of the bytes in the response buffer, and saves them for future callers.
func (r TestResponse) BodyBytes() []byte {
if r.bodyCache == nil {
r.bodyCache = r.ResponseRecorder.Body.Bytes()
}
return r.bodyCache
}
func (r TestResponse) DumpBody() {
log.Printf("%v", r.Body.String())
}
func (r TestResponse) GetRestDocument() RestDocument {
restDoc := NewRestDocument()
err := base.JSONUnmarshal(r.Body.Bytes(), restDoc)
if err != nil {
panic(fmt.Sprintf("Error parsing body into RestDocument. Body: %s. Err: %v", r.Body.String(), err))
}
return *restDoc
}
func request(method, resource, body string) *http.Request {
request, err := http.NewRequest(method, "http://localhost"+resource, bytes.NewBufferString(body))
request.RequestURI = resource // This doesn't get filled in by NewRequest
FixQuotedSlashes(request)
if err != nil {
panic(fmt.Sprintf("http.NewRequest failed: %v", err))
}
return request
}
func requestByUser(method, resource, body, username string) *http.Request {
r := request(method, resource, body)
r.SetBasicAuth(username, "letmein")
return r
}
func requireStatus(t testing.TB, response *TestResponse, expectedStatus int) {
require.Equalf(t, expectedStatus, response.Code,
"Response status %d %q (expected %d %q)\nfor %s <%s> : %s",
response.Code, http.StatusText(response.Code),
expectedStatus, http.StatusText(expectedStatus),
response.Req.Method, response.Req.URL, response.Body)
}
func assertStatus(t testing.TB, response *TestResponse, expectedStatus int) {
assert.Equalf(t, expectedStatus, response.Code,
"Response status %d %q (expected %d %q)\nfor %s <%s> : %s",
response.Code, http.StatusText(response.Code),
expectedStatus, http.StatusText(expectedStatus),
response.Req.Method, response.Req.URL, response.Body)
}
func assertHTTPErrorReason(t testing.TB, response *TestResponse, expectedStatus int, expectedReason string) {
var httpError struct {
Reason string `json:"reason"`
}
err := base.JSONUnmarshal(response.BodyBytes(), &httpError)
require.NoError(t, err, "Failed to unmarshal HTTP error: %v", response.BodyBytes())
assertStatus(t, response, expectedStatus)
assert.Equal(t, expectedReason, httpError.Reason)
}
// gocb V2 accepts expiry as a duration and converts to a uint32 epoch time, then does the reverse on retrieval.
// Sync Gateway's bucket interface uses uint32 expiry. The net result is that expiry values written and then read via SG's
// bucket API go through a transformation based on time.Now (or time.Until) that can result in inexact matches.
// assertExpiry validates that the two expiry values are within a 10 second window
func assertExpiry(t testing.TB, expected uint32, actual uint32) {
assert.True(t, base.DiffUint32(expected, actual) < 10, fmt.Sprintf("Unexpected difference between expected: %v actual %v", expected, actual))
}
func NewSlowResponseRecorder(responseDelay time.Duration, responseRecorder *httptest.ResponseRecorder) *SlowResponseRecorder {
responseStarted := sync.WaitGroup{}
responseStarted.Add(1)
responseFinished := sync.WaitGroup{}
responseFinished.Add(1)
return &SlowResponseRecorder{
responseDelay: responseDelay,
ResponseRecorder: responseRecorder,
responseStarted: &responseStarted,
responseFinished: &responseFinished,
}
}
type SlowResponseRecorder struct {
*httptest.ResponseRecorder
responseDelay time.Duration
responseStarted *sync.WaitGroup
responseFinished *sync.WaitGroup
}
func (s *SlowResponseRecorder) WaitForResponseToStart() {
s.responseStarted.Wait()
}
func (s *SlowResponseRecorder) WaitForResponseToFinish() {
s.responseFinished.Wait()
}
func (s *SlowResponseRecorder) Write(buf []byte) (int, error) {
s.responseStarted.Done()
time.Sleep(s.responseDelay)
numBytesWritten, err := s.ResponseRecorder.Write(buf)
s.responseFinished.Done()
return numBytesWritten, err
}
// The parameters used to create a BlipTester
type BlipTesterSpec struct {
// Run Sync Gateway in "No conflicts" mode. Will be propgated to the underyling RestTester
noConflictsMode bool
// If an underlying RestTester is created, it will propagate this setting to the underlying RestTester.
guestEnabled bool
// The Sync Gateway username and password to connect with. If set, then you
// may want to disable "Admin Party" mode, which will allow guest user access.
// By default, the created user will have access to a single channel that matches their username.
// If you need to grant the user access to more channels, you can override this behavior with the
// connectingUserChannelGrants field
connectingUsername string
connectingPassword string
// By default, the created user will have access to a single channel that matches their username.
// If you need to grant the user access to more channels, you can override this behavior by specifying
// the channels the user should have access in this string slice
connectingUserChannelGrants []string
// Allow tests to further customized a RestTester or re-use it across multiple BlipTesters if needed.
// If a RestTester is passed in, certain properties of the BlipTester such as guestEnabled will be ignored, since
// those properties only affect the creation of the RestTester.
// If nil, a default restTester will be created based on the properties in this spec
// restTester *RestTester
// Supported blipProtocols for the client to use in order of preference
blipProtocols []string
}
// State associated with a BlipTester
// Note that it's not safe to have multiple goroutines access a single BlipTester due to the
// fact that certain methods register profile handlers on the BlipContext
type BlipTester struct {
// The underlying RestTester which is used to bootstrap the initial blip websocket creation,
// as well as providing a way for tests to access Sync Gateway over REST to hit admin-only endpoints
// which are not available via blip. Since a test may need to create multiple BlipTesters for multiple
// user contexts, a single RestTester may be shared among multiple BlipTester instances.
restTester *RestTester
// This flag is used to avoid closing the contained restTester. This functionality is to avoid a double close in
// some areas.
avoidRestTesterClose bool
// The blip context which contains blip related state and the sender/reciever goroutines associated
// with this websocket connection
blipContext *blip.Context
// The blip sender that can be used for sending messages over the websocket connection
sender *blip.Sender
}
// Close the bliptester
func (bt BlipTester) Close() {
bt.sender.Close()
if !bt.avoidRestTesterClose {
bt.restTester.Close()
}
}
// Returns database context for blipTester (assumes underlying rest tester is based on a single db - returns first it finds)
func (bt BlipTester) DatabaseContext() *db.DatabaseContext {
dbs := bt.restTester.ServerContext().AllDatabases()