Skip to content

Commit

Permalink
prepare for #210 (#325)
Browse files Browse the repository at this point in the history
  • Loading branch information
fenollp authored Mar 18, 2021
1 parent 0ef6b18 commit d28d2bb
Show file tree
Hide file tree
Showing 47 changed files with 491 additions and 464 deletions.
55 changes: 44 additions & 11 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,62 @@ jobs:
matrix:
# Locked at https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idruns-on
os:
- ubuntu-18.04
- ubuntu-20.04
- windows-2019
- macos-10.15
runs-on: ${{ matrix.os }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v2

- uses: actions/setup-go@v2
with:
go-version: 1.x
- run: go version

- id: go-cache-paths
run: |
echo "::set-output name=go-build::$(go env GOCACHE)"
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
- name: Go Build Cache
uses: actions/cache@v2
with:
path: ${{ steps.go-cache-paths.outputs.go-build }}
key: ${{ runner.os }}-go-build-${{ hashFiles('**/go.sum') }}

- name: Go Mod Cache
uses: actions/cache@v2
with:
path: ${{ steps.go-cache-paths.outputs.go-mod }}
key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }}


- uses: actions/checkout@v2

- run: go mod download && go mod tidy && go mod verify
- run: git --no-pager diff && [[ $(git --no-pager diff --name-only | wc -l) = 0 ]]
shell: bash
- if: runner.os == 'Linux'
run: git --no-pager diff && [[ $(git --no-pager diff --name-only | wc -l) = 0 ]]

- run: go vet ./...
- run: git --no-pager diff && [[ $(git --no-pager diff --name-only | wc -l) = 0 ]]
shell: bash
- if: runner.os == 'Linux'
run: git --no-pager diff && [[ $(git --no-pager diff --name-only | wc -l) = 0 ]]

- run: go fmt ./...
- run: git --no-pager diff && [[ $(git --no-pager diff --name-only | wc -l) = 0 ]]
shell: bash
- if: runner.os == 'Linux'
run: git --no-pager diff && [[ $(git --no-pager diff --name-only | wc -l) = 0 ]]

- run: go test ./...
- run: git --no-pager diff && [[ $(git --no-pager diff --name-only | wc -l) = 0 ]]
shell: bash
- if: runner.os == 'Linux'
run: git --no-pager diff && [[ $(git --no-pager diff --name-only | wc -l) = 0 ]]


- if: runner.os == 'Linux'
name: Errors must not be capitalized https://github.com/golang/go/wiki/CodeReviewComments#error-strings
run: |
! git grep -E '(fmt|errors)[^(]+\(.[A-Z]'
- if: runner.os == 'Linux'
name: Did you mean %q
run: |
! git grep -E "'[%].'"
14 changes: 5 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Here's some projects that depend on _kin-openapi_:

