1/* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16// helpers for test 17// place this is the tsconfig.json files section _before_ 18// any actual test cases 19 20var tcaseCount = 0; 21var testCount = 0; 22 23function initTest(): void { 24 tcaseCount = 0; 25 testCount = 0; 26} 27 28function reportTestResults(): void { 29 console.debug(`\nPassed all ${tcaseCount} cases / ${testCount} test asertions !`); 30 initTest(); 31} 32 33/* 34 How to structure project tests: 35 A project can have several tsuites, 36 a tsuite can have several tcases, 37 a tcase can make several test (asertions) 38 39 An own file per tsuite is recommeneded 40 index_test.ts calls all tsuites. 41*/ 42 43function tsuite(msg: string, testMe: () => void): () => void { 44 const msg1 = msg; 45 const testMe1 = testMe; 46 return function () { 47 console.debug(`\n\n====== ${msg1}`); 48 testMe1(); 49 console.debug(`\n`); 50 } 51} 52 53function tcase(msg: string, testMe: () => void): void { 54 console.debug(`\n------ ${msg}`); 55 testMe(); 56 tcaseCount++; 57} 58 59function test(msg: string, asertion: boolean): void { 60 if (!asertion) { 61 console.error(`Failed: '${msg}'.`); 62 process.exit(-1); 63 } 64 console.debug(`Passed: '${msg}'.`); 65 testCount++ 66} 67 68/* 69 use to intercept a function call on an object to asert is was called 70 use returned object { called: boolean, args: 'arguments' of call } 71 to forumate 'test' clauses 72 */ 73function spyOn(source: Object, funcName: string): { called: boolean, args: any[] } { 74 const origFunc = source[funcName]; 75 const source1 = source; 76 const sourceDescr = source.constructor ? source.constructor.name : "unknown object"; 77 let accessRecord = { called: false, args: undefined }; 78 source[funcName] = function () { 79 console.debug(`SpyOn: ----- '${funcName}' on '${sourceDescr}' about to be called, ${arguments.length} arguments ...`); 80 origFunc.call(source1, ...arguments); 81 accessRecord.called = true; 82 accessRecord.args = /* deep copy */ JSON.parse(JSON.stringify(arguments)); 83 console.debug(`SpyOn: ----- '${funcName}' on '${sourceDescr}' done!`); 84 }; 85 return accessRecord; 86} 87 88 89function eqSet(as, bs) { 90 if (as.size !== bs.size) return false; 91 for (var a of as) if (!bs.has(a)) return false; 92 return true; 93} 94