From 346b92c5f2b965b64c55dd8e485cb61c553e8b2e Mon Sep 17 00:00:00 2001 From: LijieZhang1998 Date: Fri, 4 Oct 2024 15:16:40 -0500 Subject: [PATCH] BAAS-33539: add nil check in the builtin_date.go --- builtin_date.go | 7 ++++- builtin_date_test.go | 62 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 builtin_date_test.go diff --git a/builtin_date.go b/builtin_date.go index 305145b8..1118974e 100644 --- a/builtin_date.go +++ b/builtin_date.go @@ -541,7 +541,12 @@ func mkTime(year, m, day, hour, min, sec, nsec int64, loc *time.Location) (t tim } func _intArg(call FunctionCall, argNum int) (int64, bool) { - n := call.Argument(argNum).ToNumber() + arg := call.Argument(argNum) + if arg == nil { + return 0, false + } + + n := arg.ToNumber() if IsNaN(n) { return 0, false } diff --git a/builtin_date_test.go b/builtin_date_test.go new file mode 100644 index 00000000..c9157984 --- /dev/null +++ b/builtin_date_test.go @@ -0,0 +1,62 @@ +package goja + +import ( + "testing" +) + +func TestIntArg(t *testing.T) { + r := New() + for _, tc := range []struct { + description string + argNum int + funcCall FunctionCall + expectedValue int64 + expectedOk bool + }{ + { + description: "should return time value properly", + argNum: 0, + funcCall: FunctionCall{ctx: r.vm.ctx, Arguments: []Value{valueInt(2024)}}, + expectedValue: 2024, + expectedOk: true, + }, + { + description: "should return 0 when one argument is nil", + argNum: 0, + funcCall: FunctionCall{ctx: r.vm.ctx, Arguments: []Value{nil}}, + expectedValue: 0, + expectedOk: false, + }, + { + description: "should return 0 when argument is empty", + argNum: 0, + funcCall: FunctionCall{ctx: r.vm.ctx, Arguments: []Value{}}, + expectedValue: 0, + expectedOk: false, + }, + { + description: "should return 0 when the args field is nil", + argNum: 0, + funcCall: FunctionCall{ctx: r.vm.ctx}, + expectedValue: 0, + expectedOk: false, + }, + } { + t.Run(tc.description, func(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("should not have panic: %v", r) + } + }() + + res, ok := _intArg(tc.funcCall, tc.argNum) + if ok != tc.expectedOk { + t.Fatalf("Expected ok value: %t, actual ok value: %t", tc.expectedOk, ok) + } + if res != tc.expectedValue { + t.Fatalf("Expected time value: %d, actual time value: %d", tc.expectedValue, res) + } + }) + } + +}