Skip to content

Commit

Permalink
test: add coverage for mem check on setOwnStr
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabri3l committed Dec 2, 2024
1 parent a6ac8ae commit e17fb0e
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
2 changes: 1 addition & 1 deletion object.go
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ func (o *baseObject) setOwnStr(name unistring.String, val Value, throw bool) boo
o.val.runtime.typeErrorResult(throw, "Cannot add property %s, object is not extensible", name)
return false
} else {
if o.val.runtime.shouldForceMemCheck {
if o.val != nil && o.val.runtime != nil && o.val.runtime.shouldForceMemCheck {
memCtx := newMemUsageContextClone()
if memCtx != nil {
memUsage, err := val.MemUsage(memCtx)
Expand Down
61 changes: 61 additions & 0 deletions object_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package goja

import (
"context"
"fmt"
"reflect"
"strings"
Expand Down Expand Up @@ -829,3 +830,63 @@ func TestPrimitiveValueObjectMemUsage(t *testing.T) {
})
}
}

func TestSetOwnStr(t *testing.T) {
for _, tc := range []struct {
name string
memLimit uint64
expectedPanic bool
shouldForceMemCheck bool
}{
{
name: "should not panic when setting a value in an object",
memLimit: 1000,
expectedPanic: false,
shouldForceMemCheck: false,
},
{
name: "should panic when setting a value in an object over the mem limit and mem usage check is forced",
memLimit: 0,
expectedPanic: true,
shouldForceMemCheck: true,
},
{
name: "should not panic when setting a value in an object over the mem limit and mem usage check is not forced",
memLimit: 0,
expectedPanic: false,
shouldForceMemCheck: false,
},
{
name: "should not panic when setting a value in an object under the mem limit and mem usage check is forced",
memLimit: 1000,
expectedPanic: false,
shouldForceMemCheck: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
defer func() {
r := recover()
if tc.expectedPanic && r == nil {
t.Error("The code is expected to panic, but it didn't")
}
if !tc.expectedPanic && r != nil {
t.Errorf("The code panicked, but it should not have: %v", r)
}
}()
v := &Object{
runtime: NewWithContext(context.Background(), tc.shouldForceMemCheck),
}
o := &baseObject{
val: v,
extensible: true,
}
o.init()
v.self = o

// Creating a mem usage context so it populates the package variable
NewMemUsageContext(100, tc.memLimit, 100, 100, 0.5, nil)

o.setOwnStr("test", valueInt(123), false)
})
}
}

0 comments on commit e17fb0e

Please sign in to comment.