Skip to content

Commit

Permalink
fix: openapiExamplesFromProtoExamples for yaml [grpc-ecosystem#3095]
Browse files Browse the repository at this point in the history
  • Loading branch information
hedhyw committed Jan 5, 2023
1 parent 8f97225 commit 3ade9c8
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
2 changes: 1 addition & 1 deletion protoc-gen-openapiv2/internal/genopenapi/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -2768,7 +2768,7 @@ func openapiExamplesFromProtoExamples(in map[string]string) map[string]interface
switch mimeType {
case "application/json":
// JSON example objects are rendered raw.
out[mimeType] = json.RawMessage(exampleStr)
out[mimeType] = RawExample(exampleStr)
default:
// All other mimetype examples are rendered as strings.
out[mimeType] = exampleStr
Expand Down
48 changes: 48 additions & 0 deletions protoc-gen-openapiv2/internal/genopenapi/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,54 @@ import (

var marshaler = &runtime.JSONPb{}

func TestOpenapiExamplesFromProtoExamples(t *testing.T) {
examples := openapiExamplesFromProtoExamples(map[string]string{
"application/json": `{"Hello": "Worldr!"}`,
"plain/text": "Hello, World!",
})

testCases := map[Format]string{
FormatJSON: `
{
"application/json": {
"Hello": "Worldr!"
},
"plain/text": "Hello, World!"
}
`,
FormatYAML: `
application/json:
Hello: Worldr!
plain/text: Hello, World!
`,
}

spaceRemover := strings.NewReplacer(" ", "", "\t", "", "\n", "")

for format, expected := range testCases {
t.Run(string(format), func(t *testing.T) {
var buf bytes.Buffer

encoder, err := format.NewEncoder(&buf)
if err != nil {
t.Fatalf("creating encoder: %s", err)
}

err = encoder.Encode(examples)
if err != nil {
t.Fatalf("encoding: %s", err)
}

actual := spaceRemover.Replace(buf.String())
expected = spaceRemover.Replace(expected)

if expected != actual {
t.Fatalf("expected:\n%s\nactual:\n%s", expected, actual)
}
})
}
}

func crossLinkFixture(f *descriptor.File) *descriptor.File {
for _, m := range f.Messages {
m.File = f
Expand Down

0 comments on commit 3ade9c8

Please sign in to comment.