Skip to content

Commit

Permalink
Add memory leak tests
Browse files Browse the repository at this point in the history
  • Loading branch information
myaaaaaaaaa committed Jul 7, 2024
1 parent 0607aa5 commit b5f8645
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
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)
}
})
}
}

0 comments on commit b5f8645

Please sign in to comment.