-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathutilities_testing.go
More file actions
2880 lines (2426 loc) · 103 KB
/
utilities_testing.go
File metadata and controls
2880 lines (2426 loc) · 103 KB
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 (
"bufio"
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httptest"
"net/url"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"text/template"
"time"
"github.com/couchbase/go-blip"
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/google/uuid"
"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)
ImportFilter string // put the import filter function source in here (optional)
DatabaseConfig *DatabaseConfig // Supports additional config options. BucketConfig, Name, Sync, Unsupported will be ignored (overridden)
MutateStartupConfig func(config *StartupConfig) // Function to mutate the startup configuration before the server context gets created. This overrides options the RT sets.
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
EnableUserQueries bool // Enable the feature-flag for user N1QL/etc queries
CustomTestBucket *base.TestBucket // If set, use this bucket instead of requesting a new one.
LeakyBucketConfig *base.LeakyBucketConfig // Set to create and use a leaky bucket on the RT and DB. A test bucket cannot be passed in if using this option.
adminInterface string // adminInterface overrides the default admin interface.
SgReplicateEnabled bool // SgReplicateManager disabled by default for RestTester
AutoImport *bool
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
serverless bool // Runs SG in serverless mode. Must be used in conjunction with persistent config
collectionConfig collectionConfiguration
numCollections int
syncGatewayVersion *base.ComparableBuildVersion // alternate version of Sync Gateway to use on startup
allowDbConfigEnvVars *bool
maxConcurrentRevs *int
UseXattrConfig bool
}
type collectionConfiguration uint8
const (
useSingleCollection = iota
useSingleCollectionDefaultOnly
useMultipleCollection
)
var defaultTestingCORSOrigin = []string{"http://example.com", "*", "http://staging.example.com"}
// globalBlipTesterClients stores the active blip tester clients to ensure they are cleaned up at the end of a test
var globalBlipTesterClients *activeBlipTesterClients
func init() {
globalBlipTesterClients = &activeBlipTesterClients{m: make(map[string]int32), lock: sync.Mutex{}}
}
// activeBlipTesterClients tracks the number of active blip tester clients to make sure they are closed at the end of a test and goroutines are not leaked.
type activeBlipTesterClients struct {
m map[string]int32
lock sync.Mutex
}
// add increments the count of a blip tester client for a particular test
func (a *activeBlipTesterClients) add(name string) {
a.lock.Lock()
defer a.lock.Unlock()
a.m[name]++
}
// remove decrements the count of a blip tester client for a particular test
func (a *activeBlipTesterClients) remove(tb testing.TB, name string) {
a.lock.Lock()
defer a.lock.Unlock()
require.Contains(tb, a.m, name, "Can not remove blip tester client '%s' that was never added", name)
a.m[name]--
if a.m[name] == 0 {
delete(a.m, name)
}
}
// RestTester provides a fake server for testing endpoints
type RestTester struct {
*RestTesterConfig
testingTB atomic.Pointer[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
DiagnosticHandler http.Handler
diagnosticHandlerOnce sync.Once
closed bool
}
func (rt *RestTester) TB() testing.TB {
return *rt.testingTB.Load()
}
// restTesterDefaultUserPassword is usable as a default password for SendUserRequest
const RestTesterDefaultUserPassword = "letmein"
// NewRestTester returns a rest tester and corresponding keyspace backed by a single database and a single collection. This collection may be named or default collection based on global test configuration.
func NewRestTester(tb testing.TB, restConfig *RestTesterConfig) *RestTester {
return newRestTester(tb, restConfig, useSingleCollection, 1)
}
// NewRestTesterPersistentConfig returns a rest tester with persistent config setup and a single database. A convenience function for NewRestTester.
func NewRestTesterPersistentConfig(tb testing.TB) *RestTester {
config := &RestTesterConfig{
PersistentConfig: true,
}
rt := newRestTester(tb, config, useSingleCollection, 1)
RequireStatus(tb, rt.CreateDatabase("db", rt.NewDbConfig()), http.StatusCreated)
return rt
}
// newRestTester creates the underlying rest testers, use public functions.
func newRestTester(tb testing.TB, restConfig *RestTesterConfig, collectionConfig collectionConfiguration, numCollections int) *RestTester {
var rt RestTester
if tb == nil {
panic("tester parameter cannot be nil")
}
rt.testingTB.Store(&tb)
if restConfig != nil {
rt.RestTesterConfig = restConfig
} else {
rt.RestTesterConfig = &RestTesterConfig{}
}
rt.RestTesterConfig.collectionConfig = collectionConfig
rt.RestTesterConfig.numCollections = numCollections
rt.RestTesterConfig.useTLSServer = base.ServerIsTLS(base.UnitTestUrl())
return &rt
}
// NewRestTester returns a rest tester backed by a single database and a single default collection.
func NewRestTesterDefaultCollection(tb testing.TB, restConfig *RestTesterConfig) *RestTester {
return newRestTester(tb, restConfig, useSingleCollectionDefaultOnly, 1)
}
// NewRestTester multiple collections a rest tester backed by a single database and any number of collections and the names of the keyspaces of collections created.
func NewRestTesterMultipleCollections(tb testing.TB, restConfig *RestTesterConfig, numCollections int) *RestTester {
if !base.TestsUseNamedCollections() {
tb.Skip("This test requires named collections and is running against a bucket type that does not support them")
}
if numCollections == 0 {
tb.Errorf("0 is not a valid number of collections to specify")
}
return newRestTester(tb, restConfig, useMultipleCollection, numCollections)
}
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.CustomTestBucket
if testBucket == nil {
testBucket = base.GetTestBucket(rt.TB())
if rt.LeakyBucketConfig != nil {
leakyConfig := *rt.LeakyBucketConfig
// Ignore closures to avoid double closing panics
leakyConfig.IgnoreClose = true
testBucket = testBucket.LeakyBucketClone(leakyConfig)
}
} else if rt.LeakyBucketConfig != nil {
rt.TB().Fatalf("A passed in TestBucket cannot be used on the RestTester when defining a LeakyBucketConfig")
}
rt.TestBucket = testBucket
if rt.InitSyncSeq > 0 {
if base.TestsUseNamedCollections() {
rt.TB().Fatalf("RestTester InitSyncSeq doesn't support non-default collections")
}
log.Printf("Initializing %s to %d", base.DefaultMetadataKeys.SyncSeqKey(), rt.InitSyncSeq)
tbDatastore := testBucket.GetMetadataStore()
_, incrErr := tbDatastore.Incr(base.DefaultMetadataKeys.SyncSeqKey(), rt.InitSyncSeq, rt.InitSyncSeq, 0)
if incrErr != nil {
rt.TB().Fatalf("Error initializing %s in test bucket: %v", base.DefaultMetadataKeys.SyncSeqKey(), incrErr)
}
}
corsConfig := &auth.CORSConfig{
Origin: defaultTestingCORSOrigin,
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())
sc.Unsupported.Serverless.Enabled = &rt.serverless
sc.Unsupported.AllowDbConfigEnvVars = rt.RestTesterConfig.allowDbConfigEnvVars
sc.Unsupported.UseXattrConfig = &rt.UseXattrConfig
sc.Replicator.MaxConcurrentRevs = rt.RestTesterConfig.maxConcurrentRevs
if rt.serverless {
if !rt.PersistentConfig {
rt.TB().Fatalf("Persistent config must be used when running in serverless mode")
}
sc.BucketCredentials = map[string]*base.CredentialsConfig{
testBucket.GetName(): {
Username: base.TestClusterUsername(),
Password: base.TestClusterPassword(),
},
}
}
if rt.RestTesterConfig.GroupID != nil {
sc.Bootstrap.ConfigGroupID = *rt.RestTesterConfig.GroupID
} else if rt.RestTesterConfig.PersistentConfig {
// If running in persistent config mode, the database has to be manually created. If the db name is the same as a
// past tests db name, a db already exists error could happen if the past tests bucket is still flushing. Prevent this
// by using a unique group ID for each new rest tester.
uniqueUUID, err := uuid.NewRandom()
if err != nil {
rt.TB().Fatalf("Could not generate random config group ID UUID: %v", err)
}
sc.Bootstrap.ConfigGroupID = uniqueUUID.String()
}
sc.Unsupported.UserQueries = base.BoolPtr(rt.EnableUserQueries)
if rt.MutateStartupConfig != nil {
rt.MutateStartupConfig(&sc)
}
sc.Unsupported.UserQueries = base.BoolPtr(rt.EnableUserQueries)
// Allow EE-only config even in CE for testing using group IDs.
if err := sc.Validate(base.TestCtx(rt.TB()), 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(base.TestCtx(rt.TB()), &sc, rt.RestTesterConfig.PersistentConfig)
rt.RestTesterServerContext.allowScopesInPersistentConfig = true
if rt.RestTesterConfig.syncGatewayVersion != nil {
rt.RestTesterServerContext.BootstrapContext.sgVersion = *rt.RestTesterConfig.syncGatewayVersion
}
ctx := rt.Context()
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()
require.NoError(rt.TB(), rt.RestTesterServerContext.initializeGocbAdminConnection(ctx))
}
require.NoError(rt.TB(), rt.RestTesterServerContext.initializeBootstrapConnection(ctx))
// Copy this startup config at this point into initial startup config
require.NoError(rt.TB(), base.DeepCopyInefficient(&rt.RestTesterServerContext.initialStartupConfig, &sc))
// 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 base.TestsUseNamedCollections() && rt.collectionConfig != useSingleCollectionDefaultOnly && (!*rt.DatabaseConfig.UseViews || base.UnitTestUrlIsWalrus()) {
// If scopes is already set, assume the caller has a plan
if rt.DatabaseConfig.Scopes == nil {
// Configure non default collections by default
rt.DatabaseConfig.Scopes = GetCollectionsConfigWithFiltering(rt.TB(), testBucket, rt.numCollections, stringPtrOrNil(rt.SyncFn), stringPtrOrNil(rt.ImportFilter))
}
} else {
// override SyncFn and ImportFilter if set
if rt.SyncFn != "" {
rt.DatabaseConfig.Sync = &rt.SyncFn
}
if rt.ImportFilter != "" {
rt.DatabaseConfig.ImportFilter = &rt.ImportFilter
}
}
// 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
if rt.DatabaseConfig.Name == "" {
rt.DatabaseConfig.Name = "db"
}
rt.DatabaseConfig.EnableXattrs = &useXattrs
if rt.EnableNoConflictsMode {
boolVal := false
rt.DatabaseConfig.AllowConflicts = &boolVal
}
rt.DatabaseConfig.SGReplicateEnabled = base.BoolPtr(rt.RestTesterConfig.SgReplicateEnabled)
// Check for override of AutoImport in the rt config
if rt.AutoImport != nil {
rt.DatabaseConfig.AutoImport = *rt.AutoImport
}
autoImport, _ := rt.DatabaseConfig.AutoImportEnabled(ctx)
if rt.DatabaseConfig.ImportPartitions == nil && base.TestUseXattrs() && base.IsEnterpriseEdition() && autoImport {
// Speed up test setup - most tests don't need more than one partition given we only have one node
rt.DatabaseConfig.ImportPartitions = base.Uint16Ptr(1)
}
_, isLeaky := base.AsLeakyBucket(rt.TestBucket)
var err error
if rt.LeakyBucketConfig != nil || isLeaky {
_, err = rt.RestTesterServerContext.AddDatabaseFromConfigWithBucket(ctx, rt.TB(), *rt.DatabaseConfig, testBucket.Bucket)
} else {
_, err = rt.RestTesterServerContext.AddDatabaseFromConfig(ctx, *rt.DatabaseConfig)
}
require.NoError(rt.TB(), err)
ctx = rt.Context() // get new ctx with db info before passing it down
// 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(ctx, rt.DatabaseConfig.Name).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
}
// MetadataStore returns the datastore for the database on the RestTester
func (rt *RestTester) MetadataStore() base.DataStore {
return rt.GetDatabase().MetadataStore
}
// GetCollectionsConfig sets up a ScopesConfig from a TestBucket for use with non default collections.
func GetCollectionsConfig(t testing.TB, testBucket *base.TestBucket, numCollections int) ScopesConfig {
return GetCollectionsConfigWithFiltering(t, testBucket, numCollections, nil, nil)
}
// GetCollectionsConfigWithFiltering sets up a ScopesConfig from a TestBucket for use with non default collections. The sync function will be passed for all collections.
func GetCollectionsConfigWithFiltering(t testing.TB, testBucket *base.TestBucket, numCollections int, syncFn *string, importFilter *string) ScopesConfig {
// Get a datastore as provided by the test
stores := testBucket.GetNonDefaultDatastoreNames()
require.True(t, len(stores) >= numCollections, "Requested more collections %d than found on testBucket %d", numCollections, len(stores))
defaultCollectionConfig := &CollectionConfig{}
if syncFn != nil {
defaultCollectionConfig.SyncFn = syncFn
}
if importFilter != nil {
defaultCollectionConfig.ImportFilter = importFilter
}
scopesConfig := ScopesConfig{}
for i := 0; i < numCollections; i++ {
dataStoreName := stores[i]
if scopeConfig, ok := scopesConfig[dataStoreName.ScopeName()]; ok {
if _, ok := scopeConfig.Collections[dataStoreName.CollectionName()]; ok {
// already present
} else {
scopeConfig.Collections[dataStoreName.CollectionName()] = defaultCollectionConfig
}
} else {
scopesConfig[dataStoreName.ScopeName()] = ScopeConfig{
Collections: map[string]*CollectionConfig{
dataStoreName.CollectionName(): defaultCollectionConfig,
}}
}
}
return scopesConfig
}
// GetSingleDataStoreNamesFromScopes config returns a lexically sorted list of configured datastores.
func GetDataStoreNamesFromScopesConfig(config ScopesConfig) []sgbucket.DataStoreName {
var names []string
for scopeName, scopeConfig := range config {
for collectionName, _ := range scopeConfig.Collections {
names = append(names, fmt.Sprintf("%s%s%s", scopeName, base.ScopeCollectionSeparator, collectionName))
}
}
sort.Strings(names)
var dataStoreNames []sgbucket.DataStoreName
for _, scopeAndCollection := range names {
keyspace := strings.Split(scopeAndCollection, base.ScopeCollectionSeparator)
dataStoreNames = append(dataStoreNames, base.ScopeAndCollectionName{Scope: keyspace[0], Collection: keyspace[1]})
}
return dataStoreNames
}
// LeakyBucket gets the bucket from the RestTester as a leaky bucket allowing for callbacks to be set on the fly.
// The RestTester must have been set up to create and use a leaky bucket by setting LeakyBucketConfig in the RT
// config when calling NewRestTester.
func (rt *RestTester) LeakyBucket() *base.LeakyDataStore {
if rt.LeakyBucketConfig == nil {
rt.TB().Fatalf("Cannot get leaky bucket when LeakyBucketConfig was not set on RestTester initialisation")
}
leakyDataStore, ok := base.AsLeakyDataStore(rt.Bucket().DefaultDataStore())
if !ok {
rt.TB().Fatalf("Could not get bucket (type %T) as a leaky bucket", rt.Bucket())
}
return leakyDataStore
}
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) (resp *TestResponse) {
dbcJSON, err := base.JSONMarshal(config)
require.NoError(rt.TB(), err)
if rt.AdminInterfaceAuthentication {
resp = rt.SendAdminRequestWithAuth(http.MethodPut, fmt.Sprintf("/%s/", dbName), string(dbcJSON), base.TestClusterUsername(), base.TestClusterPassword())
} else {
resp = rt.SendAdminRequest(http.MethodPut, fmt.Sprintf("/%s/", dbName), string(dbcJSON))
}
return resp
}
// ReplaceDbConfig is a utility function to replace a database config through the REST API
func (rt *RestTester) ReplaceDbConfig(dbName string, config DbConfig) *TestResponse {
dbcJSON, err := base.JSONMarshal(config)
require.NoError(rt.TB(), err)
resp := rt.SendAdminRequest(http.MethodPut, fmt.Sprintf("/%s/_config", dbName), string(dbcJSON))
return resp
}
// UpsertDbConfig is a utility function to upsert a database through the REST API
func (rt *RestTester) UpsertDbConfig(dbName string, config DbConfig) *TestResponse {
dbcJSON, err := base.JSONMarshal(config)
require.NoError(rt.TB(), err)
resp := rt.SendAdminRequest(http.MethodPost, fmt.Sprintf("/%s/_config", dbName), string(dbcJSON))
return resp
}
// GetDatabase Returns a database found for server context, if there is only one database. Fails the test harness if there is not a database defined.
func (rt *RestTester) GetDatabase() *db.DatabaseContext {
require.Len(rt.TB(), rt.ServerContext().AllDatabases(), 1)
for _, database := range rt.ServerContext().AllDatabases() {
return database
}
return nil
}
// CreateUser creates a user with the default password and channels scoped to a single test collection.
func (rt *RestTester) CreateUser(username string, channels []string, roles ...string) {
var response *TestResponse
if rt.AdminInterfaceAuthentication {
response = rt.SendAdminRequestWithAuth(http.MethodPut, "/{{.db}}/_user/"+username, GetUserPayload(rt.TB(), "", RestTesterDefaultUserPassword, "", rt.GetSingleDataStore(), channels, roles), base.TestClusterUsername(), base.TestClusterPassword())
} else {
response = rt.SendAdminRequest(http.MethodPut, "/{{.db}}/_user/"+username, GetUserPayload(rt.TB(), "", RestTesterDefaultUserPassword, "", rt.GetSingleDataStore(), channels, roles))
}
RequireStatus(rt.TB(), response, http.StatusCreated)
}
// CreateRole creates a role with channels scoped to a single test collection.
func (rt *RestTester) CreateRole(rolename string, channels []string) {
var response *TestResponse
if rt.AdminInterfaceAuthentication {
response = rt.SendAdminRequestWithAuth(http.MethodPut, "/{{.db}}/_role/"+rolename, GetRolePayload(rt.TB(), rolename, rt.GetSingleDataStore(), channels), base.TestClusterUsername(), base.TestClusterPassword())
} else {
response = rt.SendAdminRequest(http.MethodPut, "/{{.db}}/_role/"+rolename, GetRolePayload(rt.TB(), rolename, rt.GetSingleDataStore(), channels))
}
RequireStatus(rt.TB(), response, http.StatusCreated)
}
func (rt *RestTester) GetUserAdminAPI(username string) auth.PrincipalConfig {
response := rt.SendAdminRequest(http.MethodGet, "/{{.db}}/_user/"+username, "")
RequireStatus(rt.TB(), response, http.StatusOK)
var responseConfig auth.PrincipalConfig
err := json.Unmarshal(response.Body.Bytes(), &responseConfig)
require.NoError(rt.TB(), err)
return responseConfig
}
// GetSingleTestDatabaseCollection will return a DatabaseCollection if there is only one. Depending on test environment configuration, it may or may not be the default collection.
func (rt *RestTester) GetSingleTestDatabaseCollection() (*db.DatabaseCollection, context.Context) {
c := db.GetSingleDatabaseCollection(rt.TB(), rt.GetDatabase())
ctx := base.UserLogCtx(c.AddCollectionContext(rt.Context()), "gotest", base.UserDomainBuiltin, nil)
return c, ctx
}
// GetSingleTestDatabaseCollectionWithUser will return a DatabaseCollection if there is only one. Depending on test environment configuration, it may or may not be the default collection.
func (rt *RestTester) GetSingleTestDatabaseCollectionWithUser() (*db.DatabaseCollectionWithUser, context.Context) {
c, ctx := rt.GetSingleTestDatabaseCollection()
return &db.DatabaseCollectionWithUser{DatabaseCollection: c}, ctx
}
// GetSingleDataStore will return a datastore if there is only one collection configured on the RestTester database.
func (rt *RestTester) GetSingleDataStore() base.DataStore {
collection, _ := rt.GetSingleTestDatabaseCollection()
ds, err := rt.GetDatabase().Bucket.NamedDataStore(base.ScopeAndCollectionName{
Scope: collection.ScopeName,
Collection: collection.Name,
})
require.NoError(rt.TB(), err)
return ds
}
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) {
collection, ctx := rt.GetSingleTestDatabaseCollection()
doc, err := collection.GetDocument(ctx, 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 {
collection, ctx := rt.GetSingleTestDatabaseCollection()
return collection.WaitForSequence(ctx, seq)
}
func (rt *RestTester) WaitForPendingChanges() {
ctx := rt.Context()
for _, collection := range rt.GetDbCollections() {
require.NoError(rt.TB(), collection.WaitForPendingChanges(ctx))
}
}
func (rt *RestTester) SetAdminParty(partyTime bool) error {
ctx := rt.Context()
a := rt.GetDatabase().Authenticator(ctx)
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)
}
if len(a.Collections) == 0 {
guest.SetExplicitChannels(chans, 1)
} else {
for scopeName, scope := range a.Collections {
for collectionName, _ := range scope {
guest.SetCollectionExplicitChannels(scopeName, collectionName, chans, 1)
}
}
}
return a.Save(guest)
}
func (rt *RestTester) Close() {
if rt.TB() == nil {
panic("RestTester not properly initialized please use NewRestTester function")
}
ctx := rt.Context() // capture ctx before closing rt
rt.closed = true
if rt.RestTesterServerContext != nil {
rt.RestTesterServerContext.Close(ctx)
}
if rt.TestBucket != nil {
rt.TestBucket.Close(ctx)
rt.TestBucket = nil
}
}
func (rt *RestTester) SendRequest(method, resource string, body string) *TestResponse {
return rt.Send(Request(method, rt.mustTemplateResource(resource), body))
}
func (rt *RestTester) SendRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse {
req := Request(method, rt.mustTemplateResource(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, rt.mustTemplateResource(resource), body)
req.SetBasicAuth(username, password)
for k, v := range headers {
req.Header.Set(k, v)
}
return rt.Send(req)
}
// templateResource is a non-fatal version of rt.mustTemplateResource
func (rt *RestTester) templateResource(resource string) (string, error) {
tmpl, err := template.New("urltemplate").
Option("missingkey=error").
Parse(resource)
if err != nil {
return "", err
}
data := make(map[string]string)
require.NotNil(rt.TB(), rt.ServerContext())
if rt.ServerContext() != nil {
databases := rt.ServerContext().AllDatabases()
var dbNames []string
for dbName := range databases {
dbNames = append(dbNames, dbName)
}
sort.Strings(dbNames)
multipleDatabases := len(dbNames) > 1
for i, dbName := range dbNames {
database := databases[dbName]
dbPrefix := ""
if !multipleDatabases {
data["db"] = database.Name
} else {
dbPrefix = fmt.Sprintf("db%d", i+1)
data[dbPrefix] = database.Name
}
if len(database.CollectionByID) == 1 {
if multipleDatabases {
data[fmt.Sprintf("db%dkeyspace", i+1)] = getKeyspaces(rt.TB(), database)[0]
} else {
keyspace := rt.GetSingleKeyspace()
data["keyspace"] = keyspace
data["scopeAndCollection"] = getScopeAndCollectionFromKeyspace(rt.TB(), keyspace)
}
continue
}
for j, keyspace := range getKeyspaces(rt.TB(), database) {
if !multipleDatabases {
data[fmt.Sprintf("keyspace%d", j+1)] = keyspace
data[fmt.Sprintf("scopeAndCollection%d", j+1)] = getScopeAndCollectionFromKeyspace(rt.TB(), keyspace)
} else {
data[fmt.Sprintf("db%dkeyspace%d", i+1, j+1)] = keyspace
}
}
}
}
var uri bytes.Buffer
if err := tmpl.Execute(&uri, data); err != nil {
return "", err
}
return uri.String(), nil
}
// mustTemplateResource provides some convenience templates for standard values.
//
// * If there is a single database: {{.db}} refers to single db
// * If there is only a single collection: {{.keyspace}} refers to a single collection, named or unamed
// * If there are multiple collections, defined is {{.keyspace1}},{{.keyspace2}},...
//
// This function causes the test to fail immediately if the given resource cannot be parsed.
func (rt *RestTester) mustTemplateResource(resource string) string {
uri, err := rt.templateResource(resource)
require.NoErrorf(rt.TB(), err, "URL template error: %v", err)
return uri
}
func (rt *RestTester) SendAdminRequestWithAuth(method, resource string, body string, username string, password string) *TestResponse {
request := Request(method, rt.mustTemplateResource(resource), body)
request.SetBasicAuth(username, password)
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
rt.TestAdminHandler().ServeHTTP(response, request)
return response
}
func (rt *RestTester) Send(request *http.Request) *TestResponse {
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
rt.TestPublicHandler().ServeHTTP(response, request)
return response
}
func (rt *RestTester) SendMetricsRequest(method, resource, body string) *TestResponse {
return rt.sendMetrics(Request(method, rt.mustTemplateResource(resource), body))
}
func (rt *RestTester) SendMetricsRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse {
request := Request(method, rt.mustTemplateResource(resource), body)
for k, v := range headers {
request.Header.Set(k, v)
}
return rt.sendMetrics(request)
}
func (rt *RestTester) sendMetrics(request *http.Request) *TestResponse {
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
rt.TestMetricsHandler().ServeHTTP(response, request)
return response
}
// SendDiagnosticRequest runs a request against the diagnostic handler.
func (rt *RestTester) SendDiagnosticRequest(method, resource, body string) *TestResponse {
request := Request(method, rt.mustTemplateResource(resource), body)
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
rt.TestDiagnosticHandler().ServeHTTP(response, Request(method, rt.mustTemplateResource(resource), body))
return response
}
// SendDiagnosticRequestWithHeaders runs a request against the diagnostic handler with headers.
func (rt *RestTester) SendDiagnosticRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse {
request := Request(method, rt.mustTemplateResource(resource), body)
for k, v := range headers {
request.Header.Set(k, v)
}
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
rt.TestDiagnosticHandler().ServeHTTP(response, request)
return response
}
func (rt *RestTester) TestAdminHandlerNoConflictsMode() http.Handler {
rt.EnableNoConflictsMode = true
return rt.TestAdminHandler()
}
var fakeRestTesterIP = net.IPv4(127, 0, 0, 99)
func (rt *RestTester) TestAdminHandler() http.Handler {
rt.adminHandlerOnce.Do(func() {
rt.AdminHandler = CreateAdminHandler(rt.ServerContext())
rt.ServerContext().addHTTPServer(adminServer, &serverInfo{nil, &net.TCPAddr{IP: fakeRestTesterIP, Port: 4985}})
})
return rt.AdminHandler
}
func (rt *RestTester) TestPublicHandler() http.Handler {
rt.publicHandlerOnce.Do(func() {
rt.PublicHandler = CreatePublicHandler(rt.ServerContext())
rt.ServerContext().addHTTPServer(publicServer, &serverInfo{nil, &net.TCPAddr{IP: fakeRestTesterIP, Port: 4984}})
})
return rt.PublicHandler
}
func (rt *RestTester) TestMetricsHandler() http.Handler {
rt.metricsHandlerOnce.Do(func() {
rt.MetricsHandler = CreateMetricHandler(rt.ServerContext())
rt.ServerContext().addHTTPServer(metricsServer, &serverInfo{nil, &net.TCPAddr{IP: fakeRestTesterIP, Port: 4986}})
})
return rt.MetricsHandler
}
// TestDiagnosticHandler is called to lazily create a handler against the diagnostic interface.
func (rt *RestTester) TestDiagnosticHandler() http.Handler {
rt.diagnosticHandlerOnce.Do(func() {
rt.DiagnosticHandler = createDiagnosticHandler(rt.ServerContext())
rt.ServerContext().addHTTPServer(diagnosticServer, &serverInfo{nil, &net.TCPAddr{IP: fakeRestTesterIP, Port: 4987}})
})
return rt.DiagnosticHandler
}
type ChangesResults struct {
Results []db.ChangeEntry
Last_Seq db.SequenceID
}
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, "DocID %q missing from results %v", docID, cr.Results)
}
}
func (cr ChangesResults) RequireRevID(t testing.TB, revIDs []string) {
require.Equal(t, len(revIDs), len(cr.Results))
for _, rev := range revIDs {
var found bool
for _, changeEntry := range cr.Results {
if changeEntry.Changes[0]["rev"] == rev {
found = true
break
}
}
require.True(t, found, "RevID %q missing from results %v", rev, cr.Results)
}
}
// RequireChangeRevVersion asserts that the given ChangeRev has the expected version for a given entry returned by _changes feed
func RequireChangeRevVersion(t *testing.T, expected DocVersion, changeRev db.ChangeRev) {
RequireDocVersionEqual(t, expected, DocVersion{RevID: changeRev["rev"]})
}
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, fmt.Errorf("expecting %d changes, got %d", numChangesExpected, len(changes.Results)), 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, rt.mustTemplateResource(changesURL), username, useAdminPort)
sleeper := base.CreateSleeperFunc(200, 100)
err, changesVal := base.RetryLoop(rt.Context(), "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 {
return WaitForConditionWithOptions(rt.Context(), successFunc, maxNumAttempts, timeToSleepMs)
}
func WaitForConditionWithOptions(ctx context.Context, 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(ctx, "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(rt.Context(), "Wait for condition options", conditionFunc, sleeper)
if err != nil {
return err
}
return nil
}
func (rt *RestTester) SendAdminRequest(method, resource, body string) *TestResponse {
request := Request(method, rt.mustTemplateResource(resource), body)
response := &TestResponse{ResponseRecorder: httptest.NewRecorder(), Req: request}
rt.TestAdminHandler().ServeHTTP(response, request)
return response
}
func (rt *RestTester) SendUserRequest(method, resource, body, username string) *TestResponse {
return rt.Send(RequestByUser(method, rt.mustTemplateResource(resource), body, username))
}
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, "")
}