1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
package openapi3
import (
"fmt"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestLoaderReadFromURIFunc(t *testing.T) {
loader := NewLoader()
loader.IsExternalRefsAllowed = true
loader.ReadFromURIFunc = func(loader *Loader, url *url.URL) ([]byte, error) {
return os.ReadFile(filepath.Join("testdata", url.Path))
}
doc, err := loader.LoadFromFile("recursiveRef/openapi.yml")
require.NoError(t, err)
require.NotNil(t, doc)
require.NoError(t, doc.Validate(loader.Context))
require.Equal(t, "bar", doc.
Paths.Value("/foo").
Get.
Responses.Status(200).Value.
Content.Get("application/json").
Schema.Value.
Properties["foo2"].Value.
Properties["foo"].Value.
Properties["bar"].Value.
Example)
}
type multipleSourceLoaderExample struct {
Sources map[string][]byte
}
func (l *multipleSourceLoaderExample) LoadFromURI(
loader *Loader,
location *url.URL,
) ([]byte, error) {
source := l.resolveSourceFromURI(location)
if source == nil {
return nil, fmt.Errorf("unsupported URI: %q", location.String())
}
return source, nil
}
func (l *multipleSourceLoaderExample) resolveSourceFromURI(location fmt.Stringer) []byte {
return l.Sources[location.String()]
}
func TestResolveSchemaExternalRef(t *testing.T) {
rootLocation := &url.URL{Scheme: "http", Host: "example.com", Path: "spec.json"}
externalLocation := &url.URL{Scheme: "http", Host: "example.com", Path: "external.json"}
rootSpec := []byte(fmt.Sprintf(
`{"openapi":"3.0.0","info":{"title":"MyAPI","version":"0.1","description":"An API"},"paths":{},"components":{"schemas":{"Root":{"allOf":[{"$ref":"%s#/components/schemas/External"}]}}}}`,
externalLocation.String(),
))
externalSpec := []byte(`{"openapi":"3.0.0","info":{"title":"MyAPI","version":"0.1","description":"External Spec"},"paths":{},"components":{"schemas":{"External":{"type":"string"}}}}`)
multipleSourceLoader := &multipleSourceLoaderExample{
Sources: map[string][]byte{
rootLocation.String(): rootSpec,
externalLocation.String(): externalSpec,
},
}
loader := &Loader{
IsExternalRefsAllowed: true,
ReadFromURIFunc: multipleSourceLoader.LoadFromURI,
}
doc, err := loader.LoadFromURI(rootLocation)
require.NoError(t, err)
err = doc.Validate(loader.Context)
require.NoError(t, err)
refRootVisited := doc.Components.Schemas["Root"].Value.AllOf[0]
require.Equal(t, fmt.Sprintf("%s#/components/schemas/External", externalLocation.String()), refRootVisited.Ref)
require.NotNil(t, refRootVisited.Value)
}
|