1/* 2 * Copyright (c) 2022 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 16export class ArgumentMatchers { 17 ANY = "<any>"; 18 ANY_STRING = "<any String>"; 19 ANY_BOOLEAN = "<any Boolean>"; 20 ANY_NUMBER = "<any Number>"; 21 ANY_OBJECT = "<any Object>"; 22 ANY_FUNCTION = "<any Function>"; 23 MATCH_REGEXS = "<match regexs>"; 24 25 static any() { 26 } 27 28 static anyString() { 29 } 30 31 static anyBoolean() { 32 } 33 34 static anyNumber() { 35 } 36 37 static anyObj() { 38 } 39 40 static anyFunction() { 41 } 42 43 static matchRegexs(regex: any) { 44 if (ArgumentMatchers.isRegExp(regex)) { 45 return regex; 46 } 47 throw Error("not a regex"); 48 } 49 50 static isRegExp(value: string) { 51 return Object.prototype.toString.call(value) === "[object RegExp]"; 52 } 53 54 matcheReturnKey(...args: Array<any>) { 55 let arg = args[0]; 56 let regex = args[1]; 57 let stubSetKey = args[2]; 58 59 if (stubSetKey && stubSetKey == this.ANY) { 60 return this.ANY; 61 } 62 63 if (typeof arg === "string" && !regex) { 64 return this.ANY_STRING; 65 } 66 67 if (typeof arg === "boolean" && !regex) { 68 return this.ANY_BOOLEAN; 69 } 70 71 if (typeof arg === "number" && !regex) { 72 return this.ANY_NUMBER; 73 } 74 75 if (typeof arg === "object" && !regex) { 76 return this.ANY_OBJECT; 77 } 78 79 if (typeof arg === "function" && !regex) { 80 return this.ANY_FUNCTION; 81 } 82 83 if (typeof arg === "string" && regex) { 84 return regex.test(arg); 85 } 86 87 return null; 88 } 89 90 matcheStubKey(key: any) { 91 92 if (key === ArgumentMatchers.any) { 93 return this.ANY; 94 } 95 96 if (key === ArgumentMatchers.anyString) { 97 return this.ANY_STRING; 98 } 99 if (key === ArgumentMatchers.anyBoolean) { 100 return this.ANY_BOOLEAN; 101 } 102 if (key === ArgumentMatchers.anyNumber) { 103 return this.ANY_NUMBER; 104 } 105 if (key === ArgumentMatchers.anyObj) { 106 return this.ANY_OBJECT; 107 } 108 if (key === ArgumentMatchers.anyFunction) { 109 return this.ANY_FUNCTION; 110 } 111 112 if (ArgumentMatchers.isRegExp(key)) { 113 return key; 114 } 115 116 return null; 117 } 118}