Skip to content

Commit

Permalink
feat: Example/SchemaExample: allow \r \n \t
Browse files Browse the repository at this point in the history
  • Loading branch information
mschneider82 committed Mar 8, 2022
1 parent 334111b commit 69276ee
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
16 changes: 14 additions & 2 deletions operation.go
Expand Up @@ -535,6 +535,17 @@ func setDefault(param *spec.Parameter, schemaType string, value string) error {
return nil
}

var unescaper = strings.NewReplacer(`\r`, "\r", `\n`, "\n", `\t`, "\t")

// unescapeExample replaces \r \n \t in example string values
func unescapeExample(val interface{}) (example interface{}) {
example = val
if str, ok := val.(string); ok {
example = unescaper.Replace(str)
}
return
}

func setSchemaExample(param *spec.Parameter, schemaType string, value string) error {
val, err := defineType(schemaType, value)
if err != nil {
Expand All @@ -544,7 +555,8 @@ func setSchemaExample(param *spec.Parameter, schemaType string, value string) er
if param.Schema == nil {
return nil
}
param.Schema.Example = val

param.Schema.Example = unescapeExample(val)
return nil
}

Expand All @@ -553,7 +565,7 @@ func setExample(param *spec.Parameter, schemaType string, value string) error {
if err != nil {
return nil // Don't set a example value if it's not valid
}
param.Example = val
param.Example = unescapeExample(val)
return nil
}

Expand Down
12 changes: 9 additions & 3 deletions operation_test.go
Expand Up @@ -1880,6 +1880,9 @@ func TestParseParamCommentByExampleUnsupportedType(t *testing.T) {

setExample(&param, NUMBER, "10")
assert.Equal(t, param.Example, float64(10))

setExample(&param, STRING, "string \\nvalue")
assert.Equal(t, param.Example, "string \nvalue")
}

func TestParseParamCommentBySchemaExampleString(t *testing.T) {
Expand Down Expand Up @@ -1918,13 +1921,16 @@ func TestParseParamCommentBySchemaExampleUnsupportedType(t *testing.T) {

param.Schema = &spec.Schema{}
setSchemaExample(&param, STRING, "string value")
assert.Equal(t, param.Schema.Example, "string value")
assert.Equal(t, "string value", param.Schema.Example)

setSchemaExample(&param, INTEGER, "10")
assert.Equal(t, param.Schema.Example, 10)
assert.Equal(t, 10, param.Schema.Example)

setSchemaExample(&param, NUMBER, "10")
assert.Equal(t, param.Schema.Example, float64(10))
assert.Equal(t, float64(10), param.Schema.Example)

setSchemaExample(&param, STRING, "string \\r\\nvalue")
assert.Equal(t, "string \r\nvalue", param.Schema.Example)
}

func TestParseParamArrayWithEnums(t *testing.T) {
Expand Down

0 comments on commit 69276ee

Please sign in to comment.