Skip to content

Commit

Permalink
Merge pull request #126 from LijieZhang1998/baas-33539
Browse files Browse the repository at this point in the history
BAAS-33539: Add nil check in the builtin_date.go
  • Loading branch information
LijieZhang1998 authored Oct 7, 2024
2 parents 1023e46 + 346b92c commit 476c6e0
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
7 changes: 6 additions & 1 deletion builtin_date.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
62 changes: 62 additions & 0 deletions builtin_date_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}

}

0 comments on commit 476c6e0

Please sign in to comment.