# Some recipes
## Loading OpenAPI document
Use `SwaggerLoader`, which resolves all JSON references:
Use `SwaggerLoader`, which resolves all references:
```go
swagger, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile("swagger.json")
```
Expand Down Expand Up @@ -108,9 +108,7 @@ func main() {
responseValidationInput := &openapi3filter.ResponseValidationInput{
RequestValidationInput: requestValidationInput,
Status: respStatus,
Header: http.Header{
"Content-Type": []string{respContentType},
},
Header: http.Header{"Content-Type": []string{respContentType}},
}
if respBody != nil {
data, _ := json.Marshal(respBody)
Expand Down Expand Up @@ -160,7 +158,7 @@ func xmlBodyDecoder(body []byte) (interface{}, error) {
}
```

## Custom function for check uniqueness of JSON array
## Custom function to check uniqueness of array items

By defaut, the library check unique items by below predefined function

Expand All @@ -169,8 +167,6 @@ func isSliceOfUniqueItems(xs []interface{}) bool {
s := len(xs)
m := make(map[string]struct{}, s)
for _, x := range xs {
// The input slice is coverted from a JSON string, there shall
// have no error when covert it back.
key, _ := json.Marshal(&x)
m[string(key)] = struct{}{}
}
Expand All @@ -180,7 +176,7 @@ func isSliceOfUniqueItems(xs []interface{}) bool {

In the predefined function using `json.Marshal` to generate a string can
be used as a map key which is to support check the uniqueness of an array
when the array items are JSON objects or JSON arraies. You can register
when the array items are objects or arrays. You can register
you own function according to your input data to get better performance:

```go
Expand All @@ -194,7 +190,7 @@ func main() {
}

func arrayUniqueItemsChecker(items []interface{}) bool {
// Check the uniqueness of the input slice(array in JSON)
// Check the uniqueness of the input slice
}
```

Expand Down
6 changes: 3 additions & 3 deletions jsoninfo/marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ func (encoder *ObjectEncoder) EncodeStructFieldsAndExtensions(value interface{})
// Follow "encoding/json" semantics
if reflection.Kind() != reflect.Ptr {
// Panic because this is a clear programming error
panic(fmt.Errorf("Value %s is not a pointer", reflection.Type().String()))
panic(fmt.Errorf("value %s is not a pointer", reflection.Type().String()))
}
if reflection.IsNil() {
// Panic because this is a clear programming error
panic(fmt.Errorf("Value %s is nil", reflection.Type().String()))
panic(fmt.Errorf("value %s is nil", reflection.Type().String()))
}

// Take the element
Expand Down Expand Up @@ -146,7 +146,7 @@ iteration:
continue iteration
}
default:
panic(fmt.Errorf("Field '%s' has unsupported type %s", field.JSONName, field.Type.String()))
panic(fmt.Errorf("field %q has unsupported type %s", field.JSONName, field.Type.String()))
}

// No special treament is needed
Expand Down
12 changes: 6 additions & 6 deletions jsoninfo/unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type ObjectDecoder struct {
func NewObjectDecoder(data []byte) (*ObjectDecoder, error) {
var remainingFields map[string]json.RawMessage
if err := json.Unmarshal(data, &remainingFields); err != nil {
return nil, fmt.Errorf("Failed to unmarshal extension properties: %v\nInput: %s", err, data)
return nil, fmt.Errorf("failed to unmarshal extension properties: %v (%s)", err, data)
}
return &ObjectDecoder{
Data: data,
Expand All @@ -41,18 +41,18 @@ func (decoder *ObjectDecoder) DecodeExtensionMap() map[string]json.RawMessage {
func (decoder *ObjectDecoder) DecodeStructFieldsAndExtensions(value interface{}) error {
reflection := reflect.ValueOf(value)
if reflection.Kind() != reflect.Ptr {
panic(fmt.Errorf("Value %T is not a pointer", value))
panic(fmt.Errorf("value %T is not a pointer", value))
}
if reflection.IsNil() {
panic(fmt.Errorf("Value %T is nil", value))
panic(fmt.Errorf("value %T is nil", value))
}
reflection = reflection.Elem()
for (reflection.Kind() == reflect.Interface || reflection.Kind() == reflect.Ptr) && !reflection.IsNil() {
reflection = reflection.Elem()
}
reflectionType := reflection.Type()
if reflectionType.Kind() != reflect.Struct {
panic(fmt.Errorf("Value %T is not a struct", value))
panic(fmt.Errorf("value %T is not a struct", value))
}
typeInfo := GetTypeInfo(reflectionType)

Expand Down Expand Up @@ -87,7 +87,7 @@ func (decoder *ObjectDecoder) DecodeStructFieldsAndExtensions(value interface{})
continue
}
}
return fmt.Errorf("Error while unmarshalling property '%s' (%s): %v",
return fmt.Errorf("failed to unmarshal property %q (%s): %v",
field.JSONName, fieldValue.Type().String(), err)
}
if !isPtr {
Expand All @@ -109,7 +109,7 @@ func (decoder *ObjectDecoder) DecodeStructFieldsAndExtensions(value interface{})
continue
}
}
return fmt.Errorf("Error while unmarshalling property '%s' (%s): %v",
return fmt.Errorf("failed to unmarshal property %q (%s): %v",
field.JSONName, fieldPtr.Type().String(), err)
}

Expand Down
2 changes: 1 addition & 1 deletion jsoninfo/unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ func TestDecodeStructFieldsAndExtensions(t *testing.T) {
}{}
err = d.DecodeStructFieldsAndExtensions(&value)
require.Error(t, err)
require.EqualError(t, err, "Error while unmarshalling property 'field1' (*int): json: cannot unmarshal string into Go value of type int")
require.EqualError(t, err, `failed to unmarshal property "field1" (*int): json: cannot unmarshal string into Go value of type int`)
require.Equal(t, 0, value.Field1)
require.Equal(t, 2, len(d.DecodeExtensionMap()))
})
Expand Down
11 changes: 4 additions & 7 deletions jsoninfo/unsupported_properties_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/json"
"fmt"
"sort"
"strings"
)

// UnsupportedPropertiesError is a helper for extensions that want to refuse
Expand All @@ -27,7 +26,7 @@ func (err *UnsupportedPropertiesError) Error() string {
m := err.UnsupportedProperties
typeInfo := GetTypeInfoForValue(err.Value)
if m == nil || typeInfo == nil {
return "Invalid UnsupportedPropertiesError"
return fmt.Sprintf("invalid %T", *err)
}
keys := make([]string, 0, len(m))
for k := range m {
Expand All @@ -36,10 +35,8 @@ func (err *UnsupportedPropertiesError) Error() string {
sort.Strings(keys)
supported := typeInfo.FieldNames()
if len(supported) == 0 {
return fmt.Sprintf("Type '%T' doesn't take any properties. Unsupported properties: '%s'\n",
err.Value, strings.Join(keys, "', '"))
return fmt.Sprintf("type \"%T\" doesn't take any properties. Unsupported properties: %+v",
err.Value, keys)
}
return fmt.Sprintf("Unsupported properties: '%s'\nSupported properties are: '%s'",
strings.Join(keys, "', '"),
strings.Join(supported, "', '"))
return fmt.Sprintf("unsupported properties: %+v (supported properties are: %+v)", keys, supported)
}
4 changes: 2 additions & 2 deletions openapi2/openapi2.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func (pathItem *PathItem) GetOperation(method string) *Operation {
case http.MethodPut:
return pathItem.Put
default:
panic(fmt.Errorf("Unsupported HTTP method '%s'", method))
panic(fmt.Errorf("unsupported HTTP method %q", method))
}
}

Expand All @@ -141,7 +141,7 @@ func (pathItem *PathItem) SetOperation(method string, operation *Operation) {
case http.MethodPut:
pathItem.Put = operation
default:
panic(fmt.Errorf("Unsupported HTTP method '%s'", method))
panic(fmt.Errorf("unsupported HTTP method %q", method))
}
}

Expand Down
4 changes: 2 additions & 2 deletions openapi2conv/openapi2_conv.go
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ func ToV3SecurityScheme(securityScheme *openapi2.SecurityScheme) (*openapi3.Secu
case "password":
flows.Password = flow
default:
return nil, fmt.Errorf("Unsupported flow '%s'", securityScheme.Flow)
return nil, fmt.Errorf("unsupported flow %q", securityScheme.Flow)
}
}
return &openapi3.SecuritySchemeRef{
Expand Down Expand Up @@ -1077,7 +1077,7 @@ func FromV3SecurityScheme(swagger *openapi3.Swagger, ref *openapi3.SecuritySchem
}
}
default:
return nil, fmt.Errorf("Unsupported security scheme type '%s'", securityScheme.Type)
return nil, fmt.Errorf("unsupported security scheme type %q", securityScheme.Type)
}
return result, nil
}
Expand Down
24 changes: 19 additions & 5 deletions openapi3/discriminator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,19 @@ import (
"github.com/stretchr/testify/require"
)

var jsonSpecWithDiscriminator = []byte(`
func TestParsingDiscriminator(t *testing.T) {
const spec = `
{
"openapi": "3.0.0",
"info": {
"version": "1.0.0",
"title": "title",
"description": "desc",
"contact": {
"email": "email"
}
},
"paths": {},
"components": {
"schemas": {
"MyResponseType": {
Expand All @@ -33,10 +43,14 @@ var jsonSpecWithDiscriminator = []byte(`
}
}
}
`)
`

