From 5d0ec2343c047371e228b24ad701c78e7fa47a6f Mon Sep 17 00:00:00 2001 From: Kaushal Madappa Date: Fri, 4 Sep 2020 14:48:00 +0530 Subject: [PATCH] Fix openapi3.referencedDocumentPath (#248) --- openapi3/swagger_loader.go | 23 +++---- ...er_loader_referenced_document_path_test.go | 60 +++++++++++++++++++ 2 files changed, 73 insertions(+), 10 deletions(-) create mode 100644 openapi3/swagger_loader_referenced_document_path_test.go diff --git a/openapi3/swagger_loader.go b/openapi3/swagger_loader.go index 71216a28a..aae028065 100644 --- a/openapi3/swagger_loader.go +++ b/openapi3/swagger_loader.go @@ -876,16 +876,19 @@ func unescapeRefString(ref string) string { } func referencedDocumentPath(documentPath *url.URL, ref string) (*url.URL, error) { - newDocumentPath := documentPath - if documentPath != nil { - refDirectory, err := url.Parse(path.Dir(ref)) - if err != nil { - return nil, err - } - joinedDirectory := path.Join(path.Dir(documentPath.String()), refDirectory.String()) - if newDocumentPath, err = url.Parse(joinedDirectory + "/"); err != nil { - return nil, err - } + if documentPath == nil { + return nil, nil + } + + newDocumentPath, err := copyURL(documentPath) + if err != nil { + return nil, err } + refPath, err := url.Parse(ref) + if err != nil { + return nil, err + } + newDocumentPath.Path = path.Join(path.Dir(newDocumentPath.Path), path.Dir(refPath.Path)) + "/" + return newDocumentPath, nil } diff --git a/openapi3/swagger_loader_referenced_document_path_test.go b/openapi3/swagger_loader_referenced_document_path_test.go new file mode 100644 index 000000000..de219c369 --- /dev/null +++ b/openapi3/swagger_loader_referenced_document_path_test.go @@ -0,0 +1,60 @@ +package openapi3 + +import ( + "net/url" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestReferencedDocumentPath(t *testing.T) { + httpURL, err := url.Parse("http://example.com/path/to/schemas/test1.yaml") + require.NoError(t, err) + + fileURL, err := url.Parse("path/to/schemas/test1.yaml") + require.NoError(t, err) + + refEmpty := "" + refNoComponent := "moreschemas/test2.yaml" + refWithComponent := "moreschemas/test2.yaml#/components/schemas/someobject" + + for _, test := range []struct { + path *url.URL + ref, expected string + }{ + { + path: httpURL, + ref: refEmpty, + expected: "http://example.com/path/to/schemas/", + }, + { + path: httpURL, + ref: refNoComponent, + expected: "http://example.com/path/to/schemas/moreschemas/", + }, + { + path: httpURL, + ref: refWithComponent, + expected: "http://example.com/path/to/schemas/moreschemas/", + }, + { + path: fileURL, + ref: refEmpty, + expected: "path/to/schemas/", + }, + { + path: fileURL, + ref: refNoComponent, + expected: "path/to/schemas/moreschemas/", + }, + { + path: fileURL, + ref: refWithComponent, + expected: "path/to/schemas/moreschemas/", + }, + } { + result, err := referencedDocumentPath(test.path, test.ref) + require.NoError(t, err) + require.Equal(t, test.expected, result.String()) + } +}