more unit tests

This commit is contained in:
Yann Hamon 2020-06-06 16:32:27 +02:00
parent 0d2da2d582
commit cdcacb080d
2 changed files with 149 additions and 0 deletions

View file

@ -0,0 +1,46 @@
package registry
import (
"testing"
)
func TestSchemaURL(t *testing.T) {
for i, testCase := range []struct {
resourceKind, resourceAPIVersion, k8sVersion, expected string
strict bool
}{
{
"Deployment",
"apps/v1",
"1.16.0",
"https://kubernetesjsonschema.dev/v1.16.0-standalone-strict/deployment-apps-v1.json",
true,
},
{
"Deployment",
"apps/v1",
"1.16.0",
"https://kubernetesjsonschema.dev/v1.16.0-standalone/deployment-apps-v1.json",
false,
},
{
"Service",
"v1",
"1.18.0",
"https://kubernetesjsonschema.dev/v1.18.0-standalone/service-v1.json",
false,
},
{
"Service",
"v1",
"master",
"https://kubernetesjsonschema.dev/master-standalone/service-v1.json",
false,
},
} {
reg := NewKubernetesRegistry(testCase.strict)
if got := reg.schemaURL(testCase.resourceKind, testCase.resourceAPIVersion, testCase.k8sVersion); got != testCase.expected {
t.Errorf("%d - got %s, expected %s", i+1, got, testCase.expected)
}
}
}

View file

@ -0,0 +1,103 @@
package validator
import (
"fmt"
"github.com/xeipuuv/gojsonschema"
"testing"
)
func TestValidate(t *testing.T) {
for i, testCase := range []struct {
name string
rawResource, schema []byte
expect error
}{
{
"valid resource",
[]byte(`
firstName: foo
lastName: bar
`),
[]byte(`{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}`),
nil,
},
{
"invalid resource",
[]byte(`
firstName: foo
lastName: bar
`),
[]byte(`{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "number"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}`),
fmt.Errorf("Invalid type. Expected: number, given: string"),
},
{
"resource has invalid yaml",
[]byte(`
firstName foo
lastName: bar
`),
[]byte(`{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "number"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}`),
fmt.Errorf("error unmarshalling resource: error converting YAML to JSON: yaml: line 3: mapping values are not allowed in this context"),
},
} {
schema, err := gojsonschema.NewSchema(gojsonschema.NewBytesLoader(testCase.schema))
if err != nil {
t.Errorf("failed parsing test schema")
}
if got := Validate(testCase.rawResource, schema); ((got == nil) != (testCase.expect == nil)) || (got != nil && (got.Error() != testCase.expect.Error())) {
t.Errorf("%d - expected %s, got %s", i, testCase.expect, got)
}
}
}