Fix the dependency issue (#231)

This commit is contained in:
Robbie Zhang
2018-06-21 12:09:42 -07:00
committed by GitHub
parent 027b76651d
commit 6ec1098bb8
16629 changed files with 74837 additions and 4975021 deletions

View File

@@ -1,117 +0,0 @@
## Contribution Guidelines
### Pull requests are always welcome
We are always thrilled to receive pull requests, and do our best to
process them as fast as possible. Not sure if that typo is worth a pull
request? Do it! We will appreciate it.
If your pull request is not accepted on the first try, don't be
discouraged! If there's a problem with the implementation, hopefully you
received feedback on what to improve.
We're trying very hard to keep go-swagger lean and focused. We don't want it
to do everything for everybody. This means that we might decide against
incorporating a new feature. However, there might be a way to implement
that feature *on top of* go-swagger.
### Conventions
Fork the repo and make changes on your fork in a feature branch:
- If it's a bugfix branch, name it XXX-something where XXX is the number of the
issue
- If it's a feature branch, create an enhancement issue to announce your
intentions, and name it XXX-something where XXX is the number of the issue.
Submit unit tests for your changes. Go has a great test framework built in; use
it! Take a look at existing tests for inspiration. Run the full test suite on
your branch before submitting a pull request.
Update the documentation when creating or modifying features. Test
your documentation changes for clarity, concision, and correctness, as
well as a clean documentation build. See ``docs/README.md`` for more
information on building the docs and how docs get released.
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
committing your changes. Most editors have plugins that do this automatically.
Pull requests descriptions should be as clear as possible and include a
reference to all the issues that they address.
Pull requests must not contain commits from other users or branches.
Commit messages must start with a capitalized and short summary (max. 50
chars) written in the imperative, followed by an optional, more detailed
explanatory text which is separated from the summary by an empty line.
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Be
sure to post a comment after pushing. The new commits will show up in the pull
request automatically, but the reviewers will not be notified unless you
comment.
Before the pull request is merged, make sure that you squash your commits into
logical units of work using `git rebase -i` and `git push -f`. After every
commit the test suite should be passing. Include documentation changes in the
same commit so that a revert would remove all traces of the feature or fix.
Commits that fix or close an issue should include a reference like `Closes #XXX`
or `Fixes #XXX`, which will automatically close the issue when merged.
### Sign your work
The sign-off is a simple line at the end of the explanation for the
patch, which certifies that you wrote it or otherwise have the right to
pass it on as an open-source patch. The rules are pretty simple: if you
can certify the below (from
[developercertificate.org](http://developercertificate.org/)):
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
then you just add a line to every git commit message:
Signed-off-by: Joe Smith <joe@gmail.com>
using your real name (sorry, no pseudonyms or anonymous contributions.)
You can add the sign off when creating the git commit via `git commit -s`.

View File

@@ -1,3 +0,0 @@
secrets.yml
coverage.out
.idea

View File

@@ -1,18 +0,0 @@
language: go
go:
- 1.7
install:
- go get -u github.com/stretchr/testify/assert
- go get -u gopkg.in/yaml.v2
- go get -u github.com/go-openapi/swag
- go get -u github.com/go-openapi/jsonpointer
- go get -u github.com/go-openapi/spec
- go get -u github.com/go-openapi/strfmt
- go get -u github.com/go-openapi/loads/fmts
script:
- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./...
after_success:
- bash <(curl -s https://codecov.io/bash)
notifications:
slack:
secure: Sf7kZf7ZGbnwWUMpffHwMu5A0cHkLK2MYY32LNTPj4+/3qC3Ghl7+9v4TSLOqOlCwdRNjOGblAq7s+GDJed6/xgRQl1JtCi1klzZNrYX4q01pgTPvvGcwbBkIYgeMaPeIRcK9OZnud7sRXdttozgTOpytps2U6Js32ip7uj5mHSg2ub0FwoSJwlS6dbezZ8+eDhoha0F/guY99BEwx8Bd+zROrT2TFGsSGOFGN6wFc7moCqTHO/YkWib13a2QNXqOxCCVBy/lt76Wp+JkeFppjHlzs/2lP3EAk13RIUAaesdEUHvIHrzCyNJEd3/+KO2DzsWOYfpktd+KBCvgaYOsoo7ubdT3IROeAegZdCgo/6xgCEsmFc9ZcqCfN5yNx2A+BZ2Vwmpws+bQ1E1+B5HDzzaiLcYfG4X2O210QVGVDLWsv1jqD+uPYeHY2WRfh5ZsIUFvaqgUEnwHwrK44/8REAhQavt1QAj5uJpsRd7CkRVPWRNK+yIky+wgbVUFEchRNmS55E7QWf+W4+4QZkQi7vUTMc9nbTUu2Es9NfvfudOpM2wZbn98fjpb/qq/nRv6Bk+ca+7XD5/IgNLMbWp2ouDdzbiHLCOfDUiHiDJhLfFZx9Bwo7ZwfzeOlbrQX66bx7xRKYmOe4DLrXhNcpbsMa8qbfxlZRCmYbubB/Y8h4=

View File

@@ -1,74 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at ivan+abuse@flanders.co.nz. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -1,6 +0,0 @@
# OpenAPI initiative analysis [![Build Status](https://travis-ci.org/go-openapi/analysis.svg?branch=master)](https://travis-ci.org/go-openapi/analysis) [![codecov](https://codecov.io/gh/go-openapi/analysis/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/analysis) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io)
[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/analysis/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/analysis?status.svg)](http://godoc.org/github.com/go-openapi/analysis)
A foundational library to analyze an OAI specification document for easier reasoning about the content.

View File

@@ -1,284 +0,0 @@
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package analysis
import (
"encoding/json"
"fmt"
"path/filepath"
"sort"
"testing"
"github.com/go-openapi/loads/fmts"
"github.com/go-openapi/spec"
"github.com/go-openapi/swag"
"github.com/stretchr/testify/assert"
)
func schemeNames(schemes []SecurityRequirement) []string {
var names []string
for _, v := range schemes {
names = append(names, v.Name)
}
sort.Sort(sort.StringSlice(names))
return names
}
func TestAnalyzer(t *testing.T) {
formatParam := spec.QueryParam("format").Typed("string", "")
limitParam := spec.QueryParam("limit").Typed("integer", "int32")
limitParam.Extensions = spec.Extensions(map[string]interface{}{})
limitParam.Extensions.Add("go-name", "Limit")
skipParam := spec.QueryParam("skip").Typed("integer", "int32")
pi := spec.PathItem{}
pi.Parameters = []spec.Parameter{*limitParam}
op := &spec.Operation{}
op.Consumes = []string{"application/x-yaml"}
op.Produces = []string{"application/x-yaml"}
op.Security = []map[string][]string{
map[string][]string{"oauth2": []string{}},
map[string][]string{"basic": nil},
}
op.ID = "someOperation"
op.Parameters = []spec.Parameter{*skipParam}
pi.Get = op
pi2 := spec.PathItem{}
pi2.Parameters = []spec.Parameter{*limitParam}
op2 := &spec.Operation{}
op2.ID = "anotherOperation"
op2.Parameters = []spec.Parameter{*skipParam}
pi2.Get = op2
spec := &spec.Swagger{
SwaggerProps: spec.SwaggerProps{
Consumes: []string{"application/json"},
Produces: []string{"application/json"},
Security: []map[string][]string{
map[string][]string{"apikey": nil},
},
SecurityDefinitions: map[string]*spec.SecurityScheme{
"basic": spec.BasicAuth(),
"apiKey": spec.APIKeyAuth("api_key", "query"),
"oauth2": spec.OAuth2AccessToken("http://authorize.com", "http://token.com"),
},
Parameters: map[string]spec.Parameter{"format": *formatParam},
Paths: &spec.Paths{
Paths: map[string]spec.PathItem{
"/": pi,
"/items": pi2,
},
},
},
}
analyzer := New(spec)
assert.Len(t, analyzer.consumes, 2)
assert.Len(t, analyzer.produces, 2)
assert.Len(t, analyzer.operations, 1)
assert.Equal(t, analyzer.operations["GET"]["/"], spec.Paths.Paths["/"].Get)
expected := []string{"application/x-yaml"}
sort.Sort(sort.StringSlice(expected))
consumes := analyzer.ConsumesFor(spec.Paths.Paths["/"].Get)
sort.Sort(sort.StringSlice(consumes))
assert.Equal(t, expected, consumes)
produces := analyzer.ProducesFor(spec.Paths.Paths["/"].Get)
sort.Sort(sort.StringSlice(produces))
assert.Equal(t, expected, produces)
expected = []string{"application/json"}
sort.Sort(sort.StringSlice(expected))
consumes = analyzer.ConsumesFor(spec.Paths.Paths["/items"].Get)
sort.Sort(sort.StringSlice(consumes))
assert.Equal(t, expected, consumes)
produces = analyzer.ProducesFor(spec.Paths.Paths["/items"].Get)
sort.Sort(sort.StringSlice(produces))
assert.Equal(t, expected, produces)
expectedSchemes := []SecurityRequirement{SecurityRequirement{"oauth2", []string{}}, SecurityRequirement{"basic", nil}}
schemes := analyzer.SecurityRequirementsFor(spec.Paths.Paths["/"].Get)
assert.Equal(t, schemeNames(expectedSchemes), schemeNames(schemes))
securityDefinitions := analyzer.SecurityDefinitionsFor(spec.Paths.Paths["/"].Get)
assert.Equal(t, securityDefinitions["basic"], *spec.SecurityDefinitions["basic"])
assert.Equal(t, securityDefinitions["oauth2"], *spec.SecurityDefinitions["oauth2"])
parameters := analyzer.ParamsFor("GET", "/")
assert.Len(t, parameters, 2)
operations := analyzer.OperationIDs()
assert.Len(t, operations, 2)
producers := analyzer.RequiredProduces()
assert.Len(t, producers, 2)
consumers := analyzer.RequiredConsumes()
assert.Len(t, consumers, 2)
authSchemes := analyzer.RequiredSecuritySchemes()
assert.Len(t, authSchemes, 3)
ops := analyzer.Operations()
assert.Len(t, ops, 1)
assert.Len(t, ops["GET"], 2)
op, ok := analyzer.OperationFor("get", "/")
assert.True(t, ok)
assert.NotNil(t, op)
op, ok = analyzer.OperationFor("delete", "/")
assert.False(t, ok)
assert.Nil(t, op)
}
func TestDefinitionAnalysis(t *testing.T) {
doc, err := loadSpec(filepath.Join("fixtures", "definitions.yml"))
if assert.NoError(t, err) {
analyzer := New(doc)
definitions := analyzer.allSchemas
// parameters
assertSchemaRefExists(t, definitions, "#/parameters/someParam/schema")
assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/parameters/1/schema")
assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/parameters/1/schema")
// responses
assertSchemaRefExists(t, definitions, "#/responses/someResponse/schema")
assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/responses/default/schema")
assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/responses/200/schema")
// definitions
assertSchemaRefExists(t, definitions, "#/definitions/tag")
assertSchemaRefExists(t, definitions, "#/definitions/tag/properties/id")
assertSchemaRefExists(t, definitions, "#/definitions/tag/properties/value")
assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category")
assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category/properties/id")
assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category/properties/value")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalProps")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalProps/additionalProperties")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/items/0")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/items/1")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/additionalItems")
assertSchemaRefExists(t, definitions, "#/definitions/withNot")
assertSchemaRefExists(t, definitions, "#/definitions/withNot/not")
assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf")
assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf/anyOf/0")
assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf/anyOf/1")
assertSchemaRefExists(t, definitions, "#/definitions/withAllOf")
assertSchemaRefExists(t, definitions, "#/definitions/withAllOf/allOf/0")
assertSchemaRefExists(t, definitions, "#/definitions/withAllOf/allOf/1")
allOfs := analyzer.allOfs
assert.Len(t, allOfs, 1)
assert.Contains(t, allOfs, "#/definitions/withAllOf")
}
}
func loadSpec(path string) (*spec.Swagger, error) {
spec.PathLoader = func(path string) (json.RawMessage, error) {
ext := filepath.Ext(path)
if ext == ".yml" || ext == ".yaml" {
return fmts.YAMLDoc(path)
}
data, err := swag.LoadFromFileOrHTTP(path)
if err != nil {
return nil, err
}
return json.RawMessage(data), nil
}
data, err := fmts.YAMLDoc(path)
if err != nil {
return nil, err
}
var sw spec.Swagger
if err := json.Unmarshal(data, &sw); err != nil {
return nil, err
}
return &sw, nil
}
func TestReferenceAnalysis(t *testing.T) {
doc, err := loadSpec(filepath.Join("fixtures", "references.yml"))
if assert.NoError(t, err) {
definitions := New(doc).references
// parameters
assertRefExists(t, definitions.parameters, "#/paths/~1some~1where~1{id}/parameters/0")
assertRefExists(t, definitions.parameters, "#/paths/~1some~1where~1{id}/get/parameters/0")
// path items
assertRefExists(t, definitions.pathItems, "#/paths/~1other~1place")
// responses
assertRefExists(t, definitions.responses, "#/paths/~1some~1where~1{id}/get/responses/404")
// definitions
assertRefExists(t, definitions.schemas, "#/responses/notFound/schema")
assertRefExists(t, definitions.schemas, "#/paths/~1some~1where~1{id}/get/responses/200/schema")
assertRefExists(t, definitions.schemas, "#/definitions/tag/properties/audit")
// items
assertRefExists(t, definitions.allRefs, "#/paths/~1some~1where~1{id}/get/parameters/1/items")
}
}
func assertRefExists(t testing.TB, data map[string]spec.Ref, key string) bool {
if _, ok := data[key]; !ok {
return assert.Fail(t, fmt.Sprintf("expected %q to exist in the ref bag", key))
}
return true
}
func assertSchemaRefExists(t testing.TB, data map[string]SchemaRef, key string) bool {
if _, ok := data[key]; !ok {
return assert.Fail(t, fmt.Sprintf("expected %q to exist in schema ref bag", key))
}
return true
}
func TestPatternAnalysis(t *testing.T) {
doc, err := loadSpec(filepath.Join("fixtures", "patterns.yml"))
if assert.NoError(t, err) {
pt := New(doc).patterns
// parameters
assertPattern(t, pt.parameters, "#/parameters/idParam", "a[A-Za-Z0-9]+")
assertPattern(t, pt.parameters, "#/paths/~1some~1where~1{id}/parameters/1", "b[A-Za-z0-9]+")
assertPattern(t, pt.parameters, "#/paths/~1some~1where~1{id}/get/parameters/0", "[abc][0-9]+")
// responses
assertPattern(t, pt.headers, "#/responses/notFound/headers/ContentLength", "[0-9]+")
assertPattern(t, pt.headers, "#/paths/~1some~1where~1{id}/get/responses/200/headers/X-Request-Id", "d[A-Za-z0-9]+")
// definitions
assertPattern(t, pt.schemas, "#/paths/~1other~1place/post/parameters/0/schema/properties/value", "e[A-Za-z0-9]+")
assertPattern(t, pt.schemas, "#/paths/~1other~1place/post/responses/200/schema/properties/data", "[0-9]+[abd]")
assertPattern(t, pt.schemas, "#/definitions/named", "f[A-Za-z0-9]+")
assertPattern(t, pt.schemas, "#/definitions/tag/properties/value", "g[A-Za-z0-9]+")
// items
assertPattern(t, pt.items, "#/paths/~1some~1where~1{id}/get/parameters/1/items", "c[A-Za-z0-9]+")
assertPattern(t, pt.items, "#/paths/~1other~1place/post/responses/default/headers/Via/items", "[A-Za-z]+")
}
}
func assertPattern(t testing.TB, data map[string]string, key, pattern string) bool {
if assert.Contains(t, data, key) {
return assert.Equal(t, pattern, data[key])
}
return false
}

View File

@@ -1,43 +0,0 @@
---
swagger: "2.0"
info:
version: "0.1.0"
title: allOf analysis
paths:
"/some/where/{id}":
parameters:
- name: id
in: path
type: integer
format: int32
- name: bodyId
in: body
schema:
type: object
get:
parameters:
- name: limit
in: query
type: integer
format: int32
required: false
- name: body
in: body
schema:
type: object
responses:
default:
schema:
type: object
200:
schema:
type: object
definitions:
tag:
type: object
properties:
id:
type: integer
format: int64
value:
type: string

View File

@@ -1,86 +0,0 @@
---
swagger: "2.0"
info:
version: "0.1.0"
title: Definition analysis
parameters:
someParam:
name: someParam
in: body
schema:
type: object
responses:
someResponse:
schema:
type: object
paths:
"/some/where/{id}":
parameters:
- name: id
in: path
type: integer
format: int32
- name: bodyId
in: body
schema:
type: object
get:
parameters:
- name: limit
in: query
type: integer
format: int32
required: false
- name: body
in: body
schema:
type: object
responses:
default:
schema:
type: object
200:
schema:
type: object
definitions:
tag:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
definitions:
category:
type: object
properties:
id:
type: integer
format: int32
value:
type: string
withAdditionalProps:
type: object
additionalProperties:
type: boolean
withAdditionalItems:
type: array
items:
- type: string
- type: bool
additionalItems:
type: integer
format: int32
withNot:
type: object
not:
$ref: "#/definitions/tag"
withAnyOf:
anyOf:
- type: object
- type: string
withAllOf:
allOf:
- type: object
- type: string

View File

@@ -1,50 +0,0 @@
definitions:
named:
type: string
tag:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
audit:
$ref: "#/definitions/record"
record:
type: object
properties:
createdAt:
type: string
format: date-time
nestedThing:
type: object
properties:
record:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
- allOf:
- type: string
format: date
- type: object
additionalProperties:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
properties:
value:
type: string
name:
$ref: "definitions2.yml#/coordinate"

View File

@@ -1,9 +0,0 @@
coordinate:
type: object
properties:
id:
type: integer
format: int64
createdAt:
type: string
format: date-time

View File

@@ -1,13 +0,0 @@
error:
type: object
required:
- id
- message
properties:
id:
type: integer
format: int64
readOnly: true
message:
type: string
readOnly: true

View File

@@ -1,35 +0,0 @@
bodyParam:
name: body
in: body
schema:
type: object
properties:
record:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
- allOf:
- type: string
format: date
- type: object
properties:
id:
type: integer
format: int64
value:
type: string
name:
type: object
properties:
id:
type: integer
format: int64
createdAt:
type: string
format: date-time

View File

@@ -1,32 +0,0 @@
genericResponse:
type: object
properties:
record:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
- allOf:
- type: string
format: date
- type: object
properties:
id:
type: integer
format: int64
value:
type: string
name:
type: object
properties:
id:
type: integer
format: int64
createdAt:
type: string
format: date-time

View File

@@ -1,12 +0,0 @@
parameters:
idParam:
name: id
in: path
type: integer
format: int32
limitParam:
name: limit
in: query
type: integer
format: int32
required: false

View File

@@ -1,9 +0,0 @@
get:
operationId: modelOp
summary: many model variations
description: Used to see if a codegen can render all the possible parameter variations for a header param
tags:
- testcgen
responses:
default:
description: Generic Out

View File

@@ -1,4 +0,0 @@
responses:
notFound:
schema:
$ref: "errors.yml#/error"

View File

@@ -1,95 +0,0 @@
---
swagger: "2.0"
info:
version: "0.1.0"
title: reference analysis
parameters:
someParam:
name: someParam
in: body
schema:
$ref: "external/definitions.yml#/definitions/record"
responses:
someResponse:
schema:
$ref: "external/definitions.yml#/definitions/record"
paths:
"/some/where/{id}":
parameters:
- $ref: "external/parameters.yml#/parameters/idParam"
- name: bodyId
in: body
schema:
$ref: "external/definitions.yml#/definitions/record"
get:
parameters:
- $ref: "external/parameters.yml#/parameters/limitParam"
- name: other
in: query
type: array
items:
$ref: "external/definitions.yml#/definitions/named"
- name: body
in: body
schema:
$ref: "external/definitions.yml#/definitions/record"
responses:
default:
schema:
$ref: "external/definitions.yml#/definitions/record"
404:
$ref: "external/responses.yml#/responses/notFound"
200:
schema:
$ref: "external/definitions.yml#/definitions/tag"
"/other/place":
$ref: "external/pathItem.yml"
definitions:
namedAgain:
$ref: "external/definitions.yml#/definitions/named"
datedTag:
allOf:
- type: string
format: date
- $ref: "external/definitions.yml#/definitions/tag"
records:
type: array
items:
- $ref: "external/definitions.yml#/definitions/record"
datedRecords:
type: array
items:
- type: string
format: date-time
- $ref: "external/definitions.yml#/definitions/record"
datedTaggedRecords:
type: array
items:
- type: string
format: date-time
- $ref: "external/definitions.yml#/definitions/record"
additionalItems:
$ref: "external/definitions.yml#/definitions/tag"
otherRecords:
type: array
items:
$ref: "external/definitions.yml#/definitions/record"
tags:
type: object
additionalProperties:
$ref: "external/definitions.yml#/definitions/tag"
namedThing:
type: object
properties:
name:
$ref: "external/definitions.yml#/definitions/named"

View File

@@ -1,85 +0,0 @@
---
swagger: "2.0"
info:
version: "0.1.0"
title: reference analysis
parameters:
someParam:
name: some
in: query
type: string
responses:
notFound:
description: "Not Found"
schema:
$ref: "external/errors.yml#/error"
paths:
"/some/where/{id}":
parameters:
- $ref: "external/parameters.yml#/parameters/idParam"
get:
parameters:
- $ref: "external/parameters.yml#/parameters/limitParam"
- $ref: "#/parameters/someParam"
- name: other
in: query
type: string
- $ref: "external/nestedParams.yml#/bodyParam"
responses:
default:
$ref: "external/nestedResponses.yml#/genericResponse"
404:
$ref: "#/responses/notFound"
200:
description: "RecordHolder"
schema:
type: object
properties:
record:
$ref: "external/definitions.yml#/definitions/nestedThing"
"/other/place":
$ref: "external/pathItem.yml"
definitions:
namedAgain:
$ref: "external/definitions.yml#/definitions/named"
datedTag:
allOf:
- type: string
format: date
- $ref: "external/definitions.yml#/definitions/tag"
records:
type: array
items:
- $ref: "external/definitions.yml#/definitions/record"
datedRecords:
type: array
items:
- type: string
format: date-time
- $ref: "external/definitions.yml#/definitions/record"
otherRecords:
type: array
items:
$ref: "external/definitions.yml#/definitions/record"
tags:
type: object
additionalProperties:
$ref: "external/definitions.yml#/definitions/tag"
namedThing:
type: object
properties:
name:
$ref: "external/definitions.yml#/definitions/named"
namedAgain:
$ref: "#/definitions/namedAgain"

View File

@@ -1,187 +0,0 @@
---
swagger: "2.0"
info:
version: "0.1.0"
title: reference analysis
parameters:
someParam:
name: someParam
in: body
schema:
type: object
properties:
createdAt:
type: string
format: date-time
responses:
someResponse:
schema:
type: object
properties:
createdAt:
type: string
format: date-time
paths:
"/some/where/{id}":
parameters:
- name: id
in: path
type: integer
format: int32
- name: bodyId
in: body
schema:
type: object
properties:
createdAt:
type: string
format: date-time
post:
responses:
default:
description: all good
get:
parameters:
- name: limit
in: query
type: integer
format: int32
required: false
- name: other
in: query
type: array
items:
type: object
properties:
id:
type: integer
format: int64
- name: body
in: body
schema:
type: object
properties:
createdAt:
type: string
format: date-time
responses:
default:
schema:
type: object
properties:
createdAt:
type: string
format: date-time
404:
schema:
$ref: "errors.yml#/error"
200:
schema:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
"/other/place":
$ref: "external/pathItem.yml"
definitions:
namedAgain:
type: object
properties:
id:
type: integer
format: int64
datedTag:
allOf:
- type: string
format: date
- type: object
properties:
id:
type: integer
format: int64
value:
type: string
records:
type: array
items:
- type: object
properties:
createdAt:
type: string
format: date-time
datedRecords:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
datedTaggedRecords:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
additionalItems:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
otherRecords:
type: array
items:
type: object
properties:
createdAt:
type: string
format: date-time
tags:
type: object
additionalProperties:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
namedThing:
type: object
properties:
name:
type: object
properties:
id:
type: integer
format: int64
# depth first should have this at the bottom, it's just a very long name
pneumonoultramicroscopicsilicovolcanoconiosisAntidisestablishmentarianism:
type: object
properties:
floccinaucinihilipilificationCreatedAt:
type: integer
format: int64

View File

@@ -1,298 +0,0 @@
---
swagger: "2.0"
info:
version: "0.1.0"
title: reference analysis
parameters:
someParam:
name: someParam
in: body
schema:
type: object
properties:
createdAt:
type: string
format: date-time
responses:
someResponse:
schema:
type: object
properties:
createdAt:
type: string
format: date-time
paths:
"/some/where/{id}":
parameters:
- name: id
in: path
type: integer
format: int32
- name: bodyId
in: body
schema:
type: array
items:
type: object
properties:
createdAt:
type: string
format: date-time
post:
responses:
default:
description: all good
get:
parameters:
- name: limit
in: query
type: integer
format: int32
required: false
- name: other
in: query
type: array
items:
type: object
properties:
id:
type: integer
format: int64
- name: body
in: body
schema:
type: object
properties:
record:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
- allOf:
- type: string
format: date
- type: object
properties:
id:
type: integer
format: int64
value:
type: string
name:
type: object
properties:
id:
type: integer
format: int64
createdAt:
type: string
format: date-time
responses:
default:
schema:
type: object
properties:
record:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
- allOf:
- type: string
format: date
- type: object
properties:
id:
type: integer
format: int64
value:
type: string
name:
type: object
properties:
id:
type: integer
format: int64
createdAt:
type: string
format: date-time
404:
schema:
$ref: "errors.yml#/error"
200:
schema:
type: object
properties:
record:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
- allOf:
- type: string
format: date
- type: object
properties:
id:
type: integer
format: int64
value:
type: string
name:
type: object
properties:
id:
type: integer
format: int64
createdAt:
type: string
format: date-time
"/other/place":
$ref: "external/pathItem.yml"
definitions:
namedAgain:
type: object
properties:
id:
type: integer
format: int64
datedTag:
allOf:
- type: string
format: date
- type: object
properties:
id:
type: integer
format: int64
value:
type: string
records:
type: array
items:
- type: object
properties:
createdAt:
type: string
format: date-time
datedRecords:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
datedTaggedRecords:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
additionalItems:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
otherRecords:
type: array
items:
type: object
properties:
createdAt:
type: string
format: date-time
tags:
type: object
additionalProperties:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
namedThing:
type: object
properties:
name:
type: object
properties:
id:
type: integer
format: int64
nestedThing:
type: object
properties:
record:
type: array
items:
- type: string
format: date-time
- type: object
properties:
createdAt:
type: string
format: date-time
- allOf:
- type: string
format: date
- type: object
additionalProperties:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
properties:
id:
type: integer
format: int64
value:
type: string
name:
type: object
properties:
id:
type: integer
format: int64
createdAt:
type: string
format: date-time

View File

@@ -1,124 +0,0 @@
---
swagger: "2.0"
info:
version: "0.1.0"
title: reference analysis
parameters:
idParam:
name: id
in: path
type: string
pattern: 'a[A-Za-Z0-9]+'
responses:
notFound:
headers:
ContentLength:
type: string
pattern: '[0-9]+'
schema:
$ref: "#/definitions/error"
paths:
"/some/where/{id}":
parameters:
- $ref: "#/parameters/idParam"
- name: name
in: query
pattern: 'b[A-Za-z0-9]+'
- name: bodyId
in: body
schema:
type: object
get:
parameters:
- name: filter
in: query
type: string
pattern: "[abc][0-9]+"
- name: other
in: query
type: array
items:
type: string
pattern: 'c[A-Za-z0-9]+'
- name: body
in: body
schema:
type: object
responses:
default:
schema:
type: object
404:
$ref: "#/responses/notFound"
200:
headers:
X-Request-Id:
type: string
pattern: 'd[A-Za-z0-9]+'
schema:
$ref: "#/definitions/tag"
"/other/place":
post:
parameters:
- name: body
in: body
schema:
type: object
properties:
value:
type: string
pattern: 'e[A-Za-z0-9]+'
responses:
default:
headers:
Via:
type: array
items:
type: string
pattern: '[A-Za-z]+'
200:
schema:
type: object
properties:
data:
type: string
pattern: "[0-9]+[abd]"
definitions:
named:
type: string
pattern: 'f[A-Za-z0-9]+'
tag:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
pattern: 'g[A-Za-z0-9]+'
audit:
$ref: "#/definitions/record"
record:
type: object
properties:
createdAt:
type: string
format: date-time
error:
type: object
required:
- id
- message
properties:
id:
type: integer
format: int64
readOnly: true
message:
type: string
readOnly: true

View File

@@ -1,89 +0,0 @@
---
swagger: "2.0"
info:
version: "0.1.0"
title: reference analysis
parameters:
idParam:
name: id
in: path
type: integer
format: int32
limitParam:
name: limit
in: query
type: integer
format: int32
required: false
responses:
notFound:
schema:
$ref: "#/definitions/error"
paths:
"/some/where/{id}":
parameters:
- $ref: "#/parameters/idParam"
- name: bodyId
in: body
schema:
type: object
get:
parameters:
- $ref: "#/parameters/limitParam"
- name: other
in: query
type: array
items:
$ref: "#/definitions/named"
- name: body
in: body
schema:
type: object
responses:
default:
schema:
type: object
404:
$ref: "#/responses/notFound"
200:
schema:
$ref: "#/definitions/tag"
"/other/place":
$ref: "#/x-shared-path/getItems"
definitions:
named:
type: string
tag:
type: object
properties:
id:
type: integer
format: int64
value:
type: string
audit:
$ref: "#/definitions/record"
record:
type: object
properties:
createdAt:
type: string
format: date-time
error:
type: object
required:
- id
- message
properties:
id:
type: integer
format: int64
readOnly: true
message:
type: string
readOnly: true

View File

@@ -1,805 +0,0 @@
package analysis
import (
"path/filepath"
"strings"
"testing"
"github.com/go-openapi/jsonpointer"
"github.com/go-openapi/spec"
"github.com/stretchr/testify/assert"
)
func TestSaveDefinition(t *testing.T) {
sp := &spec.Swagger{}
saveSchema(sp, "theName", spec.StringProperty())
assert.Contains(t, sp.Definitions, "theName")
}
func TestNameFromRef(t *testing.T) {
values := []struct{ Source, Expected string }{
{"#/definitions/errorModel", "errorModel"},
{"http://somewhere.com/definitions/errorModel", "errorModel"},
{"http://somewhere.com/definitions/errorModel.json", "errorModel"},
{"/definitions/errorModel", "errorModel"},
{"/definitions/errorModel.json", "errorModel"},
{"http://somewhere.com", "somewhereCom"},
{"#", ""},
}
for _, v := range values {
assert.Equal(t, v.Expected, nameFromRef(spec.MustCreateRef(v.Source)))
}
}
func TestDefinitionName(t *testing.T) {
values := []struct {
Source, Expected string
Definitions spec.Definitions
}{
{"#/definitions/errorModel", "errorModel", map[string]spec.Schema(nil)},
{"http://somewhere.com/definitions/errorModel", "errorModel", map[string]spec.Schema(nil)},
{"#/definitions/errorModel", "errorModel", map[string]spec.Schema{"apples": *spec.StringProperty()}},
{"#/definitions/errorModel", "errorModelOAIGen", map[string]spec.Schema{"errorModel": *spec.StringProperty()}},
{"#/definitions/errorModel", "errorModelOAIGen1", map[string]spec.Schema{"errorModel": *spec.StringProperty(), "errorModelOAIGen": *spec.StringProperty()}},
{"#", "oaiGen", nil},
}
for _, v := range values {
assert.Equal(t, v.Expected, uniqifyName(v.Definitions, nameFromRef(spec.MustCreateRef(v.Source))))
}
}
func TestUpdateRef(t *testing.T) {
bp := filepath.Join("fixtures", "external_definitions.yml")
sp, err := loadSpec(bp)
if assert.NoError(t, err) {
values := []struct {
Key string
Ref spec.Ref
}{
{"#/parameters/someParam/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/parameters/1/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema", spec.MustCreateRef("#/definitions/record")},
{"#/responses/someResponse/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/namedAgain", spec.MustCreateRef("#/definitions/named")},
{"#/definitions/datedTag/allOf/1", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/datedRecords/items/1", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/datedTaggedRecords/items/1", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/datedTaggedRecords/additionalItems", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/otherRecords/items", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/tags/additionalProperties", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/namedThing/properties/name", spec.MustCreateRef("#/definitions/named")},
}
for _, v := range values {
err := updateRef(sp, v.Key, v.Ref)
if assert.NoError(t, err) {
ptr, err := jsonpointer.New(v.Key[1:])
if assert.NoError(t, err) {
vv, _, err := ptr.Get(sp)
if assert.NoError(t, err) {
switch tv := vv.(type) {
case *spec.Schema:
assert.Equal(t, v.Ref.String(), tv.Ref.String())
case spec.Schema:
assert.Equal(t, v.Ref.String(), tv.Ref.String())
case *spec.SchemaOrBool:
assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String())
case *spec.SchemaOrArray:
assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String())
default:
assert.Fail(t, "unknown type", "got %T", vv)
}
}
}
}
}
}
}
func TestImportExternalReferences(t *testing.T) {
bp := filepath.Join(".", "fixtures", "external_definitions.yml")
sp, err := loadSpec(bp)
if assert.NoError(t, err) {
values := []struct {
Key string
Ref spec.Ref
}{
{"#/parameters/someParam/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/parameters/1/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema", spec.MustCreateRef("#/definitions/record")},
{"#/responses/someResponse/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/namedAgain", spec.MustCreateRef("#/definitions/named")},
{"#/definitions/datedTag/allOf/1", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/datedRecords/items/1", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/datedTaggedRecords/items/1", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/datedTaggedRecords/additionalItems", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/otherRecords/items", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/tags/additionalProperties", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/namedThing/properties/name", spec.MustCreateRef("#/definitions/named")},
}
for _, v := range values {
// technically not necessary to run for each value, but if things go right
// this is idempotent, so having it repeat shouldn't matter
// this validates that behavior
err := importExternalReferences(&FlattenOpts{
Spec: New(sp),
BasePath: bp,
})
if assert.NoError(t, err) {
ptr, err := jsonpointer.New(v.Key[1:])
if assert.NoError(t, err) {
vv, _, err := ptr.Get(sp)
if assert.NoError(t, err) {
switch tv := vv.(type) {
case *spec.Schema:
assert.Equal(t, v.Ref.String(), tv.Ref.String(), "for %s", v.Key)
case spec.Schema:
assert.Equal(t, v.Ref.String(), tv.Ref.String(), "for %s", v.Key)
case *spec.SchemaOrBool:
assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String(), "for %s", v.Key)
case *spec.SchemaOrArray:
assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String(), "for %s", v.Key)
default:
assert.Fail(t, "unknown type", "got %T", vv)
}
}
}
}
}
assert.Len(t, sp.Definitions, 11)
assert.Contains(t, sp.Definitions, "tag")
assert.Contains(t, sp.Definitions, "named")
assert.Contains(t, sp.Definitions, "record")
}
}
func TestRewriteSchemaRef(t *testing.T) {
bp := filepath.Join("fixtures", "inline_schemas.yml")
sp, err := loadSpec(bp)
if assert.NoError(t, err) {
values := []struct {
Key string
Ref spec.Ref
}{
{"#/parameters/someParam/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/parameters/1/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema", spec.MustCreateRef("#/definitions/record")},
{"#/responses/someResponse/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema", spec.MustCreateRef("#/definitions/record")},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/namedAgain", spec.MustCreateRef("#/definitions/named")},
{"#/definitions/datedTag/allOf/1", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/datedRecords/items/1", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/datedTaggedRecords/items/1", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/datedTaggedRecords/additionalItems", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/otherRecords/items", spec.MustCreateRef("#/definitions/record")},
{"#/definitions/tags/additionalProperties", spec.MustCreateRef("#/definitions/tag")},
{"#/definitions/namedThing/properties/name", spec.MustCreateRef("#/definitions/named")},
}
for i, v := range values {
err := rewriteSchemaToRef(sp, v.Key, v.Ref)
if assert.NoError(t, err) {
ptr, err := jsonpointer.New(v.Key[1:])
if assert.NoError(t, err) {
vv, _, err := ptr.Get(sp)
if assert.NoError(t, err) {
switch tv := vv.(type) {
case *spec.Schema:
assert.Equal(t, v.Ref.String(), tv.Ref.String(), "at %d for %s", i, v.Key)
case spec.Schema:
assert.Equal(t, v.Ref.String(), tv.Ref.String(), "at %d for %s", i, v.Key)
case *spec.SchemaOrBool:
assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String(), "at %d for %s", i, v.Key)
case *spec.SchemaOrArray:
assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String(), "at %d for %s", i, v.Key)
default:
assert.Fail(t, "unknown type", "got %T", vv)
}
}
}
}
}
}
}
func TestSplitKey(t *testing.T) {
type KeyFlag uint64
const (
isOperation KeyFlag = 1 << iota
isDefinition
isSharedOperationParam
isOperationParam
isOperationResponse
isDefaultResponse
isStatusCodeResponse
)
values := []struct {
Key string
Flags KeyFlag
PathItemRef spec.Ref
PathRef spec.Ref
Name string
}{
{
"#/paths/~1some~1where~1{id}/parameters/1/schema",
isOperation | isSharedOperationParam,
spec.Ref{},
spec.MustCreateRef("#/paths/~1some~1where~1{id}"),
"",
},
{
"#/paths/~1some~1where~1{id}/get/parameters/2/schema",
isOperation | isOperationParam,
spec.MustCreateRef("#/paths/~1some~1where~1{id}/GET"),
spec.MustCreateRef("#/paths/~1some~1where~1{id}"),
"",
},
{
"#/paths/~1some~1where~1{id}/get/responses/default/schema",
isOperation | isOperationResponse | isDefaultResponse,
spec.MustCreateRef("#/paths/~1some~1where~1{id}/GET"),
spec.MustCreateRef("#/paths/~1some~1where~1{id}"),
"Default",
},
{
"#/paths/~1some~1where~1{id}/get/responses/200/schema",
isOperation | isOperationResponse | isStatusCodeResponse,
spec.MustCreateRef("#/paths/~1some~1where~1{id}/GET"),
spec.MustCreateRef("#/paths/~1some~1where~1{id}"),
"OK",
},
{
"#/definitions/namedAgain",
isDefinition,
spec.Ref{},
spec.Ref{},
"namedAgain",
},
{
"#/definitions/datedRecords/items/1",
isDefinition,
spec.Ref{},
spec.Ref{},
"datedRecords",
},
{
"#/definitions/datedRecords/items/1",
isDefinition,
spec.Ref{},
spec.Ref{},
"datedRecords",
},
{
"#/definitions/datedTaggedRecords/items/1",
isDefinition,
spec.Ref{},
spec.Ref{},
"datedTaggedRecords",
},
{
"#/definitions/datedTaggedRecords/additionalItems",
isDefinition,
spec.Ref{},
spec.Ref{},
"datedTaggedRecords",
},
{
"#/definitions/otherRecords/items",
isDefinition,
spec.Ref{},
spec.Ref{},
"otherRecords",
},
{
"#/definitions/tags/additionalProperties",
isDefinition,
spec.Ref{},
spec.Ref{},
"tags",
},
{
"#/definitions/namedThing/properties/name",
isDefinition,
spec.Ref{},
spec.Ref{},
"namedThing",
},
}
for i, v := range values {
parts := keyParts(v.Key)
pref := parts.PathRef()
piref := parts.PathItemRef()
assert.Equal(t, v.PathRef.String(), pref.String(), "pathRef: %s at %d", v.Key, i)
assert.Equal(t, v.PathItemRef.String(), piref.String(), "pathItemRef: %s at %d", v.Key, i)
if v.Flags&isOperation != 0 {
assert.True(t, parts.IsOperation(), "isOperation: %s at %d", v.Key, i)
} else {
assert.False(t, parts.IsOperation(), "isOperation: %s at %d", v.Key, i)
}
if v.Flags&isDefinition != 0 {
assert.True(t, parts.IsDefinition(), "isDefinition: %s at %d", v.Key, i)
assert.Equal(t, v.Name, parts.DefinitionName(), "definition name: %s at %d", v.Key, i)
} else {
assert.False(t, parts.IsDefinition(), "isDefinition: %s at %d", v.Key, i)
if v.Name != "" {
assert.Equal(t, v.Name, parts.ResponseName(), "response name: %s at %d", v.Key, i)
}
}
if v.Flags&isOperationParam != 0 {
assert.True(t, parts.IsOperationParam(), "isOperationParam: %s at %d", v.Key, i)
} else {
assert.False(t, parts.IsOperationParam(), "isOperationParam: %s at %d", v.Key, i)
}
if v.Flags&isSharedOperationParam != 0 {
assert.True(t, parts.IsSharedOperationParam(), "isSharedOperationParam: %s at %d", v.Key, i)
} else {
assert.False(t, parts.IsSharedOperationParam(), "isSharedOperationParam: %s at %d", v.Key, i)
}
if v.Flags&isOperationResponse != 0 {
assert.True(t, parts.IsOperationResponse(), "isOperationResponse: %s at %d", v.Key, i)
} else {
assert.False(t, parts.IsOperationResponse(), "isOperationResponse: %s at %d", v.Key, i)
}
if v.Flags&isDefaultResponse != 0 {
assert.True(t, parts.IsDefaultResponse(), "isDefaultResponse: %s at %d", v.Key, i)
} else {
assert.False(t, parts.IsDefaultResponse(), "isDefaultResponse: %s at %d", v.Key, i)
}
if v.Flags&isStatusCodeResponse != 0 {
assert.True(t, parts.IsStatusCodeResponse(), "isStatusCodeResponse: %s at %d", v.Key, i)
} else {
assert.False(t, parts.IsStatusCodeResponse(), "isStatusCodeResponse: %s at %d", v.Key, i)
}
}
}
func definitionPtr(key string) string {
if !strings.HasPrefix(key, "#/definitions") {
return key
}
return strings.Join(strings.Split(key, "/")[:3], "/")
}
func TestNamesFromKey(t *testing.T) {
bp := filepath.Join("fixtures", "inline_schemas.yml")
sp, err := loadSpec(bp)
if assert.NoError(t, err) {
values := []struct {
Key string
Names []string
}{
{"#/paths/~1some~1where~1{id}/parameters/1/schema", []string{"GetSomeWhereID params body", "PostSomeWhereID params body"}},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema", []string{"GetSomeWhereID params body"}},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema", []string{"GetSomeWhereID Default body"}},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema", []string{"GetSomeWhereID OK body"}},
{"#/definitions/namedAgain", []string{"namedAgain"}},
{"#/definitions/datedTag/allOf/1", []string{"datedTag allOf 1"}},
{"#/definitions/datedRecords/items/1", []string{"datedRecords tuple 1"}},
{"#/definitions/datedTaggedRecords/items/1", []string{"datedTaggedRecords tuple 1"}},
{"#/definitions/datedTaggedRecords/additionalItems", []string{"datedTaggedRecords tuple additionalItems"}},
{"#/definitions/otherRecords/items", []string{"otherRecords items"}},
{"#/definitions/tags/additionalProperties", []string{"tags additionalProperties"}},
{"#/definitions/namedThing/properties/name", []string{"namedThing name"}},
}
for i, v := range values {
ptr, err := jsonpointer.New(definitionPtr(v.Key)[1:])
if assert.NoError(t, err) {
vv, _, err := ptr.Get(sp)
if assert.NoError(t, err) {
switch tv := vv.(type) {
case *spec.Schema:
aschema, err := Schema(SchemaOpts{Schema: tv, Root: sp, BasePath: bp})
if assert.NoError(t, err) {
names := namesFromKey(keyParts(v.Key), aschema, opRefsByRef(gatherOperations(New(sp), nil)))
assert.Equal(t, v.Names, names, "for %s at %d", v.Key, i)
}
case spec.Schema:
aschema, err := Schema(SchemaOpts{Schema: &tv, Root: sp, BasePath: bp})
if assert.NoError(t, err) {
names := namesFromKey(keyParts(v.Key), aschema, opRefsByRef(gatherOperations(New(sp), nil)))
assert.Equal(t, v.Names, names, "for %s at %d", v.Key, i)
}
default:
assert.Fail(t, "unknown type", "got %T", vv)
}
}
}
}
}
}
func TestDepthFirstSort(t *testing.T) {
bp := filepath.Join("fixtures", "inline_schemas.yml")
sp, err := loadSpec(bp)
values := []string{
"#/paths/~1some~1where~1{id}/parameters/1/schema/properties/createdAt",
"#/paths/~1some~1where~1{id}/parameters/1/schema",
"#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/createdAt",
"#/paths/~1some~1where~1{id}/get/parameters/2/schema",
"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/id",
"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/value",
"#/paths/~1some~1where~1{id}/get/responses/200/schema",
"#/paths/~1some~1where~1{id}/get/responses/404/schema",
"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/createdAt",
"#/paths/~1some~1where~1{id}/get/responses/default/schema",
"#/definitions/datedRecords/items/1/properties/createdAt",
"#/definitions/datedTaggedRecords/items/1/properties/createdAt",
"#/definitions/namedThing/properties/name/properties/id",
"#/definitions/records/items/0/properties/createdAt",
"#/definitions/datedTaggedRecords/additionalItems/properties/id",
"#/definitions/datedTaggedRecords/additionalItems/properties/value",
"#/definitions/otherRecords/items/properties/createdAt",
"#/definitions/tags/additionalProperties/properties/id",
"#/definitions/tags/additionalProperties/properties/value",
"#/definitions/datedRecords/items/0",
"#/definitions/datedRecords/items/1",
"#/definitions/datedTag/allOf/0",
"#/definitions/datedTag/allOf/1",
"#/definitions/datedTag/properties/id",
"#/definitions/datedTag/properties/value",
"#/definitions/datedTaggedRecords/items/0",
"#/definitions/datedTaggedRecords/items/1",
"#/definitions/namedAgain/properties/id",
"#/definitions/namedThing/properties/name",
"#/definitions/pneumonoultramicroscopicsilicovolcanoconiosisAntidisestablishmentarianism/properties/floccinaucinihilipilificationCreatedAt",
"#/definitions/records/items/0",
"#/definitions/datedTaggedRecords/additionalItems",
"#/definitions/otherRecords/items",
"#/definitions/tags/additionalProperties",
"#/definitions/datedRecords",
"#/definitions/datedTag",
"#/definitions/datedTaggedRecords",
"#/definitions/namedAgain",
"#/definitions/namedThing",
"#/definitions/otherRecords",
"#/definitions/pneumonoultramicroscopicsilicovolcanoconiosisAntidisestablishmentarianism",
"#/definitions/records",
"#/definitions/tags",
}
if assert.NoError(t, err) {
a := New(sp)
result := sortDepthFirst(a.allSchemas)
assert.Equal(t, values, result)
}
}
func TestNameInlinedSchemas(t *testing.T) {
bp := filepath.Join(".", "fixtures", "nested_inline_schemas.yml")
sp, err := loadSpec(bp)
values := []struct {
Key string
Location string
Ref spec.Ref
}{
{"#/paths/~1some~1where~1{id}/parameters/1/schema/items", "#/definitions/postSomeWhereIdParamsBody/items", spec.MustCreateRef("#/definitions/postSomeWhereIdParamsBodyItems")},
{"#/paths/~1some~1where~1{id}/parameters/1/schema", "#/paths/~1some~1where~1{id}/parameters/1/schema", spec.MustCreateRef("#/definitions/postSomeWhereIdParamsBody")},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/record/items/2/properties/name", "#/definitions/getSomeWhereIdParamsBodyRecordItems2/properties/name", spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems2Name")},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/record/items/1", "#/definitions/getSomeWhereIdParamsBodyRecord/items/1", spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems1")},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/record/items/2", "#/definitions/getSomeWhereIdParamsBodyRecord/items/2", spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems2")},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/record", "#/definitions/getSomeWhereIdParamsBodyOAIGen/properties/record", spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecord")},
{"#/paths/~1some~1where~1{id}/get/parameters/2/schema", "#/paths/~1some~1where~1{id}/get/parameters/2/schema", spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyOAIGen")},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/record/items/2/properties/name", "#/definitions/getSomeWhereIdOKBodyRecordItems2/properties/name", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBodyRecordItems2Name")},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/record/items/1", "#/definitions/getSomeWhereIdOKBodyRecord/items/1", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBodyRecordItems1")},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/record/items/2", "#/definitions/getSomeWhereIdOKBodyRecord/items/2", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBodyRecordItems2")},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/record", "#/definitions/getSomeWhereIdOKBody/properties/record", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBodyRecord")},
{"#/paths/~1some~1where~1{id}/get/responses/200/schema", "#/paths/~1some~1where~1{id}/get/responses/200/schema", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBody")},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/record/items/2/properties/name", "#/definitions/getSomeWhereIdDefaultBodyRecordItems2/properties/name", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBodyRecordItems2Name")},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/record/items/1", "#/definitions/getSomeWhereIdDefaultBodyRecord/items/1", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBodyRecordItems1")},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/record/items/2", "#/definitions/getSomeWhereIdDefaultBodyRecord/items/2", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBodyRecordItems2")},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/record", "#/definitions/getSomeWhereIdDefaultBody/properties/record", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBodyRecord")},
{"#/paths/~1some~1where~1{id}/get/responses/default/schema", "#/paths/~1some~1where~1{id}/get/responses/default/schema", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBody")},
{"#/definitions/nestedThing/properties/record/items/2/allOf/1/additionalProperties", "#/definitions/nestedThingRecordItems2AllOf1/additionalProperties", spec.MustCreateRef("#/definitions/nestedThingRecordItems2AllOf1AdditionalProperties")},
{"#/definitions/nestedThing/properties/record/items/2/allOf/1", "#/definitions/nestedThingRecordItems2/allOf/1", spec.MustCreateRef("#/definitions/nestedThingRecordItems2AllOf1")},
{"#/definitions/nestedThing/properties/record/items/2/properties/name", "#/definitions/nestedThingRecordItems2/properties/name", spec.MustCreateRef("#/definitions/nestedThingRecordItems2Name")},
{"#/definitions/nestedThing/properties/record/items/1", "#/definitions/nestedThingRecord/items/1", spec.MustCreateRef("#/definitions/nestedThingRecordItems1")},
{"#/definitions/nestedThing/properties/record/items/2", "#/definitions/nestedThingRecord/items/2", spec.MustCreateRef("#/definitions/nestedThingRecordItems2")},
{"#/definitions/datedRecords/items/1", "#/definitions/datedRecords/items/1", spec.MustCreateRef("#/definitions/datedRecordsItems1")},
{"#/definitions/datedTaggedRecords/items/1", "#/definitions/datedTaggedRecords/items/1", spec.MustCreateRef("#/definitions/datedTaggedRecordsItems1")},
{"#/definitions/namedThing/properties/name", "#/definitions/namedThing/properties/name", spec.MustCreateRef("#/definitions/namedThingName")},
{"#/definitions/nestedThing/properties/record", "#/definitions/nestedThing/properties/record", spec.MustCreateRef("#/definitions/nestedThingRecord")},
{"#/definitions/records/items/0", "#/definitions/records/items/0", spec.MustCreateRef("#/definitions/recordsItems0")},
{"#/definitions/datedTaggedRecords/additionalItems", "#/definitions/datedTaggedRecords/additionalItems", spec.MustCreateRef("#/definitions/datedTaggedRecordsItemsAdditionalItems")},
{"#/definitions/otherRecords/items", "#/definitions/otherRecords/items", spec.MustCreateRef("#/definitions/otherRecordsItems")},
{"#/definitions/tags/additionalProperties", "#/definitions/tags/additionalProperties", spec.MustCreateRef("#/definitions/tagsAdditionalProperties")},
}
if assert.NoError(t, err) {
err := nameInlinedSchemas(&FlattenOpts{
Spec: New(sp),
BasePath: bp,
})
if assert.NoError(t, err) {
for i, v := range values {
ptr, err := jsonpointer.New(v.Location[1:])
if assert.NoError(t, err, "at %d for %s", i, v.Key) {
vv, _, err := ptr.Get(sp)
if assert.NoError(t, err, "at %d for %s", i, v.Key) {
switch tv := vv.(type) {
case *spec.Schema:
assert.Equal(t, v.Ref.String(), tv.Ref.String(), "at %d for %s", i, v.Key)
case spec.Schema:
assert.Equal(t, v.Ref.String(), tv.Ref.String(), "at %d for %s", i, v.Key)
case *spec.SchemaOrBool:
var sRef spec.Ref
if tv != nil && tv.Schema != nil {
sRef = tv.Schema.Ref
}
assert.Equal(t, v.Ref.String(), sRef.String(), "at %d for %s", i, v.Key)
case *spec.SchemaOrArray:
var sRef spec.Ref
if tv != nil && tv.Schema != nil {
sRef = tv.Schema.Ref
}
assert.Equal(t, v.Ref.String(), sRef.String(), "at %d for %s", i, v.Key)
default:
assert.Fail(t, "unknown type", "got %T", vv)
}
}
}
}
}
for k, rr := range New(sp).allSchemas {
if !strings.HasPrefix(k, "#/responses") && !strings.HasPrefix(k, "#/parameters") {
if rr.Schema != nil && rr.Schema.Ref.String() == "" && !rr.TopLevel {
asch, err := Schema(SchemaOpts{Schema: rr.Schema, Root: sp, BasePath: bp})
if assert.NoError(t, err, "for key: %s", k) {
if !asch.IsSimpleSchema {
assert.Fail(t, "not a top level schema", "for key: %s", k)
}
}
}
}
}
}
}
func TestFlatten(t *testing.T) {
bp := filepath.Join(".", "fixtures", "flatten.yml")
sp, err := loadSpec(bp)
values := []struct {
Key string
Location string
Ref spec.Ref
Expected interface{}
}{
{
"#/responses/notFound/schema",
"#/responses/notFound/schema",
spec.MustCreateRef("#/definitions/error"),
nil,
},
{
"#/paths/~1some~1where~1{id}/parameters/0",
"#/paths/~1some~1where~1{id}/parameters/0/name",
spec.Ref{},
"id",
},
{
"#/paths/~1other~1place",
"#/paths/~1other~1place/get/operationId",
spec.Ref{},
"modelOp",
},
{
"#/paths/~1some~1where~1{id}/get/parameters/0",
"#/paths/~1some~1where~1{id}/get/parameters/0/name",
spec.Ref{},
"limit",
},
{
"#/paths/~1some~1where~1{id}/get/parameters/1",
"#/paths/~1some~1where~1{id}/get/parameters/1/name",
spec.Ref{},
"some",
},
{
"#/paths/~1some~1where~1{id}/get/parameters/2",
"#/paths/~1some~1where~1{id}/get/parameters/2/name",
spec.Ref{},
"other",
},
{
"#/paths/~1some~1where~1{id}/get/parameters/3",
"#/paths/~1some~1where~1{id}/get/parameters/3/schema",
spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBody"),
"",
},
{
"#/paths/~1some~1where~1{id}/get/responses/200",
"#/paths/~1some~1where~1{id}/get/responses/200/schema",
spec.MustCreateRef("#/definitions/getSomeWhereIdOKBody"),
"",
},
{
"#/definitions/namedAgain",
"",
spec.MustCreateRef("#/definitions/named"),
"",
},
{
"#/definitions/namedThing/properties/name",
"",
spec.MustCreateRef("#/definitions/named"),
"",
},
{
"#/definitions/namedThing/properties/namedAgain",
"",
spec.MustCreateRef("#/definitions/namedAgain"),
"",
},
{
"#/definitions/datedRecords/items/1",
"",
spec.MustCreateRef("#/definitions/record"),
"",
},
{
"#/definitions/otherRecords/items",
"",
spec.MustCreateRef("#/definitions/record"),
"",
},
{
"#/definitions/tags/additionalProperties",
"",
spec.MustCreateRef("#/definitions/tag"),
"",
},
{
"#/definitions/datedTag/allOf/1",
"",
spec.MustCreateRef("#/definitions/tag"),
"",
},
{
"#/definitions/nestedThingRecordItems2/allOf/1",
"",
spec.MustCreateRef("#/definitions/nestedThingRecordItems2AllOf1"),
"",
},
{
"#/definitions/nestedThingRecord/items/1",
"",
spec.MustCreateRef("#/definitions/nestedThingRecordItems1"),
"",
},
{
"#/definitions/nestedThingRecord/items/2",
"",
spec.MustCreateRef("#/definitions/nestedThingRecordItems2"),
"",
},
{
"#/definitions/nestedThing/properties/record",
"",
spec.MustCreateRef("#/definitions/nestedThingRecord"),
"",
},
{
"#/definitions/named",
"#/definitions/named/type",
spec.Ref{},
spec.StringOrArray{"string"},
},
{
"#/definitions/error",
"#/definitions/error/properties/id/type",
spec.Ref{},
spec.StringOrArray{"integer"},
},
{
"#/definitions/record",
"#/definitions/record/properties/createdAt/format",
spec.Ref{},
"date-time",
},
{
"#/definitions/getSomeWhereIdOKBody",
"#/definitions/getSomeWhereIdOKBody/properties/record",
spec.MustCreateRef("#/definitions/nestedThing"),
nil,
},
{
"#/definitions/getSomeWhereIdParamsBody",
"#/definitions/getSomeWhereIdParamsBody/properties/record",
spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecord"),
nil,
},
{
"#/definitions/getSomeWhereIdParamsBodyRecord",
"#/definitions/getSomeWhereIdParamsBodyRecord/items/1",
spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems1"),
nil,
},
{
"#/definitions/getSomeWhereIdParamsBodyRecord",
"#/definitions/getSomeWhereIdParamsBodyRecord/items/2",
spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems2"),
nil,
},
{
"#/definitions/getSomeWhereIdParamsBodyRecordItems2",
"#/definitions/getSomeWhereIdParamsBodyRecordItems2/allOf/0/format",
spec.Ref{},
"date",
},
{
"#/definitions/getSomeWhereIdParamsBodyRecordItems2Name",
"#/definitions/getSomeWhereIdParamsBodyRecordItems2Name/properties/createdAt/format",
spec.Ref{},
"date-time",
},
{
"#/definitions/getSomeWhereIdParamsBodyRecordItems2",
"#/definitions/getSomeWhereIdParamsBodyRecordItems2/properties/name",
spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems2Name"),
"date",
},
}
if assert.NoError(t, err) {
err := Flatten(FlattenOpts{Spec: New(sp), BasePath: bp})
if assert.NoError(t, err) {
for i, v := range values {
pk := v.Key[1:]
if v.Location != "" {
pk = v.Location[1:]
}
ptr, err := jsonpointer.New(pk)
if assert.NoError(t, err, "at %d for %s", i, v.Key) {
d, _, err := ptr.Get(sp)
if assert.NoError(t, err) {
if v.Ref.String() != "" {
switch s := d.(type) {
case *spec.Schema:
assert.Equal(t, v.Ref.String(), s.Ref.String(), "at %d for %s", i, v.Key)
case spec.Schema:
assert.Equal(t, v.Ref.String(), s.Ref.String(), "at %d for %s", i, v.Key)
case *spec.SchemaOrArray:
var sRef spec.Ref
if s != nil && s.Schema != nil {
sRef = s.Schema.Ref
}
assert.Equal(t, v.Ref.String(), sRef.String(), "at %d for %s", i, v.Key)
case *spec.SchemaOrBool:
var sRef spec.Ref
if s != nil && s.Schema != nil {
sRef = s.Schema.Ref
}
assert.Equal(t, v.Ref.String(), sRef.String(), "at %d for %s", i, v.Key)
default:
assert.Fail(t, "unknown type", "got %T at %d for %s", d, i, v.Key)
}
} else {
assert.Equal(t, v.Expected, d)
}
}
}
}
}
}
}

View File

@@ -1,266 +0,0 @@
package analysis
import (
"encoding/json"
"fmt"
"path"
"testing"
"net/http"
"net/http/httptest"
"github.com/go-openapi/spec"
"github.com/stretchr/testify/assert"
)
var knownSchemas = []*spec.Schema{
spec.BoolProperty(), // 0
spec.StringProperty(), // 1
spec.Int8Property(), // 2
spec.Int16Property(), // 3
spec.Int32Property(), // 4
spec.Int64Property(), // 5
spec.Float32Property(), // 6
spec.Float64Property(), // 7
spec.DateProperty(), // 8
spec.DateTimeProperty(), // 9
(&spec.Schema{}), // 10
(&spec.Schema{}).Typed("object", ""), // 11
(&spec.Schema{}).Typed("", ""), // 12
(&spec.Schema{}).Typed("", "uuid"), // 13
}
func newCObj() *spec.Schema {
return (&spec.Schema{}).Typed("object", "").SetProperty("id", *spec.Int64Property())
}
var complexObject = newCObj()
var complexSchemas = []*spec.Schema{
complexObject,
spec.ArrayProperty(complexObject),
spec.MapProperty(complexObject),
}
func knownRefs(base string) []spec.Ref {
urls := []string{"bool", "string", "integer", "float", "date", "object", "format"}
var result []spec.Ref
for _, u := range urls {
result = append(result, spec.MustCreateRef(fmt.Sprintf("%s/%s", base, path.Join("known", u))))
}
return result
}
func complexRefs(base string) []spec.Ref {
urls := []string{"object", "array", "map"}
var result []spec.Ref
for _, u := range urls {
result = append(result, spec.MustCreateRef(fmt.Sprintf("%s/%s", base, path.Join("complex", u))))
}
return result
}
func refServer() *httptest.Server {
mux := http.NewServeMux()
mux.Handle("/known/bool", schemaHandler(knownSchemas[0]))
mux.Handle("/known/string", schemaHandler(knownSchemas[1]))
mux.Handle("/known/integer", schemaHandler(knownSchemas[5]))
mux.Handle("/known/float", schemaHandler(knownSchemas[6]))
mux.Handle("/known/date", schemaHandler(knownSchemas[8]))
mux.Handle("/known/object", schemaHandler(knownSchemas[11]))
mux.Handle("/known/format", schemaHandler(knownSchemas[13]))
mux.Handle("/complex/object", schemaHandler(complexSchemas[0]))
mux.Handle("/complex/array", schemaHandler(complexSchemas[1]))
mux.Handle("/complex/map", schemaHandler(complexSchemas[2]))
return httptest.NewServer(mux)
}
func refSchema(ref spec.Ref) *spec.Schema {
return &spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
}
func schemaHandler(schema *spec.Schema) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, schema)
})
}
func writeJSON(w http.ResponseWriter, data interface{}) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
if err := enc.Encode(data); err != nil {
panic(err)
}
}
func TestSchemaAnalysis_KnownTypes(t *testing.T) {
for i, v := range knownSchemas {
sch, err := Schema(SchemaOpts{Schema: v})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsKnownType, "item at %d should be a known type", i)
}
}
for i, v := range complexSchemas {
sch, err := Schema(SchemaOpts{Schema: v})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.False(t, sch.IsKnownType, "item at %d should not be a known type", i)
}
}
serv := refServer()
defer serv.Close()
for i, ref := range knownRefs(serv.URL) {
sch, err := Schema(SchemaOpts{Schema: refSchema(ref)})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsKnownType, "item at %d should be a known type", i)
}
}
for i, ref := range complexRefs(serv.URL) {
sch, err := Schema(SchemaOpts{Schema: refSchema(ref)})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.False(t, sch.IsKnownType, "item at %d should not be a known type", i)
}
}
}
func TestSchemaAnalysis_Array(t *testing.T) {
for i, v := range append(knownSchemas, (&spec.Schema{}).Typed("array", "")) {
sch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(v)})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsArray, "item at %d should be an array type", i)
assert.True(t, sch.IsSimpleArray, "item at %d should be a simple array type", i)
}
}
for i, v := range complexSchemas {
sch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(v)})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsArray, "item at %d should be an array type", i)
assert.False(t, sch.IsSimpleArray, "item at %d should not be a simple array type", i)
}
}
serv := refServer()
defer serv.Close()
for i, ref := range knownRefs(serv.URL) {
sch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(refSchema(ref))})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsArray, "item at %d should be an array type", i)
assert.True(t, sch.IsSimpleArray, "item at %d should be a simple array type", i)
}
}
for i, ref := range complexRefs(serv.URL) {
sch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(refSchema(ref))})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.False(t, sch.IsKnownType, "item at %d should not be a known type", i)
assert.True(t, sch.IsArray, "item at %d should be an array type", i)
assert.False(t, sch.IsSimpleArray, "item at %d should not be a simple array type", i)
}
}
}
func TestSchemaAnalysis_Map(t *testing.T) {
for i, v := range append(knownSchemas, spec.MapProperty(nil)) {
sch, err := Schema(SchemaOpts{Schema: spec.MapProperty(v)})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsMap, "item at %d should be a map type", i)
assert.True(t, sch.IsSimpleMap, "item at %d should be a simple map type", i)
}
}
for i, v := range complexSchemas {
sch, err := Schema(SchemaOpts{Schema: spec.MapProperty(v)})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsMap, "item at %d should be a map type", i)
assert.False(t, sch.IsSimpleMap, "item at %d should not be a simple map type", i)
}
}
}
func TestSchemaAnalysis_ExtendedObject(t *testing.T) {
for i, v := range knownSchemas {
wex := spec.MapProperty(v).SetProperty("name", *spec.StringProperty())
sch, err := Schema(SchemaOpts{Schema: wex})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsExtendedObject, "item at %d should be an extended map object type", i)
assert.False(t, sch.IsMap, "item at %d should not be a map type", i)
assert.False(t, sch.IsSimpleMap, "item at %d should not be a simple map type", i)
}
}
}
func TestSchemaAnalysis_Tuple(t *testing.T) {
at := spec.ArrayProperty(nil)
at.Items = &spec.SchemaOrArray{}
at.Items.Schemas = append(at.Items.Schemas, *spec.StringProperty(), *spec.Int64Property())
sch, err := Schema(SchemaOpts{Schema: at})
if assert.NoError(t, err) {
assert.True(t, sch.IsTuple)
assert.False(t, sch.IsTupleWithExtra)
assert.False(t, sch.IsKnownType)
assert.False(t, sch.IsSimpleSchema)
}
}
func TestSchemaAnalysis_TupleWithExtra(t *testing.T) {
at := spec.ArrayProperty(nil)
at.Items = &spec.SchemaOrArray{}
at.Items.Schemas = append(at.Items.Schemas, *spec.StringProperty(), *spec.Int64Property())
at.AdditionalItems = &spec.SchemaOrBool{Allows: true}
at.AdditionalItems.Schema = spec.Int32Property()
sch, err := Schema(SchemaOpts{Schema: at})
if assert.NoError(t, err) {
assert.False(t, sch.IsTuple)
assert.True(t, sch.IsTupleWithExtra)
assert.False(t, sch.IsKnownType)
assert.False(t, sch.IsSimpleSchema)
}
}
func TestSchemaAnalysis_BaseType(t *testing.T) {
cl := (&spec.Schema{}).Typed("object", "").SetProperty("type", *spec.StringProperty()).WithDiscriminator("type")
sch, err := Schema(SchemaOpts{Schema: cl})
if assert.NoError(t, err) {
assert.True(t, sch.IsBaseType)
assert.False(t, sch.IsKnownType)
assert.False(t, sch.IsSimpleSchema)
}
}
func TestSchemaAnalysis_SimpleSchema(t *testing.T) {
for i, v := range append(knownSchemas, spec.ArrayProperty(nil), spec.MapProperty(nil)) {
sch, err := Schema(SchemaOpts{Schema: v})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.True(t, sch.IsSimpleSchema, "item at %d should be a simple schema", i)
}
asch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(v)})
if assert.NoError(t, err, "failed to analyze array schema at %d: %v", i, err) {
assert.True(t, asch.IsSimpleSchema, "array item at %d should be a simple schema", i)
}
msch, err := Schema(SchemaOpts{Schema: spec.MapProperty(v)})
if assert.NoError(t, err, "failed to analyze map schema at %d: %v", i, err) {
assert.True(t, msch.IsSimpleSchema, "map item at %d should be a simple schema", i)
}
}
for i, v := range complexSchemas {
sch, err := Schema(SchemaOpts{Schema: v})
if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) {
assert.False(t, sch.IsSimpleSchema, "item at %d should not be a simple schema", i)
}
}
}