Skip to content

Commit

Permalink
Schema leak (#522)
Browse files Browse the repository at this point in the history
* remove s.schemas in doRemoveSchema

* add tests for addSchema

* use slices pkg to search for candidates

---------

Co-authored-by: joshmeranda <[email protected]>
  • Loading branch information
joshmeranda and joshmeranda authored Nov 25, 2024
1 parent 6fe644a commit b4a72e5
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 5 deletions.
16 changes: 11 additions & 5 deletions types/schemas.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"reflect"
"slices"
"strings"
"sync"

Expand Down Expand Up @@ -84,6 +85,10 @@ func (s *Schemas) doRemoveSchema(schema Schema) *Schemas {
s.removeEmbed(&schema)
}

s.schemas = slices.DeleteFunc(s.schemas, func(candidate *Schema) bool {
return candidate.ID == schema.ID
})

return s
}

Expand Down Expand Up @@ -136,11 +141,12 @@ func (s *Schemas) doAddSchema(schema Schema, replace bool) *Schemas {
schemas[schema.ID] = &schema

if replace {
for i, candidate := range s.schemas {
if candidate.ID == schema.ID {
s.schemas[i] = &schema
break
}
i := slices.IndexFunc(s.schemas, func(candidate *Schema) bool {
return candidate.ID == schema.ID
})

if i >= 0 {
s.schemas[i] = &schema
}
} else {
s.schemas = append(s.schemas, &schema)
Expand Down
76 changes: 76 additions & 0 deletions types/schemas_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package types

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestSchemas(t *testing.T) {
version := APIVersion{
Group: "meta.cattle.io",
Version: "v1",
Path: "/shire",
}

s := NewSchemas().
AddSchema(Schema{
ID: "baggins",
PluralName: "bagginses",
Version: version,
CollectionMethods: []string{},
ResourceMethods: []string{},
ResourceFields: map[string]Field{},
}).
AddSchema(Schema{
ID: "hobbit",
PluralName: "hobbits",
Embed: true,
EmbedType: "baggins",
Version: version,
CollectionMethods: []string{},
ResourceMethods: []string{},
ResourceFields: map[string]Field{
"breakfasts": {Type: "int"},
"name": {Type: "string"},
},
})

expected := []*Schema{
{
ID: "hobbit",
PluralName: "hobbits",
Embed: true,
EmbedType: "baggins",
Version: version,
CollectionMethods: []string{},
ResourceMethods: []string{},
ResourceFields: map[string]Field{
"breakfasts": {Type: "int"},
"name": {Type: "string"},
},
CodeName: "Hobbit",
CodeNamePlural: "Hobbits",
BaseType: "hobbit",
Type: "/meta/schemas/schema",
},
{
ID: "baggins",
PluralName: "bagginses",
Version: version,
CollectionMethods: []string{},
ResourceMethods: []string{},
ResourceFields: map[string]Field{
"breakfasts": {Type: "int"},
"name": {Type: "string"},
},
CodeName: "Baggins",
CodeNamePlural: "Bagginses",
BaseType: "baggins",
Type: "/meta/schemas/schema",
},
}
actual := s.Schemas()

assert.ElementsMatch(t, expected, actual)
}

0 comments on commit b4a72e5

Please sign in to comment.