Skip to content

Commit

Permalink
Merge pull request #59 from muonsoft/deps-updated
Browse files Browse the repository at this point in the history
Deps updated
  • Loading branch information
strider2038 authored Jun 22, 2021
2 parents a05944a + 1c34e60 commit 01f9ed2
Show file tree
Hide file tree
Showing 24 changed files with 166 additions and 143 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: ^1.15
go-version: ^1.16
id: go

- name: Checkout code
Expand Down
26 changes: 14 additions & 12 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
module github.com/muonsoft/openapi-mock

go 1.15
go 1.16

require (
github.com/asaskevich/govalidator v0.0.0-20200907205600-7a23bdc65eef // indirect
github.com/clbanning/mxj v1.8.4
github.com/getkin/kin-openapi v0.26.0
github.com/felixge/httpsnoop v1.0.2 // indirect
github.com/getkin/kin-openapi v0.63.0
github.com/go-openapi/swag v0.19.15 // indirect
github.com/go-ozzo/ozzo-routing/v2 v2.3.0
github.com/go-ozzo/ozzo-validation/v4 v4.3.0
github.com/gofrs/uuid v3.3.0+incompatible
github.com/golang/gddo v0.0.0-20200831202555-721e228c7686 // indirect
github.com/gofrs/uuid v4.0.0+incompatible
github.com/golang/gddo v0.0.0-20210115222349-20d68f94ee1f // indirect
github.com/gorilla/handlers v1.5.1
github.com/kelseyhightower/envconfig v1.4.0
github.com/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb
github.com/mailru/easyjson v0.7.7 // indirect
github.com/muonsoft/api-testing v0.2.0
github.com/muonsoft/validation v0.4.0
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.7.0
github.com/spf13/cobra v1.1.1
github.com/sirupsen/logrus v1.8.1
github.com/spf13/cobra v1.1.3
github.com/stretchr/objx v0.3.0 // indirect
github.com/stretchr/testify v1.6.1
github.com/unrolled/secure v1.0.8
golang.org/x/sys v0.0.0-20201107080550-4d91cf3a1aaf // indirect
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776
syreclabs.com/go/faker v1.2.2
github.com/unrolled/secure v1.0.9
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
syreclabs.com/go/faker v1.2.3
)
78 changes: 50 additions & 28 deletions go.sum

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion internal/application/config/Load.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func Load(filename string) (*Configuration, error) {

err = fileConfig.Validate()
if err != nil {
return nil, &ErrInvalidConfiguration{ValidationError: err}
return nil, &InvalidConfigurationError{ValidationError: err}
}

return createApplicationConfiguration(fileConfig), nil
Expand Down
4 changes: 2 additions & 2 deletions internal/application/config/Load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func TestLoad_InvalidFile_Error(t *testing.T) {
config, err := Load("errors.go")

assert.Nil(t, config)
assert.EqualError(t, err, "failed to load configuration: yaml: line 16: mapping values are not allowed in this context")
assert.EqualError(t, err, "failed to load configuration: yaml: line 15: mapping values are not allowed in this context")
}

func TestLoad_FileWithInvalidValues_Error(t *testing.T) {
Expand All @@ -106,7 +106,7 @@ func TestLoad_FileWithInvalidValues_Error(t *testing.T) {
"invalid option 'application.log_format': must be one of: tty, json; "+
"invalid option 'application.log_level': must be one of: panic, fatal, error, warn, warning, info, debug, trace; "+
"invalid option 'generation.use_examples': must be one of: no, if_present, exclusively; "+
"invalid option 'http.port': cannot be blank")
"invalid option 'http.port': value should be between 1 and 65535 if present")
}

