-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathtest-helper.js
1767 lines (1598 loc) · 51.3 KB
/
test-helper.js
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 DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const { assert } = require('chai');
const sinon = require('sinon');
const util = require('util');
const path = require('path');
const policies = require('../lib/policies');
const types = require('../lib/types');
const utils = require('../lib/utils');
const spawn = require('child_process').spawn;
const childProcessExec = require('child_process').exec;
const http = require('http');
const temp = require('temp').track(true);
const Client = require('../lib/client');
const defaultOptions = require('../lib/client-options').defaultOptions;
const { Host, HostMap } = require('../lib/host');
const OperationState = require('../lib/operation-state');
const promiseUtils = require('../lib/promise-utils');
util.inherits(RetryMultipleTimes, policies.retry.RetryPolicy);
const cassandraVersionByDse = {
'4.8': '2.1',
'5.0': '3.0',
'5.1': '3.11',
'6.0': '3.11',
'6.7': '3.11',
'6.8': '3.11',
'6.9': '3.11'
};
const cassandraVersionByHcd = {
'1.0': '4.0',
};
const afterNextHandlers = [];
let testUnhandledError = null;
// Use a afterEach handler at root level
afterEach(async () => {
while (afterNextHandlers.length > 0) {
const handler = afterNextHandlers.pop();
await handler();
}
});
afterEach('unhandled check', function () {
if (testUnhandledError !== null) {
const err = testUnhandledError;
testUnhandledError = null;
this.test.error(err);
}
});
// Add a listener for unhandled rejections and throw the error to exit with 1
process.on('unhandledRejection', reason => {
testUnhandledError = reason;
});
const helper = {
/**
* Creates a ccm cluster, initializes a Client instance the before() and after() hooks, create
* @param {Number|String} nodeLength A number representing the amount of nodes in a single datacenter or a string
* representing the amount of nodes in each datacenter, ie: "3:4".
* @param {Object} [options]
* @param {Object} [options.ccmOptions]
* @param {Boolean} [options.initClient] Determines whether to create a Client instance.
* @param {Object} [options.clientOptions] The options to use to initialize the client.
* @param {String} [options.keyspace] Name of the keyspace to create.
* @param {Number} [options.replicationFactor] Keyspace replication factor.
* @param {Array<String>} [options.queries] Queries to run after client creation.
* @param {Boolean} [options.removeClusterAfter=true] Determines whether ccm remove should be called on after().
*/
setup: function (nodeLength, options) {
options = options || utils.emptyObject;
before(helper.ccmHelper.start(nodeLength || 1, options.ccmOptions));
const initClient = options.initClient !== false;
let client;
let keyspace;
if (initClient) {
client = new Client(utils.extend({}, options.clientOptions, helper.baseOptions));
before(client.connect.bind(client));
keyspace = options.keyspace || helper.getRandomName('ks');
before(helper.toTask(client.execute, client, helper.createKeyspaceCql(keyspace, options.replicationFactor)));
before(helper.toTask(client.execute, client, 'USE ' + keyspace));
if (options.queries) {
before(function (done) {
utils.eachSeries(options.queries, function (q, next) {
client.execute(q, next);
}, done);
});
}
after(client.shutdown.bind(client));
}
if (options.removeClusterAfter !== false) {
after(helper.ccmHelper.remove);
}
return {
client: client,
keyspace: keyspace
};
},
/**
* Sync throws the error
* @type Function
*/
throwop: function (err) {
if (err) {
throw err;
}
},
/** @type Function */
noop: function () {
//do nothing
},
/** @type Function */
failop: function () {
throw new Error('Method should not be called');
},
/**
* Uses the last parameter as callback, invokes it via setImmediate
*/
callbackNoop: function () {
const args = Array.prototype.slice.call(arguments);
const cb = args[args.length-1];
if (typeof cb !== 'function') {
throw new Error('Helper method needs a callback as last parameter');
}
setImmediate(cb);
},
/**
* Returns a function that returns the provided value
* @param value
*/
functionOf: function (value) {
return (function fnOfFixedValue() {
return value;
});
},
/**
* @type {ClientOptions}
*/
baseOptions: (function () {
return {
//required
contactPoints: ['127.0.0.1'],
localDataCenter: 'dc1',
// retry all queries multiple times (for improved test resiliency).
policies: { retry: new RetryMultipleTimes(3) }
};
})(),
/**
* Returns a pseudo-random name in the form of 'ab{n}', n being an int zero padded with string length 16
* @returns {string}
*/
getRandomName: function (prefix) {
if (!prefix) {
prefix = 'ab';
}
const value = Math.floor(Math.random() * utils.maxInt);
return prefix + ('000000000000000' + value.toString()).slice(-16);
},
ipPrefix: '127.0.0.',
ccm: {},
ads: {},
/**
* Returns a cql string with a CREATE TABLE command containing all common types
* @param {String} tableName
* @returns {String}
*/
createTableCql: function (tableName) {
return util.format('CREATE TABLE %s (' +
' id uuid primary key,' +
' ascii_sample ascii,' +
' text_sample text,' +
' int_sample int,' +
' bigint_sample bigint,' +
' float_sample float,' +
' double_sample double,' +
' decimal_sample decimal,' +
' blob_sample blob,' +
' boolean_sample boolean,' +
' timestamp_sample timestamp,' +
' inet_sample inet,' +
' timeuuid_sample timeuuid,' +
' map_sample map<text, text>,' +
' list_sample list<text>,' +
' list_sample2 list<int>,' +
' set_sample set<text>)', tableName);
},
/**
* Returns a cql string with a CREATE TABLE command 1 partition key and 1 clustering key
* @param {String} tableName
* @returns {String}
*/
createTableWithClusteringKeyCql: function (tableName) {
return util.format('CREATE TABLE %s (' +
' id1 uuid,' +
' id2 timeuuid,' +
' text_sample text,' +
' int_sample int,' +
' bigint_sample bigint,' +
' float_sample float,' +
' double_sample double,' +
' map_sample map<uuid, int>,' +
' list_sample list<timeuuid>,' +
' set_sample set<int>,' +
' PRIMARY KEY (id1, id2))', tableName);
},
createKeyspaceCql: function (keyspace, replicationFactor, durableWrites) {
return util.format('CREATE KEYSPACE %s' +
' WITH replication = {\'class\': \'SimpleStrategy\', \'replication_factor\' : %d}' +
' AND durable_writes = %s;', keyspace, replicationFactor || 1, !!durableWrites
);
},
assertValueEqual: function (val1, val2) {
if (val1 === null && val2 === null) {
return;
}
if (val1 instanceof Buffer && val2 instanceof Buffer) {
val1 = val1.toString('hex');
val2 = val2.toString('hex');
}
if ((val1 instanceof types.Long && val2 instanceof types.Long) ||
(val1 instanceof Date && val2 instanceof Date) ||
(val1 instanceof types.InetAddress && val2 instanceof types.InetAddress) ||
(val1 instanceof types.Uuid && val2 instanceof types.Uuid)) {
val1 = val1.toString();
val2 = val2.toString();
}
if (Array.isArray(val1) ||
(val1.constructor && val1.constructor.name === 'Object') ||
val1 instanceof helper.Map) {
val1 = util.inspect(val1, {depth: null});
val2 = util.inspect(val2, {depth: null});
}
assert.strictEqual(val1, val2);
},
assertInstanceOf: function (instance, constructor) {
assert.notEqual(instance, null, 'Expected instance, obtained ' + instance);
assert.ok(instance instanceof constructor, 'Expected instance of ' + constructor.name + ', actual constructor: ' + instance.constructor.name);
},
assertNotInstanceOf: function (instance, constructor) {
assert.notEqual(instance, null, 'Expected instance, obtained ' + instance);
assert.ok(!(instance instanceof constructor), 'Expected instance different than ' + constructor.name + ', actual constructor: ' + instance.constructor.name);
},
assertContains: function (value, searchValue, caseInsensitive) {
const originalValue = value;
const originalSearchValue = searchValue;
assert.strictEqual(typeof value, 'string');
const message = 'String: "%s" does not contain "%s"';
if (caseInsensitive !== false) {
value = value.toLowerCase();
searchValue = searchValue.toLowerCase();
}
assert.ok(value.indexOf(searchValue) >= 0, util.format(message, originalValue, originalSearchValue));
},
/**
* Asserts that the value has some properties defined and the value of those properties
* @param {Object} value
* @param {Object} expectedProperties
* @param {Boolean} [strictEquality=true]
*/
assertProperties: (value, expectedProperties, strictEquality) => {
const properties = Object.keys(expectedProperties);
if (properties.length === 0) {
throw new Error('expectedProperties should be defined as an object');
}
assert.ok(value, 'value should be defined');
const assertFn = strictEquality !== false ? assert.strictEqual : assert.equal;
properties.forEach(key => assertFn(value[key], expectedProperties[key]));
},
/**
* Tests for deep equality of Maps between the actual and expected parameters
* @param actual
* @param expected
*/
assertMapEqual: (actual, expected) => {
helper.assertInstanceOf(actual, Map);
helper.assertInstanceOf(expected, Map);
assert.deepStrictEqual(Array.from(actual.keys()), Array.from(expected.keys()), 'Map keys do not match ');
expected.forEach((value, key) => {
assert.deepStrictEqual(actual.get(key), value, `Value for '${key}' does not match`);
});
},
/**
* Asserts promise gets rejected with the provided error
*/
assertThrowsAsync: async (promise, type, message) => {
let err;
try {
await promise;
} catch (e) {
err = e;
}
assert.instanceOf(err, Error);
if (type) {
assert.instanceOf(err, type);
}
if (message) {
let re = message;
if (typeof message === 'string') {
re = new RegExp(message);
}
assert.match(err.message, re);
}
return err;
},
/**
* Invokes the provided function once after the calling test finished.
* @param {Function} fn
*/
afterThisTest: function(fn) {
afterNextHandlers.push(fn);
},
/**
* Invokes client.shutdown() after this test finishes.
* @param {Client} client
* @returns {Client}
*/
shutdownAfterThisTest: function(client) {
this.afterThisTest(() => client.shutdown());
return client;
},
/**
* Returns a function that waits on schema agreement before executing callback
* @param {Client} client
* @param {Function} callback
* @returns {Function}
*/
waitSchema: function (client, callback) {
return (function (err) {
if (err) {
return callback(err);
}
if (!client.hosts) {
throw new Error('No hosts on Client');
}
if (client.hosts.length === 1) {
return callback();
}
setTimeout(callback, 200 * client.hosts.length);
});
},
/**
* @returns {Function} A function with a single callback param, applying the fn with parameters
*/
toTask: function (fn, context) {
const params = Array.prototype.slice.call(arguments, 2);
return (function (next) {
params.push(next);
fn.apply(context, params);
});
},
waitCallback: function (ms, callback) {
if (!ms) {
ms = 0;
}
return (function (err) {
if (err) {
return callback(err);
}
setTimeout(callback, ms);
});
},
/**
* Gets the Apache Cassandra version.
* When the server is DSE/HCD, gets the Apache Cassandra equivalent.
*/
getCassandraVersion: function () {
const serverInfo = this.getServerInfo();
if (serverInfo.distribution === 'cassandra') {
return serverInfo.version;
}
const literalVersion = serverInfo.version.split('.').slice(0, 2).join('.');
if (serverInfo.distribution === 'hcd') {
return cassandraVersionByHcd[literalVersion] || cassandraVersionByHcd['1.0'];
}
if (serverInfo.distribution === 'dse') {
return cassandraVersionByDse[literalVersion] || cassandraVersionByDse['6.7'];
}
throw new Error('Unknown distribution ' + serverInfo.distribution);
},
/**
* Gets the server version and type.
* @return {{version: String, isDse: Boolean, isHcd: Boolean, distribution: String}}
*/
getServerInfo: function () {
return {
version: process.env['CCM_VERSION'] || '3.11.4',
isDse: process.env['CCM_DISTRIBUTION'] === 'dse',
isHcd: process.env['CCM_DISTRIBUTION'] === 'hcd',
distribution: process.env['CCM_DISTRIBUTION'] || 'cassandra'
};
},
getSimulatedCassandraVersion: function() {
let version = this.getCassandraVersion();
// simulacron does not support protocol V2 and V1, so cap at 2.1.
if (version < '2.1') {
version = '2.1.19';
} else if (version >= '4.0') {
// simulacron does not support protocol V5, so cap at 3.11
version = '3.11.2';
}
return version;
},
/**
* Determines if the current server is a DSE instance *AND* version is greater than or equals to the version provided
* @param {String} version The version in string format, dot separated.
* @returns {Boolean}
*/
isDseGreaterThan: function (version) {
const serverInfo = this.getServerInfo();
if (!serverInfo.isDse) {
return false;
}
return helper.versionCompare(serverInfo.version, version);
},
/** Determines if the current server is a DSE instance. */
isDse: function () {
return this.getServerInfo().isDse;
},
/** Determines if the current server is a HCD instance. */
isHcd: function () {
return this.getServerInfo().isHcd;
},
/**
* Determines if the current C* or DSE instance version is greater than or equals to the C* version provided
* @param {String} version The version in string format, dot separated.
* @returns {Boolean}
*/
isCassandraGreaterThan: function (version) {
return helper.versionCompare(helper.getCassandraVersion(), version);
},
versionCompare: function (instanceVersionStr, version) {
let expected = [1, 0]; //greater than or equals to
if (version.indexOf('<=') === 0) {
version = version.substr(2);
expected = [-1, 0]; //less than or equals to
}
else if (version.indexOf('<') === 0) {
version = version.substr(1);
expected = [-1]; //less than
}
const instanceVersion = instanceVersionStr.split('.').map(function (x) { return parseInt(x, 10);});
const compareVersion = version.split('.').map(function (x) { return parseInt(x, 10) || 0;});
for (let i = 0; i < compareVersion.length; i++) {
const compare = compareVersion[i] || 0;
if (instanceVersion[i] > compare) {
//is greater
return expected.indexOf(1) >= 0;
}
else if (instanceVersion[i] < compare) {
//is smaller
return expected.indexOf(-1) >= 0;
}
}
//are equal
return expected.indexOf(0) >= 0;
},
log: function(levels) {
if (!levels) {
levels = ['info', 'warning', 'error'];
}
return (function (l) {
if (levels.indexOf(l) >= 0) {
// eslint-disable-next-line no-console, no-undef
console.log.apply(console, arguments);
}
});
},
/**
* @returns {Array}
*/
fillArray: function (length, val) {
const result = new Array(length);
for (let i = 0; i < length; i++) {
result[i] = val;
}
return result;
},
/**
* @returns {Array}
*/
iteratorToArray: function (iterator) {
const result = [];
let item = iterator.next();
while (!item.done) {
result.push(item.value);
item = iterator.next();
}
return result;
},
/** @returns {Promise<Array} */
asyncIteratorToArray: async function (iterable) {
const result = [];
const iterator = iterable[Symbol.asyncIterator]();
while (true) {
const item = await iterator.next();
if (item.done) {
break;
}
const length = result.push(item.value);
if (length > 1000) {
throw new Error('Unexpected never ending async iterator');
}
}
return result;
},
/**
* @param arr
* @param {Function|String} predicate function to compare or property name to compare
* @param val
* @returns {*}
*/
find: function (arr, predicate, val) {
if (arr == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate === 'string') {
const propName = predicate;
predicate = function (item) {
return (item && item[propName] === val);
};
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
let value;
for (let i = 0; i < arr.length; i++) {
value = arr[i];
if (predicate.call(null, value, i, arr)) {
return value;
}
}
return undefined;
},
/**
* @param {Array} arr
* @param {Function }predicate
*/
first: function (arr, predicate) {
const filterArr = arr.filter(predicate);
if (filterArr.length === 0) {
throw new Error('Item not found: ' + predicate);
}
return filterArr[0];
},
Map: MapPolyFill,
Set: SetPolyFill,
AllowListPolicy: AllowListPolicy,
FallthroughRetryPolicy: FallthroughRetryPolicy,
/**
* Determines if test tracing is enabled
*/
isTracing: function () {
return (process.env.TEST_TRACE === 'on');
},
trace: function (format) {
if (!helper.isTracing()) {
return;
}
// eslint-disable-next-line no-console, no-undef
console.log('\t...' + util.format.apply(null, arguments));
},
/**
* Version dependent it() method for mocha test case
* @param {String} testVersion Minimum version of Cassandra needed for this test
* @param {String} testCase Test case name
* @param {Function} func
*/
vit: function (testVersion, testCase, func) {
executeIfVersion(testVersion, it, [testCase, func]);
},
/**
* Version dependent describe() method for mocha test case
* @param {String} testVersion Minimum version of DSE/Cassandra needed for this test
* @param {String} title Title of the describe section.
* @param {Function} func
*/
vdescribe: function (testVersion, title, func) {
executeIfVersion(testVersion, describe, [title, func]);
},
/**
* Given a {Host} returns the last octet of its ip address.
* i.e. (127.0.0.247:9042) -> 247.
*
* @param {Host|string} host or host address to get ip address of.
* @returns {string} Last octet of the host address.
*/
lastOctetOf: function(host) {
const address = typeof host === "string" ? host : host.address;
const ipAddress = address.split(':')[0].split('.');
return ipAddress[ipAddress.length-1];
},
/**
* Given a {Client} and a {Number} returns the host whose last octet
* ends with the requested number.
* @param {Client|HostMap|Array<Host>} hostsOrClient Client to lookup hosts from.
* @param {Number} number last octet of requested host.
* @param {Boolean} [throwWhenNotFound] Determines whether this method should throw an error when the host
* can not be found.
* @returns {Host}
*/
findHost: function(hostsOrClient, number, throwWhenNotFound) {
let hostArray;
if (hostsOrClient instanceof HostMap) {
hostArray = hostsOrClient.values();
} else if (hostsOrClient instanceof Client) {
hostArray = hostsOrClient.hosts.values();
} else if (Array.isArray(hostsOrClient)) {
hostArray = hostsOrClient;
} else {
throw new Error('First parameter must be the host array/map or the Client');
}
const host = hostArray.find(h => +this.lastOctetOf(h) === +number);
if (throwWhenNotFound && !host) {
throw new Error(`Host ${number} not found`);
}
return host;
},
/**
* Provides utilities to asynchronously wait on conditions.
*/
wait: {
until: async function(condition, maxAttempts = 500, delay = 20) {
for (let i = 0; i <= maxAttempts; i++) {
// Condition can be both sync or async
const c = await condition();
if (!c) {
if (i === maxAttempts) {
throw new Error(`Condition still false after ${maxAttempts * delay}ms: ${condition.toString()}`);
}
await helper.delayAsync(delay);
} else {
break;
}
}
},
forNodeUp: async function (hostsOrClient, lastOctet, maxAttempts = 500, delay = 20) {
const host = helper.findHost(hostsOrClient, lastOctet, true);
await this.until(() => host.isUp(), maxAttempts, delay);
},
forAllNodesUp: async function (client, maxAttempts = 500, delay = 20) {
await this.until(() => !client.hosts.values().find(h => !h.isUp()), maxAttempts, delay);
},
forAllNodesDown: async function (client, maxAttempts = 500, delay = 20) {
await this.until(() => !client.hosts.values().find(h => h.isUp()), maxAttempts, delay);
},
forNodeDown: async function (hostsOrClient, lastOctet, maxAttempts = 500, delay = 20) {
const host = helper.findHost(hostsOrClient, lastOctet, true);
await this.until(() => !host.isUp(), maxAttempts, delay);
},
forNodeToBeAdded: async function (hostsOrClient, lastOctet, maxAttempts = 1000, delay = 20) {
await this.until(() => helper.findHost(hostsOrClient, lastOctet), maxAttempts, delay);
},
forNodeToBeRemoved: async function (hostsOrClient, lastOctet, maxAttempts = 1000, delay = 20) {
await this.until(() => !helper.findHost(hostsOrClient, lastOctet), maxAttempts, delay);
}
},
/**
* Returns a function, that when invoked shutdowns the client and callbacks
* @param {Client} client
* @param {Function} callback
* @returns {Function}
*/
finish: function (client, callback) {
return (function onFinish(err) {
client.shutdown(function () {
assert.ifError(err);
callback();
});
});
},
/**
* Returns a handler that executes multiple queries
* @param {Client} client
* @param {Array<string>} queries
*/
executeTask: function (client, queries) {
return (function (done) {
utils.series([
client.connect.bind(client),
function executeQueries(next) {
utils.eachSeries(queries, function (query, eachNext) {
client.execute(query, eachNext);
}, next);
}
], helper.finish(client, done));
});
},
/**
* Executes a function at regular intervals while the condition is false and the amount of attempts < maxAttempts.
* @param {Function} condition
* @param {Number} delay
* @param {Number} maxAttempts
* @param {Function} done
*/
setIntervalUntil: function (condition, delay, maxAttempts, done) {
let attempts = 0;
utils.whilst(
function whilstCondition() {
return !condition();
},
function whilstItem(next) {
if (attempts++ >= maxAttempts) {
return next(new Error(util.format('Condition still false after %d attempts: %s', maxAttempts, condition)));
}
setTimeout(next, delay);
},
done);
},
/**
* Returns a method that executes a function at regular intervals while the condition is false and the amount of
* attempts < maxAttempts.
* @param {Function} condition
* @param {Number} delay
* @param {Number} maxAttempts
*/
setIntervalUntilTask: function (condition, delay, maxAttempts) {
const self = this;
return (function setIntervalUntilHandler(done) {
self.setIntervalUntil(condition, delay, maxAttempts, done);
});
},
/**
* Executes a function at regular intervals while the condition is false and the amount of attempts < maxAttempts.
* @param {Function} condition
* @param {Number} delay
* @param {Number} maxAttempts
*/
setIntervalUntilPromise: function (condition, delay, maxAttempts) {
return new Promise((resolve, reject) => {
this.setIntervalUntil(condition, delay, maxAttempts, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
},
/**
* Returns a method that delays invoking the callback
*/
delay: function (delayMs) {
return (function delayedHandler(next) {
setTimeout(next, delayMs);
});
},
delayAsync: (delayMs) => promiseUtils.delay(delayMs),
queries: {
basic: "SELECT key FROM system.local",
basicNoResults: "SELECT key from system.local WHERE key = 'not_existent'"
},
getPoolingOptions: function (localLength, remoteLength, heartBeatInterval) {
const pooling = {
heartBeatInterval: heartBeatInterval || 0,
coreConnectionsPerHost: {}
};
pooling.coreConnectionsPerHost[types.distance.local] = localLength || 1;
pooling.coreConnectionsPerHost[types.distance.remote] = remoteLength || 1;
pooling.coreConnectionsPerHost[types.distance.ignored] = 0;
return pooling;
},
getHostsMock: function (hostsInfo, prepareQueryCb, sendStreamCb, protocolVersion) {
return hostsInfo.map(function (info, index) {
protocolVersion = protocolVersion || types.protocolVersion.maxSupported;
const h = new Host(index.toString(), protocolVersion, defaultOptions(), {});
h.isUp = function () {
return !(info.isUp === false);
};
h.checkHealth = utils.noop;
h.log = utils.noop;
h.shouldBeIgnored = !!info.ignored;
h.prepareCalled = 0;
h.sendStreamCalled = 0;
h.connectionKeyspace = [];
h.borrowConnection = function () {
if (!h.isUp() || h.shouldBeIgnored) {
throw new Error('This host should not be used');
}
return ({
protocolVersion: protocolVersion,
keyspace: 'ks',
changeKeyspace: (keyspace) => {
this.keyspace = keyspace;
h.connectionKeyspace.push(keyspace);
return Promise.resolve();
},
prepareOnce: function (q, ks, cb) {
h.prepareCalled++;
if (prepareQueryCb) {
return prepareQueryCb(q, h, cb);
}
cb(null, { id: 1, meta: {} });
},
sendStream: function (r, o, cb) {
h.sendStreamCalled++;
if (sendStreamCb) {
return sendStreamCb(r, h, cb);
}
const op = new OperationState(r, o, cb);
setImmediate(function () {
op.setResult(null, {});
});
return op;
},
prepareOnceAsync: function (q, ks) {
return new Promise((resolve, reject) => {
h.prepareCalled++;
if (prepareQueryCb) {
return prepareQueryCb(q, h, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
}
resolve({ id: 1, meta: {} });
});
}
});
};
return sinon.spy(h);
});
},
getLoadBalancingPolicyFake: function getLoadBalancingPolicyFake(hostsInfo, prepareQueryCb, sendStreamCb, protocolVersion) {
const hosts = this.getHostsMock(hostsInfo, prepareQueryCb, sendStreamCb, protocolVersion);
const fake = {
newQueryPlan: function (q, ks, cb) {
cb(null, utils.arrayIterator(hosts));
},
/**
* Returns the array of hosts used in the query plan.
*/
getFixedQueryPlan: function () {
return hosts;
},
getDistance: function () {
return types.distance.local;
},
/**
* Shutdowns the hosts and invoke the optional callback.
*/
shutdown: function (cb) {
hosts.forEach(h => h.shutdown(false));
if (cb) {
cb();
}
}
};
helper.afterThisTest(() => fake.shutdown());
return fake;
},
/**
* Returns true if the tests are being run on Windows
* @returns {boolean}
*/
isWin: function () {
return process.platform.indexOf('win') === 0;
},
/**
* Invokes a function multiple times and returns a Promise that is resolved when all the promises have completed.
* @param {Number} times
* @param {Function} fn
* @returns {Promise}
*/
repeat: function(times, fn) {
const arr = new Array(times);
for (let i = 0; i < times; i++) {
arr[i] = fn(i);
}
return Promise.all(arr);
},
requireOptional: function (moduleName) {
try {
// eslint-disable-next-line
return require(moduleName);
}
catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
return null;
}
throw err;
}
},
assertBufferString: function (instance, textValue) {
this.assertInstanceOf(instance, Buffer);
assert.strictEqual(instance.toString(), textValue);
},
conditionalDescribe: function (condition, text) {
if (condition) {
return describe;
}
return (function xdescribeWithText(name, fn) {
return xdescribe(util.format('%s [%s]', name, text), fn);
});
},
getOptions: function (options) {
return utils.extend({}, helper.baseOptions, options);
},
/**
* @param {ResultSet} result
*/
keyedById: function (result) {
const map = {};
const columnKeys = result.columns.map(function (c) { return c.name;});
if (columnKeys.indexOf('id') < 0 || columnKeys.indexOf('value') < 0) {
throw new Error('ResultSet must contain the columns id and value');
}
result.rows.forEach(function (row) {
map[row['id']] = row['value'];
});
return map;
},
/**
* Connects to the cluster, makes a few queries and shutsdown the client
* @param {Client} client
* @param {Function} callback
*/
connectAndQuery: function (client, callback) {
const self = this;
utils.series([
client.connect.bind(client),
function doSomeQueries(next) {
utils.timesSeries(10, function (n, timesNext) {
client.execute(self.queries.basic, timesNext);
}, next);