func TestParsingDiscriminator(t *testing.T) {
loader, err := NewSwaggerLoader().LoadSwaggerFromData(jsonSpecWithDiscriminator)
loader := NewSwaggerLoader()
doc, err := loader.LoadSwaggerFromData([]byte(spec))
require.NoError(t, err)
require.Equal(t, 2, len(loader.Components.Schemas["MyResponseType"].Value.Discriminator.Mapping))

err = doc.Validate(loader.Context)
require.NoError(t, err)

require.Equal(t, 2, len(doc.Components.Schemas["MyResponseType"].Value.Discriminator.Mapping))
}
2 changes: 1 addition & 1 deletion openapi3/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func (encoding *Encoding) Validate(c context.Context) error {
sm.Style == SerializationDeepObject && sm.Explode:
// it is a valid
default:
return fmt.Errorf("Serialization method with style=%q and explode=%v is not supported by media type", sm.Style, sm.Explode)
return fmt.Errorf("serialization method with style=%q and explode=%v is not supported by media type", sm.Style, sm.Explode)
}

return nil
Expand Down
6 changes: 3 additions & 3 deletions openapi3/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ func (value *Info) Validate(c context.Context) error {
}

if value.Version == "" {
return errors.New("value of version must be a non-empty JSON string")
return errors.New("value of version must be a non-empty string")
}

