Skip to content

Commit d88bd17

Browse files
test: add TestGraphQLParseSchemaAlloc() to better test larger GraphQL schemas
Signed-off-by: Rob Myers <[email protected]>
1 parent b8c49cf commit d88bd17

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Diff for: v1/topdown/graphql_test.go

+75
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import (
88
"context"
99
"fmt"
1010
"os"
11+
"runtime"
12+
"strings"
1113
"testing"
1214

1315
"github.com/open-policy-agent/opa/v1/ast"
@@ -889,3 +891,76 @@ func TestGraphQLParseSchema(t *testing.T) {
889891
})
890892
}
891893
}
894+
895+
func TestGraphQLParseSchemaAlloc(t *testing.T) {
896+
cases := []struct {
897+
note string
898+
schema *ast.Term
899+
maxAlloc uint64
900+
}{
901+
{
902+
note: "default schema",
903+
schema: ast.NewTerm(ast.String(schemaWithExtraEmployeeTypes(0))),
904+
maxAlloc: 1 * 1024 * 1024,
905+
},
906+
// Uncomment when https://github.com/open-policy-agent/opa/pull/7509 is merged
907+
// {
908+
// note: "default schema plus 100 additional types",
909+
// schema: ast.NewTerm(ast.String(schemaWithExtraEmployeeTypes(100))),
910+
// maxAlloc: 10 * 1024 * 1024,
911+
// },
912+
// {
913+
// note: "default schema plus 1,000 additional types",
914+
// schema: ast.NewTerm(ast.String(schemaWithExtraEmployeeTypes(1000))),
915+
// maxAlloc: 100 * 1024 * 1024,
916+
// },
917+
// {
918+
// note: "default schema plus 10,000 additional types",
919+
// schema: ast.NewTerm(ast.String(schemaWithExtraEmployeeTypes(10000))),
920+
// maxAlloc: 1000000,
921+
// },
922+
}
923+
924+
for _, tc := range cases {
925+
926+
t.Run(tc.note, func(t *testing.T) {
927+
928+
var startMemStats runtime.MemStats
929+
runtime.ReadMemStats(&startMemStats)
930+
931+
_ = builtinGraphQLParseSchema(
932+
BuiltinContext{
933+
InterQueryBuiltinValueCache: nil,
934+
},
935+
[]*ast.Term{tc.schema},
936+
func(term *ast.Term) error {
937+
return nil
938+
},
939+
)
940+
941+
var finishMemStats runtime.MemStats
942+
runtime.ReadMemStats(&finishMemStats)
943+
allocDifference := finishMemStats.Alloc - startMemStats.Alloc
944+
runtime.GC()
945+
946+
if allocDifference > tc.maxAlloc {
947+
t.Errorf("Parsing schema '%s' expected alloc < %d, got %d", tc.note, tc.maxAlloc, allocDifference)
948+
return
949+
}
950+
})
951+
}
952+
}
953+
954+
// Inflate GraphQL schema size with `count` extra types
955+
func schemaWithExtraEmployeeTypes(count int) string {
956+
957+
// build up `count` more types on basic schema
958+
var builder strings.Builder
959+
builder.WriteString(employeeGQLSchema)
960+
961+
for range count {
962+
fmt.Fprintf(&builder, "\ntype Employee%d {\n id: String!\n salary: Int!\n}\n", count)
963+
}
964+
965+
return builder.String()
966+
}

0 commit comments

Comments
 (0)