Add unit-test for generateOpenAPISchema

Added title for all fields and added unit-test for generateOpenAPISchema FixOpenSchema,
This commit is contained in:
zzxwill
2021-01-06 14:34:17 +08:00
parent 775991cfaa
commit 2243632d0c
2 changed files with 15 additions and 20 deletions

View File

@@ -22,7 +22,7 @@ const (
// UsageTag is usage comment annotation
UsageTag = "+usage="
// ShortTag is the short alias annotation
ShortTag = "\\n+short"
ShortTag = "\n+short"
)
// OpenAPISchema is the struct for OpenAPI Schema generated by Cue OpenAPI
@@ -159,32 +159,22 @@ func fixOpenAPISchema(name string, schema *openapi3.Schema) {
fixOpenAPISchema(k, s)
}
case "array":
if name != "" {
schema.Title = name
}
fixOpenAPISchema("", schema.Items.Value)
default:
if name != "" {
schema.Title = name
}
}
if name != "" {
schema.Title = name
}
line := schema.Description
if strings.Contains(line, UsageTag) {
newDescription := strings.ReplaceAll(line, UsageTag, "")
if strings.Contains(newDescription, ShortTag) {
newDescription = strings.ReplaceAll(newDescription, ShortTag, "")
newDescription = strings.Split(newDescription, ShortTag)[0]
}
schema.Description = newDescription
}
}
// addTitleField adds title field
func addTitleField(line, propertyName string) string {
blanks := strings.Split(line, "\"")[0]
title := fmt.Sprintf("%s\"title\": \"%s\"", blanks, propertyName)
return title + ",\n"
}
// getParameterItemName gets the name of a parameter item
func getParameterItemName(previousLine string) (string, error) {
// parse property name, like from `"cmd": {\n`

View File

@@ -8,6 +8,8 @@ import (
"strings"
"testing"
"github.com/getkin/kin-openapi/openapi3"
"github.com/crossplane/crossplane-runtime/pkg/test"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
@@ -156,10 +158,13 @@ func TestAppendCueReference(t *testing.T) {
os.RemoveAll(temporaryDir)
}
func TestAddTitleField(t *testing.T) {
got := addTitleField(" \"description\": \"cpu core\"", "cpu")
title := " \"title\": \"cpu\",\n"
assert.Equal(t, title, got)
func TestFixOpenAPISchema(t *testing.T) {
swagger, _ := openapi3.NewSwaggerLoader().LoadSwaggerFromFile(filepath.Join(TestDir, "webservice.json"))
schema := swagger.Components.Schemas["parameter"].Value
fixOpenAPISchema("", schema)
fixedSchema, _ := schema.MarshalJSON()
expectedSchema, _ := ioutil.ReadFile(filepath.Join(TestDir, "webserviceFixed.json"))
assert.Equal(t, fixedSchema, expectedSchema)
}
func TestGetParameterItemName(t *testing.T) {