func TestLoad_DebugIsOn_LogLevelIsTrace(t *testing.T) {
Expand Down
33 changes: 13 additions & 20 deletions internal/application/config/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,41 @@ package config

import (
"fmt"
"sort"
"strings"

validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/muonsoft/validation"
)

type ErrLoadFailed struct {
type LoadingFailedError struct {
Previous error
}

func (err *ErrLoadFailed) Error() string {
func (err *LoadingFailedError) Error() string {
return fmt.Sprintf("failed to load configuration: %s", err.Previous.Error())
}

func (err *ErrLoadFailed) Unwrap() error {
func (err *LoadingFailedError) Unwrap() error {
return err.Previous
}

type ErrInvalidConfiguration struct {
type InvalidConfigurationError struct {
ValidationError error
}

func (err *ErrInvalidConfiguration) Error() string {
violations := err.ValidationError.(validation.Errors)

keys := make([]string, 0, len(violations))
for key := range violations {
keys = append(keys, key)
func (err *InvalidConfigurationError) Error() string {
violations, ok := validation.UnwrapViolationList(err.ValidationError)
if !ok {
return fmt.Sprintf("failed to validate configuration: %s", err.ValidationError)
}
sort.Strings(keys)

var message strings.Builder
message.WriteString("configuration has invalid values: ")

for i, key := range keys {
err := violations[key]
if err != nil {
if i > 0 {
message.WriteString("; ")
}
message.WriteString(fmt.Sprintf("invalid option '%s': %s", key, err.Error()))
for violation := violations.First(); violation != nil; violation = violation.Next() {
if violation != violations.First() {
message.WriteString("; ")
}
message.WriteString(fmt.Sprintf("invalid option '%s': %s", violation.PropertyPath().String(), violation.Message()))
}

return message.String()
Expand Down
52 changes: 25 additions & 27 deletions internal/application/config/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"io/ioutil"
"strings"

validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/muonsoft/validation"
"github.com/muonsoft/validation/it"
"github.com/muonsoft/validation/validator"
"gopkg.in/yaml.v3"
)

Expand Down Expand Up @@ -46,13 +48,13 @@ type generationConfiguration struct {
func loadFileConfiguration(filename string) (*fileConfiguration, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, &ErrLoadFailed{Previous: err}
return nil, &LoadingFailedError{Previous: err}
}

var fileConfig fileConfiguration
err = yaml.Unmarshal(data, &fileConfig)
if err != nil {
return nil, &ErrLoadFailed{Previous: err}
return nil, &LoadingFailedError{Previous: err}
}

return &fileConfig, nil
Expand All @@ -66,33 +68,29 @@ var invalidLogFormat = fmt.Sprintf("must be one of: %s", strings.Join(logFormats
var invalidLogLevel = fmt.Sprintf("must be one of: %s", strings.Join(logLevels, ", "))
var invalidUseExample = fmt.Sprintf("must be one of: %s", strings.Join(useExampleOptions, ", "))

func stringsAsInterfaces(ss []string) []interface{} {
ii := make([]interface{}, len(ss))
for i, s := range ss {
ii[i] = s
}
return ii
}

func (config *fileConfiguration) Validate() error {
return validation.Errors{
"http.port": validation.Validate(
config.HTTP.Port,
validation.Required.When(config.HTTP.Port != nil),
validation.Min(uint16(1)),
validation.Max(uint16(65535)),
return validator.Validate(
validation.StringProperty(
"application.log_format",
&config.Application.LogFormat,
it.IsOneOfStrings(logFormats...).Message(invalidLogFormat),
),
"application.log_format": validation.Validate(
config.Application.LogFormat,
validation.In(stringsAsInterfaces(logFormats)...).Error(invalidLogFormat),
validation.StringProperty(
"application.log_level",
&config.Application.LogLevel,
it.IsOneOfStrings(logLevels...).Message(invalidLogLevel),
),
"application.log_level": validation.Validate(
config.Application.LogLevel,
validation.In(stringsAsInterfaces(logLevels)...).Error(invalidLogLevel),
validation.StringProperty(
"generation.use_examples",
&config.Generation.UseExamples,
it.IsOneOfStrings(useExampleOptions...).Message(invalidUseExample),
),
"generation.use_examples": validation.Validate(
config.Generation.UseExamples,
validation.In(stringsAsInterfaces(useExampleOptions)...).Error(invalidUseExample),
validation.NumberProperty(
"http.port",
config.HTTP.Port,
it.IsBetweenIntegers(1, 65535).
When(config.HTTP.Port != nil).
Message("value should be between {{ min }} and {{ max }} if present"),
),
}.Filter()
)
}
10 changes: 7 additions & 3 deletions internal/application/di/Factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import (
"os"

"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers"
"github.com/getkin/kin-openapi/routers/legacy"
"github.com/gorilla/handlers"
"github.com/muonsoft/openapi-mock/internal/application/config"
responseGenerator "github.com/muonsoft/openapi-mock/internal/openapi/generator"
Expand Down Expand Up @@ -49,7 +50,7 @@ func (factory *Factory) CreateSpecificationLoader() loader.SpecificationLoader {
return loader.New()
}

func (factory *Factory) CreateHTTPHandler(router *openapi3filter.Router) http.Handler {
func (factory *Factory) CreateHTTPHandler(router routers.Router) http.Handler {
generatorOptions := data.Options{
UseExamples: factory.configuration.UseExamples,
NullProbability: factory.configuration.NullProbability,
Expand Down Expand Up @@ -102,7 +103,10 @@ func (factory *Factory) CreateHTTPServer() (server.Server, error) {

logger.Infof("OpenAPI specification was successfully loaded from '%s'", factory.configuration.SpecificationURL)

router := openapi3filter.NewRouter().WithSwagger(specification)
router, err := legacy.NewRouter(specification)
if err != nil {
return nil, fmt.Errorf("failed to set up routing for '%s': %w", factory.configuration.SpecificationURL, err)
}
httpHandler := factory.CreateHTTPHandler(router)

serverLogger := log.New(loggerWriter, "[HTTP]: ", log.LstdFlags)
Expand Down
4 changes: 2 additions & 2 deletions internal/openapi/generator/ResponseGenerator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ package generator
import (
"net/http"

"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers"
"github.com/muonsoft/openapi-mock/internal/openapi/generator/content"
"github.com/muonsoft/openapi-mock/internal/openapi/generator/data"
"github.com/muonsoft/openapi-mock/internal/openapi/generator/negotiator"
)

type ResponseGenerator interface {
GenerateResponse(request *http.Request, route *openapi3filter.Route) (*Response, error)
GenerateResponse(request *http.Request, route *routers.Route) (*Response, error)
}

func New(dataGenerator data.MediaGenerator) ResponseGenerator {
Expand Down
4 changes: 2 additions & 2 deletions internal/openapi/generator/content/htmlGenerator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type HTMLGeneratorSuite struct {
logger *logrus.Logger
hook *test.Hook

examples map[string]*openapi3.ExampleRef
examples openapi3.Examples

htmlGenerator *htmlGenerator
}
Expand All @@ -30,7 +30,7 @@ func (suite *HTMLGeneratorSuite) SetupTest() {
suite.contentGenerator = &generatormock.MediaGenerator{}
suite.logger, suite.hook = test.NewNullLogger()

suite.examples = map[string]*openapi3.ExampleRef{}
suite.examples = make(openapi3.Examples)

suite.htmlGenerator = &htmlGenerator{
contentGenerator: suite.contentGenerator,
Expand Down
4 changes: 2 additions & 2 deletions internal/openapi/generator/content/plainTextProcessor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type PlainTextGeneratorSuite struct {
logger *logrus.Logger
hook *test.Hook

examples map[string]*openapi3.ExampleRef
examples openapi3.Examples

plainTextGenerator *plainTextGenerator
}
Expand All @@ -30,7 +30,7 @@ func (suite *PlainTextGeneratorSuite) SetupTest() {
suite.contentGenerator = &generatormock.MediaGenerator{}
suite.logger, suite.hook = test.NewNullLogger()

suite.examples = map[string]*openapi3.ExampleRef{}
suite.examples = make(openapi3.Examples)

suite.plainTextGenerator = &plainTextGenerator{
contentGenerator: suite.contentGenerator,
Expand Down
4 changes: 2 additions & 2 deletions internal/openapi/generator/coordinatingGenerator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package generator
import (
"net/http"

"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers"
"github.com/muonsoft/openapi-mock/internal/openapi/generator/content"
"github.com/muonsoft/openapi-mock/internal/openapi/generator/negotiator"
"github.com/pkg/errors"
Expand All @@ -15,7 +15,7 @@ type coordinatingGenerator struct {
contentGenerator content.Generator
}

func (generator *coordinatingGenerator) GenerateResponse(request *http.Request, route *openapi3filter.Route) (*Response, error) {
func (generator *coordinatingGenerator) GenerateResponse(request *http.Request, route *routers.Route) (*Response, error) {
responseKey, statusCode, err := generator.statusCodeNegotiator.NegotiateStatusCode(request, route.Operation.Responses)
if err != nil {
return nil, errors.WithMessage(err, "[coordinatingGenerator] failed to negotiate response")
Expand Down
8 changes: 4 additions & 4 deletions internal/openapi/generator/coordinatingGenerator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"testing"

"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers"
contentmock "github.com/muonsoft/openapi-mock/test/mocks/openapi/generator/content"
negotiatormock "github.com/muonsoft/openapi-mock/test/mocks/openapi/generator/negotiator"
"github.com/stretchr/testify/mock"
Expand Down Expand Up @@ -47,7 +47,7 @@ func (suite *CoordinatingGeneratorSuite) TestGenerateResponse_RouteWithValidResp
"contentType": mediaType,
},
}
route := &openapi3filter.Route{}
route := &routers.Route{}
route.Operation = &openapi3.Operation{}
route.Operation.Responses = openapi3.Responses{
"200": {
Expand Down Expand Up @@ -75,7 +75,7 @@ func (suite *CoordinatingGeneratorSuite) TestGenerateResponse_ContentGenerationE
"contentType": mediaType,
},
}
route := &openapi3filter.Route{}
route := &routers.Route{}
route.Operation = &openapi3.Operation{}
route.Operation.Responses = openapi3.Responses{
"200": {
Expand All @@ -101,7 +101,7 @@ func (suite *CoordinatingGeneratorSuite) TestGenerateResponse_StatusCodeNegotiat
"contentType": mediaType,
},
}
route := &openapi3filter.Route{}
route := &routers.Route{}
route.Operation = &openapi3.Operation{}
route.Operation.Responses = openapi3.Responses{
"200": {
Expand Down
8 changes: 4 additions & 4 deletions internal/openapi/handler/ResponseGeneratorHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,21 @@ import (
"net/http"

"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers"
"github.com/muonsoft/openapi-mock/internal/openapi/generator"
"github.com/muonsoft/openapi-mock/internal/openapi/responder"
"github.com/muonsoft/openapi-mock/pkg/logcontext"
"github.com/pkg/errors"
)

type responseGeneratorHandler struct {
router *openapi3filter.Router
router routers.Router
responseGenerator generator.ResponseGenerator
responder responder.Responder
}

func NewResponseGeneratorHandler(
router *openapi3filter.Router,
router routers.Router,
responseGenerator generator.ResponseGenerator,
responder responder.Responder,
) http.Handler {
Expand All @@ -37,8 +38,7 @@ func (handler *responseGeneratorHandler) ServeHTTP(writer http.ResponseWriter, r
ctx := request.Context()
logger := logcontext.LoggerFromContext(ctx)

route, pathParameters, err := handler.router.FindRoute(request.Method, request.URL)

route, pathParameters, err := handler.router.FindRoute(request)
if err != nil {
http.NotFound(writer, request)

Expand Down
Loading

0 comments on commit 01f9ed2

Please sign in to comment.