From a939617a95218299e66ff532a1b697f3f88781a4 Mon Sep 17 00:00:00 2001 From: Glen Van Ginkel Date: Sat, 10 Oct 2020 19:55:14 +0100 Subject: [PATCH] Type check optional arguments --- src/Runtime.ts | 4 +--- test/jmespath.spec.js | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/Runtime.ts b/src/Runtime.ts index 029ba0e..d19985c 100644 --- a/src/Runtime.ts +++ b/src/Runtime.ts @@ -102,11 +102,9 @@ export class Runtime { let currentSpec: InputArgument[]; let actualType: InputArgument; let typeMatched: boolean; - let isOptional: boolean; for (let i = 0; i < signature.length; i += 1) { typeMatched = false; currentSpec = signature[i].types; - isOptional = signature[i].optional ?? false; actualType = this.getTypeName(args[i]) as InputArgument; let j: number; for (j = 0; j < currentSpec.length; j += 1) { @@ -115,7 +113,7 @@ export class Runtime { break; } } - if (!typeMatched && !isOptional) { + if (!typeMatched && actualType !== undefined) { const expected = currentSpec .map((typeIdentifier): string => { return this.TYPE_NAME_TABLE[typeIdentifier]; diff --git a/test/jmespath.spec.js b/test/jmespath.spec.js index effd0af..f83792d 100644 --- a/test/jmespath.spec.js +++ b/test/jmespath.spec.js @@ -240,7 +240,7 @@ describe('registerFunction', () => { () => { /* EMPTY FUNCTION */ }, - [{ types: [jmespath.TYPE_ANY] }], + [{ types: [jmespath.TYPE_ANY] }, { types: [jmespath.TYPE_NUMBER], optional: true }], ); expect(() => search( @@ -250,7 +250,25 @@ describe('registerFunction', () => { }, 'tooFewArgs()', ), - ).toThrow('ArgumentError: tooFewArgs() takes 1 argument but received 0'); + ).toThrow('ArgumentError: tooFewArgs() takes 1 arguments but received 0'); + expect(() => + search( + { + foo: 60, + bar: 10, + }, + 'tooFewArgs(foo, @)', + ), + ).toThrow('TypeError: tooFewArgs() expected argument 2 to be type (number) but received type object instead.'); + expect(() => + search( + { + foo: 60, + bar: 10, + }, + 'tooFewArgs(foo, `2`, @)', + ), + ).toThrow('ArgumentError: tooFewArgs() takes 1 arguments but received 3'); }); it('alerts too many arguments', () => { registerFunction(