Skip to content

Commit ceae068

Browse files
authored
Fix openapi3.referencedDocumentPath (#248)
1 parent 2392e46 commit ceae068

2 files changed

Lines changed: 73 additions & 10 deletions

File tree

openapi3/swagger_loader.go

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -876,16 +876,19 @@ func unescapeRefString(ref string) string {
876876
}
877877

878878
func referencedDocumentPath(documentPath *url.URL, ref string) (*url.URL, error) {
879-
newDocumentPath := documentPath
880-
if documentPath != nil {
881-
refDirectory, err := url.Parse(path.Dir(ref))
882-
if err != nil {
883-
return nil, err
884-
}
885-
joinedDirectory := path.Join(path.Dir(documentPath.String()), refDirectory.String())
886-
if newDocumentPath, err = url.Parse(joinedDirectory + "/"); err != nil {
887-
return nil, err
888-
}
879+
if documentPath == nil {
880+
return nil, nil
881+
}
882+
883+
newDocumentPath, err := copyURL(documentPath)
884+
if err != nil {
885+
return nil, err
889886
}
887+
refPath, err := url.Parse(ref)
888+
if err != nil {
889+
return nil, err
890+
}
891+
newDocumentPath.Path = path.Join(path.Dir(newDocumentPath.Path), path.Dir(refPath.Path)) + "/"
892+
890893
return newDocumentPath, nil
891894
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package openapi3
2+
3+
import (
4+
"net/url"
5+
"testing"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func TestReferencedDocumentPath(t *testing.T) {
11+
httpURL, err := url.Parse("http://example.com/path/to/schemas/test1.yaml")
12+
require.NoError(t, err)
13+
14+
fileURL, err := url.Parse("path/to/schemas/test1.yaml")
15+
require.NoError(t, err)
16+
17+
refEmpty := ""
18+
refNoComponent := "moreschemas/test2.yaml"
19+
refWithComponent := "moreschemas/test2.yaml#/components/schemas/someobject"
20+
21+
for _, test := range []struct {
22+
path *url.URL
23+
ref, expected string
24+
}{
25+
{
26+
path: httpURL,
27+
ref: refEmpty,
28+
expected: "http://example.com/path/to/schemas/",
29+
},
30+
{
31+
path: httpURL,
32+
ref: refNoComponent,
33+
expected: "http://example.com/path/to/schemas/moreschemas/",
34+
},
35+
{
36+
path: httpURL,
37+
ref: refWithComponent,
38+
expected: "http://example.com/path/to/schemas/moreschemas/",
39+
},
40+
{
41+
path: fileURL,
42+
ref: refEmpty,
43+
expected: "path/to/schemas/",
44+
},
45+
{
46+
path: fileURL,
47+
ref: refNoComponent,
48+
expected: "path/to/schemas/moreschemas/",
49+
},
50+
{
51+
path: fileURL,
52+
ref: refWithComponent,
53+
expected: "path/to/schemas/moreschemas/",
54+
},
55+
} {
56+
result, err := referencedDocumentPath(test.path, test.ref)
57+
require.NoError(t, err)
58+
require.Equal(t, test.expected, result.String())
59+
}
60+
}

0 commit comments

Comments
 (0)