From 3d92fc0b1a3cde8b5066c797bb4bfd2d2d73c59c Mon Sep 17 00:00:00 2001 From: Marcel Boehm Date: Tue, 7 May 2024 16:00:13 +0200 Subject: [PATCH] Fix RenderAndReload error handling --- document.go | 11 +++++------ document_test.go | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/document.go b/document.go index 742f7f7f..98aa9f42 100644 --- a/document.go +++ b/document.go @@ -198,21 +198,20 @@ func (d *document) Serialize() ([]byte, error) { } func (d *document) RenderAndReload() ([]byte, Document, *DocumentModel[v3high.Document], []error) { - newBytes, rerr := d.Render() if rerr != nil { return nil, nil, nil, []error{rerr} } - var errs []error - newDoc, err := NewDocumentWithConfiguration(newBytes, d.config) - errs = append(errs, err) + if err != nil { + return nil, nil, nil, []error{err} + } // build the model. m, buildErrs := newDoc.BuildV3Model() - if buildErrs != nil { - return newBytes, newDoc, m, errs + if len(buildErrs) > 0 { + return newBytes, newDoc, m, buildErrs } // this document is now dead, long live the new document! return newBytes, newDoc, m, nil diff --git a/document_test.go b/document_test.go index 9a5118b2..e45feb9d 100644 --- a/document_test.go +++ b/document_test.go @@ -345,6 +345,29 @@ func TestDocument_RenderAndReload(t *testing.T) { h.Components.SecuritySchemes.GetOrZero("petstore_auth").Flows.Implicit.AuthorizationUrl) } +func TestDocument_RenderAndReload_WithErrors(t *testing.T) { + // load an OpenAPI 3 specification from bytes + petstore, _ := os.ReadFile("test_specs/petstorev3.json") + + // create a new document from specification bytes + doc, err := NewDocument(petstore) + // if anything went wrong, an error is thrown + if err != nil { + panic(fmt.Sprintf("cannot create new document: %e", err)) + } + + // because we know this is a v3 spec, we can build a ready to go model from it. + m, _ := doc.BuildV3Model() + + // Remove a schema to make the model invalid + _, present := m.Model.Components.Schemas.Delete("Pet") + assert.True(t, present, "expected schema Pet to exist") + + _, _, _, errors := doc.RenderAndReload() + assert.Len(t, errors, 2) + assert.Equal(t, errors[0].Error(), "component '#/components/schemas/Pet' does not exist in the specification") +} + func TestDocument_Render(t *testing.T) { // load an OpenAPI 3 specification from bytes petstore, _ := os.ReadFile("test_specs/petstorev3.json")