forked from ccxt/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.ts
1903 lines (1831 loc) · 90.9 KB
/
tests.ts
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
// ----------------------------------------------------------------------------
import assert from 'assert';
import { Exchange } from '../../ccxt.js';
import { Str } from '../base/types.js';
import {
// errors
AuthenticationError,
NotSupported,
InvalidProxySettings,
ExchangeNotAvailable,
OperationFailed,
OnMaintenance,
// shared
getCliArgValue,
//
baseMainTestClass,
dump,
jsonParse,
jsonStringify,
convertAscii,
ioFileExists,
ioFileRead,
ioDirRead,
callMethod,
callMethodSync,
callExchangeMethodDynamically,
callExchangeMethodDynamicallySync,
getRootException,
exceptionMessage,
exitScript,
getExchangeProp,
setExchangeProp,
initExchange,
getTestFilesSync,
getTestFiles,
setFetchResponse,
isNullValue,
close,
} from './tests.helpers.js';
class testMainClass extends baseMainTestClass {
parseCliArgs () {
this.responseTests = getCliArgValue ('--responseTests');
this.idTests = getCliArgValue ('--idTests');
this.requestTests = getCliArgValue ('--requestTests');
this.info = getCliArgValue ('--info');
this.verbose = getCliArgValue ('--verbose');
this.debug = getCliArgValue ('--debug');
this.privateTest = getCliArgValue ('--private');
this.privateTestOnly = getCliArgValue ('--privateOnly');
this.sandbox = getCliArgValue ('--sandbox');
this.loadKeys = getCliArgValue ('--loadKeys');
this.wsTests = getCliArgValue ('--ws');
}
async init (exchangeId, symbolArgv, methodArgv) {
this.parseCliArgs ();
if (this.requestTests && this.responseTests) {
await this.runStaticRequestTests (exchangeId, symbolArgv);
await this.runStaticResponseTests (exchangeId, symbolArgv);
return;
}
if (this.responseTests) {
await this.runStaticResponseTests (exchangeId, symbolArgv);
return;
}
if (this.requestTests) {
await this.runStaticRequestTests (exchangeId, symbolArgv); // symbol here is the testname
return;
}
if (this.idTests) {
await this.runBrokerIdTests ();
return;
}
dump (this.newLine + '' + this.newLine + '' + '[INFO] TESTING ', this.ext, { 'exchange': exchangeId, 'symbol': symbolArgv, 'method': methodArgv, 'isWs': this.wsTests }, this.newLine);
const exchangeArgs = {
'verbose': this.verbose,
'debug': this.debug,
'enableRateLimit': true,
'timeout': 30000,
};
const exchange = initExchange (exchangeId, exchangeArgs, this.wsTests);
if (exchange.alias) {
exitScript (0);
}
await this.importFiles (exchange);
assert (Object.keys (this.testFiles).length > 0, 'Test files were not loaded'); // ensure test files are found & filled
this.expandSettings (exchange);
this.checkIfSpecificTestIsChosen (methodArgv);
await this.startTest (exchange, symbolArgv);
exitScript (0); // needed to be explicitly finished for WS tests
}
checkIfSpecificTestIsChosen (methodArgv) {
if (methodArgv !== undefined) {
const testFileNames = Object.keys (this.testFiles);
const possibleMethodNames = methodArgv.split (','); // i.e. `test.ts binance fetchBalance,fetchDeposits`
if (possibleMethodNames.length >= 1) {
for (let i = 0; i < testFileNames.length; i++) {
const testFileName = testFileNames[i];
for (let j = 0; j < possibleMethodNames.length; j++) {
let methodName = possibleMethodNames[j];
methodName = methodName.replace ('()', '');
if (testFileName === methodName) {
this.onlySpecificTests.push (testFileName);
}
}
}
}
}
}
async importFiles (exchange: Exchange) {
const properties = Object.keys (exchange.has);
properties.push ('loadMarkets');
if (this.isSynchronous) {
this.testFiles = getTestFilesSync (properties, this.wsTests);
} else {
this.testFiles = await getTestFiles (properties, this.wsTests);
}
}
loadCredentialsFromEnv (exchange: Exchange) {
const exchangeId = exchange.id;
const reqCreds = getExchangeProp (exchange, 're' + 'quiredCredentials'); // dont glue the r-e-q-u-i-r-e phrase, because leads to messed up transpilation
const objkeys = Object.keys (reqCreds);
for (let i = 0; i < objkeys.length; i++) {
const credential = objkeys[i];
const isRequired = reqCreds[credential];
if (isRequired && getExchangeProp (exchange, credential) === undefined) {
const fullKey = exchangeId + '_' + credential;
const credentialEnvName = fullKey.toUpperCase (); // example: KRAKEN_APIKEY
const credentialValue = (credentialEnvName in this.envVars) ? this.envVars[credentialEnvName] : undefined;
if (credentialValue) {
setExchangeProp (exchange, credential, credentialValue);
}
}
}
}
expandSettings (exchange: Exchange) {
const exchangeId = exchange.id;
const keysGlobal = this.rootDir + 'keys.json';
const keysLocal = this.rootDir + 'keys.local.json';
const keysGlobalExists = ioFileExists (keysGlobal);
const keysLocalExists = ioFileExists (keysLocal);
const globalSettings = keysGlobalExists ? ioFileRead (keysGlobal) : {};
const localSettings = keysLocalExists ? ioFileRead (keysLocal) : {};
const allSettings = exchange.deepExtend (globalSettings, localSettings);
const exchangeSettings = exchange.safeValue (allSettings, exchangeId, {});
if (exchangeSettings) {
const settingKeys = Object.keys (exchangeSettings);
for (let i = 0; i < settingKeys.length; i++) {
const key = settingKeys[i];
if (exchangeSettings[key]) {
let finalValue = undefined;
if (typeof exchangeSettings[key] === 'object') {
const existing = getExchangeProp (exchange, key, {});
finalValue = exchange.deepExtend (existing, exchangeSettings[key]);
} else {
finalValue = exchangeSettings[key];
}
setExchangeProp (exchange, key, finalValue);
}
}
}
// credentials
if (this.loadKeys) {
this.loadCredentialsFromEnv (exchange);
}
// skipped tests
const skippedFile = this.rootDirForSkips + 'skip-tests.json';
const skippedSettings = ioFileRead (skippedFile);
this.skippedSettingsForExchange = exchange.safeValue (skippedSettings, exchangeId, {});
const skippedSettingsForExchange = this.skippedSettingsForExchange;
// others
const timeout = exchange.safeValue (skippedSettingsForExchange, 'timeout');
if (timeout !== undefined) {
exchange.timeout = exchange.parseToInt (timeout);
}
if (getCliArgValue ('--useProxy')) {
exchange.httpProxy = exchange.safeString (skippedSettingsForExchange, 'httpProxy');
exchange.httpsProxy = exchange.safeString (skippedSettingsForExchange, 'httpsProxy');
exchange.wsProxy = exchange.safeString (skippedSettingsForExchange, 'wsProxy');
exchange.wssProxy = exchange.safeString (skippedSettingsForExchange, 'wssProxy');
}
this.skippedMethods = exchange.safeValue (skippedSettingsForExchange, 'skipMethods', {});
this.checkedPublicTests = {};
}
addPadding (message: string, size) {
// has to be transpilable
let res = '';
const messageLength = message.length; // avoid php transpilation issue
const missingSpace = size - messageLength - 0; // - 0 is added just to trick transpile to treat the .length as a string for php
if (missingSpace > 0) {
for (let i = 0; i < missingSpace; i++) {
res += ' ';
}
}
return message + res;
}
exchangeHint (exchange, market = undefined) {
let marketType = exchange.safeString2 (exchange.options, 'defaultType', 'type', '');
let marketSubType = exchange.safeString2 (exchange.options, 'defaultSubType', 'subType');
if (market !== undefined) {
marketType = market['type'];
if (market['linear']) {
marketSubType = 'linear';
} else if (market['inverse']) {
marketSubType = 'inverse';
} else if (exchange.safeValue (market, 'quanto') === true) {
marketSubType = 'quanto';
}
}
const isWs = ('ws' in exchange.has);
const wsFlag = isWs ? '(WS)' : '';
let result = exchange.id + ' ' + wsFlag + ' ' + marketType;
if (marketSubType !== undefined) {
result = result + ' [subType: ' + marketSubType + '] ';
}
return result;
}
async testMethod (methodName: string, exchange: any, args: any[], isPublic: boolean) {
// todo: temporary skip for c#
if (methodName.indexOf ('OrderBook') >= 0 && this.ext === 'cs') {
exchange.options['checksum'] = false;
}
// todo: temporary skip for php
if (methodName.indexOf ('OrderBook') >= 0 && this.ext === 'php') {
return;
}
const skippedPropertiesForMethod = this.getSkips (exchange, methodName);
const isLoadMarkets = (methodName === 'loadMarkets');
const isFetchCurrencies = (methodName === 'fetchCurrencies');
const isProxyTest = (methodName === this.proxyTestFileName);
// if this is a private test, and the implementation was already tested in public, then no need to re-test it in private test (exception is fetchCurrencies, because our approach in base exchange)
if (!isPublic && (methodName in this.checkedPublicTests) && !isFetchCurrencies) {
return;
}
let skipMessage = undefined;
const supportedByExchange = (methodName in exchange.has) && exchange.has[methodName];
if (!isLoadMarkets && (this.onlySpecificTests.length > 0 && !exchange.inArray (methodName, this.onlySpecificTests))) {
skipMessage = '[INFO] IGNORED_TEST';
} else if (!isLoadMarkets && !supportedByExchange && !isProxyTest) {
skipMessage = '[INFO] UNSUPPORTED_TEST'; // keep it aligned with the longest message
} else if (typeof skippedPropertiesForMethod === 'string') {
skipMessage = '[INFO] SKIPPED_TEST';
} else if (!(methodName in this.testFiles)) {
skipMessage = '[INFO] UNIMPLEMENTED_TEST';
}
// exceptionally for `loadMarkets` call, we call it before it's even checked for "skip" as we need it to be called anyway (but can skip "test.loadMarket" for it)
if (isLoadMarkets) {
await exchange.loadMarkets (true);
}
if (skipMessage) {
if (this.info) {
dump (this.addPadding (skipMessage, 25), this.exchangeHint (exchange), methodName);
}
return;
}
if (this.info) {
const argsStringified = '(' + exchange.json (args) + ')'; // args.join() breaks when we provide a list of symbols or multidimensional array; "args.toString()" breaks bcz of "array to string conversion"
dump (this.addPadding ('[INFO] TESTING', 25), this.exchangeHint (exchange), methodName, argsStringified);
}
if (this.isSynchronous) {
callMethodSync (this.testFiles, methodName, exchange, skippedPropertiesForMethod, args);
} else {
await callMethod (this.testFiles, methodName, exchange, skippedPropertiesForMethod, args);
}
if (this.info) {
dump (this.addPadding ('[INFO] TESTING DONE', 25), this.exchangeHint (exchange), methodName);
}
// add to the list of successed tests
if (isPublic) {
this.checkedPublicTests[methodName] = true;
}
return;
}
getSkips (exchange: Exchange, methodName: string) {
let finalSkips = {};
// check the exact method (i.e. `fetchTrades`) and language-specific (i.e. `fetchTrades.php`)
const methodNames = [ methodName, methodName + '.' + this.ext ];
for (let i = 0; i < methodNames.length; i++) {
const mName = methodNames[i];
if (mName in this.skippedMethods) {
// if whole method is skipped, by assigning a string to it, i.e. "fetchOrders":"blabla"
if (typeof this.skippedMethods[mName] === 'string') {
return this.skippedMethods[mName];
} else {
finalSkips = exchange.deepExtend (finalSkips, this.skippedMethods[mName]);
}
}
}
// get "object-specific" skips
const objectSkips = {
'orderBook': [ 'fetchOrderBook', 'fetchOrderBooks', 'fetchL2OrderBook', 'watchOrderBook', 'watchOrderBookForSymbols' ],
'ticker': [ 'fetchTicker', 'fetchTickers', 'watchTicker', 'watchTickers' ],
'trade': [ 'fetchTrades', 'watchTrades', 'watchTradesForSymbols' ],
'ohlcv': [ 'fetchOHLCV', 'watchOHLCV', 'watchOHLCVForSymbols' ],
'ledger': [ 'fetchLedger', 'fetchLedgerEntry' ],
'depositWithdraw': [ 'fetchDepositsWithdrawals', 'fetchDeposits', 'fetchWithdrawals' ],
'depositWithdrawFee': [ 'fetchDepositWithdrawFee', 'fetchDepositWithdrawFees' ],
};
const objectNames = Object.keys (objectSkips);
for (let i = 0; i < objectNames.length; i++) {
const objectName = objectNames[i];
const objectMethods = objectSkips[objectName];
if (exchange.inArray (methodName, objectMethods)) {
// if whole object is skipped, by assigning a string to it, i.e. "orderBook":"blabla"
if ((objectName in this.skippedMethods) && (typeof this.skippedMethods[objectName] === 'string')) {
return this.skippedMethods[objectName];
}
const extraSkips = exchange.safeDict (this.skippedMethods, objectName, {});
finalSkips = exchange.deepExtend (finalSkips, extraSkips);
}
}
// extend related skips
// - if 'timestamp' is skipped, we should do so for 'datetime' too
// - if 'bid' is skipped, skip 'ask' too
if (('timestamp' in finalSkips) && !('datetime' in finalSkips)) {
finalSkips['datetime'] = finalSkips['timestamp'];
}
if (('bid' in finalSkips) && !('ask' in finalSkips)) {
finalSkips['ask'] = finalSkips['bid'];
}
if (('baseVolume' in finalSkips) && !('quoteVolume' in finalSkips)) {
finalSkips['quoteVolume'] = finalSkips['baseVolume'];
}
return finalSkips;
}
async testSafe (methodName, exchange, args = [], isPublic = false) {
// `testSafe` method does not throw an exception, instead mutes it. The reason we
// mute the thrown exceptions here is because we don't want to stop the whole
// tests queue if any single test-method fails. Instead, they are echoed with
// formatted message "[TEST_FAILURE] ..." and that output is then regex-matched by
// run-tests.js, so the exceptions are still printed out to console from there.
const maxRetries = 3;
const argsStringified = exchange.json (args); // args.join() breaks when we provide a list of symbols or multidimensional array; "args.toString()" breaks bcz of "array to string conversion"
for (let i = 0; i < maxRetries; i++) {
try {
await this.testMethod (methodName, exchange, args, isPublic);
return true;
}
catch (ex) {
const e = getRootException (ex);
const isLoadMarkets = (methodName === 'loadMarkets');
const isAuthError = (e instanceof AuthenticationError);
const isNotSupported = (e instanceof NotSupported);
const isOperationFailed = (e instanceof OperationFailed); // includes "DDoSProtection", "RateLimitExceeded", "RequestTimeout", "ExchangeNotAvailable", "OperationFailed", "InvalidNonce", ...
if (isOperationFailed) {
// if last retry was gone with same `tempFailure` error, then let's eventually return false
if (i === maxRetries - 1) {
const isOnMaintenance = (e instanceof OnMaintenance);
const isExchangeNotAvailable = (e instanceof ExchangeNotAvailable);
let shouldFail = undefined;
let returnSuccess = undefined;
if (isLoadMarkets) {
// if "loadMarkets" does not succeed, we must return "false" to caller method, to stop tests continual
returnSuccess = false;
// we might not break exchange tests, if exchange is on maintenance at this moment
if (isOnMaintenance) {
shouldFail = false;
} else {
shouldFail = true;
}
}
else {
// for any other method tests:
if (isExchangeNotAvailable && !isOnMaintenance) {
// break exchange tests if "ExchangeNotAvailable" exception is thrown, but it's not maintenance
shouldFail = true;
returnSuccess = false;
} else {
// in all other cases of OperationFailed, show Warning, but don't mark test as failed
shouldFail = false;
returnSuccess = true;
}
}
// output the message
const failType = shouldFail ? '[TEST_FAILURE]' : '[TEST_WARNING]';
dump (failType, 'Method could not be tested due to a repeated Network/Availability issues', ' | ', this.exchangeHint (exchange), methodName, argsStringified, exceptionMessage (e));
return returnSuccess;
}
else {
// wait and retry again
// (increase wait time on every retry)
await exchange.sleep (i * 1000);
continue;
}
}
// if it's not temporary failure, then ...
else {
// if it's loadMarkets, then fail test, because it's mandatory for tests
if (isLoadMarkets) {
dump ('[TEST_FAILURE]', 'Exchange can not load markets', exceptionMessage (e), this.exchangeHint (exchange), methodName, argsStringified);
return false;
}
// if the specific arguments to the test method throws "NotSupported" exception
// then let's don't fail the test
if (isNotSupported) {
if (this.info) {
dump ('[INFO] NOT_SUPPORTED', exceptionMessage (e), this.exchangeHint (exchange), methodName, argsStringified);
}
return true;
}
// If public test faces authentication error, we don't break (see comments under `testSafe` method)
if (isPublic && isAuthError) {
if (this.info) {
dump ('[INFO]', 'Authentication problem for public method', exceptionMessage (e), this.exchangeHint (exchange), methodName, argsStringified);
}
return true;
}
// in rest of the cases, fail the test
else {
dump ('[TEST_FAILURE]', exceptionMessage (e), this.exchangeHint (exchange), methodName, argsStringified);
return false;
}
}
}
}
return true;
}
async runPublicTests (exchange, symbol) {
let tests = {
'fetchCurrencies': [],
'fetchTicker': [ symbol ],
'fetchTickers': [ symbol ],
'fetchLastPrices': [ symbol ],
'fetchOHLCV': [ symbol ],
'fetchTrades': [ symbol ],
'fetchOrderBook': [ symbol ],
'fetchL2OrderBook': [ symbol ],
'fetchOrderBooks': [],
'fetchBidsAsks': [],
'fetchStatus': [],
'fetchTime': [],
};
if (this.wsTests) {
tests = {
// @ts-ignore
'watchOHLCV': [ symbol ],
'watchOHLCVForSymbols': [ symbol ], // argument type will be handled inside test
'watchTicker': [ symbol ],
'watchTickers': [ symbol ],
'watchBidsAsks': [ symbol ],
'watchOrderBook': [ symbol ],
'watchOrderBookForSymbols': [ [ symbol ] ],
'watchTrades': [ symbol ],
'watchTradesForSymbols': [ [ symbol ] ],
};
}
const market = exchange.market (symbol);
const isSpot = market['spot'];
if (!this.wsTests) {
if (isSpot) {
tests['fetchCurrencies'] = [];
} else {
tests['fetchFundingRates'] = [ symbol ];
tests['fetchFundingRate'] = [ symbol ];
tests['fetchFundingRateHistory'] = [ symbol ];
tests['fetchIndexOHLCV'] = [ symbol ];
tests['fetchMarkOHLCV'] = [ symbol ];
tests['fetchPremiumIndexOHLCV'] = [ symbol ];
}
}
this.publicTests = tests;
await this.runTests (exchange, tests, true);
}
async runTests (exchange: any, tests: any, isPublicTest:boolean) {
const testNames = Object.keys (tests);
const promises = [];
for (let i = 0; i < testNames.length; i++) {
const testName = testNames[i];
const testArgs = tests[testName];
promises.push (this.testSafe (testName, exchange, testArgs, isPublicTest));
}
// todo - not yet ready in other langs too
// promises.push (testThrottle ());
const results = await Promise.all (promises);
// now count which test-methods retuned `false` from "testSafe" and dump that info below
const failedMethods = [];
for (let i = 0; i < testNames.length; i++) {
const testName = testNames[i];
const testReturnedValue = results[i];
if (!testReturnedValue) {
failedMethods.push (testName);
}
}
const testPrefixString = isPublicTest ? 'PUBLIC_TESTS' : 'PRIVATE_TESTS';
if (failedMethods.length) {
const errorsString = failedMethods.join (', ');
dump ('[TEST_FAILURE]', this.exchangeHint (exchange), testPrefixString, 'Failed methods : ' + errorsString);
}
if (this.info) {
dump (this.addPadding ('[INFO] END ' + testPrefixString + ' ' + this.exchangeHint (exchange), 25));
}
}
async loadExchange (exchange) {
const result = await this.testSafe ('loadMarkets', exchange, [], true);
if (!result) {
return false;
}
const exchangeSymbolsLength = exchange.symbols.length;
dump ('[INFO:MAIN] Exchange loaded', exchangeSymbolsLength, 'symbols');
return true;
}
getTestSymbol (exchange, isSpot, symbols) {
let symbol = undefined;
const preferredSpotSymbol = exchange.safeString (this.skippedSettingsForExchange, 'preferredSpotSymbol');
const preferredSwapSymbol = exchange.safeString (this.skippedSettingsForExchange, 'preferredSwapSymbol');
if (isSpot && preferredSpotSymbol) {
return preferredSpotSymbol;
} else if (!isSpot && preferredSwapSymbol) {
return preferredSwapSymbol;
}
for (let i = 0; i < symbols.length; i++) {
const s = symbols[i];
const market = exchange.safeValue (exchange.markets, s);
if (market !== undefined) {
const active = exchange.safeValue (market, 'active');
if (active || (active === undefined)) {
symbol = s;
break;
}
}
}
return symbol;
}
getExchangeCode (exchange, codes = undefined) {
if (codes === undefined) {
codes = [ 'BTC', 'ETH', 'XRP', 'LTC', 'BCH', 'EOS', 'BNB', 'BSV', 'USDT' ];
}
const code = codes[0];
for (let i = 0; i < codes.length; i++) {
if (codes[i] in exchange.currencies) {
return codes[i];
}
}
return code;
}
getMarketsFromExchange (exchange, spot = true) {
const res = {};
const markets = exchange.markets;
const keys = Object.keys (markets);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const market = markets[key];
if (spot && market['spot']) {
res[market['symbol']] = market;
} else if (!spot && !market['spot']) {
res[market['symbol']] = market;
}
}
return res;
}
getValidSymbol (exchange, spot = true) {
const currentTypeMarkets = this.getMarketsFromExchange (exchange, spot);
const codes = [
'BTC',
'ETH',
'XRP',
'LTC',
'BNB',
'DASH',
'DOGE',
'ETC',
'TRX',
// fiats
'USDT',
'USDC',
'USD',
'EUR',
'TUSD',
'CNY',
'JPY',
'BRL',
];
const spotSymbols = [
'BTC/USDT',
'BTC/USDC',
'BTC/USD',
'BTC/CNY',
'BTC/EUR',
'BTC/AUD',
'BTC/BRL',
'BTC/JPY',
'ETH/USDT',
'ETH/USDC',
'ETH/USD',
'ETH/CNY',
'ETH/EUR',
'ETH/AUD',
'ETH/BRL',
'ETH/JPY',
// fiats
'EUR/USDT',
'EUR/USD',
'EUR/USDC',
'USDT/EUR',
'USD/EUR',
'USDC/EUR',
// non-fiats
'BTC/ETH',
'ETH/BTC',
];
const swapSymbols = [
// linear
'BTC/USDT:USDT',
'BTC/USDC:USDC',
'BTC/USD:USD',
'ETH/USDT:USDT',
'ETH/USDC:USDC',
'ETH/USD:USD',
// inverse
'BTC/USD:BTC',
'ETH/USD:ETH',
];
const targetSymbols = spot ? spotSymbols : swapSymbols;
let symbol = this.getTestSymbol (exchange, spot, targetSymbols);
// if symbols wasn't found from above hardcoded list, then try to locate any symbol which has our target hardcoded 'base' code
if (symbol === undefined) {
for (let i = 0; i < codes.length; i++) {
const currentCode = codes[i];
const marketsArrayForCurrentCode = exchange.filterBy (currentTypeMarkets, 'base', currentCode);
const indexedMkts = exchange.indexBy (marketsArrayForCurrentCode, 'symbol');
const symbolsArrayForCurrentCode = Object.keys (indexedMkts);
const symbolsLength = symbolsArrayForCurrentCode.length;
if (symbolsLength) {
symbol = this.getTestSymbol (exchange, spot, symbolsArrayForCurrentCode);
break;
}
}
}
// if there wasn't found any symbol with our hardcoded 'base' code, then just try to find symbols that are 'active'
if (symbol === undefined) {
const activeMarkets = exchange.filterBy (currentTypeMarkets, 'active', true);
const activeSymbols = [];
for (let i = 0; i < activeMarkets.length; i++) {
activeSymbols.push (activeMarkets[i]['symbol']);
}
symbol = this.getTestSymbol (exchange, spot, activeSymbols);
}
if (symbol === undefined) {
const values = Object.values (currentTypeMarkets);
const valuesLength = values.length;
if (valuesLength > 0) {
const first = values[0];
if (first !== undefined) {
symbol = first['symbol'];
}
}
}
return symbol;
}
async testExchange (exchange, providedSymbol = undefined) {
let spotSymbol = undefined;
let swapSymbol = undefined;
if (providedSymbol !== undefined) {
const market = exchange.market (providedSymbol);
if (market['spot']) {
spotSymbol = providedSymbol;
} else {
swapSymbol = providedSymbol;
}
} else {
if (exchange.has['spot']) {
spotSymbol = this.getValidSymbol (exchange, true);
}
if (exchange.has['swap']) {
swapSymbol = this.getValidSymbol (exchange, false);
}
}
if (spotSymbol !== undefined) {
dump ('[INFO:MAIN] Selected SPOT SYMBOL:', spotSymbol);
}
if (swapSymbol !== undefined) {
dump ('[INFO:MAIN] Selected SWAP SYMBOL:', swapSymbol);
}
if (!this.privateTestOnly) {
// note, spot & swap tests should run sequentially, because of conflicting `exchange.options['defaultType']` setting
if (exchange.has['spot'] && spotSymbol !== undefined) {
if (this.info) {
dump ('[INFO] ### SPOT TESTS ###');
}
exchange.options['defaultType'] = 'spot';
await this.runPublicTests (exchange, spotSymbol);
}
if (exchange.has['swap'] && swapSymbol !== undefined) {
if (this.info) {
dump ('[INFO] ### SWAP TESTS ###');
}
exchange.options['defaultType'] = 'swap';
await this.runPublicTests (exchange, swapSymbol);
}
}
if (this.privateTest || this.privateTestOnly) {
if (exchange.has['spot'] && spotSymbol !== undefined) {
exchange.options['defaultType'] = 'spot';
await this.runPrivateTests (exchange, spotSymbol);
}
if (exchange.has['swap'] && swapSymbol !== undefined) {
exchange.options['defaultType'] = 'swap';
await this.runPrivateTests (exchange, swapSymbol);
}
}
}
async runPrivateTests (exchange, symbol) {
if (!exchange.checkRequiredCredentials (false)) {
dump ('[INFO] Skipping private tests', 'Keys not found');
return;
}
const code = this.getExchangeCode (exchange);
// if (exchange.deepExtendedTest) {
// await test ('InvalidNonce', exchange, symbol);
// await test ('OrderNotFound', exchange, symbol);
// await test ('InvalidOrder', exchange, symbol);
// await test ('InsufficientFunds', exchange, symbol, balance); // danger zone - won't execute with non-empty balance
// }
let tests = {
'signIn': [ ],
'fetchBalance': [ ],
'fetchAccounts': [ ],
'fetchTransactionFees': [ ],
'fetchTradingFees': [ ],
'fetchStatus': [ ],
'fetchOrders': [ symbol ],
'fetchOpenOrders': [ symbol ],
'fetchClosedOrders': [ symbol ],
'fetchMyTrades': [ symbol ],
'fetchLeverageTiers': [ [ symbol ] ],
'fetchLedger': [ code ],
'fetchTransactions': [ code ],
'fetchDeposits': [ code ],
'fetchWithdrawals': [ code ],
'fetchBorrowInterest': [ code, symbol ],
// 'addMargin': [ ],
// 'reduceMargin': [ ],
// 'setMargin': [ ],
// 'setMarginMode': [ ],
// 'setLeverage': [ ],
'cancelAllOrders': [ symbol ],
// 'cancelOrder': [ ],
// 'cancelOrders': [ ],
'fetchCanceledOrders': [ symbol ],
'fetchMarginModes': [ symbol ],
// 'fetchClosedOrder': [ ],
// 'fetchOpenOrder': [ ],
// 'fetchOrder': [ ],
// 'fetchOrderTrades': [ ],
'fetchPosition': [ symbol ],
'fetchDeposit': [ code ],
'createDepositAddress': [ code ],
'fetchDepositAddress': [ code ],
'fetchDepositAddresses': [ code ],
'fetchDepositAddressesByNetwork': [ code ],
// 'editOrder': [ ],
'fetchBorrowRateHistory': [ code ],
'fetchLedgerEntry': [ code ],
// 'fetchWithdrawal': [ ],
// 'transfer': [ ],
// 'withdraw': [ ],
};
if (this.wsTests) {
tests = {
// @ts-ignore
'watchBalance': [ code ],
'watchMyTrades': [ symbol ],
'watchOrders': [ symbol ],
'watchPosition': [ symbol ],
'watchPositions': [ symbol ],
};
}
const market = exchange.market (symbol);
const isSpot = market['spot'];
if (!this.wsTests) {
if (isSpot) {
tests['fetchCurrencies'] = [ ];
} else {
// derivatives only
tests['fetchPositions'] = [ symbol ]; // this test fetches all positions for 1 symbol
tests['fetchPosition'] = [ symbol ];
tests['fetchPositionRisk'] = [ symbol ];
tests['setPositionMode'] = [ symbol ];
tests['setMarginMode'] = [ symbol ];
tests['fetchOpenInterestHistory'] = [ symbol ];
tests['fetchFundingRateHistory'] = [ symbol ];
tests['fetchFundingHistory'] = [ symbol ];
}
}
// const combinedTests = exchange.deepExtend (this.publicTests, privateTests);
await this.runTests (exchange, tests, false);
}
async testProxies (exchange) {
// these tests should be synchronously executed, because of conflicting nature of proxy settings
const proxyTestName = this.proxyTestFileName;
// todo: temporary skip for sync py
if (this.ext === 'py' && this.isSynchronous) {
return;
}
// try proxy several times
const maxRetries = 3;
let exception = undefined;
for (let j = 0; j < maxRetries; j++) {
try {
await this.testMethod (proxyTestName, exchange, [], true);
return; // if successfull, then end the test
} catch (e) {
exception = e;
await exchange.sleep (j * 1000);
}
}
// if exception was set, then throw it
if (exception !== undefined) {
const errorMessage = '[TEST_FAILURE] Failed ' + proxyTestName + ' : ' + exceptionMessage (exception);
// temporary comment the below, because c# transpilation failure
// throw new Exchange Error (errorMessage.toString ());
dump ('[TEST_WARNING]' + errorMessage.toString ());
}
}
async startTest (exchange, symbol) {
// we do not need to test aliases
if (exchange.alias) {
return;
}
if (this.sandbox || getExchangeProp (exchange, 'sandbox')) {
exchange.setSandboxMode (true);
}
// because of python-async, we need proper `.close()` handling
try {
const result = await this.loadExchange (exchange);
if (!result) {
if (!this.isSynchronous) {
await close (exchange);
}
return;
}
// if (exchange.id === 'binance') {
// // we test proxies functionality just for one random exchange on each build, because proxy functionality is not exchange-specific, instead it's all done from base methods, so just one working sample would mean it works for all ccxt exchanges
// // await this.testProxies (exchange);
// }
await this.testExchange (exchange, symbol);
if (!this.isSynchronous) {
await close (exchange);
}
} catch (e) {
if (!this.isSynchronous) {
await close (exchange);
}
throw e;
}
}
assertStaticError (cond:boolean, message: string, calculatedOutput, storedOutput, key = undefined) {
// -----------------------------------------------------------------------------
// --- Init of static tests functions------------------------------------------
// -----------------------------------------------------------------------------
const calculatedString = jsonStringify (calculatedOutput);
const storedString = jsonStringify (storedOutput);
let errorMessage = message + ' computed ' + storedString + ' stored: ' + calculatedString;
if (key !== undefined) {
errorMessage = ' | ' + key + ' | ' + 'computed value: ' + storedString + ' stored value: ' + calculatedString;
}
assert (cond, errorMessage);
}
loadMarketsFromFile (id: string) {
// load markets from file
// to make this test as fast as possible
// and basically independent from the exchange
// so we can run it offline
const filename = this.rootDir + './ts/src/test/static/markets/' + id + '.json';
const content = ioFileRead (filename);
return content;
}
loadCurrenciesFromFile (id: string) {
const filename = this.rootDir + './ts/src/test/static/currencies/' + id + '.json';
const content = ioFileRead (filename);
return content;
}
loadStaticData (folder: string, targetExchange: Str = undefined) {
const result = {};
if (targetExchange) {
// read a single exchange
const path = folder + targetExchange + '.json';
if (!ioFileExists (path)) {
dump ('[WARN] tests not found: ' + path);
return undefined;
}
result[targetExchange] = ioFileRead (path);
return result;
}
const files = ioDirRead (folder);
for (let i = 0; i < files.length; i++) {
const file = files[i];
const exchangeName = file.replace ('.json', '');
const content = ioFileRead (folder + file);
result[exchangeName] = content;
}
return result;
}
removeHostnamefromUrl (url: string) {
if (url === undefined) {
return undefined;
}
const urlParts = url.split ('/');
let res = '';
for (let i = 0; i < urlParts.length; i++) {
if (i > 2) {
const current = urlParts[i];
if (current.indexOf ('?') > -1) {
// handle urls like this: /v1/account/accounts?AccessK
const currentParts = current.split ('?');
res += '/';
res += currentParts[0];
break;
}
res += '/';
res += current;
}
}
return res;
}
urlencodedToDict (url: string) {
const result = {};
const parts = url.split ('&');
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const keyValue = part.split ('=');
const keysLength = keyValue.length;
if (keysLength !== 2) {
continue;
}
const key = keyValue[0];
let value = keyValue[1];
if ((value !== undefined) && ((value.startsWith ('[')) || (value.startsWith ('{')))) {
// some exchanges might return something like this: timestamp=1699382693405&batchOrders=[{\"symbol\":\"LTCUSDT\",\"side\":\"BUY\",\"newClientOrderI
value = jsonParse (value);
}
result[key] = value;
}
return result;
}
assertNewAndStoredOutput (exchange: Exchange, skipKeys: string[], newOutput, storedOutput, strictTypeCheck = true, assertingKey = undefined) {
if (isNullValue (newOutput) && isNullValue (storedOutput)) {
return true;
// c# requirement
}
if (!newOutput && !storedOutput) {
return true;
// c# requirement
}
if ((typeof storedOutput === 'object') && (typeof newOutput === 'object')) {
const storedOutputKeys = Object.keys (storedOutput);
const newOutputKeys = Object.keys (newOutput);
const storedKeysLength = storedOutputKeys.length;
const newKeysLength = newOutputKeys.length;
this.assertStaticError (storedKeysLength === newKeysLength, 'output length mismatch', storedOutput, newOutput);
// iterate over the keys
for (let i = 0; i < storedOutputKeys.length; i++) {
const key = storedOutputKeys[i];
if (exchange.inArray (key, skipKeys)) {
continue;
}
if (!(exchange.inArray (key, newOutputKeys))) {
this.assertStaticError (false, 'output key missing: ' + key, storedOutput, newOutput);
}
const storedValue = storedOutput[key];
const newValue = newOutput[key];
this.assertNewAndStoredOutput (exchange, skipKeys, newValue, storedValue, strictTypeCheck, key);
}
} else if (Array.isArray (storedOutput) && (Array.isArray (newOutput))) {
const storedArrayLength = storedOutput.length;
const newArrayLength = newOutput.length;
this.assertStaticError (storedArrayLength === newArrayLength, 'output length mismatch', storedOutput, newOutput);
for (let i = 0; i < storedOutput.length; i++) {