Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add memory leak tests #258

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ $(GOBIN)/gocredits:
.PHONY: test
test: build
go test -v -race ./...
MEM_THRESHOLD=20 go test -bench=Leak -benchtime 999999x

.PHONY: lint
lint: $(GOBIN)/staticcheck
Expand Down
53 changes: 53 additions & 0 deletions memory_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package gojq_test

import (
"os"
"runtime"
"strconv"
"strings"
"testing"

"github.com/itchyny/gojq"
)

func BenchmarkMemoryLeak(b *testing.B) {
benchCases := []string{
`range(.) | select(false)`,
`range(.) | if (false) then . else empty end`,
}
const MB = 1024 * 1024
memThreshold := float32(10)
if memEnv := os.Getenv("MEM_THRESHOLD"); memEnv != "" {
num, err := strconv.Atoi(memEnv)
if err != nil {
b.Fatal("MEM_THRESHOLD:", err)
}
memThreshold = float32(num)
}
memThreshold *= MB
for _, bc := range benchCases {
query, err := gojq.Parse(bc)
if err != nil {
b.Fatal(err)
}
b.Run(strings.ReplaceAll(bc, " ", ""), func(b *testing.B) {
var memStats runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&memStats)
memUsage1 := float32(memStats.HeapAlloc)
iter := query.Run(b.N)
for {
_, ok := iter.Next()
if !ok {
break
}
}
runtime.ReadMemStats(&memStats)
memUsage2 := float32(memStats.HeapAlloc)
b.Logf("%.1f MB => %.1f MB (%d iterations)", memUsage1/MB, memUsage2/MB, b.N)
if memUsage2-memUsage1 > memThreshold {
b.Errorf("MEM_THRESHOLD (%.0f MB) passed, failing...", memThreshold/MB)
}
})
}
}
Loading