if value.Title == "" {
return errors.New("value of title must be a non-empty JSON string")
return errors.New("value of title must be a non-empty string")
}

return nil
Expand Down Expand Up @@ -87,7 +87,7 @@ func (value *License) UnmarshalJSON(data []byte) error {

func (value *License) Validate(c context.Context) error {
if value.Name == "" {
return errors.New("value of license name must be a non-empty JSON string")
return errors.New("value of license name must be a non-empty string")
}
return nil
}
2 changes: 1 addition & 1 deletion openapi3/link.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (value *Link) Validate(c context.Context) error {
return errors.New("missing operationId or operationRef on link")
}
if value.OperationID != "" && value.OperationRef != "" {
return fmt.Errorf("operationId '%s' and operationRef '%s' are mutually exclusive", value.OperationID, value.OperationRef)
return fmt.Errorf("operationId %q and operationRef %q are mutually exclusive", value.OperationID, value.OperationRef)
}
return nil
}
2 changes: 1 addition & 1 deletion openapi3/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func (operation *Operation) Validate(c context.Context) error {
return err
}
} else {
return errors.New("value of responses must be a JSON object")
return errors.New("value of responses must be an object")
}
return nil
}
2 changes: 1 addition & 1 deletion openapi3/operation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestOperationValidation(t *testing.T) {
{
"when no Responses object is provided",
operationWithoutResponses(),
errors.New("value of responses must be a JSON object"),
errors.New("value of responses must be an object"),
},
{
"when a Responses object is provided",
Expand Down
2 changes: 1 addition & 1 deletion openapi3/parameter.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (p Parameters) JSONLookup(token string) (interface{}, error) {
}

if index < 0 || index >= len(p) {
return nil, fmt.Errorf("index out of bounds array[0,%d] index '%d'", len(p), index)
return nil, fmt.Errorf("index %d out of bounds of array of length %d", index, len(p))
}

ref := p[index]
Expand Down
Loading

0 comments on commit d28d2bb

Please sign in to comment.