Skip to content

Commit

Permalink
test: add coverage for mem usage in newArrayValues
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabri3l committed Dec 2, 2024
1 parent 64e01f4 commit a6ac8ae
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 4 deletions.
55 changes: 54 additions & 1 deletion builtin_arrray_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package goja

import "testing"
import (
"context"
"testing"
)

func TestArrayProtoProp(t *testing.T) {
const SCRIPT = `
Expand Down Expand Up @@ -338,3 +341,53 @@ func TestArrayProto(t *testing.T) {
`
testScriptWithTestLib(SCRIPT, _undefined, t)
}

func TestNewArrayValues(t *testing.T) {
for _, tc := range []struct {
name string
memLimit uint64
expectedPanic bool
shouldForceMemCheck bool
}{
{
name: "should not panic when creating a new array under the mem limit",
memLimit: 1000,
expectedPanic: false,
shouldForceMemCheck: false,
},
{
name: "should panic when creating a new array over the mem limit and mem usage check is forced",
memLimit: 0,
expectedPanic: true,
shouldForceMemCheck: true,
},
{
name: "should not panic when creating a new array over the mem limit and mem usage check is not forced",
memLimit: 0,
expectedPanic: false,
shouldForceMemCheck: false,
},
{
name: "should not panic when creating a new array 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)
}
}()
vm := NewWithContext(context.Background(), tc.shouldForceMemCheck)
// Creating a mem usage context so it populates the package variable
NewMemUsageContext(100, tc.memLimit, 100, 100, 0.5, nil)
vm.newArrayValues([]Value{valueInt(0)})
})
}
}
6 changes: 3 additions & 3 deletions mem_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ type MemUsageContext struct {
memoryLimit uint64
}

var memContextMu sync.Mutex
var memContextMu sync.RWMutex
var latestMemUsageContext *MemUsageContext

func NewMemUsageContext(
Expand Down Expand Up @@ -100,8 +100,8 @@ func NewMemUsageContext(
}

func newMemUsageContextClone() *MemUsageContext {
memContextMu.Lock()
defer memContextMu.Unlock()
memContextMu.RLock()
defer memContextMu.RUnlock()
if latestMemUsageContext != nil {
return &MemUsageContext{
visitTracker: visitTracker{objsVisited: make(map[objectImpl]struct{}), stashesVisited: make(map[*stash]struct{})},
Expand Down

0 comments on commit a6ac8ae

Please sign in to comment.