From e4cc15713c8588ad67df620967399a412dbd7519 Mon Sep 17 00:00:00 2001 From: Frederic BIDON Date: Thu, 7 Dec 2023 12:46:04 +0100 Subject: [PATCH] chore: relint & update * updated go version requirement to go1.19 * updated dependencies, excepted: * yaml (upgrade to v3 deferred to another PR) * otel (upgrade is breaking: deferred to another PR) * ci: updated linting rules, in line with other go-openapi repos * exception: disabled the "nilerr" linter, which currently crashes for this repo * ci:updated github actions, in line with other go-openapi repos * doc: updated README links and badges * major relinting of all test code * relinting non-test code is deferred to another PR (hopefully with less changes) * changes to non-test code are limited to: * addition of (temporary) nolint directives * gofmt/typos in comments * unused params TODO in forthcoming PRs: * [ ] upgrade to yaml/v3 * [ ] upgrade OTEL packages * [ ] gradually remove most "nolint" directives in non-test code * [ ] complete test refactoring: some nolint directives have been added to skip more complex refacoring (e.g. duplicate code) Signed-off-by: Frederic BIDON --- .github/workflows/ci.yaml | 32 - .github/workflows/go-test.yml | 50 ++ .github/workflows/lint.yaml | 12 - .golangci.yml | 56 +- README.md | 11 +- authinfo_test.go | 10 +- bytestream.go | 8 +- bytestream_test.go | 149 ++--- client/auth_info_test.go | 43 +- client/keepalive_test.go | 12 +- client/opentelemetry_test.go | 31 +- client/opentracing_test.go | 2 +- client/request.go | 10 +- client/request_test.go | 664 +++++++++++--------- client/response_test.go | 6 +- client/runtime.go | 20 +- client/runtime_test.go | 657 +++++++++---------- client_operation.go | 4 +- client_request.go | 2 + client_request_test.go | 6 +- client_response_test.go | 7 +- csv_test.go | 19 +- file_test.go | 3 +- flagext/byte_size_test.go | 20 +- go.mod | 22 +- go.sum | 149 ++--- headers_test.go | 5 +- internal/testing/petstore/api.go | 49 +- internal/testing/simplepetstore/api.go | 2 +- internal/testing/simplepetstore/api_test.go | 61 +- json_test.go | 18 +- middleware/body_test.go | 113 ++-- middleware/context.go | 11 +- middleware/context_test.go | 217 ++++--- middleware/denco/router.go | 17 +- middleware/denco/router_test.go | 59 +- middleware/denco/server_test.go | 85 ++- middleware/doc.go | 87 +-- middleware/go18.go | 1 + middleware/header/header.go | 4 +- middleware/operation_test.go | 17 +- middleware/parameter.go | 7 +- middleware/parameter_test.go | 120 ++-- middleware/rapidoc.go | 4 +- middleware/rapidoc_test.go | 7 +- middleware/redoc.go | 2 +- middleware/redoc_test.go | 7 +- middleware/request_test.go | 180 +++--- middleware/route_authenticator_test.go | 33 +- middleware/route_param_test.go | 6 +- middleware/router.go | 2 +- middleware/router_test.go | 87 +-- middleware/security_test.go | 52 +- middleware/spec.go | 1 - middleware/spec_test.go | 59 +- middleware/string_conversion_test.go | 59 +- middleware/swaggerui_oauth2_test.go | 7 +- middleware/swaggerui_test.go | 7 +- middleware/untyped/api.go | 10 +- middleware/untyped/api_test.go | 38 +- middleware/untyped_request_test.go | 119 ++-- middleware/validation_test.go | 29 +- request.go | 2 +- request_test.go | 26 +- security/apikey_auth_test.go | 90 +-- security/authenticator.go | 6 +- security/authorizer_test.go | 4 +- security/basic_auth_test.go | 97 +-- security/bearer_auth_test.go | 157 +++-- text_test.go | 51 +- xml_test.go | 7 +- yamlpc/yaml_test.go | 15 +- 72 files changed, 2145 insertions(+), 1897 deletions(-) delete mode 100644 .github/workflows/ci.yaml create mode 100644 .github/workflows/go-test.yml delete mode 100644 .github/workflows/lint.yaml diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml deleted file mode 100644 index 6d8db668..00000000 --- a/.github/workflows/ci.yaml +++ /dev/null @@ -1,32 +0,0 @@ -name: Go - -on: [push, pull_request] - -jobs: - build: - runs-on: ${{ matrix.os }} - - strategy: - matrix: - os: [ ubuntu-latest, macos-latest, windows-latest ] - fail-fast: false - - steps: - - uses: actions/checkout@v2 - - - name: Set up Go - uses: actions/setup-go@v2 - with: - go-version: 1.18.8 - - - name: Setup gotestsum - uses: autero1/action-gotestsum@v1.0.0 - with: - gotestsum_version: 1.7.0 - - - name: Test - run: gotestsum --format short-verbose -- -race -timeout=20m -coverprofile=coverage_txt -covermode=atomic ./... - - - uses: codecov/codecov-action@v2 - with: - files: coverage_txt diff --git a/.github/workflows/go-test.yml b/.github/workflows/go-test.yml new file mode 100644 index 00000000..e1a95c7a --- /dev/null +++ b/.github/workflows/go-test.yml @@ -0,0 +1,50 @@ +name: go test + +on: [push, pull_request] + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: stable + check-latest: true + cache: true + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + version: latest + only-new-issues: true + + test: + name: Unit tests + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ ubuntu-latest, macos-latest, windows-latest ] + go_version: ['oldstable', 'stable' ] + + steps: + - name: Run unit tests + uses: actions/setup-go@v4 + with: + go-version: '${{ matrix.go_version }}' + check-latest: true + cache: true + + - uses: actions/checkout@v3 + + - run: go test -v -race -coverprofile="coverage-${{ matrix.os }}.${{ matrix.go_version }}.out" -covermode=atomic ./... + + - name: Upload coverage to codecov + uses: codecov/codecov-action@v3 + with: + files: './coverage-${{ matrix.os }}.${{ matrix.go_version }}.out' + flags: '${{ matrix.go_version }}' + os: '${{ matrix.os }}' + fail_ci_if_error: false + verbose: true diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml deleted file mode 100644 index 5df42590..00000000 --- a/.github/workflows/lint.yaml +++ /dev/null @@ -1,12 +0,0 @@ -name: golangci-lint -on: [push, pull_request] -jobs: - golangci: - name: lint - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: golangci-lint - uses: golangci/golangci-lint-action@v2 - with: - only-new-issues: true diff --git a/.golangci.yml b/.golangci.yml index b1aa7928..1c75557b 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,44 +1,62 @@ linters-settings: govet: - # Using err repeatedly considered as shadowing. - check-shadowing: false + check-shadowing: true golint: min-confidence: 0 gocyclo: - min-complexity: 30 + min-complexity: 45 maligned: suggest-new: true dupl: - threshold: 100 + threshold: 200 goconst: min-len: 2 - min-occurrences: 4 + min-occurrences: 3 + linters: + enable-all: true disable: + - nilerr # nilerr crashes on this repo - maligned + - unparam - lll + - gochecknoinits - gochecknoglobals + - funlen - godox - gocognit - whitespace - wsl - - funlen - - gochecknoglobals - - gochecknoinits - - scopelint - wrapcheck - - exhaustivestruct - - exhaustive - - nlreturn - testpackage - - gci - - gofumpt - - goerr113 + - nlreturn - gomnd - - tparallel + - exhaustivestruct + - goerr113 + - errorlint - nestif - godot - - errorlint - - noctx + - gofumpt + - paralleltest + - tparallel + - thelper + - ifshort + - exhaustruct + - varnamelen + - gci + - depguard + - errchkjson + - inamedparam + - nonamedreturns + - musttag + - ireturn + - forcetypeassert + - cyclop + # deprecated linters + - deadcode - interfacer - - nilerr + - scopelint + - varcheck + - structcheck + - golint + - nosnakecase diff --git a/README.md b/README.md index 5b1ec649..b07e0ad9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,10 @@ -# runtime [![Build Status](https://travis-ci.org/go-openapi/runtime.svg?branch=client-context)](https://travis-ci.org/go-openapi/runtime) [![codecov](https://codecov.io/gh/go-openapi/runtime/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/runtime) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) +# runtime [![Build Status](https://github.com/go-openapi/runtime/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/runtime/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/runtime/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/runtime) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/runtime/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/runtime?status.svg)](http://godoc.org/github.com/go-openapi/runtime) +[![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/runtime/master/LICENSE) +[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/runtime.svg)](https://pkg.go.dev/github.com/go-openapi/runtime) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/runtime)](https://goreportcard.com/report/github.com/go-openapi/runtime) -# golang Open-API toolkit - runtime +# go OpenAPI toolkit runtime -The runtime component for use in codegeneration or as untyped usage. +The runtime component for use in code generation or as untyped usage. diff --git a/authinfo_test.go b/authinfo_test.go index 6f8de1f8..5f111a97 100644 --- a/authinfo_test.go +++ b/authinfo_test.go @@ -19,15 +19,17 @@ import ( "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAuthInfoWriter(t *testing.T) { + const bearerToken = "Bearer the-token-goes-here" + hand := ClientAuthInfoWriterFunc(func(r ClientRequest, _ strfmt.Registry) error { - return r.SetHeaderParam(HeaderAuthorization, "Bearer the-token-goes-here") + return r.SetHeaderParam(HeaderAuthorization, bearerToken) }) tr := new(TestClientRequest) - err := hand.AuthenticateRequest(tr, nil) - assert.NoError(t, err) - assert.Equal(t, "Bearer the-token-goes-here", tr.Headers.Get(HeaderAuthorization)) + require.NoError(t, hand.AuthenticateRequest(tr, nil)) + assert.Equal(t, bearerToken, tr.Headers.Get(HeaderAuthorization)) } diff --git a/bytestream.go b/bytestream.go index 6eb6ceb5..3142a090 100644 --- a/bytestream.go +++ b/bytestream.go @@ -52,10 +52,10 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { return errors.New("ByteStreamConsumer requires a reader") // early exit } - close := defaultCloser + close := defaultCloser //nolint:revive,predeclared if vals.Close { if cl, ok := reader.(io.Closer); ok { - close = cl.Close + close = cl.Close //nolint:revive } } //nolint:errcheck // closing a reader wouldn't fail. @@ -109,10 +109,10 @@ func ByteStreamProducer(opts ...byteStreamOpt) Producer { if writer == nil { return errors.New("ByteStreamProducer requires a writer") // early exit } - close := defaultCloser + close := defaultCloser //nolint:revive,predeclared if vals.Close { if cl, ok := writer.(io.Closer); ok { - close = cl.Close + close = cl.Close //nolint:revive } } //nolint:errcheck // TODO: closing a writer would fail. diff --git a/bytestream_test.go b/bytestream_test.go index 86e6bbf3..af0c90cd 100644 --- a/bytestream_test.go +++ b/bytestream_test.go @@ -8,55 +8,52 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestByteStreamConsumer(t *testing.T) { cons := ByteStreamConsumer() - expected := "the data for the stream to be sent over the wire" + const expected = "the data for the stream to be sent over the wire" // can consume as a Writer var b bytes.Buffer - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &b)) { - assert.Equal(t, expected, b.String()) - } + require.NoError(t, cons.Consume(bytes.NewBufferString(expected), &b)) + assert.Equal(t, expected, b.String()) - //can consume as a string + // can consume as a string var s string - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &s)) { - assert.Equal(t, expected, s) - } + require.NoError(t, cons.Consume(bytes.NewBufferString(expected), &s)) + assert.Equal(t, expected, s) // can consume as an UnmarshalBinary var bu binaryUnmarshalDummy - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bu)) { - assert.Equal(t, expected, bu.str) - } + require.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bu)) + assert.Equal(t, expected, bu.str) // can consume as a binary slice var bs []byte - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bs)) { - assert.Equal(t, expected, string(bs)) - } + require.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bs)) + assert.Equal(t, expected, string(bs)) + type binarySlice []byte var bs2 binarySlice - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bs2)) { - assert.Equal(t, expected, string(bs2)) - } + require.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bs2)) + assert.Equal(t, expected, string(bs2)) // passing in a nilslice wil result in an error var ns *[]byte - assert.Error(t, cons.Consume(bytes.NewBufferString(expected), &ns)) + require.Error(t, cons.Consume(bytes.NewBufferString(expected), &ns)) // passing in nil wil result in an error as well - assert.Error(t, cons.Consume(bytes.NewBufferString(expected), nil)) + require.Error(t, cons.Consume(bytes.NewBufferString(expected), nil)) // a reader who results in an error, will make it fail - assert.Error(t, cons.Consume(new(nopReader), &bu)) - assert.Error(t, cons.Consume(new(nopReader), &bs)) + require.Error(t, cons.Consume(new(nopReader), &bu)) + require.Error(t, cons.Consume(new(nopReader), &bs)) // the readers can also not be nil - assert.Error(t, cons.Consume(nil, &bs)) + require.Error(t, cons.Consume(nil, &bs)) } type binaryUnmarshalDummy struct { @@ -74,70 +71,61 @@ func (b *binaryUnmarshalDummy) UnmarshalBinary(bytes []byte) error { func TestByteStreamProducer(t *testing.T) { cons := ByteStreamProducer() - expected := "the data for the stream to be sent over the wire" + const expected = "the data for the stream to be sent over the wire" var rdr bytes.Buffer // can produce using a reader - if assert.NoError(t, cons.Produce(&rdr, bytes.NewBufferString(expected))) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, bytes.NewBufferString(expected))) + assert.Equal(t, expected, rdr.String()) + rdr.Reset() // can produce using a binary marshaller - if assert.NoError(t, cons.Produce(&rdr, &binaryMarshalDummy{expected})) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, &binaryMarshalDummy{expected})) + assert.Equal(t, expected, rdr.String()) + rdr.Reset() // string can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, expected)) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, expected)) + assert.Equal(t, expected, rdr.String()) + rdr.Reset() // binary slices can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, []byte(expected))) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, []byte(expected))) + assert.Equal(t, expected, rdr.String()) + rdr.Reset() // errors can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, errors.New(expected))) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, errors.New(expected))) + assert.Equal(t, expected, rdr.String()) + rdr.Reset() // structs can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, Error{Message: expected})) { - assert.Equal(t, fmt.Sprintf(`{"message":%q}`, expected), rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, Error{Message: expected})) + assert.Equal(t, fmt.Sprintf(`{"message":%q}`, expected), rdr.String()) + rdr.Reset() // struct pointers can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, &Error{Message: expected})) { - assert.Equal(t, fmt.Sprintf(`{"message":%q}`, expected), rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, &Error{Message: expected})) + assert.Equal(t, fmt.Sprintf(`{"message":%q}`, expected), rdr.String()) + rdr.Reset() // slices can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, []string{expected})) { - assert.Equal(t, fmt.Sprintf(`[%q]`, expected), rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, []string{expected})) + assert.Equal(t, fmt.Sprintf(`[%q]`, expected), rdr.String()) + rdr.Reset() type binarySlice []byte - if assert.NoError(t, cons.Produce(&rdr, binarySlice(expected))) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } + require.NoError(t, cons.Produce(&rdr, binarySlice(expected))) + assert.Equal(t, expected, rdr.String()) + rdr.Reset() // when binaryMarshal data is used, its potential error gets propagated - assert.Error(t, cons.Produce(&rdr, new(binaryMarshalDummy))) + require.Error(t, cons.Produce(&rdr, new(binaryMarshalDummy))) // nil data should never be accepted either - assert.Error(t, cons.Produce(&rdr, nil)) + require.Error(t, cons.Produce(&rdr, nil)) // nil readers should also never be acccepted - assert.Error(t, cons.Produce(nil, bytes.NewBufferString(expected))) + require.Error(t, cons.Produce(nil, bytes.NewBufferString(expected))) } type binaryMarshalDummy struct { @@ -195,19 +183,17 @@ func TestBytestreamConsumer_Close(t *testing.T) { // can consume as a Writer var b bytes.Buffer r := &closingReader{b: bytes.NewBufferString(expected)} - if assert.NoError(t, cons.Consume(r, &b)) { - assert.Equal(t, expected, b.String()) - assert.EqualValues(t, 1, r.calledClose) - } + require.NoError(t, cons.Consume(r, &b)) + assert.Equal(t, expected, b.String()) + assert.EqualValues(t, 1, r.calledClose) // can consume as a Writer cons = ByteStreamConsumer() b.Reset() r = &closingReader{b: bytes.NewBufferString(expected)} - if assert.NoError(t, cons.Consume(r, &b)) { - assert.Equal(t, expected, b.String()) - assert.EqualValues(t, 0, r.calledClose) - } + require.NoError(t, cons.Consume(r, &b)) + assert.Equal(t, expected, b.String()) + assert.EqualValues(t, 0, r.calledClose) } func TestBytestreamProducer_Close(t *testing.T) { @@ -217,26 +203,23 @@ func TestBytestreamProducer_Close(t *testing.T) { // can consume as a Writer r := &closingWriter{} // can produce using a reader - if assert.NoError(t, cons.Produce(r, bytes.NewBufferString(expected))) { - assert.Equal(t, expected, r.String()) - assert.EqualValues(t, 1, r.calledClose) - } + require.NoError(t, cons.Produce(r, bytes.NewBufferString(expected))) + assert.Equal(t, expected, r.String()) + assert.EqualValues(t, 1, r.calledClose) cons = ByteStreamProducer() r = &closingWriter{} // can produce using a reader - if assert.NoError(t, cons.Produce(r, bytes.NewBufferString(expected))) { - assert.Equal(t, expected, r.String()) - assert.EqualValues(t, 0, r.calledClose) - } + require.NoError(t, cons.Produce(r, bytes.NewBufferString(expected))) + assert.Equal(t, expected, r.String()) + assert.EqualValues(t, 0, r.calledClose) cons = ByteStreamProducer() r = &closingWriter{} data := &closingReader{b: bytes.NewBufferString(expected)} // can produce using a readcloser - if assert.NoError(t, cons.Produce(r, data)) { - assert.Equal(t, expected, r.String()) - assert.EqualValues(t, 0, r.calledClose) - assert.EqualValues(t, 1, data.calledClose) - } + require.NoError(t, cons.Produce(r, data)) + assert.Equal(t, expected, r.String()) + assert.EqualValues(t, 0, r.calledClose) + assert.EqualValues(t, 1, data.calledClose) } diff --git a/client/auth_info_test.go b/client/auth_info_test.go index bb73672d..1e3cc403 100644 --- a/client/auth_info_test.go +++ b/client/auth_info_test.go @@ -20,61 +20,66 @@ import ( "github.com/go-openapi/runtime" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestBasicAuth(t *testing.T) { - r, _ := newRequest("GET", "/", nil) + r, err := newRequest(http.MethodGet, "/", nil) + require.NoError(t, err) writer := BasicAuth("someone", "with a password") - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) + err = writer.AuthenticateRequest(r, nil) + require.NoError(t, err) req := new(http.Request) req.Header = make(http.Header) req.Header.Set(runtime.HeaderAuthorization, r.header.Get(runtime.HeaderAuthorization)) usr, pw, ok := req.BasicAuth() - if assert.True(t, ok) { - assert.Equal(t, "someone", usr) - assert.Equal(t, "with a password", pw) - } + require.True(t, ok) + assert.Equal(t, "someone", usr) + assert.Equal(t, "with a password", pw) } func TestAPIKeyAuth_Query(t *testing.T) { - r, _ := newRequest("GET", "/", nil) + r, err := newRequest(http.MethodGet, "/", nil) + require.NoError(t, err) writer := APIKeyAuth("api_key", "query", "the-shared-key") - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) + err = writer.AuthenticateRequest(r, nil) + require.NoError(t, err) assert.Equal(t, "the-shared-key", r.query.Get("api_key")) } func TestAPIKeyAuth_Header(t *testing.T) { - r, _ := newRequest("GET", "/", nil) + r, err := newRequest(http.MethodGet, "/", nil) + require.NoError(t, err) writer := APIKeyAuth("x-api-token", "header", "the-shared-key") - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) + err = writer.AuthenticateRequest(r, nil) + require.NoError(t, err) assert.Equal(t, "the-shared-key", r.header.Get("x-api-token")) } func TestBearerTokenAuth(t *testing.T) { - r, _ := newRequest("GET", "/", nil) + r, err := newRequest(http.MethodGet, "/", nil) + require.NoError(t, err) writer := BearerToken("the-shared-token") - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) + err = writer.AuthenticateRequest(r, nil) + require.NoError(t, err) assert.Equal(t, "Bearer the-shared-token", r.header.Get(runtime.HeaderAuthorization)) } func TestCompose(t *testing.T) { - r, _ := newRequest("GET", "/", nil) + r, err := newRequest(http.MethodGet, "/", nil) + require.NoError(t, err) writer := Compose(APIKeyAuth("x-api-key", "header", "the-api-key"), APIKeyAuth("x-secret-key", "header", "the-secret-key")) - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) + err = writer.AuthenticateRequest(r, nil) + require.NoError(t, err) assert.Equal(t, "the-api-key", r.header.Get("x-api-key")) assert.Equal(t, "the-secret-key", r.header.Get("x-secret-key")) diff --git a/client/keepalive_test.go b/client/keepalive_test.go index 5046450c..b558e048 100644 --- a/client/keepalive_test.go +++ b/client/keepalive_test.go @@ -47,7 +47,7 @@ func TestDrainingReadCloser(t *testing.T) { ts := &drainingReadCloser{rdr: rdr} _, err := ts.Read(buf) require.NoError(t, err) - ts.Close() + require.NoError(t, ts.Close()) assert.Equal(t, "There", string(buf)) assert.Equal(t, " are many things to do", disc.String()) assert.Equal(t, 3, rdr.readCalled) @@ -64,12 +64,12 @@ func TestDrainingReadCloser_SeenEOF(t *testing.T) { buf := make([]byte, 5) ts := &drainingReadCloser{rdr: rdr} _, err := ts.Read(buf) - assert.NoError(t, err) + require.NoError(t, err) _, err = ts.Read(nil) - assert.Equal(t, io.EOF, err) - ts.Close() - assert.Equal(t, string(buf), "There") - assert.Equal(t, disc.String(), "") + require.ErrorIs(t, err, io.EOF) + require.NoError(t, ts.Close()) + assert.Equal(t, "There", string(buf)) + assert.Empty(t, disc.String()) assert.Equal(t, 2, rdr.readCalled) assert.Equal(t, 1, rdr.closeCalled) } diff --git a/client/opentelemetry_test.go b/client/opentelemetry_test.go index 94d8eadb..da0f6830 100644 --- a/client/opentelemetry_test.go +++ b/client/opentelemetry_test.go @@ -2,6 +2,7 @@ package client import ( "context" + "net/http" "testing" "github.com/go-openapi/runtime" @@ -92,7 +93,7 @@ func Test_injectOpenTelemetrySpanContext(t *testing.T) { tr := newOpenTelemetryTransport(&mockRuntime{runtime.TestClientRequest{Headers: header}}, "", nil) tr.config.Propagator = propagation.TraceContext{} _, err := tr.Submit(operation) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, header, 1) } @@ -107,18 +108,20 @@ func assertOpenTelemetrySubmit(t *testing.T, operation *runtime.ClientOperation, spans := exporter.GetSpans() assert.Len(t, spans, expectedSpanCount) - if expectedSpanCount == 1 { - span := spans[0] - assert.Equal(t, "getCluster", span.Name) - assert.Equal(t, "go-openapi", span.InstrumentationLibrary.Name) - assert.Equal(t, span.Status.Code, codes.Error) - assert.Equal(t, []attribute.KeyValue{ - attribute.String("net.peer.name", "remote_host"), - attribute.String("http.route", "/kubernetes-clusters/{cluster_id}"), - attribute.String("http.method", "GET"), - attribute.String("span.kind", trace.SpanKindClient.String()), - attribute.String("http.scheme", "https"), - attribute.Int("http.status_code", 490), - }, span.Attributes) + if expectedSpanCount != 1 { + return } + + span := spans[0] + assert.Equal(t, "getCluster", span.Name) + assert.Equal(t, "go-openapi", span.InstrumentationLibrary.Name) + assert.Equal(t, codes.Error, span.Status.Code) + assert.Equal(t, []attribute.KeyValue{ + attribute.String("net.peer.name", "remote_host"), + attribute.String("http.route", "/kubernetes-clusters/{cluster_id}"), + attribute.String("http.method", http.MethodGet), + attribute.String("span.kind", trace.SpanKindClient.String()), + attribute.String("http.scheme", "https"), + attribute.Int("http.status_code", 490), + }, span.Attributes) } diff --git a/client/opentracing_test.go b/client/opentracing_test.go index d3df0652..9bb5cabf 100644 --- a/client/opentracing_test.go +++ b/client/opentracing_test.go @@ -42,7 +42,7 @@ type mockRuntime struct { func (m *mockRuntime) Submit(operation *runtime.ClientOperation) (interface{}, error) { _ = operation.Params.WriteToRequest(&m.req, nil) _, _ = operation.Reader.ReadResponse(&tres{}, nil) - return nil, nil + return nil, nil //nolint:nilnil } func testOperation(ctx context.Context) *runtime.ClientOperation { diff --git a/client/request.go b/client/request.go index 4c00ed3a..8b433865 100644 --- a/client/request.go +++ b/client/request.go @@ -102,7 +102,7 @@ func logClose(err error, pw *io.PipeWriter) { } } -func (r *request) buildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, error) { +func (r *request) buildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, error) { //nolint:gocyclo,maintidx // build the data if err := r.writer.WriteToRequest(r, registry); err != nil { return nil, err @@ -317,13 +317,13 @@ DoneChoosingBodySource: urlPath := path.Join(basePathURL.Path, pathPatternURL.Path) for k, v := range r.pathParams { - urlPath = strings.Replace(urlPath, "{"+k+"}", url.PathEscape(v), -1) + urlPath = strings.Replace(urlPath, "{"+k+"}", url.PathEscape(v), -1) //nolint:gocritic } if reinstateSlash { - urlPath = urlPath + "/" + urlPath = urlPath + "/" //nolint:gocritic } - req, err := http.NewRequest(r.method, urlPath, body) + req, err := http.NewRequest(r.method, urlPath, body) //nolint:noctx if err != nil { return nil, err } @@ -361,7 +361,7 @@ func (r *request) GetMethod() string { func (r *request) GetPath() string { path := r.pathPattern for k, v := range r.pathParams { - path = strings.Replace(path, "{"+k+"}", v, -1) + path = strings.Replace(path, "{"+k+"}", v, -1) //nolint:gocritic } return path } diff --git a/client/request_test.go b/client/request_test.go index 4a5e68ef..a8ab7d29 100644 --- a/client/request_test.go +++ b/client/request_test.go @@ -30,11 +30,10 @@ import ( "strings" "testing" + "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/go-openapi/runtime" ) var testProducers = map[string]runtime.Producer{ @@ -44,7 +43,9 @@ var testProducers = map[string]runtime.Producer{ } func TestBuildRequest_SetHeaders(t *testing.T) { - r, _ := newRequest("GET", "/flats/{id}/", nil) + r, err := newRequest(http.MethodGet, "/flats/{id}/", nil) + require.NoError(t, err) + // single value _ = r.SetHeaderParam("X-Rate-Limit", "500") assert.Equal(t, "500", r.header.Get("X-Rate-Limit")) @@ -57,14 +58,16 @@ func TestBuildRequest_SetHeaders(t *testing.T) { } func TestBuildRequest_SetPath(t *testing.T) { - r, _ := newRequest("GET", "/flats/{id}/?hello=world", nil) + r, err := newRequest(http.MethodGet, "/flats/{id}/?hello=world", nil) + require.NoError(t, err) _ = r.SetPathParam("id", "1345") assert.Equal(t, "1345", r.pathParams["id"]) } func TestBuildRequest_SetQuery(t *testing.T) { - r, _ := newRequest("GET", "/flats/{id}/", nil) + r, err := newRequest(http.MethodGet, "/flats/{id}/", nil) + require.NoError(t, err) // single value _ = r.SetQueryParam("hello", "there") @@ -77,7 +80,8 @@ func TestBuildRequest_SetQuery(t *testing.T) { func TestBuildRequest_SetForm(t *testing.T) { // non-multipart - r, _ := newRequest("POST", "/flats", nil) + r, err := newRequest(http.MethodPost, "/flats", nil) + require.NoError(t, err) _ = r.SetFormParam("hello", "world") assert.Equal(t, "world", r.formFields.Get("hello")) _ = r.SetFormParam("goodbye", "cruel", "world") @@ -86,30 +90,30 @@ func TestBuildRequest_SetForm(t *testing.T) { func TestBuildRequest_SetFile(t *testing.T) { // needs to convert form to multipart - r, _ := newRequest("POST", "/flats/{id}/image", nil) + r, err := newRequest(http.MethodPost, "/flats/{id}/image", nil) + require.NoError(t, err) + // error if it isn't there - err := r.SetFileParam("not there", os.NewFile(0, "./i-dont-exist")) - assert.Error(t, err) + err = r.SetFileParam("not there", os.NewFile(0, "./i-dont-exist")) + require.Error(t, err) + // error if it isn't a file err = r.SetFileParam("directory", os.NewFile(0, "../client")) - assert.Error(t, err) + require.Error(t, err) // success adds it to the map err = r.SetFileParam("file", mustGetFile("./runtime.go")) - if assert.NoError(t, err) { - fl, ok := r.fileFields["file"] - if assert.True(t, ok) { - assert.Equal(t, "runtime.go", filepath.Base(fl[0].Name())) - } - } + require.NoError(t, err) + fl, ok := r.fileFields["file"] + require.True(t, ok) + assert.Equal(t, "runtime.go", filepath.Base(fl[0].Name())) + // success adds a file param with multiple files err = r.SetFileParam("otherfiles", mustGetFile("./runtime.go"), mustGetFile("./request.go")) - if assert.NoError(t, err) { - fl, ok := r.fileFields["otherfiles"] - if assert.True(t, ok) { - assert.Equal(t, "runtime.go", filepath.Base(fl[0].Name())) - assert.Equal(t, "request.go", filepath.Base(fl[1].Name())) - } - } + require.NoError(t, err) + fl, ok = r.fileFields["otherfiles"] + require.True(t, ok) + assert.Equal(t, "runtime.go", filepath.Base(fl[0].Name())) + assert.Equal(t, "request.go", filepath.Base(fl[1].Name())) } func mustGetFile(path string) *os.File { @@ -121,7 +125,9 @@ func mustGetFile(path string) *os.File { } func TestBuildRequest_SetBody(t *testing.T) { - r, _ := newRequest("GET", "/flats/{id}/?hello=world", nil) + r, err := newRequest(http.MethodGet, "/flats/{id}/?hello=world", nil) + require.NoError(t, err) + bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}} _ = r.SetBodyParam(bd) @@ -129,49 +135,53 @@ func TestBuildRequest_SetBody(t *testing.T) { } func TestBuildRequest_BuildHTTP_NoPayload(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(nil) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("POST", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodPost, "/flats/{id}/", reqWrtr) + require.NoError(t, err) req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - } + require.NoError(t, err) + require.NotNil(t, req) + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) } func TestBuildRequest_BuildHTTP_Payload(t *testing.T) { bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}} - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(bd) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expectedBody, _ := json.Marshal(bd) - actualBody, _ := io.ReadAll(req.Body) - assert.Equal(t, append(expectedBody, '\n'), actualBody) - } + require.NoError(t, err) + require.NotNil(t, req) + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + expectedBody, err := json.Marshal(bd) + require.NoError(t, err) + actualBody, err := io.ReadAll(req.Body) + require.NoError(t, err) + assert.Equal(t, append(expectedBody, '\n'), actualBody) } func TestBuildRequest_BuildHTTP_SetsInAuth(t *testing.T) { bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}} - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(bd) _ = req.SetQueryParam("hello", "wrong") _ = req.SetPathParam("id", "wrong") @@ -179,7 +189,7 @@ func TestBuildRequest_BuildHTTP_SetsInAuth(t *testing.T) { return nil }) - auth := runtime.ClientAuthInfoWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + auth := runtime.ClientAuthInfoWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(bd) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") @@ -187,18 +197,22 @@ func TestBuildRequest_BuildHTTP_SetsInAuth(t *testing.T) { return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) req, err := r.buildHTTP(runtime.JSONMime, "", testProducers, nil, auth) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expectedBody, _ := json.Marshal(bd) - actualBody, _ := io.ReadAll(req.Body) - assert.Equal(t, append(expectedBody, '\n'), actualBody) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + expectedBody, err := json.Marshal(bd) + require.NoError(t, err) + actualBody, err := io.ReadAll(req.Body) + require.NoError(t, err) + assert.Equal(t, append(expectedBody, '\n'), actualBody) } func TestBuildRequest_BuildHTTP_XMLPayload(t *testing.T) { @@ -207,189 +221,213 @@ func TestBuildRequest_BuildHTTP_XMLPayload(t *testing.T) { Name string `xml:"name"` Hobby string `xml:"hobby"` }{{xml.Name{}, "Tom", "Organ trail"}, {xml.Name{}, "John", "Bird watching"}} - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(bd) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.XMLMime) req, err := r.BuildHTTP(runtime.XMLMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expectedBody, _ := xml.Marshal(bd) - actualBody, _ := io.ReadAll(req.Body) - assert.Equal(t, expectedBody, actualBody) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + expectedBody, err := xml.Marshal(bd) + require.NoError(t, err) + actualBody, err := io.ReadAll(req.Body) + require.NoError(t, err) + assert.Equal(t, expectedBody, actualBody) } func TestBuildRequest_BuildHTTP_TextPayload(t *testing.T) { - bd := "Tom: Organ trail; John: Bird watching" - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + const bd = "Tom: Organ trail; John: Bird watching" + + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(bd) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.TextMime) req, err := r.BuildHTTP(runtime.TextMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expectedBody := []byte(bd) - actualBody, _ := io.ReadAll(req.Body) - assert.Equal(t, expectedBody, actualBody) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + expectedBody := []byte(bd) + actualBody, err := io.ReadAll(req.Body) + require.NoError(t, err) + assert.Equal(t, expectedBody, actualBody) } func TestBuildRequest_BuildHTTP_Form(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetFormParam("something", "some value") _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expected := []byte("something=some+value") - actual, _ := io.ReadAll(req.Body) - assert.Equal(t, expected, actual) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + expected := []byte("something=some+value") + actual, _ := io.ReadAll(req.Body) + assert.Equal(t, expected, actual) } func TestBuildRequest_BuildHTTP_Form_URLEncoded(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetFormParam("something", "some value") _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.URLencodedFormMime) req, err := r.BuildHTTP(runtime.URLencodedFormMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, runtime.URLencodedFormMime, req.Header.Get(runtime.HeaderContentType)) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expected := []byte("something=some+value") - actual, _ := io.ReadAll(req.Body) - assert.Equal(t, expected, actual) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, runtime.URLencodedFormMime, req.Header.Get(runtime.HeaderContentType)) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + expected := []byte("something=some+value") + actual, _ := io.ReadAll(req.Body) + assert.Equal(t, expected, actual) } func TestBuildRequest_BuildHTTP_Form_Content_Length(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetFormParam("something", "some value") _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime) req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - assert.Condition(t, func() bool { return req.ContentLength > 0 }, - "ContentLength must great than 0. got %d", req.ContentLength) - expected := []byte("something=some+value") - actual, _ := io.ReadAll(req.Body) - assert.Equal(t, expected, actual) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + assert.Condition(t, func() bool { return req.ContentLength > 0 }, + "ContentLength must great than 0. got %d", req.ContentLength) + expected := []byte("something=some+value") + actual, _ := io.ReadAll(req.Body) + assert.Equal(t, expected, actual) } func TestBuildRequest_BuildHTTP_FormMultipart(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetFormParam("something", "some value") _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime) req, err := r.BuildHTTP(runtime.MultipartFormMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expected1 := []byte("Content-Disposition: form-data; name=\"something\"") - expected2 := []byte("some value") - actual, _ := io.ReadAll(req.Body) - actuallines := bytes.Split(actual, []byte("\r\n")) - assert.Equal(t, 6, len(actuallines)) - boundary := string(actuallines[0]) - lastboundary := string(actuallines[4]) - assert.True(t, strings.HasPrefix(boundary, "--")) - assert.True(t, strings.HasPrefix(lastboundary, "--") && strings.HasSuffix(lastboundary, "--")) - assert.Equal(t, lastboundary, boundary+"--") - assert.Equal(t, expected1, actuallines[1]) - assert.Equal(t, expected2, actuallines[3]) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + expected1 := []byte("Content-Disposition: form-data; name=\"something\"") + expected2 := []byte("some value") + actual, err := io.ReadAll(req.Body) + require.NoError(t, err) + actuallines := bytes.Split(actual, []byte("\r\n")) + assert.Len(t, actuallines, 6) + boundary := string(actuallines[0]) + lastboundary := string(actuallines[4]) + assert.True(t, strings.HasPrefix(boundary, "--")) + assert.True(t, strings.HasPrefix(lastboundary, "--") && strings.HasSuffix(lastboundary, "--")) + assert.Equal(t, lastboundary, boundary+"--") + assert.Equal(t, expected1, actuallines[1]) + assert.Equal(t, expected2, actuallines[3]) } func TestBuildRequest_BuildHTTP_FormMultiples(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetFormParam("something", "some value", "another value") _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime) req, err := r.BuildHTTP(runtime.MultipartFormMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expected1 := []byte("Content-Disposition: form-data; name=\"something\"") - expected2 := []byte("some value") - expected3 := []byte("another value") - actual, _ := io.ReadAll(req.Body) - actuallines := bytes.Split(actual, []byte("\r\n")) - assert.Equal(t, 10, len(actuallines)) - boundary := string(actuallines[0]) - lastboundary := string(actuallines[8]) - assert.True(t, strings.HasPrefix(boundary, "--")) - assert.True(t, strings.HasPrefix(lastboundary, "--") && strings.HasSuffix(lastboundary, "--")) - assert.Equal(t, lastboundary, boundary+"--") - assert.Equal(t, expected1, actuallines[1]) - assert.Equal(t, expected2, actuallines[3]) - assert.Equal(t, actuallines[0], actuallines[4]) - assert.Equal(t, expected1, actuallines[5]) - assert.Equal(t, expected3, actuallines[7]) - } -} - + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + expected1 := []byte("Content-Disposition: form-data; name=\"something\"") + expected2 := []byte("some value") + expected3 := []byte("another value") + actual, err := io.ReadAll(req.Body) + require.NoError(t, err) + actuallines := bytes.Split(actual, []byte("\r\n")) + assert.Len(t, actuallines, 10) + boundary := string(actuallines[0]) + lastboundary := string(actuallines[8]) + assert.True(t, strings.HasPrefix(boundary, "--")) + assert.True(t, strings.HasPrefix(lastboundary, "--") && strings.HasSuffix(lastboundary, "--")) + assert.Equal(t, lastboundary, boundary+"--") + assert.Equal(t, expected1, actuallines[1]) + assert.Equal(t, expected2, actuallines[3]) + assert.Equal(t, actuallines[0], actuallines[4]) + assert.Equal(t, expected1, actuallines[5]) + assert.Equal(t, expected3, actuallines[7]) +} + +//nolint:dupl func TestBuildRequest_BuildHTTP_Files(t *testing.T) { - cont, _ := os.ReadFile("./runtime.go") - cont2, _ := os.ReadFile("./request.go") - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + cont, err := os.ReadFile("./runtime.go") + require.NoError(t, err) + cont2, err := os.ReadFile("./request.go") + require.NoError(t, err) + + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetFormParam("something", "some value") _ = req.SetFileParam("file", mustGetFile("./runtime.go")) _ = req.SetFileParam("otherfiles", mustGetFile("./runtime.go"), mustGetFile("./request.go")) @@ -398,43 +436,52 @@ func TestBuildRequest_BuildHTTP_Files(t *testing.T) { _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - mediaType, params, err := mime.ParseMediaType(req.Header.Get(runtime.HeaderContentType)) - if assert.NoError(t, err) { - assert.Equal(t, runtime.MultipartFormMime, mediaType) - boundary := params["boundary"] - mr := multipart.NewReader(req.Body, boundary) - defer req.Body.Close() - frm, err := mr.ReadForm(1 << 20) - if assert.NoError(t, err) { - assert.Equal(t, "some value", frm.Value["something"][0]) - fileverifier := func(name string, index int, filename string, content []byte) { - mpff := frm.File[name][index] - mpf, _ := mpff.Open() - defer mpf.Close() - assert.Equal(t, filename, mpff.Filename) - actual, _ := io.ReadAll(mpf) - assert.Equal(t, content, actual) - } - fileverifier("file", 0, "runtime.go", cont) + require.NoError(t, err) + require.NotNil(t, req) - fileverifier("otherfiles", 0, "runtime.go", cont) - fileverifier("otherfiles", 1, "request.go", cont2) - } - } + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + + mediaType, params, err := mime.ParseMediaType(req.Header.Get(runtime.HeaderContentType)) + require.NoError(t, err) + + assert.Equal(t, runtime.MultipartFormMime, mediaType) + boundary := params["boundary"] + mr := multipart.NewReader(req.Body, boundary) + defer req.Body.Close() + frm, err := mr.ReadForm(1 << 20) + require.NoError(t, err) + + assert.Equal(t, "some value", frm.Value["something"][0]) + fileverifier := func(name string, index int, filename string, content []byte) { + mpff := frm.File[name][index] + mpf, e := mpff.Open() + require.NoError(t, e) + defer mpf.Close() + assert.Equal(t, filename, mpff.Filename) + actual, e := io.ReadAll(mpf) + require.NoError(t, e) + assert.Equal(t, content, actual) } + fileverifier("file", 0, "runtime.go", cont) + + fileverifier("otherfiles", 0, "runtime.go", cont) + fileverifier("otherfiles", 1, "request.go", cont2) } +//nolint:dupl func TestBuildRequest_BuildHTTP_Files_URLEncoded(t *testing.T) { - cont, _ := os.ReadFile("./runtime.go") - cont2, _ := os.ReadFile("./request.go") - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + cont, err := os.ReadFile("./runtime.go") + require.NoError(t, err) + cont2, err := os.ReadFile("./request.go") + require.NoError(t, err) + + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetFormParam("something", "some value") _ = req.SetFileParam("file", mustGetFile("./runtime.go")) _ = req.SetFileParam("otherfiles", mustGetFile("./runtime.go"), mustGetFile("./request.go")) @@ -443,37 +490,41 @@ func TestBuildRequest_BuildHTTP_Files_URLEncoded(t *testing.T) { _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.URLencodedFormMime) req, err := r.BuildHTTP(runtime.URLencodedFormMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - mediaType, params, err := mime.ParseMediaType(req.Header.Get(runtime.HeaderContentType)) - if assert.NoError(t, err) { - assert.Equal(t, runtime.URLencodedFormMime, mediaType) - boundary := params["boundary"] - mr := multipart.NewReader(req.Body, boundary) - defer req.Body.Close() - frm, err := mr.ReadForm(1 << 20) - if assert.NoError(t, err) { - assert.Equal(t, "some value", frm.Value["something"][0]) - fileverifier := func(name string, index int, filename string, content []byte) { - mpff := frm.File[name][index] - mpf, _ := mpff.Open() - defer mpf.Close() - assert.Equal(t, filename, mpff.Filename) - actual, _ := io.ReadAll(mpf) - assert.Equal(t, content, actual) - } - fileverifier("file", 0, "runtime.go", cont) + require.NoError(t, err) + require.NotNil(t, req) - fileverifier("otherfiles", 0, "runtime.go", cont) - fileverifier("otherfiles", 1, "request.go", cont2) - } - } + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/flats/1234/", req.URL.Path) + mediaType, params, err := mime.ParseMediaType(req.Header.Get(runtime.HeaderContentType)) + require.NoError(t, err) + + assert.Equal(t, runtime.URLencodedFormMime, mediaType) + boundary := params["boundary"] + mr := multipart.NewReader(req.Body, boundary) + defer req.Body.Close() + frm, err := mr.ReadForm(1 << 20) + require.NoError(t, err) + + assert.Equal(t, "some value", frm.Value["something"][0]) + fileverifier := func(name string, index int, filename string, content []byte) { + mpff := frm.File[name][index] + mpf, e := mpff.Open() + require.NoError(t, e) + defer mpf.Close() + assert.Equal(t, filename, mpff.Filename) + actual, e := io.ReadAll(mpf) + require.NoError(t, e) + assert.Equal(t, content, actual) } + fileverifier("file", 0, "runtime.go", cont) + + fileverifier("otherfiles", 0, "runtime.go", cont) + fileverifier("otherfiles", 1, "request.go", cont2) } type contentTypeProvider struct { @@ -486,9 +537,12 @@ func (p contentTypeProvider) ContentType() string { } func TestBuildRequest_BuildHTTP_File_ContentType(t *testing.T) { - cont, _ := os.ReadFile("./runtime.go") - cont2, _ := os.ReadFile("./request.go") - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + cont, err := os.ReadFile("./runtime.go") + require.NoError(t, err) + cont2, err := os.ReadFile("./request.go") + require.NoError(t, err) + + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetPathParam("id", "1234") _ = req.SetFileParam("file1", contentTypeProvider{ NamedReadCloser: mustGetFile("./runtime.go"), @@ -498,136 +552,150 @@ func TestBuildRequest_BuildHTTP_File_ContentType(t *testing.T) { return nil }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodGet, "/flats/{id}/", reqWrtr) + require.NoError(t, err) _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "/flats/1234/", req.URL.Path) - mediaType, params, err := mime.ParseMediaType(req.Header.Get(runtime.HeaderContentType)) - if assert.NoError(t, err) { - assert.Equal(t, runtime.MultipartFormMime, mediaType) - boundary := params["boundary"] - mr := multipart.NewReader(req.Body, boundary) - defer req.Body.Close() - frm, err := mr.ReadForm(1 << 20) - if assert.NoError(t, err) { - fileverifier := func(name string, index int, filename string, content []byte, contentType string) { - mpff := frm.File[name][index] - mpf, _ := mpff.Open() - defer mpf.Close() - assert.Equal(t, filename, mpff.Filename) - actual, _ := io.ReadAll(mpf) - assert.Equal(t, content, actual) - assert.Equal(t, mpff.Header.Get("Content-Type"), contentType) - } - fileverifier("file1", 0, "runtime.go", cont, "application/octet-stream") - fileverifier("file2", 0, "request.go", cont2, "text/plain; charset=utf-8") - } - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "/flats/1234/", req.URL.Path) + mediaType, params, err := mime.ParseMediaType(req.Header.Get(runtime.HeaderContentType)) + require.NoError(t, err) + assert.Equal(t, runtime.MultipartFormMime, mediaType) + boundary := params["boundary"] + mr := multipart.NewReader(req.Body, boundary) + defer req.Body.Close() + frm, err := mr.ReadForm(1 << 20) + require.NoError(t, err) + + fileverifier := func(name string, index int, filename string, content []byte, contentType string) { + mpff := frm.File[name][index] + mpf, e := mpff.Open() + require.NoError(t, e) + defer mpf.Close() + assert.Equal(t, filename, mpff.Filename) + actual, e := io.ReadAll(mpf) + require.NoError(t, e) + assert.Equal(t, content, actual) + assert.Equal(t, mpff.Header.Get("Content-Type"), contentType) } + fileverifier("file1", 0, "runtime.go", cont, "application/octet-stream") + fileverifier("file2", 0, "request.go", cont2, "text/plain; charset=utf-8") } func TestBuildRequest_BuildHTTP_BasePath(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(nil) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("POST", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodPost, "/flats/{id}/", reqWrtr) + require.NoError(t, err) req, err := r.BuildHTTP(runtime.JSONMime, "/basepath", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) - } + require.NoError(t, err) + require.NotNil(t, req) + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) } func TestBuildRequest_BuildHTTP_EscapedPath(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(nil) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234/?*&^%") _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) - r, _ := newRequest("POST", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodPost, "/flats/{id}/", reqWrtr) + require.NoError(t, err) req, err := r.BuildHTTP(runtime.JSONMime, "/basepath", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/basepath/flats/1234/?*&^%/", req.URL.Path) - assert.Equal(t, "/basepath/flats/1234%2F%3F%2A&%5E%25/", req.URL.RawPath) - assert.Equal(t, req.URL.RawPath, req.URL.EscapedPath()) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "200", req.Header.Get("x-rate-limit")) + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/basepath/flats/1234/?*&^%/", req.URL.Path) + assert.Equal(t, "/basepath/flats/1234%2F%3F%2A&%5E%25/", req.URL.RawPath) + assert.Equal(t, req.URL.RawPath, req.URL.EscapedPath()) } func TestBuildRequest_BuildHTTP_BasePathWithQueryParameters(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(nil) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") return nil }) - r, _ := newRequest("POST", "/flats/{id}/", reqWrtr) + r, err := newRequest(http.MethodPost, "/flats/{id}/", reqWrtr) + require.NoError(t, err) req, err := r.BuildHTTP(runtime.JSONMime, "/basepath?foo=bar", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "bar", req.URL.Query().Get("foo")) - assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "bar", req.URL.Query().Get("foo")) + assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) } func TestBuildRequest_BuildHTTP_PathPatternWithQueryParameters(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(nil) _ = req.SetQueryParam("hello", "world") _ = req.SetPathParam("id", "1234") return nil }) - r, _ := newRequest("POST", "/flats/{id}/?foo=bar", reqWrtr) + r, err := newRequest(http.MethodPost, "/flats/{id}/?foo=bar", reqWrtr) + require.NoError(t, err) req, err := r.BuildHTTP(runtime.JSONMime, "/basepath", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "bar", req.URL.Query().Get("foo")) - assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "bar", req.URL.Query().Get("foo")) + assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) } func TestBuildRequest_BuildHTTP_StaticParametersPathPatternPrevails(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(nil) _ = req.SetPathParam("id", "1234") return nil }) - r, _ := newRequest("POST", "/flats/{id}/?hello=world", reqWrtr) + r, err := newRequest(http.MethodPost, "/flats/{id}/?hello=world", reqWrtr) + require.NoError(t, err) req, err := r.BuildHTTP(runtime.JSONMime, "/basepath?hello=kitty", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "world", req.URL.Query().Get("hello")) + assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) } func TestBuildRequest_BuildHTTP_StaticParametersConflictClientPrevails(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { + reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { _ = req.SetBodyParam(nil) _ = req.SetQueryParam("hello", "there") _ = req.SetPathParam("id", "1234") return nil }) - r, _ := newRequest("POST", "/flats/{id}/?hello=world", reqWrtr) + r, err := newRequest(http.MethodPost, "/flats/{id}/?hello=world", reqWrtr) + require.NoError(t, err) req, err := r.BuildHTTP(runtime.JSONMime, "/basepath?hello=kitty", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "there", req.URL.Query().Get("hello")) - assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) - } + require.NoError(t, err) + require.NotNil(t, req) + + assert.Equal(t, "there", req.URL.Query().Get("hello")) + assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) } type testReqFn func(*testing.T, *http.Request) @@ -644,13 +712,14 @@ func (t *testRoundTripper) RoundTrip(req *http.Request) (resp *http.Response, er } func TestGetBodyCallsBeforeRoundTrip(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusCreated) _, err := rw.Write([]byte("test result")) require.NoError(t, err) })) defer server.Close() - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) client := http.DefaultClient transport := http.DefaultTransport @@ -660,19 +729,20 @@ func TestGetBodyCallsBeforeRoundTrip(t *testing.T) { testHarness: t, testFn: func(t *testing.T, req *http.Request) { // Read the body once before sending the request - body, err := req.GetBody() - require.NoError(t, err) - bodyContent, err := io.ReadAll(io.Reader(body)) + body, e := req.GetBody() + require.NoError(t, e) + bodyContent, e := io.ReadAll(io.Reader(body)) + require.NoError(t, e) + require.EqualValues(t, req.ContentLength, len(bodyContent)) - require.NoError(t, err) require.EqualValues(t, "\"test body\"\n", string(bodyContent)) // Read the body a second time before sending the request - body, err = req.GetBody() - require.NoError(t, err) - bodyContent, err = io.ReadAll(io.Reader(body)) - require.NoError(t, err) - require.EqualValues(t, req.ContentLength, len(bodyContent)) + body, e = req.GetBody() + require.NoError(t, e) + bodyContent, e = io.ReadAll(io.Reader(body)) + require.NoError(t, e) + require.Len(t, bodyContent, int(req.ContentLength)) require.EqualValues(t, "\"test body\"\n", string(bodyContent)) }, } @@ -683,26 +753,26 @@ func TestGetBodyCallsBeforeRoundTrip(t *testing.T) { operation := &runtime.ClientOperation{ ID: "getSites", - Method: "POST", + Method: http.MethodPost, PathPattern: "/", Params: rwrtr, Client: client, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { if response.Code() == http.StatusCreated { - var result string - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + var res string + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Unexpected error code") + return nil, errors.New("unexpected error code") }), } openAPIClient := New(hu.Host, "/", []string{"http"}) res, err := openAPIClient.Submit(operation) - require.NoError(t, err) + actual := res.(string) require.EqualValues(t, "test result", actual) } diff --git a/client/response_test.go b/client/response_test.go index 458dd047..acbbf716 100644 --- a/client/response_test.go +++ b/client/response_test.go @@ -30,13 +30,13 @@ func TestResponse(t *testing.T) { under.Status = "the status message" under.StatusCode = 392 under.Header = make(http.Header) - under.Header.Set("Blah", "blah blah") + under.Header.Set("Blah", "blahblah") under.Body = io.NopCloser(bytes.NewBufferString("some content")) var resp runtime.ClientResponse = response{under} assert.EqualValues(t, under.StatusCode, resp.Code()) assert.Equal(t, under.Status, resp.Message()) - assert.Equal(t, "blah blah", resp.GetHeader("blah")) - assert.Equal(t, []string{"blah blah"}, resp.GetHeaders("blah")) + assert.Equal(t, "blahblah", resp.GetHeader("blah")) + assert.Equal(t, []string{"blahblah"}, resp.GetHeaders("blah")) assert.Equal(t, under.Body, resp.Body()) } diff --git a/client/runtime.go b/client/runtime.go index ccec0413..629866b8 100644 --- a/client/runtime.go +++ b/client/runtime.go @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//nolint:goconst package client import ( @@ -31,13 +32,12 @@ import ( "sync" "time" - "github.com/opentracing/opentracing-go" - "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/logger" "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/runtime/yamlpc" "github.com/go-openapi/strfmt" + "github.com/opentracing/opentracing-go" ) // TLSClientOptions to configure client authentication with mutual TLS @@ -70,7 +70,7 @@ type TLSClientOptions struct { LoadedCA *x509.Certificate // LoadedCAPool specifies a pool of RootCAs to use when validating the server's TLS certificate. - // If set, it will be combined with the the other loaded certificates (see LoadedCA and CA). + // If set, it will be combined with the other loaded certificates (see LoadedCA and CA). // If neither LoadedCA or CA is set, the provided pool with override the system // certificate pool. // The caller must not use the supplied pool after calling TLSClientAuth. @@ -112,7 +112,7 @@ type TLSClientOptions struct { // TLSClientAuth creates a tls.Config for mutual auth func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { // create client tls config - cfg := &tls.Config{} + cfg := &tls.Config{} //nolint:gosec // load client cert if specified if opts.Certificate != "" { @@ -158,7 +158,7 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { // When no CA certificate is provided, default to the system cert pool // that way when a request is made to a server known by the system trust store, // the name is still verified - if opts.LoadedCA != nil { + if opts.LoadedCA != nil { //nolint:gocritic caCertPool := basePool(opts.LoadedCAPool) caCertPool.AddCert(opts.LoadedCA) cfg.RootCAs = caCertPool @@ -227,7 +227,7 @@ type Runtime struct { Host string BasePath string Formats strfmt.Registry - Context context.Context + Context context.Context //nolint:containedctx Debug bool logger logger.Logger @@ -368,7 +368,7 @@ func (r *Runtime) EnableConnectionReuse() { } // takes a client operation and creates equivalent http.Request -func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*request, *http.Request, error) { +func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*request, *http.Request, error) { //nolint:revive,stylecheck params, _, auth := operation.Params, operation.Reader, operation.AuthInfo request, err := newRequest(operation.Method, operation.PathPattern, params) @@ -420,7 +420,7 @@ func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*reques return request, req, nil } -func (r *Runtime) CreateHttpRequest(operation *runtime.ClientOperation) (req *http.Request, err error) { +func (r *Runtime) CreateHttpRequest(operation *runtime.ClientOperation) (req *http.Request, err error) { //nolint:revive,stylecheck _, req, err = r.createHttpRequest(operation) return } @@ -481,7 +481,7 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error defer res.Body.Close() ct := res.Header.Get(runtime.HeaderContentType) - if ct == "" { // this should really really never occur + if ct == "" { // this should really never occur ct = r.DefaultMediaType } @@ -526,7 +526,7 @@ func (r *Runtime) SetLogger(logger logger.Logger) { middleware.Logger = logger } -type ClientResponseFunc = func(*http.Response) runtime.ClientResponse +type ClientResponseFunc = func(*http.Response) runtime.ClientResponse //nolint:revive // SetResponseReader changes the response reader implementation. func (r *Runtime) SetResponseReader(f ClientResponseFunc) { diff --git a/client/runtime_test.go b/client/runtime_test.go index 3c4c7c50..58fc2ff3 100644 --- a/client/runtime_test.go +++ b/client/runtime_test.go @@ -16,7 +16,10 @@ package client import ( "bytes" + "crypto/tls" + "crypto/x509" "encoding/json" + "encoding/pem" "encoding/xml" "errors" "io" @@ -25,19 +28,21 @@ import ( "net/http/httptest" "net/url" "os" + "path/filepath" + goruntime "runtime" "testing" "time" - "crypto/tls" - "crypto/x509" - "encoding/pem" - "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" +) - goruntime "runtime" +const ( + token = "the-super-secret-token" + bearerToken = "Bearer " + token + charsetUTF8 = ";charset=utf-8" ) // task This describes a task. Tasks require a content property to be set. @@ -60,13 +65,11 @@ func TestRuntime_TLSAuthConfig(t *testing.T) { opts.ServerName = "somewhere" cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.Len(t, cfg.Certificates, 1) - assert.NotNil(t, cfg.RootCAs) - assert.Equal(t, "somewhere", cfg.ServerName) - } - } + require.NoError(t, err) + require.NotNil(t, cfg) + assert.Len(t, cfg.Certificates, 1) + assert.NotNil(t, cfg.RootCAs) + assert.Equal(t, "somewhere", cfg.ServerName) } func TestRuntime_TLSAuthConfigWithRSAKey(t *testing.T) { @@ -93,11 +96,9 @@ func TestRuntime_TLSAuthConfigWithRSAKey(t *testing.T) { opts.LoadedCertificate = cert cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.Len(t, cfg.Certificates, 1) - } - } + require.NoError(t, err) + require.NotNil(t, cfg) + assert.Len(t, cfg.Certificates, 1) } func TestRuntime_TLSAuthConfigWithECKey(t *testing.T) { @@ -125,11 +126,9 @@ func TestRuntime_TLSAuthConfigWithECKey(t *testing.T) { opts.LoadedCertificate = cert cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.Len(t, cfg.Certificates, 1) - } - } + require.NoError(t, err) + require.NotNil(t, cfg) + assert.Len(t, cfg.Certificates, 1) } func TestRuntime_TLSAuthConfigWithLoadedCA(t *testing.T) { @@ -146,11 +145,9 @@ func TestRuntime_TLSAuthConfigWithLoadedCA(t *testing.T) { opts.LoadedCA = cert cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.NotNil(t, cfg.RootCAs) - } - } + require.NoError(t, err) + require.NotNil(t, cfg) + assert.NotNil(t, cfg.RootCAs) } func TestRuntime_TLSAuthConfigWithLoadedCAPool(t *testing.T) { @@ -170,19 +167,17 @@ func TestRuntime_TLSAuthConfigWithLoadedCAPool(t *testing.T) { opts.LoadedCAPool = pool cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - require.NotNil(t, cfg.RootCAs) + require.NoError(t, err) + require.NotNil(t, cfg) + require.NotNil(t, cfg.RootCAs) - // Using require.Len prints the (very large and incomprehensible) - // Subjects list on failure, so instead use require.Equal. - require.Equal(t, 1, len(cfg.RootCAs.Subjects())) // nolint:staticcheck - } - } + // Using require.Len prints the (very large and incomprehensible) + // Subjects list on failure, so instead use require.Equal. + assert.Len(t, cfg.RootCAs.Subjects(), 1) //nolint:staticcheck } func TestRuntime_TLSAuthConfigWithLoadedCAPoolAndLoadedCA(t *testing.T) { - certPem, err := os.ReadFile("../fixtures/certs/myCA.crt") + certPem, err := os.ReadFile(filepath.Join("..", "fixtures", "certs", "myCA.crt")) require.NoError(t, err) block, _ := pem.Decode(certPem) @@ -199,22 +194,20 @@ func TestRuntime_TLSAuthConfigWithLoadedCAPoolAndLoadedCA(t *testing.T) { pool, err = x509.SystemCertPool() require.NoError(t, err) } - startingCertCount := len(pool.Subjects()) // nolint:staticcheck + startingCertCount := len(pool.Subjects()) //nolint:staticcheck var opts TLSClientOptions opts.LoadedCAPool = pool opts.LoadedCA = cert cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - require.NotNil(t, cfg.RootCAs) + require.NoError(t, err) + require.NotNil(t, cfg) + require.NotNil(t, cfg.RootCAs) - // Using require.Len prints the (very large and incomprehensible) - // Subjects list on failure, so instead use require.Equal. - require.Equal(t, startingCertCount+1, len(cfg.RootCAs.Subjects())) // nolint:staticcheck - } - } + // Using require.Len prints the (very large and incomprehensible) + // Subjects list on failure, so instead use require.Equal. + assert.Len(t, cfg.RootCAs.Subjects(), startingCertCount+1) //nolint:staticcheck } func TestRuntime_TLSAuthConfigWithVerifyPeerCertificate(t *testing.T) { @@ -226,12 +219,10 @@ func TestRuntime_TLSAuthConfigWithVerifyPeerCertificate(t *testing.T) { opts.VerifyPeerCertificate = verify cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.True(t, cfg.InsecureSkipVerify) - assert.NotNil(t, cfg.VerifyPeerCertificate) - } - } + require.NoError(t, err) + require.NotNil(t, cfg) + assert.True(t, cfg.InsecureSkipVerify) + assert.NotNil(t, cfg.VerifyPeerCertificate) } func TestRuntime_ManualCertificateValidation(t *testing.T) { @@ -242,15 +233,15 @@ func TestRuntime_ManualCertificateValidation(t *testing.T) { {false, "task 2 content", 2}, } var verifyCalled bool - server := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) + require.NoError(t, jsongen.Encode(result)) })) // root cert - rootCertFile := "../fixtures/certs/myCA.crt" + rootCertFile := filepath.Join("..", "fixtures", "certs", "myCA.crt") rootCertPem, err := os.ReadFile(rootCertFile) require.NoError(t, err) rootCertRaw, _ := pem.Decode(rootCertPem) @@ -262,12 +253,13 @@ func TestRuntime_ManualCertificateValidation(t *testing.T) { serverCACertPool := x509.NewCertPool() serverCACertPool.AddCert(rootCert) server.TLS = &tls.Config{ - RootCAs: serverCACertPool, + RootCAs: serverCACertPool, + MinVersion: tls.VersionTLS12, } // load server certs - serverCertFile := "../fixtures/certs/mycert1.crt" - serverKeyFile := "../fixtures/certs/mycert1.key" + serverCertFile := filepath.Join("..", "fixtures", "certs", "mycert1.crt") + serverKeyFile := filepath.Join("..", "fixtures", "certs", "mycert1.key") server.TLS.Certificates = make([]tls.Certificate, 1) server.TLS.Certificates[0], err = tls.LoadX509KeyPair( serverCertFile, @@ -283,7 +275,7 @@ func TestRuntime_ManualCertificateValidation(t *testing.T) { // explicitly omitting DNSName check. client, err := TLSClient(TLSClientOptions{ InsecureSkipVerify: true, - VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { + VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error { verifyCalled = true caCertPool := x509.NewCertPool() @@ -294,18 +286,19 @@ func TestRuntime_ManualCertificateValidation(t *testing.T) { CurrentTime: time.Date(2017, time.July, 1, 1, 1, 1, 1, time.UTC), } - cert, err := x509.ParseCertificate(rawCerts[0]) - if err != nil { - return err + cert, e := x509.ParseCertificate(rawCerts[0]) + if e != nil { + return e } - _, err = cert.Verify(opts) - return err + _, e = cert.Verify(opts) + return e }, }) require.NoError(t, err) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) rt := NewWithClient(hu.Host, "/", []string{"https"}, client) rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { @@ -315,25 +308,24 @@ func TestRuntime_ManualCertificateValidation(t *testing.T) { var received []task _, err = rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - if err := consumer.Consume(response.Body(), &received); err != nil { - return nil, err + if response.Code() == http.StatusOK { + if e := consumer.Consume(response.Body(), &received); e != nil { + return nil, e } return result, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - if assert.NoError(t, err) { - assert.True(t, verifyCalled) - assert.IsType(t, []task{}, received) - assert.EqualValues(t, result, received) - } + require.NoError(t, err) + assert.True(t, verifyCalled) + assert.IsType(t, []task{}, received) + assert.EqualValues(t, result, received) } func TestRuntime_Concurrent(t *testing.T) { @@ -344,11 +336,11 @@ func TestRuntime_Concurrent(t *testing.T) { {false, "task 1 content", 1}, {false, "task 2 content", 2}, } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) + require.NoError(t, jsongen.Encode(result)) })) defer server.Close() @@ -356,12 +348,13 @@ func TestRuntime_Concurrent(t *testing.T) { return nil }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) + rt := New(hu.Host, "/", []string{"http"}) resCC := make(chan interface{}) errCC := make(chan error) var res interface{} - var err error for j := 0; j < 6; j++ { go func() { @@ -374,18 +367,18 @@ func TestRuntime_Concurrent(t *testing.T) { for i := 0; i < 3; i++ { resp, errp = rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []task + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) <-time.After(100 * time.Millisecond) @@ -405,11 +398,10 @@ func TestRuntime_Concurrent(t *testing.T) { c-- } - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []task{}, res) + actual := res.([]task) + assert.EqualValues(t, result, actual) } func TestRuntime_Canary(t *testing.T) { @@ -420,11 +412,11 @@ func TestRuntime_Canary(t *testing.T) { {false, "task 1 content", 1}, {false, "task 2 content", 2}, } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) + require.NoError(t, jsongen.Encode(result)) })) defer server.Close() @@ -432,30 +424,30 @@ func TestRuntime_Canary(t *testing.T) { return nil }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) rt := New(hu.Host, "/", []string{"http"}) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []task + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []task{}, res) + actual := res.([]task) + assert.EqualValues(t, result, actual) } type tasks struct { @@ -471,11 +463,11 @@ func TestRuntime_XMLCanary(t *testing.T) { {false, "task 2 content", 2}, }, } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Header().Add(runtime.HeaderContentType, runtime.XMLMime) rw.WriteHeader(http.StatusOK) xmlgen := xml.NewEncoder(rw) - _ = xmlgen.Encode(result) + require.NoError(t, xmlgen.Encode(result)) })) defer server.Close() @@ -483,37 +475,38 @@ func TestRuntime_XMLCanary(t *testing.T) { return nil }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) + rt := New(hu.Host, "/", []string{"http"}) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result tasks - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res tasks + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - if assert.NoError(t, err) { - assert.IsType(t, tasks{}, res) - actual := res.(tasks) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, tasks{}, res) + actual := res.(tasks) + assert.EqualValues(t, result, actual) } func TestRuntime_TextCanary(t *testing.T) { // test that it can make a simple text request // and get the response for it. result := "1: task 1 content; 2: task 2 content" - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Header().Add(runtime.HeaderContentType, runtime.TextMime) rw.WriteHeader(http.StatusOK) _, _ = rw.Write([]byte(result)) @@ -524,30 +517,31 @@ func TestRuntime_TextCanary(t *testing.T) { return nil }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) + rt := New(hu.Host, "/", []string{"http"}) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result string - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res string + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - if assert.NoError(t, err) { - assert.IsType(t, "", res) - actual := res.(string) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, "", res) + actual := res.(string) + assert.EqualValues(t, result, actual) } func TestRuntime_CSVCanary(t *testing.T) { @@ -557,7 +551,7 @@ func TestRuntime_CSVCanary(t *testing.T) { 1,task1,ok 2,task2,fail ` - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Header().Add(runtime.HeaderContentType, runtime.CSVMime) rw.WriteHeader(http.StatusOK) _, _ = rw.Write([]byte(result)) @@ -568,30 +562,31 @@ func TestRuntime_CSVCanary(t *testing.T) { return nil }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) + rt := New(hu.Host, "/", []string{"http"}) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result bytes.Buffer - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res bytes.Buffer + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - if assert.NoError(t, err) { - assert.IsType(t, bytes.Buffer{}, res) - actual := res.(bytes.Buffer) - assert.EqualValues(t, result, actual.String()) - } + require.NoError(t, err) + assert.IsType(t, bytes.Buffer{}, res) + actual := res.(bytes.Buffer) + assert.EqualValues(t, result, actual.String()) } type roundTripperFunc func(*http.Request) (*http.Response, error) @@ -616,40 +611,40 @@ func TestRuntime_CustomTransport(t *testing.T) { } assert.Equal(t, "localhost:3245", req.Host) assert.Equal(t, "localhost:3245", req.URL.Host) + var resp http.Response - resp.StatusCode = 200 + resp.StatusCode = http.StatusOK resp.Header = make(http.Header) resp.Header.Set("content-type", "application/json") buf := bytes.NewBuffer(nil) enc := json.NewEncoder(buf) - _ = enc.Encode(result) + require.NoError(t, enc.Encode(result)) resp.Body = io.NopCloser(buf) return &resp, nil }) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Schemes: []string{"ws", "wss", "https"}, Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []task + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []task{}, res) + actual := res.([]task) + assert.EqualValues(t, result, actual) } func TestRuntime_CustomCookieJar(t *testing.T) { @@ -671,7 +666,7 @@ func TestRuntime_CustomCookieJar(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - _ = jsongen.Encode([]task{}) + require.NoError(t, jsongen.Encode([]task{})) } else { rw.WriteHeader(http.StatusUnauthorized) } @@ -682,26 +677,29 @@ func TestRuntime_CustomCookieJar(t *testing.T) { return nil }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) + rt := New(hu.Host, "/", []string{"http"}) - rt.Jar, _ = cookiejar.New(nil) + rt.Jar, err = cookiejar.New(nil) + require.NoError(t, err) submit := func(authInfo runtime.ClientAuthInfoWriter) { _, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Params: rwrtr, AuthInfo: authInfo, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - return nil, nil + Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) { + if response.Code() == http.StatusOK { + return nil, nil //nolint:nilnil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - assert.NoError(t, err) + require.NoError(t, err) } submit(BasicAuth("username", "password")) @@ -709,6 +707,7 @@ func TestRuntime_CustomCookieJar(t *testing.T) { } func TestRuntime_AuthCanary(t *testing.T) { + // test that it can make a simple request // and get the response for it. // defaults all the way down @@ -717,14 +716,15 @@ func TestRuntime_AuthCanary(t *testing.T) { {false, "task 2 content", 2}, } server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Header.Get(runtime.HeaderAuthorization) != "Bearer the-super-secret-token" { - rw.WriteHeader(401) + if req.Header.Get(runtime.HeaderAuthorization) != bearerToken { + rw.WriteHeader(http.StatusUnauthorized) return } + rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) + require.NoError(t, jsongen.Encode(result)) })) defer server.Close() @@ -732,30 +732,30 @@ func TestRuntime_AuthCanary(t *testing.T) { return nil }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) rt := New(hu.Host, "/", []string{"http"}) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []task + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), - AuthInfo: BearerToken("the-super-secret-token"), + AuthInfo: BearerToken(token), }) - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []task{}, res) + actual := res.([]task) + assert.EqualValues(t, result, actual) } func TestRuntime_PickConsumer(t *testing.T) { @@ -765,11 +765,11 @@ func TestRuntime_PickConsumer(t *testing.T) { } server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if req.Header.Get("Content-Type") != "application/octet-stream" { - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") - rw.WriteHeader(400) + rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+charsetUTF8) + rw.WriteHeader(http.StatusBadRequest) return } - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") + rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+charsetUTF8) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) _ = jsongen.Encode(result) @@ -780,7 +780,9 @@ func TestRuntime_PickConsumer(t *testing.T) { return req.SetBodyParam(bytes.NewBufferString("hello")) }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) + rt := New(hu.Host, "/", []string{"http"}) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", @@ -790,23 +792,22 @@ func TestRuntime_PickConsumer(t *testing.T) { ConsumesMediaTypes: []string{"application/octet-stream"}, Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []task + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), - AuthInfo: BearerToken("the-super-secret-token"), + AuthInfo: BearerToken(token), }) - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []task{}, res) + actual := res.([]task) + assert.EqualValues(t, result, actual) } func TestRuntime_ContentTypeCanary(t *testing.T) { @@ -818,11 +819,11 @@ func TestRuntime_ContentTypeCanary(t *testing.T) { {false, "task 2 content", 2}, } server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Header.Get(runtime.HeaderAuthorization) != "Bearer the-super-secret-token" { - rw.WriteHeader(400) + if req.Header.Get(runtime.HeaderAuthorization) != bearerToken { + rw.WriteHeader(http.StatusBadRequest) return } - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") + rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+charsetUTF8) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) _ = jsongen.Encode(result) @@ -833,32 +834,33 @@ func TestRuntime_ContentTypeCanary(t *testing.T) { return nil }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) + rt := New(hu.Host, "/", []string{"http"}) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Schemes: []string{"http"}, Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []task + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), - AuthInfo: BearerToken("the-super-secret-token"), + AuthInfo: BearerToken(token), }) - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []task{}, res) + actual := res.([]task) + assert.EqualValues(t, result, actual) } func TestRuntime_ChunkedResponse(t *testing.T) { @@ -870,12 +872,12 @@ func TestRuntime_ChunkedResponse(t *testing.T) { {false, "task 2 content", 2}, } server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Header.Get(runtime.HeaderAuthorization) != "Bearer the-super-secret-token" { - rw.WriteHeader(400) + if req.Header.Get(runtime.HeaderAuthorization) != bearerToken { + rw.WriteHeader(http.StatusBadRequest) return } rw.Header().Add(runtime.HeaderTransferEncoding, "chunked") - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") + rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+charsetUTF8) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) _ = jsongen.Encode(result) @@ -886,64 +888,73 @@ func TestRuntime_ChunkedResponse(t *testing.T) { return nil }) - //specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml") - hu, _ := url.Parse(server.URL) + // specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml") + hu, err := url.Parse(server.URL) + require.NoError(t, err) rt := New(hu.Host, "/", []string{"http"}) res, err := rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/", Schemes: []string{"http"}, Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []task + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), - AuthInfo: BearerToken("the-super-secret-token"), + AuthInfo: BearerToken(token), }) - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []task{}, res) + actual := res.([]task) + assert.EqualValues(t, result, actual) } func TestRuntime_DebugValue(t *testing.T) { - original := os.Getenv("DEBUG") + t.Run("empty DEBUG means Debug is False", func(t *testing.T) { + t.Setenv("DEBUG", "") - // Emtpy DEBUG means Debug is False - _ = os.Setenv("DEBUG", "") - runtime := New("", "/", []string{"https"}) - assert.False(t, runtime.Debug) + runtime := New("", "/", []string{"https"}) + assert.False(t, runtime.Debug) + }) - // Non-Empty Debug means Debug is True + t.Run("non-Empty DEBUG means Debug is True", func(t *testing.T) { + t.Run("with numerical value", func(t *testing.T) { + t.Setenv("DEBUG", "1") - _ = os.Setenv("DEBUG", "1") - runtime = New("", "/", []string{"https"}) - assert.True(t, runtime.Debug) + runtime := New("", "/", []string{"https"}) + assert.True(t, runtime.Debug) + }) - _ = os.Setenv("DEBUG", "true") - runtime = New("", "/", []string{"https"}) - assert.True(t, runtime.Debug) + t.Run("with boolean value true", func(t *testing.T) { + t.Setenv("DEBUG", "true") - _ = os.Setenv("DEBUG", "false") - runtime = New("", "/", []string{"https"}) - assert.False(t, runtime.Debug) + runtime := New("", "/", []string{"https"}) + assert.True(t, runtime.Debug) + }) - _ = os.Setenv("DEBUG", "foo") - runtime = New("", "/", []string{"https"}) - assert.True(t, runtime.Debug) + t.Run("with boolean value false", func(t *testing.T) { + t.Setenv("DEBUG", "false") - // Make sure DEBUG is initial value once again - _ = os.Setenv("DEBUG", original) + runtime := New("", "/", []string{"https"}) + assert.False(t, runtime.Debug) + }) + + t.Run("with string value ", func(t *testing.T) { + t.Setenv("DEBUG", "foo") + + runtime := New("", "/", []string{"https"}) + assert.True(t, runtime.Debug) + }) + }) } func TestRuntime_OverrideScheme(t *testing.T) { @@ -962,13 +973,13 @@ func TestRuntime_OverrideClient(t *testing.T) { } type overrideRoundTripper struct { - overriden bool + overridden bool } -func (o *overrideRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - o.overriden = true +func (o *overrideRoundTripper) RoundTrip(_ *http.Request) (*http.Response, error) { + o.overridden = true res := new(http.Response) - res.StatusCode = 200 + res.StatusCode = http.StatusOK res.Body = io.NopCloser(bytes.NewBufferString("OK")) return res, nil } @@ -984,27 +995,26 @@ func TestRuntime_OverrideClientOperation(t *testing.T) { client2 := new(http.Client) var transport = &overrideRoundTripper{} client2.Transport = transport - if assert.NotEqual(t, client, client2) { - _, err := rt.Submit(&runtime.ClientOperation{ - Client: client2, - Params: runtime.ClientRequestWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }), - Reader: runtime.ClientResponseReaderFunc(func(_ runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) { - return nil, nil - }), - }) - if assert.NoError(t, err) { - assert.True(t, transport.overriden) - } - } + require.NotEqual(t, client, client2) + + _, err := rt.Submit(&runtime.ClientOperation{ + Client: client2, + Params: runtime.ClientRequestWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { + return nil + }), + Reader: runtime.ClientResponseReaderFunc(func(_ runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) { + return nil, nil //nolint:nilnil + }), + }) + require.NoError(t, err) + assert.True(t, transport.overridden) } func TestRuntime_PreserveTrailingSlash(t *testing.T) { var redirected bool server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") + rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+charsetUTF8) if req.URL.Path == "/api/tasks" { redirected = true @@ -1016,36 +1026,35 @@ func TestRuntime_PreserveTrailingSlash(t *testing.T) { })) defer server.Close() - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) rt := New(hu.Host, "/", []string{"http"}) - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { return nil }) - _, err := rt.Submit(&runtime.ClientOperation{ + _, err = rt.Submit(&runtime.ClientOperation{ ID: "getTasks", - Method: "GET", + Method: http.MethodGet, PathPattern: "/api/tasks/", Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) { if redirected { return nil, errors.New("expected Submit to preserve trailing slashes - this caused a redirect") } if response.Code() == http.StatusOK { - return nil, nil + return nil, nil //nolint:nilnil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - - assert.NoError(t, err) + require.NoError(t, err) } func TestRuntime_FallbackConsumer(t *testing.T) { result := `W3siY29tcGxldGVkIjpmYWxzZSwiY29udGVudCI6ImRHRnpheUF4SUdOdmJuUmxiblE9IiwiaWQiOjF9XQ==` - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Header().Add(runtime.HeaderContentType, "application/x-task") rw.WriteHeader(http.StatusOK) _, _ = rw.Write([]byte(result)) @@ -1056,11 +1065,12 @@ func TestRuntime_FallbackConsumer(t *testing.T) { return req.SetBodyParam(bytes.NewBufferString("hello")) }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) rt := New(hu.Host, "/", []string{"http"}) // without the fallback consumer - _, err := rt.Submit(&runtime.ClientOperation{ + _, err = rt.Submit(&runtime.ClientOperation{ ID: "getTasks", Method: "POST", PathPattern: "/", @@ -1068,20 +1078,18 @@ func TestRuntime_FallbackConsumer(t *testing.T) { ConsumesMediaTypes: []string{"application/octet-stream"}, Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []byte - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []byte + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - - if assert.Error(t, err) { - assert.Equal(t, `no consumer: "application/x-task"`, err.Error()) - } + require.Error(t, err) + assert.Equal(t, `no consumer: "application/x-task"`, err.Error()) // add the fallback consumer rt.Consumers["*/*"] = rt.Consumers[runtime.DefaultMime] @@ -1093,22 +1101,21 @@ func TestRuntime_FallbackConsumer(t *testing.T) { ConsumesMediaTypes: []string{"application/octet-stream"}, Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []byte - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []byte + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - if assert.NoError(t, err) { - assert.IsType(t, []byte{}, res) - actual := res.([]byte) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []byte{}, res) + actual := res.([]byte) + assert.EqualValues(t, result, actual) } func TestRuntime_AuthHeaderParamDetected(t *testing.T) { @@ -1120,8 +1127,8 @@ func TestRuntime_AuthHeaderParamDetected(t *testing.T) { {false, "task 2 content", 2}, } server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Header.Get(runtime.HeaderAuthorization) != "Bearer the-super-secret-token" { - rw.WriteHeader(401) + if req.Header.Get(runtime.HeaderAuthorization) != bearerToken { + rw.WriteHeader(http.StatusUnauthorized) return } rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) @@ -1132,10 +1139,11 @@ func TestRuntime_AuthHeaderParamDetected(t *testing.T) { defer server.Close() rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return req.SetHeaderParam(runtime.HeaderAuthorization, "Bearer the-super-secret-token") + return req.SetHeaderParam(runtime.HeaderAuthorization, bearerToken) }) - hu, _ := url.Parse(server.URL) + hu, err := url.Parse(server.URL) + require.NoError(t, err) rt := New(hu.Host, "/", []string{"http"}) rt.DefaultAuthentication = BearerToken("not-the-super-secret-token") @@ -1143,20 +1151,19 @@ func TestRuntime_AuthHeaderParamDetected(t *testing.T) { ID: "getTasks", Params: rwrtr, Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err + if response.Code() == http.StatusOK { + var res []task + if e := consumer.Consume(response.Body(), &res); e != nil { + return nil, e } - return result, nil + return res, nil } - return nil, errors.New("Generic error") + return nil, errors.New("generic error") }), }) - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } + require.NoError(t, err) + assert.IsType(t, []task{}, res) + actual := res.([]task) + assert.EqualValues(t, result, actual) } diff --git a/client_operation.go b/client_operation.go index fa21eacf..1a1975f1 100644 --- a/client_operation.go +++ b/client_operation.go @@ -30,12 +30,12 @@ type ClientOperation struct { AuthInfo ClientAuthInfoWriter Params ClientRequestWriter Reader ClientResponseReader - Context context.Context + Context context.Context //nolint:containedctx Client *http.Client } // A ClientTransport implementor knows how to submit Request objects to some destination type ClientTransport interface { - //Submit(string, RequestWriter, ResponseReader, AuthInfoWriter) (interface{}, error) + // Submit(string, RequestWriter, ResponseReader, AuthInfoWriter) (interface{}, error) Submit(*ClientOperation) (interface{}, error) } diff --git a/client_request.go b/client_request.go index d4d2b58f..654333af 100644 --- a/client_request.go +++ b/client_request.go @@ -38,6 +38,8 @@ type ClientRequestWriter interface { // ClientRequest is an interface for things that know how to // add information to a swagger client request +// +//nolint:interfacebloat type ClientRequest interface { SetHeaderParam(string, ...string) error diff --git a/client_request_test.go b/client_request_test.go index 1de7a1b1..9646e82a 100644 --- a/client_request_test.go +++ b/client_request_test.go @@ -22,14 +22,14 @@ import ( ) func TestRequestWriterFunc(t *testing.T) { - hand := ClientRequestWriterFunc(func(r ClientRequest, reg strfmt.Registry) error { - _ = r.SetHeaderParam("blah", "blah blah") + hand := ClientRequestWriterFunc(func(r ClientRequest, _ strfmt.Registry) error { + _ = r.SetHeaderParam("blah", "blahblah") _ = r.SetBodyParam(struct{ Name string }{"Adriana"}) return nil }) tr := new(TestClientRequest) _ = hand.WriteToRequest(tr, nil) - assert.Equal(t, "blah blah", tr.Headers.Get("blah")) + assert.Equal(t, "blahblah", tr.Headers.Get("blah")) assert.Equal(t, "Adriana", tr.Body.(struct{ Name string }).Name) } diff --git a/client_response_test.go b/client_response_test.go index 75a67586..c8a70c33 100644 --- a/client_response_test.go +++ b/client_response_test.go @@ -23,6 +23,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type response struct { @@ -70,7 +71,7 @@ func TestResponseReaderFuncError(t *testing.T) { return nil, NewAPIError("fake", errors.New("writer closed"), 490) }) _, err := reader.ReadResponse(response{}, nil) - assert.NotNil(t, err) + require.Error(t, err) assert.True(t, strings.Contains(err.Error(), "writer closed"), err.Error()) reader = func(r ClientResponse, _ Consumer) (interface{}, error) { @@ -83,7 +84,7 @@ func TestResponseReaderFuncError(t *testing.T) { return nil, NewAPIError("fake", err, 200) } _, err = reader.ReadResponse(response{}, nil) - assert.NotNil(t, err) - assert.True(t, strings.Contains(err.Error(), "file already closed"), err.Error()) + require.Error(t, err) + assert.Contains(t, err.Error(), "file already closed") } diff --git a/csv_test.go b/csv_test.go index e87b7919..3768684b 100644 --- a/csv_test.go +++ b/csv_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const consProdCSV = `name,country,age @@ -30,29 +31,29 @@ Mike,US,20 type csvEmptyReader struct{} -func (r *csvEmptyReader) Read(d []byte) (int, error) { +func (r *csvEmptyReader) Read(_ []byte) (int, error) { return 0, io.EOF } func TestCSVConsumer(t *testing.T) { cons := CSVConsumer() - reader := bytes.NewBuffer([]byte(consProdCSV)) + reader := bytes.NewBufferString(consProdCSV) outBuf := new(bytes.Buffer) err := cons.Consume(reader, outBuf) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consProdCSV, outBuf.String()) outBuf2 := new(bytes.Buffer) err = cons.Consume(nil, outBuf2) - assert.Error(t, err) + require.Error(t, err) err = cons.Consume(reader, struct{}{}) - assert.Error(t, err) + require.Error(t, err) emptyOutBuf := new(bytes.Buffer) err = cons.Consume(&csvEmptyReader{}, emptyOutBuf) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "", emptyOutBuf.String()) } @@ -62,13 +63,13 @@ func TestCSVProducer(t *testing.T) { rw := httptest.NewRecorder() err := prod.Produce(rw, data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consProdCSV, rw.Body.String()) rw2 := httptest.NewRecorder() err = prod.Produce(rw2, struct{}{}) - assert.Error(t, err) + require.Error(t, err) err = prod.Produce(nil, data) - assert.Error(t, err) + require.Error(t, err) } diff --git a/file_test.go b/file_test.go index 4a5a0680..d17c6075 100644 --- a/file_test.go +++ b/file_test.go @@ -6,6 +6,7 @@ import ( "github.com/go-openapi/spec" "github.com/go-openapi/validate" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidateFile(t *testing.T) { @@ -13,7 +14,7 @@ func TestValidateFile(t *testing.T) { validator := validate.NewParamValidator(fileParam, nil) result := validator.Validate("str") - assert.Equal(t, 1, len(result.Errors)) + require.Len(t, result.Errors, 1) assert.Equal( t, `f in formData must be of type file: "string"`, diff --git a/flagext/byte_size_test.go b/flagext/byte_size_test.go index 698fc0e4..f5853c11 100644 --- a/flagext/byte_size_test.go +++ b/flagext/byte_size_test.go @@ -4,13 +4,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMarshalBytesize(t *testing.T) { v, err := ByteSize(1024).MarshalFlag() - if assert.NoError(t, err) { - assert.Equal(t, "1.024kB", v) - } + require.NoError(t, err) + assert.Equal(t, "1.024kB", v) } func TestStringBytesize(t *testing.T) { @@ -21,23 +21,21 @@ func TestStringBytesize(t *testing.T) { func TestUnmarshalBytesize(t *testing.T) { var b ByteSize err := b.UnmarshalFlag("notASize") - assert.Error(t, err) + require.Error(t, err) err = b.UnmarshalFlag("1MB") - if assert.NoError(t, err) { - assert.Equal(t, ByteSize(1000000), b) - } + require.NoError(t, err) + assert.Equal(t, ByteSize(1000000), b) } func TestSetBytesize(t *testing.T) { var b ByteSize err := b.Set("notASize") - assert.Error(t, err) + require.Error(t, err) err = b.Set("2MB") - if assert.NoError(t, err) { - assert.Equal(t, ByteSize(2000000), b) - } + require.NoError(t, err) + assert.Equal(t, ByteSize(2000000), b) } func TestTypeBytesize(t *testing.T) { diff --git a/go.mod b/go.mod index c1970749..db8d2afb 100644 --- a/go.mod +++ b/go.mod @@ -3,14 +3,14 @@ module github.com/go-openapi/runtime require ( github.com/docker/go-units v0.5.0 github.com/go-openapi/analysis v0.21.4 - github.com/go-openapi/errors v0.20.3 + github.com/go-openapi/errors v0.20.4 github.com/go-openapi/loads v0.21.2 - github.com/go-openapi/spec v0.20.8 - github.com/go-openapi/strfmt v0.21.7 - github.com/go-openapi/swag v0.22.3 - github.com/go-openapi/validate v0.22.1 + github.com/go-openapi/spec v0.20.11 + github.com/go-openapi/strfmt v0.21.8 + github.com/go-openapi/swag v0.22.4 + github.com/go-openapi/validate v0.22.3 github.com/opentracing/opentracing-go v1.2.0 - github.com/stretchr/testify v1.8.2 + github.com/stretchr/testify v1.8.4 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/sdk v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 @@ -20,18 +20,18 @@ require ( require ( github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/go-logr/logr v1.2.3 // indirect + github.com/go-logr/logr v1.3.0 // indirect github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/jsonpointer v0.19.5 // indirect - github.com/go-openapi/jsonreference v0.20.0 // indirect + github.com/go-openapi/jsonpointer v0.20.0 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/oklog/ulid v1.3.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - go.mongodb.org/mongo-driver v1.11.3 // indirect + go.mongodb.org/mongo-driver v1.13.1 // indirect golang.org/x/sys v0.5.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) -go 1.18 +go 1.19 diff --git a/go.sum b/go.sum index 0b9662ef..6d8d3c4d 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,3 @@ -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/asaskevich/govalidator v0.0.0-20200907205600-7a23bdc65eef/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= @@ -11,84 +8,50 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= -github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY= +github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-openapi/analysis v0.21.2/go.mod h1:HZwRk4RRisyG8vx2Oe6aqeSQcoxRp47Xkp3+K6q+LdY= github.com/go-openapi/analysis v0.21.4 h1:ZDFLvSNxpDaomuCueM0BlSXxpANBlFYiBvr+GXrvIHc= github.com/go-openapi/analysis v0.21.4/go.mod h1:4zQ35W4neeZTqh3ol0rv/O8JBbka9QyAgQRPp9y3pfo= -github.com/go-openapi/errors v0.19.8/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= -github.com/go-openapi/errors v0.19.9/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= github.com/go-openapi/errors v0.20.2/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= -github.com/go-openapi/errors v0.20.3 h1:rz6kiC84sqNQoqrtulzaL/VERgkoCyB6WdEkc2ujzUc= -github.com/go-openapi/errors v0.20.3/go.mod h1:Z3FlZ4I8jEGxjUK+bugx3on2mIAk4txuAOhlsB1FSgk= +github.com/go-openapi/errors v0.20.4 h1:unTcVm6PispJsMECE3zWgvG4xTiKda1LIR5rCRWLG6M= +github.com/go-openapi/errors v0.20.4/go.mod h1:Z3FlZ4I8jEGxjUK+bugx3on2mIAk4txuAOhlsB1FSgk= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= -github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= +github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonpointer v0.20.0 h1:ESKJdU9ASRfaPNOPRx12IUyA1vn3R9GiE3KYD14BXdQ= +github.com/go-openapi/jsonpointer v0.20.0/go.mod h1:6PGzBjjIIumbLYysB73Klnms1mwnU4G3YHOECG3CedA= github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= -github.com/go-openapi/loads v0.21.1/go.mod h1:/DtAMXXneXFjbQMGEtbamCZb+4x7eGwkvZCvBmwUG+g= +github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= +github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= github.com/go-openapi/loads v0.21.2 h1:r2a/xFIYeZ4Qd2TnGpWDIQNcP80dIaZgf704za8enro= github.com/go-openapi/loads v0.21.2/go.mod h1:Jq58Os6SSGz0rzh62ptiu8Z31I+OTHqmULx5e/gJbNw= -github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= -github.com/go-openapi/spec v0.20.8 h1:ubHmXNY3FCIOinT8RNrrPfGc9t7I1qhPtdOGoG2AxRU= -github.com/go-openapi/spec v0.20.8/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= -github.com/go-openapi/strfmt v0.21.0/go.mod h1:ZRQ409bWMj+SOgXofQAGTIo2Ebu72Gs+WaRADcS5iNg= -github.com/go-openapi/strfmt v0.21.1/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= +github.com/go-openapi/spec v0.20.11 h1:J/TzFDLTt4Rcl/l1PmyErvkqlJDncGvPTMnCI39I4gY= +github.com/go-openapi/spec v0.20.11/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= github.com/go-openapi/strfmt v0.21.3/go.mod h1:k+RzNO0Da+k3FrrynSNN8F7n/peCmQQqbbXjtDfvmGg= -github.com/go-openapi/strfmt v0.21.7 h1:rspiXgNWgeUzhjo1YU01do6qsahtJNByjLVbPLNHb8k= -github.com/go-openapi/strfmt v0.21.7/go.mod h1:adeGTkxE44sPyLk0JV235VQAO/ZXUr8KAzYjclFs3ew= +github.com/go-openapi/strfmt v0.21.8 h1:VYBUoKYRLAlgKDrIxR/I0lKrztDQ0tuTDrbhLVP8Erg= +github.com/go-openapi/strfmt v0.21.8/go.mod h1:adeGTkxE44sPyLk0JV235VQAO/ZXUr8KAzYjclFs3ew= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-openapi/validate v0.22.1 h1:G+c2ub6q47kfX1sOBLwIQwzBVt8qmOAARyo/9Fqs9NU= -github.com/go-openapi/validate v0.22.1/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0= -github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY= -github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg= -github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= -github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= -github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs= -github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= -github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= -github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk= -github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28= -github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo= -github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk= -github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw= -github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360= -github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg= -github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE= -github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8= -github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= -github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= -github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= -github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= -github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ= -github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0= -github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw= +github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU= +github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-openapi/validate v0.22.3 h1:KxG9mu5HBRYbecRb37KRCihvGGtND2aXziBAv0NNfyI= +github.com/go-openapi/validate v0.22.3/go.mod h1:kVxh31KbfsxU8ZyoHaDbLBWU5CnMdqBUEtadQ2G4d5M= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4= -github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA= github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -98,8 +61,6 @@ github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE= -github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= @@ -110,101 +71,79 @@ github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= -github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= -github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= -github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= -github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= -go.mongodb.org/mongo-driver v1.7.3/go.mod h1:NqaYOwnXWr5Pm7AOpO5QFxKJ503nbMse/R79oO62zWg= -go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.mongodb.org/mongo-driver v1.10.0/go.mod h1:wsihk0Kdgv8Kqu1Anit4sfK+22vSFbUrAVEYRhCXrA8= -go.mongodb.org/mongo-driver v1.11.3 h1:Ql6K6qYHEzB6xvu4+AU0BoRoqf9vFPcc4o7MUIdPW8Y= -go.mongodb.org/mongo-driver v1.11.3/go.mod h1:PTSz5yu21bkT/wXpkS7WR5f0ddqw5quethTUn9WM+2g= +go.mongodb.org/mongo-driver v1.13.1 h1:YIc7HTYsKndGK4RFzJ3covLz1byri52x0IoMB0Pt/vk= +go.mongodb.org/mongo-driver v1.13.1/go.mod h1:wcDf1JBCXy2mOW0bWHwO/IOYqdca1MPCwDtFu/Z9+eo= go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM= go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU= go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY= go.opentelemetry.io/otel/sdk v1.14.0/go.mod h1:bwIC5TjrNG6QDCHNWvW4HLHtUQ4I+VQDsnjhvyZCALM= go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M= go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= -golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/headers_test.go b/headers_test.go index f012dbaa..69edaa5f 100644 --- a/headers_test.go +++ b/headers_test.go @@ -21,6 +21,7 @@ import ( "github.com/go-openapi/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseContentType(t *testing.T) { @@ -48,9 +49,9 @@ func TestParseContentType(t *testing.T) { } ct, cs, err := ContentType(headers) if v.err == nil { - assert.NoError(t, err, "input: %q, err: %v", v.hdr, err) + require.NoError(t, err, "input: %q, err: %v", v.hdr, err) } else { - assert.Error(t, err, "input: %q", v.hdr) + require.Error(t, err, "input: %q", v.hdr) assert.IsType(t, &errors.ParseError{}, err, "input: %q", v.hdr) assert.Equal(t, v.err.Error(), err.Error(), "input: %q", v.hdr) } diff --git a/internal/testing/petstore/api.go b/internal/testing/petstore/api.go index 4cb1418c..9765ad6a 100644 --- a/internal/testing/petstore/api.go +++ b/internal/testing/petstore/api.go @@ -23,19 +23,24 @@ import ( "github.com/go-openapi/errors" "github.com/go-openapi/loads" - "github.com/stretchr/testify/assert" - "github.com/go-openapi/runtime" testingutil "github.com/go-openapi/runtime/internal/testing" "github.com/go-openapi/runtime/middleware/untyped" "github.com/go-openapi/runtime/security" "github.com/go-openapi/runtime/yamlpc" + "github.com/stretchr/testify/require" +) + +const ( + apiPrincipal = "admin" + apiUser = "topuser" + otherUser = "anyother" ) // NewAPI registers a stub api for the pet store func NewAPI(t gotest.TB) (*loads.Document, *untyped.API) { spec, err := loads.Analyzed(testingutil.PetStoreJSONMessage, "") - assert.NoError(t, err) + require.NoError(t, err) api := untyped.NewAPI(spec) api.RegisterConsumer("application/json", runtime.JSONConsumer()) @@ -48,28 +53,30 @@ func NewAPI(t gotest.TB) (*loads.Document, *untyped.API) { api.RegisterProducer("application/x-yaml", yamlpc.YAMLProducer()) api.RegisterAuth("basic", security.BasicAuth(func(username, password string) (interface{}, error) { - if username == "admin" && password == "admin" { - return "admin", nil - } else if username == "topuser" && password == "topuser" { - return "topuser", nil - } else if username == "anyother" && password == "anyother" { - return "anyother", nil + switch { + case username == apiPrincipal && password == apiPrincipal: + return apiPrincipal, nil + case username == apiUser && password == apiUser: + return apiUser, nil + case username == otherUser && password == otherUser: + return otherUser, nil + default: + return nil, errors.Unauthenticated("basic") } - return nil, errors.Unauthenticated("basic") })) api.RegisterAuth("apiKey", security.APIKeyAuth("X-API-KEY", "header", func(token string) (interface{}, error) { if token == "token123" { - return "admin", nil + return apiPrincipal, nil } return nil, errors.Unauthenticated("token") })) api.RegisterAuthorizer(runtime.AuthorizerFunc(func(r *http.Request, user interface{}) error { - if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/pets") && user.(string) != "admin" { - if user.(string) == "topuser" { + if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/pets") && user.(string) != apiPrincipal { + if user.(string) == apiUser { return errors.CompositeValidationError(errors.New(errors.InvalidTypeCode, "unauthorized")) - } else { - return goerrors.New("unauthorized") } + + return goerrors.New("unauthorized") } return nil })) @@ -88,7 +95,7 @@ func NewAPI(t gotest.TB) (*loads.Document, *untyped.API) { // NewRootAPI registers a stub api for the pet store func NewRootAPI(t gotest.TB) (*loads.Document, *untyped.API) { spec, err := loads.Analyzed(testingutil.RootPetStoreJSONMessage, "") - assert.NoError(t, err) + require.NoError(t, err) api := untyped.NewAPI(spec) api.RegisterConsumer("application/json", runtime.JSONConsumer()) @@ -101,14 +108,14 @@ func NewRootAPI(t gotest.TB) (*loads.Document, *untyped.API) { api.RegisterProducer("application/x-yaml", yamlpc.YAMLProducer()) api.RegisterAuth("basic", security.BasicAuth(func(username, password string) (interface{}, error) { - if username == "admin" && password == "admin" { - return "admin", nil + if username == apiPrincipal && password == apiPrincipal { + return apiPrincipal, nil } return nil, errors.Unauthenticated("basic") })) api.RegisterAuth("apiKey", security.APIKeyAuth("X-API-KEY", "header", func(token string) (interface{}, error) { if token == "token123" { - return "admin", nil + return apiPrincipal, nil } return nil, errors.Unauthenticated("token") })) @@ -161,6 +168,6 @@ func (s *stubOperationHandler) ParameterModel() interface{} { return nil } -func (s *stubOperationHandler) Handle(params interface{}) (interface{}, error) { - return nil, nil +func (s *stubOperationHandler) Handle(_ interface{}) (interface{}, error) { + return nil, nil //nolint:nilnil } diff --git a/internal/testing/simplepetstore/api.go b/internal/testing/simplepetstore/api.go index 0ba667bc..df7f1ddc 100644 --- a/internal/testing/simplepetstore/api.go +++ b/internal/testing/simplepetstore/api.go @@ -59,7 +59,7 @@ var createPet = runtime.OperationHandlerFunc(func(data interface{}) (interface{} var deletePet = runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) { id := data.(map[string]interface{})["id"].(int64) removePet(id) - return nil, nil + return nil, nil //nolint:nilnil }) var getPetByID = runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) { diff --git a/internal/testing/simplepetstore/api_test.go b/internal/testing/simplepetstore/api_test.go index a62706ec..58f6e56a 100644 --- a/internal/testing/simplepetstore/api_test.go +++ b/internal/testing/simplepetstore/api_test.go @@ -16,67 +16,90 @@ package simplepetstore import ( "bytes" + "context" + "net/http" "net/http/httptest" "testing" - "github.com/stretchr/testify/assert" - "github.com/go-openapi/runtime" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSimplePetstoreSpec(t *testing.T) { - handler, _ := NewPetstore() + handler, err := NewPetstore() + require.NoError(t, err) + // Serves swagger spec document - r, _ := runtime.JSONRequest("GET", "/swagger.json", nil) + r, err := runtime.JSONRequest(http.MethodGet, "/swagger.json", nil) + require.NoError(t, err) + r = r.WithContext(context.Background()) rw := httptest.NewRecorder() handler.ServeHTTP(rw, r) - assert.Equal(t, 200, rw.Code) + assert.Equal(t, http.StatusOK, rw.Code) assert.Equal(t, swaggerJSON, rw.Body.String()) } func TestSimplePetstoreAllPets(t *testing.T) { - handler, _ := NewPetstore() + handler, err := NewPetstore() + require.NoError(t, err) + // Serves swagger spec document - r, _ := runtime.JSONRequest("GET", "/api/pets", nil) + r, err := runtime.JSONRequest(http.MethodGet, "/api/pets", nil) + require.NoError(t, err) + r = r.WithContext(context.Background()) rw := httptest.NewRecorder() handler.ServeHTTP(rw, r) - assert.Equal(t, 200, rw.Code) + assert.Equal(t, http.StatusOK, rw.Code) assert.Equal(t, "[{\"id\":1,\"name\":\"Dog\",\"status\":\"available\"},{\"id\":2,\"name\":\"Cat\",\"status\":\"pending\"}]\n", rw.Body.String()) } func TestSimplePetstorePetByID(t *testing.T) { - handler, _ := NewPetstore() + handler, err := NewPetstore() + require.NoError(t, err) // Serves swagger spec document - r, _ := runtime.JSONRequest("GET", "/api/pets/1", nil) + r, err := runtime.JSONRequest(http.MethodGet, "/api/pets/1", nil) + require.NoError(t, err) + r = r.WithContext(context.Background()) rw := httptest.NewRecorder() handler.ServeHTTP(rw, r) - assert.Equal(t, 200, rw.Code) + assert.Equal(t, http.StatusOK, rw.Code) assert.Equal(t, "{\"id\":1,\"name\":\"Dog\",\"status\":\"available\"}\n", rw.Body.String()) } func TestSimplePetstoreAddPet(t *testing.T) { - handler, _ := NewPetstore() + handler, err := NewPetstore() + require.NoError(t, err) + // Serves swagger spec document - r, _ := runtime.JSONRequest("POST", "/api/pets", bytes.NewBuffer([]byte(`{"name": "Fish","status": "available"}`))) + r, err := runtime.JSONRequest(http.MethodPost, "/api/pets", bytes.NewBufferString(`{"name": "Fish","status": "available"}`)) + require.NoError(t, err) + r = r.WithContext(context.Background()) rw := httptest.NewRecorder() handler.ServeHTTP(rw, r) - assert.Equal(t, 200, rw.Code) + assert.Equal(t, http.StatusOK, rw.Code) assert.Equal(t, "{\"id\":3,\"name\":\"Fish\",\"status\":\"available\"}\n", rw.Body.String()) } func TestSimplePetstoreDeletePet(t *testing.T) { - handler, _ := NewPetstore() + handler, err := NewPetstore() + require.NoError(t, err) + // Serves swagger spec document - r, _ := runtime.JSONRequest("DELETE", "/api/pets/1", nil) + r, err := runtime.JSONRequest(http.MethodDelete, "/api/pets/1", nil) + require.NoError(t, err) + r = r.WithContext(context.Background()) rw := httptest.NewRecorder() handler.ServeHTTP(rw, r) - assert.Equal(t, 204, rw.Code) + assert.Equal(t, http.StatusNoContent, rw.Code) assert.Equal(t, "", rw.Body.String()) - r, _ = runtime.JSONRequest("GET", "/api/pets/1", nil) + r, err = runtime.JSONRequest(http.MethodGet, "/api/pets/1", nil) + require.NoError(t, err) + r = r.WithContext(context.Background()) rw = httptest.NewRecorder() handler.ServeHTTP(rw, r) - assert.Equal(t, 404, rw.Code) + assert.Equal(t, http.StatusNotFound, rw.Code) assert.Equal(t, "{\"code\":404,\"message\":\"not found: pet 1\"}", rw.Body.String()) } diff --git a/json_test.go b/json_test.go index 5e11d03c..82af4c87 100644 --- a/json_test.go +++ b/json_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var consProdJSON = `{"name":"Somebody","id":1}` @@ -28,7 +29,7 @@ var consProdJSON = `{"name":"Somebody","id":1}` type eofRdr struct { } -func (r *eofRdr) Read(d []byte) (int, error) { +func (r *eofRdr) Read(_ []byte) (int, error) { return 0, io.EOF } @@ -38,14 +39,13 @@ func TestJSONConsumer(t *testing.T) { Name string ID int } - err := cons.Consume(bytes.NewBuffer([]byte(consProdJSON)), &data) - if assert.NoError(t, err) { - assert.Equal(t, "Somebody", data.Name) - assert.Equal(t, 1, data.ID) + err := cons.Consume(bytes.NewBufferString(consProdJSON), &data) + require.NoError(t, err) + assert.Equal(t, "Somebody", data.Name) + assert.Equal(t, 1, data.ID) - err = cons.Consume(new(eofRdr), &data) - assert.Error(t, err) - } + err = cons.Consume(new(eofRdr), &data) + require.Error(t, err) } func TestJSONProducer(t *testing.T) { @@ -57,6 +57,6 @@ func TestJSONProducer(t *testing.T) { rw := httptest.NewRecorder() err := prod.Produce(rw, data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consProdJSON+"\n", rw.Body.String()) } diff --git a/middleware/body_test.go b/middleware/body_test.go index de128b77..5582ab75 100644 --- a/middleware/body_test.go +++ b/middleware/body_test.go @@ -1,21 +1,22 @@ package middleware import ( + "context" "io" "net/http" "path" "testing" - "github.com/stretchr/testify/assert" - "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/internal/testing/petstore" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type eofReader struct { } -func (r *eofReader) Read(b []byte) (int, error) { +func (r *eofReader) Read(_ []byte) (int, error) { return 0, io.EOF } @@ -35,25 +36,23 @@ func TestBindRequest_BodyValidation(t *testing.T) { api.DefaultConsumes = runtime.JSONMime ctx.router = DefaultRouter(spec, ctx.api) - req, err := http.NewRequest("GET", path.Join(spec.BasePath(), "/pets"), new(eofReader)) - if assert.NoError(t, err) { - req.Header.Set("Content-Type", runtime.JSONMime) - - ri, rCtx, ok := ctx.RouteInfo(req) - if assert.True(t, ok) { - req = rCtx - err := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error { - defer r.Body.Close() - var data interface{} - err := runtime.JSONConsumer().Consume(r.Body, &data) - _ = data - return err - })) - - assert.Error(t, err) - assert.Equal(t, io.EOF, err) - } - } + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, path.Join(spec.BasePath(), "/pets"), new(eofReader)) + require.NoError(t, err) + req.Header.Set("Content-Type", runtime.JSONMime) + + ri, rCtx, ok := ctx.RouteInfo(req) + require.True(t, ok) + req = rCtx + + err = ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, _ *MatchedRoute) error { + defer r.Body.Close() + var data interface{} + e := runtime.JSONConsumer().Consume(r.Body, &data) + _ = data + return e + })) + require.Error(t, err) + assert.Equal(t, io.EOF, err) } func TestBindRequest_DeleteNoBody(t *testing.T) { @@ -62,41 +61,37 @@ func TestBindRequest_DeleteNoBody(t *testing.T) { api.DefaultConsumes = runtime.JSONMime ctx.router = DefaultRouter(spec, ctx.api) - req, err := http.NewRequest("DELETE", path.Join(spec.BasePath(), "/pets/123"), new(eofReader)) - if assert.NoError(t, err) { - req.Header.Set("Accept", "*/*") - - ri, rCtx, ok := ctx.RouteInfo(req) - if assert.True(t, ok) { - req = rCtx - bverr := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error { - return nil - })) - - assert.NoError(t, bverr) - //assert.Equal(t, io.EOF, bverr) - } - } - - req, err = http.NewRequest("DELETE", path.Join(spec.BasePath(), "/pets/123"), new(eofReader)) - if assert.NoError(t, err) { - req.Header.Set("Accept", "*/*") - req.Header.Set("Content-Type", runtime.JSONMime) - req.ContentLength = 1 - - ri, rCtx, ok := ctx.RouteInfo(req) - if assert.True(t, ok) { - req = rCtx - err := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error { - defer r.Body.Close() - var data interface{} - err := runtime.JSONConsumer().Consume(r.Body, &data) - _ = data - return err - })) - - assert.Error(t, err) - assert.Equal(t, io.EOF, err) - } - } + req, err := http.NewRequestWithContext(context.Background(), http.MethodDelete, path.Join(spec.BasePath(), "/pets/123"), new(eofReader)) + require.NoError(t, err) + + req.Header.Set("Accept", "*/*") + ri, rCtx, ok := ctx.RouteInfo(req) + require.True(t, ok) + req = rCtx + + err = ctx.BindValidRequest(req, ri, rbn(func(_ *http.Request, _ *MatchedRoute) error { + return nil + })) + require.NoError(t, err) + // assert.Equal(t, io.EOF, bverr) + + req, err = http.NewRequestWithContext(context.Background(), http.MethodDelete, path.Join(spec.BasePath(), "/pets/123"), new(eofReader)) + require.NoError(t, err) + req.Header.Set("Accept", "*/*") + req.Header.Set("Content-Type", runtime.JSONMime) + req.ContentLength = 1 + + ri, rCtx, ok = ctx.RouteInfo(req) + require.True(t, ok) + req = rCtx + + err = ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, _ *MatchedRoute) error { + defer r.Body.Close() + var data interface{} + e := runtime.JSONConsumer().Consume(r.Body, &data) + _ = data + return e + })) + require.Error(t, err) + assert.Equal(t, io.EOF, err) } diff --git a/middleware/context.go b/middleware/context.go index d21ae4e8..f68b7511 100644 --- a/middleware/context.go +++ b/middleware/context.go @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//nolint:goconst package middleware import ( @@ -37,7 +38,7 @@ import ( var Debug = logger.DebugEnabled() var Logger logger.Logger = logger.StandardLogger{} -func debugLog(format string, args ...interface{}) { +func debugLog(format string, args ...interface{}) { //nolint:goprintffuncname if Debug { Logger.Printf(format, args...) } @@ -162,7 +163,7 @@ func (r *routableUntypedAPI) HandlerFor(method, path string) (http.Handler, bool r.hlock.Unlock() return handler, ok } -func (r *routableUntypedAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { +func (r *routableUntypedAPI) ServeErrorFor(_ string) func(http.ResponseWriter, *http.Request, error) { return r.api.ServeError } func (r *routableUntypedAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { @@ -542,8 +543,8 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st } if route == nil || route.Operation == nil { - rw.WriteHeader(200) - if r.Method == "HEAD" { + rw.WriteHeader(http.StatusOK) + if r.Method == http.MethodHead { return } producers := c.api.ProducersFor(normalizeOffers(offers)) @@ -559,7 +560,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st if _, code, ok := route.Operation.SuccessResponse(); ok { rw.WriteHeader(code) - if code == 204 || r.Method == "HEAD" { + if code == http.StatusNoContent || r.Method == http.MethodHead { return } diff --git a/middleware/context_test.go b/middleware/context_test.go index d019345f..0db0042c 100644 --- a/middleware/context_test.go +++ b/middleware/context_test.go @@ -15,6 +15,7 @@ package middleware import ( + stdcontext "context" "errors" "net/http" "net/http/httptest" @@ -24,13 +25,15 @@ import ( apierrors "github.com/go-openapi/errors" "github.com/go-openapi/loads" "github.com/go-openapi/loads/fmts" - "github.com/stretchr/testify/assert" - "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/internal/testing/petstore" "github.com/go-openapi/runtime/middleware/untyped" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +const applicationJSON = "application/json" + type stubBindRequester struct { } @@ -45,8 +48,8 @@ func (s *stubOperationHandler) ParameterModel() interface{} { return nil } -func (s *stubOperationHandler) Handle(params interface{}) (interface{}, error) { - return nil, nil +func (s *stubOperationHandler) Handle(_ interface{}) (interface{}, error) { + return nil, nil //nolint:nilnil } func init() { @@ -56,7 +59,7 @@ func init() { func assertAPIError(t *testing.T, wantCode int, err error) { t.Helper() - assert.NotNil(t, err) + require.Error(t, err) ce, ok := err.(*apierrors.CompositeError) assert.True(t, ok) @@ -69,57 +72,63 @@ func assertAPIError(t *testing.T, wantCode int, err error) { func TestContentType_Issue264(t *testing.T) { swspec, err := loads.Spec("../fixtures/bugs/264/swagger.yml") - if assert.NoError(t, err) { - api := untyped.NewAPI(swspec) - api.RegisterConsumer("application/json", runtime.JSONConsumer()) - api.RegisterProducer("application/json", runtime.JSONProducer()) - api.RegisterOperation("delete", "/key/{id}", new(stubOperationHandler)) - - handler := Serve(swspec, api) - request, _ := http.NewRequest("DELETE", "/key/1", nil) - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - } + require.NoError(t, err) + + api := untyped.NewAPI(swspec) + api.RegisterConsumer(applicationJSON, runtime.JSONConsumer()) + api.RegisterProducer(applicationJSON, runtime.JSONProducer()) + api.RegisterOperation("delete", "/key/{id}", new(stubOperationHandler)) + + handler := Serve(swspec, api) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodDelete, "/key/1", nil) + require.NoError(t, err) + + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusOK, recorder.Code) } func TestContentType_Issue172(t *testing.T) { swspec, err := loads.Spec("../fixtures/bugs/172/swagger.yml") - if assert.NoError(t, err) { - api := untyped.NewAPI(swspec) - api.RegisterConsumer("application/vnd.cia.v1+json", runtime.JSONConsumer()) - api.RegisterProducer("application/vnd.cia.v1+json", runtime.JSONProducer()) - api.RegisterOperation("get", "/pets", new(stubOperationHandler)) - - handler := Serve(swspec, api) - request, _ := http.NewRequest("GET", "/pets", nil) - request.Header.Add("Accept", "application/json+special") - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusNotAcceptable, recorder.Code) - - // acceptable as defined as default by the API (not explicit in the spec) - request.Header.Add("Accept", "application/json") - recorder = httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusOK, recorder.Code) - } + require.NoError(t, err) + + api := untyped.NewAPI(swspec) + api.RegisterConsumer("application/vnd.cia.v1+json", runtime.JSONConsumer()) + api.RegisterProducer("application/vnd.cia.v1+json", runtime.JSONProducer()) + api.RegisterOperation("get", "/pets", new(stubOperationHandler)) + + handler := Serve(swspec, api) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/pets", nil) + require.NoError(t, err) + + request.Header.Add("Accept", "application/json+special") + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusNotAcceptable, recorder.Code) + + // acceptable as defined as default by the API (not explicit in the spec) + request.Header.Add("Accept", applicationJSON) + recorder = httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusOK, recorder.Code) } func TestContentType_Issue174(t *testing.T) { swspec, err := loads.Spec("../fixtures/bugs/174/swagger.yml") - if assert.NoError(t, err) { - api := untyped.NewAPI(swspec) - api.RegisterConsumer("application/json", runtime.JSONConsumer()) - api.RegisterProducer("application/json", runtime.JSONProducer()) - api.RegisterOperation("get", "/pets", new(stubOperationHandler)) - - handler := Serve(swspec, api) - request, _ := http.NewRequest("GET", "/pets", nil) - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusOK, recorder.Code) - } + require.NoError(t, err) + + api := untyped.NewAPI(swspec) + api.RegisterConsumer(applicationJSON, runtime.JSONConsumer()) + api.RegisterProducer(applicationJSON, runtime.JSONProducer()) + api.RegisterOperation("get", "/pets", new(stubOperationHandler)) + + handler := Serve(swspec, api) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/pets", nil) + require.NoError(t, err) + + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusOK, recorder.Code) } func TestServe(t *testing.T) { @@ -127,15 +136,19 @@ func TestServe(t *testing.T) { handler := Serve(spec, api) // serve spec document - request, _ := http.NewRequest("GET", "http://localhost:8080/swagger.json", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "http://localhost:8080/swagger.json", nil) + require.NoError(t, err) + request.Header.Add("Content-Type", runtime.JSONMime) request.Header.Add("Accept", runtime.JSONMime) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) + + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "http://localhost:8080/swagger-ui", nil) + require.NoError(t, err) - request, _ = http.NewRequest("GET", "http://localhost:8080/swagger-ui", nil) recorder = httptest.NewRecorder() handler.ServeHTTP(recorder, request) @@ -147,16 +160,18 @@ func TestContextAuthorize(t *testing.T) { ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := runtime.JSONRequest("GET", "/api/pets", nil) + request, err := runtime.JSONRequest(http.MethodGet, "/api/pets", nil) + require.NoError(t, err) + request = request.WithContext(stdcontext.Background()) ri, reqWithCtx, ok := ctx.RouteInfo(request) assert.True(t, ok) - assert.NotNil(t, reqWithCtx) + require.NotNil(t, reqWithCtx) request = reqWithCtx p, reqWithCtx, err := ctx.Authorize(request, ri) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, p) assert.Nil(t, reqWithCtx) @@ -165,7 +180,7 @@ func TestContextAuthorize(t *testing.T) { request.SetBasicAuth("wrong", "wrong") p, reqWithCtx, err = ctx.Authorize(request, ri) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, p) assert.Nil(t, reqWithCtx) @@ -174,9 +189,9 @@ func TestContextAuthorize(t *testing.T) { request.SetBasicAuth("admin", "admin") p, reqWithCtx, err = ctx.Authorize(request, ri) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "admin", p) - assert.NotNil(t, reqWithCtx) + require.NotNil(t, reqWithCtx) // Assign the new returned request to follow with the test request = reqWithCtx @@ -199,11 +214,13 @@ func TestContextAuthorize_WithAuthorizer(t *testing.T) { ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := runtime.JSONRequest("POST", "/api/pets", nil) + request, err := runtime.JSONRequest(http.MethodPost, "/api/pets", nil) + require.NoError(t, err) + request = request.WithContext(stdcontext.Background()) ri, reqWithCtx, ok := ctx.RouteInfo(request) assert.True(t, ok) - assert.NotNil(t, reqWithCtx) + require.NotNil(t, reqWithCtx) request = reqWithCtx @@ -215,13 +232,13 @@ func TestContextAuthorize_WithAuthorizer(t *testing.T) { request.SetBasicAuth("admin", "admin") p, reqWithCtx, err = ctx.Authorize(request, ri) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "admin", p) - assert.NotNil(t, reqWithCtx) + require.NotNil(t, reqWithCtx) request.SetBasicAuth("anyother", "anyother") p, reqWithCtx, err = ctx.Authorize(request, ri) - assert.Error(t, err) + require.Error(t, err) ae, ok := err.(apierrors.Error) assert.True(t, ok) assert.Equal(t, http.StatusForbidden, int(ae.Code())) @@ -234,7 +251,7 @@ func TestContextNegotiateContentType(t *testing.T) { ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := http.NewRequest("POST", "/api/pets", nil) + request, _ := http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", nil) // request.Header.Add("Accept", "*/*") request.Header.Add("content-type", "text/html") @@ -253,23 +270,26 @@ func TestContextBindValidRequest(t *testing.T) { ctx.router = DefaultRouter(spec, ctx.api) // invalid content-type value - request, _ := http.NewRequest("POST", "/api/pets", strings.NewReader(`{"name":"dog"}`)) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", strings.NewReader(`{"name":"dog"}`)) + require.NoError(t, err) request.Header.Add("content-type", "/json") ri, request, _ := ctx.RouteInfo(request) assertAPIError(t, 400, ctx.BindValidRequest(request, ri, new(stubBindRequester))) // unsupported content-type value - request, _ = http.NewRequest("POST", "/api/pets", strings.NewReader(`{"name":"dog"}`)) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", strings.NewReader(`{"name":"dog"}`)) + require.NoError(t, err) request.Header.Add("content-type", "text/html") ri, request, _ = ctx.RouteInfo(request) assertAPIError(t, http.StatusUnsupportedMediaType, ctx.BindValidRequest(request, ri, new(stubBindRequester))) // unacceptable accept value - request, _ = http.NewRequest("POST", "/api/pets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", nil) + require.NoError(t, err) request.Header.Add("Accept", "application/vnd.cia.v1+json") - request.Header.Add("content-type", "application/json") + request.Header.Add("content-type", applicationJSON) ri, request, _ = ctx.RouteInfo(request) assertAPIError(t, http.StatusNotAcceptable, ctx.BindValidRequest(request, ri, new(stubBindRequester))) @@ -277,19 +297,19 @@ func TestContextBindValidRequest(t *testing.T) { func TestContextBindValidRequest_Issue174(t *testing.T) { spec, err := loads.Spec("../fixtures/bugs/174/swagger.yml") - assert.NoError(t, err) + require.NoError(t, err) api := untyped.NewAPI(spec) - api.RegisterConsumer("application/json", runtime.JSONConsumer()) - api.RegisterProducer("application/json", runtime.JSONProducer()) + api.RegisterConsumer(applicationJSON, runtime.JSONConsumer()) + api.RegisterProducer(applicationJSON, runtime.JSONProducer()) api.RegisterOperation("get", "/pets", new(stubOperationHandler)) ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := http.NewRequest("GET", "/pets", nil) + request, _ := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/pets", nil) ri, request, _ := ctx.RouteInfo(request) - assert.NoError(t, ctx.BindValidRequest(request, ri, new(stubBindRequester))) + require.NoError(t, ctx.BindValidRequest(request, ri, new(stubBindRequester))) } func TestContextBindAndValidate(t *testing.T) { @@ -297,7 +317,7 @@ func TestContextBindAndValidate(t *testing.T) { ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := http.NewRequest("POST", "/api/pets", nil) + request, _ := http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", nil) request.Header.Add("Accept", "*/*") request.Header.Add("content-type", "text/html") request.ContentLength = 1 @@ -308,7 +328,7 @@ func TestContextBindAndValidate(t *testing.T) { ri, request, _ := ctx.RouteInfo(request) data, request, result := ctx.BindAndValidate(request, ri) // this requires a much more thorough test assert.NotNil(t, data) - assert.NotNil(t, result) + require.Error(t, result) v, ok := request.Context().Value(ctxBoundParams).(*validation) assert.True(t, ok) @@ -323,19 +343,19 @@ func TestContextBindAndValidate(t *testing.T) { func TestContextRender(t *testing.T) { ct := runtime.JSONMime spec, api := petstore.NewAPI(t) - assert.NotNil(t, spec) assert.NotNil(t, api) + ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := http.NewRequest("GET", "/api/pets", nil) + request, _ := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) request.Header.Set(runtime.HeaderAccept, ct) ri, request, _ := ctx.RouteInfo(request) recorder := httptest.NewRecorder() ctx.Respond(recorder, request, []string{ct}, ri, map[string]interface{}{"name": "hello"}) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "{\"name\":\"hello\"}\n", recorder.Body.String()) recorder = httptest.NewRecorder() @@ -347,17 +367,19 @@ func TestContextRender(t *testing.T) { // Panic when route is nil and there is not a producer for the requested response format recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) request.Header.Set(runtime.HeaderAccept, "text/xml") assert.Panics(t, func() { ctx.Respond(recorder, request, []string{}, nil, map[string]interface{}{"name": "hello"}) }) - request, _ = http.NewRequest("GET", "/api/pets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) request.Header.Set(runtime.HeaderAccept, ct) ri, request, _ = ctx.RouteInfo(request) recorder = httptest.NewRecorder() ctx.Respond(recorder, request, []string{ct}, ri, map[string]interface{}{"name": "hello"}) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "{\"name\":\"hello\"}\n", recorder.Body.String()) recorder = httptest.NewRecorder() @@ -368,23 +390,25 @@ func TestContextRender(t *testing.T) { // assert.Panics(t, func() { ctx.Respond(recorder, request, []string{ct}, ri, map[int]interface{}{1: "hello"}) }) // recorder = httptest.NewRecorder() - // request, _ = http.NewRequest("GET", "/pets", nil) + // request, _ = http.NewRequestWithContext(stdcontext.Background(),http.MethodGet, "/pets", nil) // assert.Panics(t, func() { ctx.Respond(recorder, request, []string{}, ri, map[string]interface{}{"name": "hello"}) }) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("DELETE", "/api/pets/1", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodDelete, "/api/pets/1", nil) + require.NoError(t, err) ri, request, _ = ctx.RouteInfo(request) ctx.Respond(recorder, request, ri.Produces, ri, nil) assert.Equal(t, 204, recorder.Code) } func TestContextValidResponseFormat(t *testing.T) { - ct := "application/json" + const ct = applicationJSON spec, api := petstore.NewAPI(t) ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := http.NewRequest("GET", "http://localhost:8080", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "http://localhost:8080", nil) + require.NoError(t, err) request.Header.Set(runtime.HeaderAccept, ct) // check there's nothing there @@ -413,7 +437,8 @@ func TestContextInvalidResponseFormat(t *testing.T) { ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := http.NewRequest("GET", "http://localhost:8080", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "http://localhost:8080", nil) + require.NoError(t, err) request.Header.Set(runtime.HeaderAccept, ct) // check there's nothing there @@ -441,7 +466,8 @@ func TestContextValidRoute(t *testing.T) { ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := http.NewRequest("GET", "/api/pets", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) // check there's nothing there cached := request.Context().Value(ctxMatchedRoute) @@ -470,7 +496,8 @@ func TestContextInvalidRoute(t *testing.T) { ctx := NewContext(spec, api, nil) ctx.router = DefaultRouter(spec, ctx.api) - request, _ := http.NewRequest("DELETE", "pets", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodDelete, "pets", nil) + require.NoError(t, err) // check there's nothing there cached := request.Context().Value(ctxMatchedRoute) @@ -492,10 +519,11 @@ func TestContextInvalidRoute(t *testing.T) { } func TestContextValidContentType(t *testing.T) { - ct := "application/json" + ct := applicationJSON ctx := NewContext(nil, nil, nil) - request, _ := http.NewRequest("GET", "http://localhost:8080", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "http://localhost:8080", nil) + require.NoError(t, err) request.Header.Set(runtime.HeaderContentType, ct) // check there's nothing there @@ -504,7 +532,7 @@ func TestContextValidContentType(t *testing.T) { // trigger the parse mt, _, rCtx, err := ctx.ContentType(request) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ct, mt) assert.NotNil(t, rCtx) assert.NotEqual(t, request, rCtx) @@ -517,7 +545,7 @@ func TestContextValidContentType(t *testing.T) { // check if the cast works and fetch from cache too mt, _, rCtx, err = ctx.ContentType(request) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ct, mt) assert.Equal(t, request, rCtx) } @@ -526,7 +554,8 @@ func TestContextInvalidContentType(t *testing.T) { ct := "application(" ctx := NewContext(nil, nil, nil) - request, _ := http.NewRequest("GET", "http://localhost:8080", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "http://localhost:8080", nil) + require.NoError(t, err) request.Header.Set(runtime.HeaderContentType, ct) // check there's nothing there @@ -535,7 +564,7 @@ func TestContextInvalidContentType(t *testing.T) { // trigger the parse mt, _, rCtx, err := ctx.ContentType(request) - assert.Error(t, err) + require.Error(t, err) assert.Empty(t, mt) assert.Nil(t, rCtx) @@ -545,6 +574,6 @@ func TestContextInvalidContentType(t *testing.T) { // check if the failure continues _, _, rCtx, err = ctx.ContentType(request) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, rCtx) } diff --git a/middleware/denco/router.go b/middleware/denco/router.go index 5d2691ec..2ddd2f94 100644 --- a/middleware/denco/router.go +++ b/middleware/denco/router.go @@ -51,7 +51,7 @@ func New() *Router { // params is a slice of the Param that arranged in the order in which parameters appeared. // e.g. when built routing path is "/path/to/:id/:name" and given path is "/path/to/1/alice". params order is [{"id": "1"}, {"name": "alice"}], not [{"name": "alice"}, {"id": "1"}]. func (rt *Router) Lookup(path string) (data interface{}, params Params, found bool) { - if data, found := rt.static[path]; found { + if data, found := rt.static[path]; found { //nolint:govet return data, nil, true } if len(rt.param.node) == 1 { @@ -131,7 +131,8 @@ func newDoubleArray() *doubleArray { // baseCheck contains BASE, CHECK and Extra flags. // From the top, 22bits of BASE, 2bits of Extra flags and 8bits of CHECK. // -// BASE (22bit) | Extra flags (2bit) | CHECK (8bit) +// BASE (22bit) | Extra flags (2bit) | CHECK (8bit) +// // |----------------------|--|--------| // 32 10 8 0 type baseCheck uint32 @@ -200,19 +201,19 @@ BACKTRACKING: for j := len(indices) - 1; j >= 0; j-- { i, idx := int(indices[j]>>32), int(indices[j]&0xffffffff) if da.bc[idx].IsSingleParam() { - idx := nextIndex(da.bc[idx].Base(), ParamCharacter) + idx := nextIndex(da.bc[idx].Base(), ParamCharacter) //nolint:govet if idx >= len(da.bc) { break } next := NextSeparator(path, i) - params := append(params, Param{Value: path[i:next]}) - if nd, params, found := da.lookup(path[next:], params, idx); found { + params := append(params, Param{Value: path[i:next]}) //nolint:govet + if nd, params, found := da.lookup(path[next:], params, idx); found { //nolint:govet return nd, params, true } } if da.bc[idx].IsWildcardParam() { - idx := nextIndex(da.bc[idx].Base(), WildcardCharacter) - params := append(params, Param{Value: path[i:]}) + idx := nextIndex(da.bc[idx].Base(), WildcardCharacter) //nolint:govet + params := append(params, Param{Value: path[i:]}) //nolint:govet return da.node[da.bc[idx].Base()], params, true } } @@ -431,7 +432,7 @@ func makeRecords(srcs []Record) (statics, params []*record) { wildcardPrefix := string(SeparatorCharacter) + string(WildcardCharacter) restconfPrefix := string(PathParamCharacter) + string(ParamCharacter) for _, r := range srcs { - if strings.Contains(r.Key, paramPrefix) || strings.Contains(r.Key, wildcardPrefix) ||strings.Contains(r.Key, restconfPrefix){ + if strings.Contains(r.Key, paramPrefix) || strings.Contains(r.Key, wildcardPrefix) || strings.Contains(r.Key, restconfPrefix) { r.Key += termChar params = append(params, &record{Record: r}) } else { diff --git a/middleware/denco/router_test.go b/middleware/denco/router_test.go index 81eb55c1..7a5fbf6d 100644 --- a/middleware/denco/router_test.go +++ b/middleware/denco/router_test.go @@ -8,6 +8,8 @@ import ( "time" "github.com/go-openapi/runtime/middleware/denco" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func routes() []denco.Record { @@ -267,17 +269,16 @@ func TestRouter_Lookup_withManyRoutes(t *testing.T) { rand.Seed(time.Now().UnixNano()) records := make([]denco.Record, n) for i := 0; i < n; i++ { - records[i] = denco.Record{Key: "/" + randomString(rand.Intn(50)+10), Value: fmt.Sprintf("route%d", i)} + records[i] = denco.Record{Key: "/" + randomString(rand.Intn(50)+10), Value: fmt.Sprintf("route%d", i)} //#nosec } router := denco.New() - if err := router.Build(records); err != nil { - t.Fatal(err) - } + require.NoError(t, router.Build(records)) + for _, r := range records { data, params, found := router.Lookup(r.Key) - if !reflect.DeepEqual(data, r.Value) || len(params) != 0 || !reflect.DeepEqual(found, true) { - t.Errorf("Router.Lookup(%q) => (%#v, %#v, %#v), want (%#v, %#v, %#v)", r.Key, data, len(params), found, r.Value, 0, true) - } + assert.Equal(t, r.Value, data) + assert.Empty(t, params) + assert.True(t, found) } } @@ -433,12 +434,13 @@ func TestRouter_Build(t *testing.T) { // test for duplicate name of path parameters. func() { r := denco.New() - if err := r.Build([]denco.Record{ - {"/:user/:id/:id", "testroute0"}, - {"/:user/:user/:id", "testroute0"}, - }); err == nil { - t.Errorf("no error returned by duplicate name of path parameters") - } + require.Errorf(t, + r.Build([]denco.Record{ + {"/:user/:id/:id", "testroute0"}, + {"/:user/:user/:id", "testroute0"}, + }), + "no error returned by duplicate name of path parameters", + ) }() } @@ -459,22 +461,17 @@ func TestRouter_Build_withoutSizeHint(t *testing.T) { } { r := denco.New() actual := r.SizeHint - expect := -1 - if !reflect.DeepEqual(actual, expect) { - t.Errorf(`before Build; Router.SizeHint => (%[1]T=%#[1]v); want (%[2]T=%#[2]v)`, actual, expect) - } + expected := -1 + + assert.Equalf(t, expected, actual, `before Build; Router.SizeHint => (%[1]T=%#[1]v); want (%[2]T=%#[2]v)`, actual, expected) records := make([]denco.Record, len(v.keys)) for i, k := range v.keys { records[i] = denco.Record{Key: k, Value: "value"} } - if err := r.Build(records); err != nil { - t.Fatal(err) - } + require.NoError(t, r.Build(records)) actual = r.SizeHint - expect = v.sizeHint - if !reflect.DeepEqual(actual, expect) { - t.Errorf(`Router.Build(%#v); Router.SizeHint => (%[2]T=%#[2]v); want (%[3]T=%#[3]v)`, records, actual, expect) - } + expected = v.sizeHint + assert.Equalf(t, expected, actual, `Router.Build(%#v); Router.SizeHint => (%[2]T=%#[2]v); want (%[3]T=%#[3]v)`, records, actual, expected) } } @@ -497,14 +494,10 @@ func TestRouter_Build_withSizeHint(t *testing.T) { records := []denco.Record{ {v.key, "value"}, } - if err := r.Build(records); err != nil { - t.Fatal(err) - } + require.NoError(t, r.Build(records)) actual := r.SizeHint - expect := v.expect - if !reflect.DeepEqual(actual, expect) { - t.Errorf(`Router.Build(%#v); Router.SizeHint => (%[2]T=%#[2]v); want (%[3]T=%#[3]v)`, records, actual, expect) - } + expected := v.expect + assert.Equalf(t, expected, actual, `Router.Build(%#v); Router.SizeHint => (%[2]T=%#[2]v); want (%[3]T=%#[3]v)`, records, actual, expected) } } @@ -523,8 +516,6 @@ func TestParams_Get(t *testing.T) { } { actual := params.Get(v.value) expected := v.expected - if !reflect.DeepEqual(actual, expected) { - t.Errorf("Params.Get(%q) => %#v, want %#v", v.value, actual, expected) - } + assert.Equal(t, expected, actual, "Params.Get(%q) => %#v, want %#v", v.value, actual, expected) } } diff --git a/middleware/denco/server_test.go b/middleware/denco/server_test.go index a2562847..e887c15d 100644 --- a/middleware/denco/server_test.go +++ b/middleware/denco/server_test.go @@ -1,6 +1,7 @@ package denco_test import ( + "context" "fmt" "io" "net/http" @@ -8,6 +9,8 @@ import ( "testing" "github.com/go-openapi/runtime/middleware/denco" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testHandlerFunc(w http.ResponseWriter, r *http.Request, params denco.Params) { @@ -22,13 +25,12 @@ func TestMux(t *testing.T) { mux.POST("/user/:name", testHandlerFunc), mux.HEAD("/user/:name", testHandlerFunc), mux.PUT("/user/:name", testHandlerFunc), - mux.Handler("GET", "/user/handler", testHandlerFunc), - mux.Handler("POST", "/user/handler", testHandlerFunc), - mux.Handler("PUT", "/user/inference", testHandlerFunc), + mux.Handler(http.MethodGet, "/user/handler", testHandlerFunc), + mux.Handler(http.MethodPost, "/user/handler", testHandlerFunc), + mux.Handler(http.MethodPut, "/user/inference", testHandlerFunc), }) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) + server := httptest.NewServer(handler) defer server.Close() @@ -36,48 +38,41 @@ func TestMux(t *testing.T) { status int method, path, expected string }{ - {200, "GET", "/", "method: GET, path: /, params: []"}, - {200, "GET", "/user/alice", "method: GET, path: /user/alice, params: [{name alice}]"}, - {200, "POST", "/user/bob", "method: POST, path: /user/bob, params: [{name bob}]"}, - {200, "HEAD", "/user/alice", ""}, - {200, "PUT", "/user/bob", "method: PUT, path: /user/bob, params: [{name bob}]"}, - {404, "POST", "/", "404 page not found\n"}, - {404, "GET", "/unknown", "404 page not found\n"}, - {404, "POST", "/user/alice/1", "404 page not found\n"}, - {200, "GET", "/user/handler", "method: GET, path: /user/handler, params: []"}, - {200, "POST", "/user/handler", "method: POST, path: /user/handler, params: []"}, - {200, "PUT", "/user/inference", "method: PUT, path: /user/inference, params: []"}, + {http.StatusOK, http.MethodGet, "/", "method: GET, path: /, params: []"}, + {http.StatusOK, http.MethodGet, "/user/alice", "method: GET, path: /user/alice, params: [{name alice}]"}, + {http.StatusOK, http.MethodPost, "/user/bob", "method: POST, path: /user/bob, params: [{name bob}]"}, + {http.StatusOK, http.MethodHead, "/user/alice", ""}, + {http.StatusOK, http.MethodPut, "/user/bob", "method: PUT, path: /user/bob, params: [{name bob}]"}, + {http.StatusNotFound, http.MethodPost, "/", "404 page not found\n"}, + {http.StatusNotFound, http.MethodGet, "/unknown", "404 page not found\n"}, + {http.StatusNotFound, http.MethodPost, "/user/alice/1", "404 page not found\n"}, + {http.StatusOK, http.MethodGet, "/user/handler", "method: GET, path: /user/handler, params: []"}, + {http.StatusOK, http.MethodPost, "/user/handler", "method: POST, path: /user/handler, params: []"}, + {http.StatusOK, http.MethodPut, "/user/inference", "method: PUT, path: /user/inference, params: []"}, } { - req, err := http.NewRequest(v.method, server.URL+v.path, nil) - if err != nil { - t.Error(err) - continue - } + req, err := http.NewRequestWithContext(context.Background(), v.method, server.URL+v.path, nil) + require.NoError(t, err) + res, err := http.DefaultClient.Do(req) - if err != nil { - t.Error(err) - continue - } + require.NoError(t, err) + defer res.Body.Close() body, err := io.ReadAll(res.Body) - if err != nil { - t.Error(err) - continue - } + require.NoError(t, err) + actual := string(body) expected := v.expected - if res.StatusCode != v.status || actual != expected { - t.Errorf(`%s "%s" => %#v %#v, want %#v %#v`, v.method, v.path, res.StatusCode, actual, v.status, expected) - } + + assert.Equalf(t, v.status, res.StatusCode, "for method %s in path %s", v.method, v.path) + assert.Equalf(t, expected, actual, "for method %s in path %s", v.method, v.path) } } func TestNotFound(t *testing.T) { mux := denco.NewMux() handler, err := mux.Build([]denco.Handler{}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) + server := httptest.NewServer(handler) defer server.Close() @@ -89,18 +84,16 @@ func TestNotFound(t *testing.T) { w.WriteHeader(http.StatusServiceUnavailable) fmt.Fprintf(w, "method: %s, path: %s, params: %v", r.Method, r.URL.Path, params) } - res, err := http.Get(server.URL) - if err != nil { - t.Fatal(err) - } + res, err := http.Get(server.URL) //nolint:noctx + require.NoError(t, err) + defer res.Body.Close() body, err := io.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) + actual := string(body) expected := "method: GET, path: /, params: []" - if res.StatusCode != http.StatusServiceUnavailable || actual != expected { - t.Errorf(`GET "/" => %#v %#v, want %#v %#v`, res.StatusCode, actual, http.StatusServiceUnavailable, expected) - } + + assert.Equal(t, http.StatusServiceUnavailable, res.StatusCode) + assert.Equal(t, expected, actual) } diff --git a/middleware/doc.go b/middleware/doc.go index eaf90606..836a9885 100644 --- a/middleware/doc.go +++ b/middleware/doc.go @@ -12,51 +12,52 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*Package middleware provides the library with helper functions for serving swagger APIs. +/* +Package middleware provides the library with helper functions for serving swagger APIs. Pseudo middleware handler - import ( - "net/http" - - "github.com/go-openapi/errors" - ) - - func newCompleteMiddleware(ctx *Context) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - // use context to lookup routes - if matched, ok := ctx.RouteInfo(r); ok { - - if matched.NeedsAuth() { - if _, err := ctx.Authorize(r, matched); err != nil { - ctx.Respond(rw, r, matched.Produces, matched, err) - return - } - } - - bound, validation := ctx.BindAndValidate(r, matched) - if validation != nil { - ctx.Respond(rw, r, matched.Produces, matched, validation) - return - } - - result, err := matched.Handler.Handle(bound) - if err != nil { - ctx.Respond(rw, r, matched.Produces, matched, err) - return - } - - ctx.Respond(rw, r, matched.Produces, matched, result) - return - } - - // Not found, check if it exists in the other methods first - if others := ctx.AllowedMethods(r); len(others) > 0 { - ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others)) - return - } - ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.Path)) - }) - } + import ( + "net/http" + + "github.com/go-openapi/errors" + ) + + func newCompleteMiddleware(ctx *Context) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + // use context to lookup routes + if matched, ok := ctx.RouteInfo(r); ok { + + if matched.NeedsAuth() { + if _, err := ctx.Authorize(r, matched); err != nil { + ctx.Respond(rw, r, matched.Produces, matched, err) + return + } + } + + bound, validation := ctx.BindAndValidate(r, matched) + if validation != nil { + ctx.Respond(rw, r, matched.Produces, matched, validation) + return + } + + result, err := matched.Handler.Handle(bound) + if err != nil { + ctx.Respond(rw, r, matched.Produces, matched, err) + return + } + + ctx.Respond(rw, r, matched.Produces, matched, result) + return + } + + // Not found, check if it exists in the other methods first + if others := ctx.AllowedMethods(r); len(others) > 0 { + ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others)) + return + } + ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.Path)) + }) + } */ package middleware diff --git a/middleware/go18.go b/middleware/go18.go index 75c762c0..1bf4939c 100644 --- a/middleware/go18.go +++ b/middleware/go18.go @@ -1,3 +1,4 @@ +//go:build go1.8 // +build go1.8 package middleware diff --git a/middleware/header/header.go b/middleware/header/header.go index e069743e..1923fa55 100644 --- a/middleware/header/header.go +++ b/middleware/header/header.go @@ -195,6 +195,8 @@ func ParseAccept2(header http.Header, key string) (specs []AcceptSpec) { } // ParseAccept parses Accept* headers. +// +//nolint:nakedret func ParseAccept(header http.Header, key string) (specs []AcceptSpec) { loop: for _, s := range header[key] { @@ -306,7 +308,7 @@ func expectTokenOrQuoted(s string) (value string, rest string) { p := make([]byte, len(s)-1) j := copy(p, s[:i]) escape := true - for i = i + 1; i < len(s); i++ { + for i = i + 1; i < len(s); i++ { //nolint:gocritic b := s[i] switch { case escape: diff --git a/middleware/operation_test.go b/middleware/operation_test.go index c6873738..12f9e114 100644 --- a/middleware/operation_test.go +++ b/middleware/operation_test.go @@ -15,15 +15,16 @@ package middleware import ( + stdcontext "context" "net/http" "net/http/httptest" "testing" "github.com/go-openapi/errors" - "github.com/stretchr/testify/assert" - "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/internal/testing/petstore" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestOperationExecutor(t *testing.T) { @@ -39,16 +40,17 @@ func TestOperationExecutor(t *testing.T) { mw := NewOperationExecutor(context) recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) request.Header.Add("Accept", "application/json") request.SetBasicAuth("admin", "admin") mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, `[{"id":1,"name":"a dog"}]`+"\n", recorder.Body.String()) spec, api = petstore.NewAPI(t) api.RegisterOperation("get", "/pets", runtime.OperationHandlerFunc(func(params interface{}) (interface{}, error) { - return nil, errors.New(422, "expected") + return nil, errors.New(http.StatusUnprocessableEntity, "expected") })) context = NewContext(spec, api, nil) @@ -56,10 +58,11 @@ func TestOperationExecutor(t *testing.T) { mw = NewOperationExecutor(context) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) request.Header.Add("Accept", "application/json") request.SetBasicAuth("admin", "admin") mw.ServeHTTP(recorder, request) - assert.Equal(t, 422, recorder.Code) + assert.Equal(t, http.StatusUnprocessableEntity, recorder.Code) assert.Equal(t, `{"code":422,"message":"expected"}`, recorder.Body.String()) } diff --git a/middleware/parameter.go b/middleware/parameter.go index 9aaf6595..97acfc12 100644 --- a/middleware/parameter.go +++ b/middleware/parameter.go @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//nolint:goconst package middleware import ( @@ -208,7 +209,7 @@ func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams if ffErr != nil { if p.parameter.Required { return errors.NewParseError(p.Name, p.parameter.In, "", ffErr) - } else { + } else { //nolint:revive return nil } } @@ -273,7 +274,7 @@ func (p *untypedParamBinder) bindValue(data []string, hasKey bool, target reflec return p.setFieldValue(target, p.parameter.Default, d, hasKey) } -func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue interface{}, data string, hasKey bool) error { +func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue interface{}, data string, hasKey bool) error { //nolint:gocyclo tpe := p.parameter.Type if p.parameter.Format != "" { tpe = p.parameter.Format @@ -317,7 +318,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in return nil } - switch target.Kind() { + switch target.Kind() { //nolint:exhaustive case reflect.Bool: if data == "" { if target.CanSet() { diff --git a/middleware/parameter_test.go b/middleware/parameter_test.go index c1f83b33..c2b0dddd 100644 --- a/middleware/parameter_test.go +++ b/middleware/parameter_test.go @@ -25,14 +25,11 @@ import ( "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/go-openapi/runtime" ) -// type email struct { -// Address string -// } - type paramFactory func(string) *spec.Parameter var paramFactories = []paramFactory{ @@ -56,12 +53,13 @@ func testCollectionFormat(t *testing.T, param *spec.Parameter, valid bool) { binder := &untypedParamBinder{ parameter: param, } - _, _, _, err := binder.readValue(runtime.Values(nil), reflect.ValueOf(nil)) + // ICI + _, _, _, err := binder.readValue(runtime.Values(nil), reflect.ValueOf(nil)) //nolint:dogsled if valid { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.Error(t, err) - assert.Equal(t, errors.InvalidCollectionFormat(param.Name, param.In, param.CollectionFormat), err) + require.Error(t, err) + require.EqualError(t, err, errors.InvalidCollectionFormat(param.Name, param.In, param.CollectionFormat).Error()) } } @@ -71,39 +69,43 @@ func requiredError(param *spec.Parameter, data interface{}) *errors.Validation { func validateRequiredTest(t *testing.T, param *spec.Parameter, value reflect.Value) { binder := np(param) + err := binder.bindValue([]string{}, true, value) - assert.Error(t, err) + require.Error(t, err) assert.NotNil(t, param) - assert.EqualError(t, requiredError(param, value.Interface()), err.Error()) + require.EqualError(t, requiredError(param, value.Interface()), err.Error()) + err = binder.bindValue([]string{""}, true, value) - if assert.Error(t, err) { - assert.EqualError(t, requiredError(param, value.Interface()), err.Error()) - } + require.Error(t, err) + require.EqualError(t, requiredError(param, value.Interface()), err.Error()) // should be impossible data, but let's go with it err = binder.bindValue([]string{"a"}, false, value) - assert.Error(t, err) - assert.EqualError(t, requiredError(param, value.Interface()), err.Error()) + require.Error(t, err) + require.EqualError(t, err, requiredError(param, value.Interface()).Error()) + err = binder.bindValue([]string{""}, false, value) - assert.Error(t, err) - assert.EqualError(t, requiredError(param, value.Interface()), err.Error()) + require.Error(t, err) + require.EqualError(t, requiredError(param, value.Interface()), err.Error()) } func validateRequiredAllowEmptyTest(t *testing.T, param *spec.Parameter, value reflect.Value) { param.AllowEmptyValue = true binder := np(param) err := binder.bindValue([]string{}, true, value) - assert.NoError(t, err) - if assert.NotNil(t, param) { - err = binder.bindValue([]string{""}, true, value) - assert.NoError(t, err) - err = binder.bindValue([]string{"1"}, false, value) - assert.Error(t, err) - assert.EqualError(t, requiredError(param, value.Interface()), err.Error()) - err = binder.bindValue([]string{""}, false, value) - assert.Error(t, err) - assert.EqualError(t, requiredError(param, value.Interface()), err.Error()) - } + require.NoError(t, err) + require.NotNil(t, param) + + err = binder.bindValue([]string{""}, true, value) + require.NoError(t, err) + + err = binder.bindValue([]string{"1"}, false, value) + require.Error(t, err) + require.EqualError(t, requiredError(param, value.Interface()), err.Error()) + + err = binder.bindValue([]string{""}, false, value) + require.Error(t, err) + require.EqualError(t, requiredError(param, value.Interface()), err.Error()) } func TestRequiredValidation(t *testing.T) { @@ -165,82 +167,89 @@ func TestTypeValidation(t *testing.T) { binder := np(intParam) err := binder.bindValue([]string{"yada"}, true, value) // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(intParam, "yada"), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(intParam, "yada").Error()) + // fails for overflow val := int64(math.MaxInt32) str := strconv.FormatInt(val, 10) + "0" v := int32(0) value = reflect.ValueOf(&v).Elem() + binder = np(intParam) err = binder.bindValue([]string{str}, true, value) - assert.Error(t, err) - assert.Equal(t, invalidTypeError(intParam, str), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(intParam, str).Error()) + // fails for invalid string longParam := newParam("badLong").Typed("integer", "int64") value = reflect.ValueOf(int64(0)) + binder = np(longParam) err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(longParam, "yada"), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(longParam, "yada").Error()) + // fails for overflow str2 := strconv.FormatInt(math.MaxInt64, 10) + "0" v2 := int64(0) vv2 := reflect.ValueOf(&v2).Elem() binder = np(longParam) err = binder.bindValue([]string{str2}, true, vv2) - assert.Error(t, err) - assert.Equal(t, invalidTypeError(longParam, str2), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(longParam, str2).Error()) + // fails for invalid string floatParam := newParam("badFloat").Typed("number", "float") value = reflect.ValueOf(float64(0)) binder = np(floatParam) err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(floatParam, "yada"), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(floatParam, "yada").Error()) + // fails for overflow str3 := strconv.FormatFloat(math.MaxFloat64, 'f', 5, 64) v3 := reflect.TypeOf(float32(0)) value = reflect.New(v3).Elem() binder = np(floatParam) err = binder.bindValue([]string{str3}, true, value) - assert.Error(t, err) - assert.Equal(t, invalidTypeError(floatParam, str3), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(floatParam, str3).Error()) + // fails for invalid string doubleParam := newParam("badDouble").Typed("number", "double") value = reflect.ValueOf(float64(0)) binder = np(doubleParam) err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(doubleParam, "yada"), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(doubleParam, "yada").Error()) + // fails for overflow str4 := "9" + strconv.FormatFloat(math.MaxFloat64, 'f', 5, 64) v4 := reflect.TypeOf(float64(0)) value = reflect.New(v4).Elem() binder = np(doubleParam) err = binder.bindValue([]string{str4}, true, value) - assert.Error(t, err) - assert.Equal(t, invalidTypeError(doubleParam, str4), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(doubleParam, str4).Error()) + // fails for invalid string dateParam := newParam("badDate").Typed("string", "date") value = reflect.ValueOf(strfmt.Date{}) binder = np(dateParam) err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(dateParam, "yada"), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(dateParam, "yada").Error()) + // fails for invalid string dateTimeParam := newParam("badDateTime").Typed("string", "date-time") value = reflect.ValueOf(strfmt.DateTime{}) binder = np(dateTimeParam) err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(dateTimeParam, "yada"), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(dateTimeParam, "yada").Error()) + // fails for invalid string byteParam := newParam("badByte").Typed("string", "byte") values := url.Values(map[string][]string{}) values.Add("badByte", "yaüda") @@ -248,9 +257,8 @@ func TestTypeValidation(t *testing.T) { value = reflect.ValueOf(&v5).Elem() binder = np(byteParam) err = binder.bindValue([]string{"yaüda"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(byteParam, "yaüda"), err) + require.Error(t, err) + require.EqualError(t, err, invalidTypeError(byteParam, "yaüda").Error()) } } diff --git a/middleware/rapidoc.go b/middleware/rapidoc.go index 4be330d6..c0593999 100644 --- a/middleware/rapidoc.go +++ b/middleware/rapidoc.go @@ -1,3 +1,4 @@ +//nolint:dupl,goconst package middleware import ( @@ -43,7 +44,6 @@ func (r *RapiDocOpts) EnsureDefaults() { // RapiDoc creates a middleware to serve a documentation site for a swagger spec. // This allows for altering the spec before starting the http listener. -// func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler { opts.EnsureDefaults() @@ -79,7 +79,7 @@ const ( {{ .Title }} - + diff --git a/middleware/rapidoc_test.go b/middleware/rapidoc_test.go index b0074653..c15550a5 100644 --- a/middleware/rapidoc_test.go +++ b/middleware/rapidoc_test.go @@ -1,20 +1,23 @@ package middleware import ( + "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRapiDocMiddleware(t *testing.T) { rapidoc := RapiDoc(RapiDocOpts{}, nil) - req, _ := http.NewRequest("GET", "/docs", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs", nil) + require.NoError(t, err) recorder := httptest.NewRecorder() rapidoc.ServeHTTP(recorder, req) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type")) assert.Contains(t, recorder.Body.String(), "API documentation") assert.Contains(t, recorder.Body.String(), "") diff --git a/middleware/redoc.go b/middleware/redoc.go index 019c8542..665d0592 100644 --- a/middleware/redoc.go +++ b/middleware/redoc.go @@ -1,3 +1,4 @@ +//nolint:dupl package middleware import ( @@ -43,7 +44,6 @@ func (r *RedocOpts) EnsureDefaults() { // Redoc creates a middleware to serve a documentation site for a swagger spec. // This allows for altering the spec before starting the http listener. -// func Redoc(opts RedocOpts, next http.Handler) http.Handler { opts.EnsureDefaults() diff --git a/middleware/redoc_test.go b/middleware/redoc_test.go index cf13da93..364d8cf0 100644 --- a/middleware/redoc_test.go +++ b/middleware/redoc_test.go @@ -1,20 +1,23 @@ package middleware import ( + "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRedocMiddleware(t *testing.T) { redoc := Redoc(RedocOpts{}, nil) - req, _ := http.NewRequest("GET", "/docs", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs", nil) + require.NoError(t, err) recorder := httptest.NewRecorder() redoc.ServeHTTP(recorder, req) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type")) assert.Contains(t, recorder.Body.String(), "API documentation") assert.Contains(t, recorder.Body.String(), "") diff --git a/middleware/request_test.go b/middleware/request_test.go index 65ef69ad..91ba915b 100644 --- a/middleware/request_test.go +++ b/middleware/request_test.go @@ -16,6 +16,7 @@ package middleware import ( "bytes" + "context" "io" "mime/multipart" "net/http" @@ -24,13 +25,16 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - + "github.com/go-openapi/runtime" "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) - "github.com/go-openapi/runtime" +const ( + csvFormat = "csv" + testURL = "http://localhost:8002/hello" ) type stubConsumer struct { @@ -71,7 +75,7 @@ type jsonRequestSlice struct { func parametersForAllTypes(fmt string) map[string]spec.Parameter { if fmt == "" { - fmt = "csv" + fmt = csvFormat } nameParam := spec.QueryParam("name").Typed("string", "") idParam := spec.PathParam("id").Typed("integer", "int64") @@ -113,7 +117,7 @@ func parametersForAllTypes(fmt string) map[string]spec.Parameter { func parametersForJSONRequestParams(fmt string) map[string]spec.Parameter { if fmt == "" { - fmt = "csv" + fmt = csvFormat } nameParam := spec.QueryParam("name").Typed("string", "") idParam := spec.PathParam("id").Typed("integer", "int64") @@ -139,7 +143,7 @@ func parametersForJSONRequestParams(fmt string) map[string]spec.Parameter { } func parametersForJSONRequestSliceParams(fmt string) map[string]spec.Parameter { if fmt == "" { - fmt = "csv" + fmt = csvFormat } nameParam := spec.QueryParam("name").Typed("string", "") idParam := spec.PathParam("id").Typed("integer", "int64") @@ -175,7 +179,8 @@ func TestRequestBindingDefaultValue(t *testing.T) { planned := strfmt.Date(dt1) dt2 := time.Date(2014, 10, 12, 8, 5, 5, 0, time.UTC) delivered := strfmt.DateTime(dt2) - uri, _ := url.Parse("http://localhost:8002/hello") + uri, err := url.Parse(testURL) + require.NoError(t, err) defaults := map[string]interface{}{ "id": id, "age": age, @@ -197,13 +202,14 @@ func TestRequestBindingDefaultValue(t *testing.T) { op3[k] = p } - req, _ := http.NewRequest("POST", uri.String(), bytes.NewBuffer(nil)) + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, uri.String(), bytes.NewBuffer(nil)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json") binder := NewUntypedRequestBinder(op3, new(spec.Swagger), strfmt.Default) data := make(map[string]interface{}) - err := binder.Bind(req, RouteParams(nil), runtime.JSONConsumer(), &data) - assert.NoError(t, err) + err = binder.Bind(req, RouteParams(nil), runtime.JSONConsumer(), &data) + require.NoError(t, err) assert.Equal(t, defaults["id"], data["id"]) assert.Equal(t, name, data["name"]) assert.Equal(t, friend, data["friend"]) @@ -224,61 +230,67 @@ func TestRequestBindingForInvalid(t *testing.T) { op1 := map[string]spec.Parameter{"Some": *invalidParam} binder := NewUntypedRequestBinder(op1, new(spec.Swagger), strfmt.Default) - req, _ := http.NewRequest("GET", "http://localhost:8002/hello?name=the-name", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:8002/hello?name=the-name", nil) + require.NoError(t, err) - err := binder.Bind(req, nil, new(stubConsumer), new(jsonRequestParams)) - assert.Error(t, err) + err = binder.Bind(req, nil, new(stubConsumer), new(jsonRequestParams)) + require.Error(t, err) op2 := parametersForJSONRequestParams("") binder = NewUntypedRequestBinder(op2, new(spec.Swagger), strfmt.Default) - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{"name":"toby","age":32}`))) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8002/hello/1?name=the-name", bytes.NewBufferString(`{"name":"toby","age":32}`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application(") data := jsonRequestParams{} err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) + require.Error(t, err) - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{]`))) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8002/hello/1?name=the-name", bytes.NewBufferString(`{]`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json") data = jsonRequestParams{} err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) + require.Error(t, err) invalidMultiParam := spec.HeaderParam("tags").CollectionOf(new(spec.Items), "multi") op3 := map[string]spec.Parameter{"Tags": *invalidMultiParam} binder = NewUntypedRequestBinder(op3, new(spec.Swagger), strfmt.Default) - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{}`))) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8002/hello/1?name=the-name", bytes.NewBufferString(`{}`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json") data = jsonRequestParams{} err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) + require.Error(t, err) invalidMultiParam = spec.PathParam("").CollectionOf(new(spec.Items), "multi") op4 := map[string]spec.Parameter{"Tags": *invalidMultiParam} binder = NewUntypedRequestBinder(op4, new(spec.Swagger), strfmt.Default) - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{}`))) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8002/hello/1?name=the-name", bytes.NewBufferString(`{}`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json") data = jsonRequestParams{} err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) + require.Error(t, err) invalidInParam := spec.HeaderParam("tags").Typed("string", "") invalidInParam.In = "invalid" op5 := map[string]spec.Parameter{"Tags": *invalidInParam} binder = NewUntypedRequestBinder(op5, new(spec.Swagger), strfmt.Default) - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{}`))) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8002/hello/1?name=the-name", bytes.NewBufferString(`{}`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json") data = jsonRequestParams{} err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) + require.Error(t, err) } func TestRequestBindingForValid(t *testing.T) { - for _, fmt := range []string{"csv", "pipes", "tsv", "ssv", "multi"} { + for _, fmt := range []string{csvFormat, "pipes", "tsv", "ssv", "multi"} { op1 := parametersForJSONRequestParams(fmt) binder := NewUntypedRequestBinder(op1, new(spec.Swagger), strfmt.Default) @@ -305,7 +317,7 @@ func TestRequestBindingForValid(t *testing.T) { urlStr := "http://localhost:8002/hello/1?name=the-name&tags=" + queryString - req, err := http.NewRequest("POST", urlStr, bytes.NewBuffer([]byte(`{"name":"toby","age":32}`))) + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, bytes.NewBufferString(`{"name":"toby","age":32}`)) require.NoError(t, err) req.Header.Set("Content-Type", "application/json;charset=utf-8") req.Header.Set("X-Request-Id", "1325959595") @@ -320,7 +332,7 @@ func TestRequestBindingForValid(t *testing.T) { RequestID: 1325959595, Tags: []string{"one", "two", "three"}, } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, data) } @@ -328,25 +340,27 @@ func TestRequestBindingForValid(t *testing.T) { binder := NewUntypedRequestBinder(op1, new(spec.Swagger), strfmt.Default) urlStr := "http://localhost:8002/hello/1?name=the-name&tags=one,two,three" - req, _ := http.NewRequest("POST", urlStr, bytes.NewBuffer([]byte(`{"name":"toby","age":32}`))) + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, bytes.NewBufferString(`{"name":"toby","age":32}`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json;charset=utf-8") req.Header.Set("X-Request-Id", "1325959595") data2 := jsonRequestPtr{} - err := binder.Bind(req, []RouteParam{{"id", "1"}}, runtime.JSONConsumer(), &data2) + err = binder.Bind(req, []RouteParam{{"id", "1"}}, runtime.JSONConsumer(), &data2) expected2 := jsonRequestPtr{ Friend: &friend{"toby", 32}, Tags: []string{"one", "two", "three"}, } - assert.NoError(t, err) + require.NoError(t, err) if data2.Friend == nil { t.Fatal("friend is nil") } assert.Equal(t, *expected2.Friend, *data2.Friend) assert.Equal(t, expected2.Tags, data2.Tags) - req, _ = http.NewRequest("POST", urlStr, bytes.NewBuffer([]byte(`[{"name":"toby","age":32}]`))) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, bytes.NewBufferString(`[{"name":"toby","age":32}]`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json;charset=utf-8") req.Header.Set("X-Request-Id", "1325959595") op2 := parametersForJSONRequestSliceParams("") @@ -358,7 +372,7 @@ func TestRequestBindingForValid(t *testing.T) { Friend: []friend{{"toby", 32}}, Tags: []string{"one", "two", "three"}, } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected3.Friend, data3.Friend) assert.Equal(t, expected3.Tags, data3.Tags) } @@ -380,21 +394,23 @@ func TestFormUpload(t *testing.T) { params := parametersForFormUpload() binder := NewUntypedRequestBinder(params, new(spec.Swagger), strfmt.Default) - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=the-name&age=32`)) + urlStr := testURL + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, bytes.NewBufferString(`name=the-name&age=32`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") data := formRequest{} res := binder.Bind(req, nil, runtime.JSONConsumer(), &data) - assert.NoError(t, res) + require.NoError(t, res) assert.Equal(t, "the-name", data.Name) assert.Equal(t, 32, data.Age) - req, _ = http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=%3&age=32`)) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, bytes.NewBufferString(`name=%3&age=32`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") data = formRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) } type fileRequest struct { @@ -417,67 +433,76 @@ func TestBindingFileUpload(t *testing.T) { body := bytes.NewBuffer(nil) writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("file", "plain-jane.txt") - assert.NoError(t, err) + require.NoError(t, err) - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) + _, err = part.Write([]byte("the file contents")) + require.NoError(t, err) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, body) + urlStr := testURL + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) data := fileRequest{} - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) assert.Equal(t, "the-name", data.Name) assert.NotNil(t, data.File) assert.NotNil(t, data.File.Header) assert.Equal(t, "plain-jane.txt", data.File.Header.Filename) bb, err := io.ReadAll(data.File.Data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("the file contents"), bb) - req, _ = http.NewRequest("POST", urlStr, body) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, body) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json") data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - req, _ = http.NewRequest("POST", urlStr, body) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, body) + require.NoError(t, err) req.Header.Set("Content-Type", "application(") data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) body = bytes.NewBuffer(nil) writer = multipart.NewWriter(body) part, err = writer.CreateFormFile("bad-name", "plain-jane.txt") - assert.NoError(t, err) - - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) - req, _ = http.NewRequest("POST", urlStr, body) + require.NoError(t, err) + + _, err = part.Write([]byte("the file contents")) + require.NoError(t, err) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - req, _ = http.NewRequest("POST", urlStr, body) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) - _, _ = req.MultipartReader() + _, err = req.MultipartReader() + require.NoError(t, err) data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) writer = multipart.NewWriter(body) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) - req, _ = http.NewRequest("POST", urlStr, body) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) } func paramsForOptionalFileUpload() *UntypedRequestBinder { @@ -493,38 +518,41 @@ func TestBindingOptionalFileUpload(t *testing.T) { body := bytes.NewBuffer(nil) writer := multipart.NewWriter(body) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, body) + urlStr := testURL + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) data := fileRequest{} - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) assert.Equal(t, "the-name", data.Name) assert.Nil(t, data.File.Data) assert.Nil(t, data.File.Header) writer = multipart.NewWriter(body) part, err := writer.CreateFormFile("file", "plain-jane.txt") - assert.NoError(t, err) - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) - - req, _ = http.NewRequest("POST", urlStr, body) + require.NoError(t, err) + _, err = part.Write([]byte("the file contents")) + require.NoError(t, err) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) + + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, urlStr, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) - assert.NoError(t, writer.Close()) + require.NoError(t, writer.Close()) data = fileRequest{} - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) assert.Equal(t, "the-name", data.Name) assert.NotNil(t, data.File) assert.NotNil(t, data.File.Header) assert.Equal(t, "plain-jane.txt", data.File.Header.Filename) bb, err := io.ReadAll(data.File.Data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("the file contents"), bb) } diff --git a/middleware/route_authenticator_test.go b/middleware/route_authenticator_test.go index ab2c41f9..aa5d9c46 100644 --- a/middleware/route_authenticator_test.go +++ b/middleware/route_authenticator_test.go @@ -1,6 +1,7 @@ package middleware import ( + "context" "errors" "net/http" "testing" @@ -17,7 +18,7 @@ type countAuthenticator struct { err error } -func (c *countAuthenticator) Authenticate(params interface{}) (bool, interface{}, error) { +func (c *countAuthenticator) Authenticate(_ interface{}) (bool, interface{}, error) { c.count++ return c.applies, c.principal, c.err } @@ -50,7 +51,7 @@ func TestAuthenticateSingle(t *testing.T) { require.False(t, ras.AllowsAnonymous()) - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) route := &MatchedRoute{} ok, prin, err := ras.Authenticate(req, route) require.NoError(t, err) @@ -77,10 +78,9 @@ func TestAuthenticateLogicalOr(t *testing.T) { } // right side matches ras := RouteAuthenticators([]RouteAuthenticator{ra1, ra2}) - require.False(t, ras.AllowsAnonymous()) - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) route := &MatchedRoute{} ok, prin, err := ras.Authenticate(req, route) require.NoError(t, err) @@ -91,16 +91,15 @@ func TestAuthenticateLogicalOr(t *testing.T) { // left side matches ras = RouteAuthenticators([]RouteAuthenticator{ra2, ra1}) - require.False(t, ras.AllowsAnonymous()) - req, _ = http.NewRequest("GET", "/", nil) + req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) route = &MatchedRoute{} ok, prin, err = ras.Authenticate(req, route) require.NoError(t, err) + require.True(t, ok) require.Equal(t, "the user", prin) - require.Equal(t, ra2, *route.Authenticator) } @@ -112,20 +111,20 @@ func TestAuthenticateLogicalAnd(t *testing.T) { Schemes: []string{"auth1"}, Scopes: map[string][]string{"auth1": nil}, } - auther := newCountAuthenticator(true, "the user", nil) + authorizer := newCountAuthenticator(true, "the user", nil) ra2 := RouteAuthenticator{ Authenticator: map[string]runtime.Authenticator{ - "auth2": auther, - "auth3": auther, + "auth2": authorizer, + "auth3": authorizer, }, Schemes: []string{"auth2", "auth3"}, Scopes: map[string][]string{"auth2": nil}, } ras := RouteAuthenticators([]RouteAuthenticator{ra1, ra2}) - require.False(t, ras.AllowsAnonymous()) - req, _ := http.NewRequest("GET", "/", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) + require.NoError(t, err) route := &MatchedRoute{} ok, prin, err := ras.Authenticate(req, route) require.NoError(t, err) @@ -133,7 +132,7 @@ func TestAuthenticateLogicalAnd(t *testing.T) { require.Equal(t, "the user", prin) require.Equal(t, ra2, *route.Authenticator) - require.Equal(t, 2, auther.count) + require.Equal(t, 2, authorizer.count) var count int successA := runtime.AuthenticatorFunc(func(_ interface{}) (bool, interface{}, error) { @@ -158,7 +157,7 @@ func TestAuthenticateLogicalAnd(t *testing.T) { require.False(t, ras.AllowsAnonymous()) - req, _ = http.NewRequest("GET", "/", nil) + req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) route = &MatchedRoute{} ok, prin, err = ras.Authenticate(req, route) require.Error(t, err) @@ -181,7 +180,7 @@ func TestAuthenticateLogicalAnd(t *testing.T) { require.False(t, ras.AllowsAnonymous()) - req, _ = http.NewRequest("GET", "/", nil) + req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) route = &MatchedRoute{} ok, prin, err = ras.Authenticate(req, route) require.Error(t, err) @@ -217,7 +216,7 @@ func TestAuthenticateOptional(t *testing.T) { ras := RouteAuthenticators([]RouteAuthenticator{ra1, ra2, ra3}) require.True(t, ras.AllowsAnonymous()) - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) route := &MatchedRoute{} ok, prin, err := ras.Authenticate(req, route) require.NoError(t, err) @@ -248,7 +247,7 @@ func TestAuthenticateOptional(t *testing.T) { ras = RouteAuthenticators([]RouteAuthenticator{ra4, ra5, ra6}) require.True(t, ras.AllowsAnonymous()) - req, _ = http.NewRequest("GET", "/", nil) + req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) route = &MatchedRoute{} ok, prin, err = ras.Authenticate(req, route) require.Error(t, err) diff --git a/middleware/route_param_test.go b/middleware/route_param_test.go index 78c92b65..714646a1 100644 --- a/middleware/route_param_test.go +++ b/middleware/route_param_test.go @@ -28,11 +28,11 @@ func TestRouteParams(t *testing.T) { }) v := coll1.Get("blah") - assert.Equal(t, v, "foo") + assert.Equal(t, "foo", v) v2 := coll1.Get("abc") - assert.Equal(t, v2, "bar") + assert.Equal(t, "bar", v2) v3 := coll1.Get("ccc") - assert.Equal(t, v3, "efg") + assert.Equal(t, "efg", v3) v4 := coll1.Get("ydkdk") assert.Empty(t, v4) } diff --git a/middleware/router.go b/middleware/router.go index 5052031c..5e057b8f 100644 --- a/middleware/router.go +++ b/middleware/router.go @@ -449,7 +449,7 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper func (d *defaultRouteBuilder) buildAuthenticators(operation *spec.Operation) RouteAuthenticators { requirements := d.analyzer.SecurityRequirementsFor(operation) - var auths []RouteAuthenticator + var auths []RouteAuthenticator //nolint:prealloc for _, reqs := range requirements { var schemes []string scopes := make(map[string][]string, len(reqs)) diff --git a/middleware/router_test.go b/middleware/router_test.go index 00e63d04..9b6a47a8 100644 --- a/middleware/router_test.go +++ b/middleware/router_test.go @@ -15,6 +15,7 @@ package middleware import ( + stdcontext "context" "net/http" "net/http/httptest" "sort" @@ -23,13 +24,13 @@ import ( "github.com/go-openapi/analysis" "github.com/go-openapi/loads" - "github.com/stretchr/testify/assert" - "github.com/go-openapi/runtime/internal/testing/petstore" "github.com/go-openapi/runtime/middleware/untyped" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func terminator(rw http.ResponseWriter, r *http.Request) { +func terminator(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusOK) } @@ -39,13 +40,15 @@ func TestRouterMiddleware(t *testing.T) { mw := NewRouter(context, http.HandlerFunc(terminator)) recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("DELETE", "/api/pets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodDelete, "/api/pets", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) assert.Equal(t, http.StatusMethodNotAllowed, recorder.Code) @@ -55,13 +58,15 @@ func TestRouterMiddleware(t *testing.T) { assert.Equal(t, "GET,POST", strings.Join(methods, ",")) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/nopets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/nopets", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) assert.Equal(t, http.StatusNotFound, recorder.Code) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/pets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/pets", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) assert.Equal(t, http.StatusNotFound, recorder.Code) @@ -71,13 +76,15 @@ func TestRouterMiddleware(t *testing.T) { mw = NewRouter(context, http.HandlerFunc(terminator)) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/pets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/pets", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("DELETE", "/pets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodDelete, "/pets", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) assert.Equal(t, http.StatusMethodNotAllowed, recorder.Code) @@ -87,7 +94,8 @@ func TestRouterMiddleware(t *testing.T) { assert.Equal(t, "GET,POST", strings.Join(methods, ",")) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/nopets", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/nopets", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) assert.Equal(t, http.StatusNotFound, recorder.Code) @@ -103,21 +111,21 @@ func TestRouterBuilder(t *testing.T) { // context := NewContext(spec, api) builder := petAPIRouterBuilder(spec, api, analyzed) - getRecords := builder.records["GET"] - postRecords := builder.records["POST"] - deleteRecords := builder.records["DELETE"] + getRecords := builder.records[http.MethodGet] + postRecords := builder.records[http.MethodPost] + deleteRecords := builder.records[http.MethodDelete] assert.Len(t, getRecords, 2) assert.Len(t, postRecords, 1) assert.Len(t, deleteRecords, 1) - assert.Empty(t, builder.records["PATCH"]) - assert.Empty(t, builder.records["OPTIONS"]) - assert.Empty(t, builder.records["HEAD"]) - assert.Empty(t, builder.records["PUT"]) + assert.Empty(t, builder.records[http.MethodPatch]) + assert.Empty(t, builder.records[http.MethodOptions]) + assert.Empty(t, builder.records[http.MethodHead]) + assert.Empty(t, builder.records[http.MethodPut]) rec := postRecords[0] - assert.Equal(t, rec.Key, "/pets") + assert.Equal(t, "/pets", rec.Key) val := rec.Value.(*routeEntry) assert.Len(t, val.Consumers, 2) assert.Len(t, val.Producers, 2) @@ -132,7 +140,7 @@ func TestRouterBuilder(t *testing.T) { assert.Len(t, val.Parameters, 1) recG := getRecords[0] - assert.Equal(t, recG.Key, "/pets") + assert.Equal(t, "/pets", recG.Key) valG := recG.Value.(*routeEntry) assert.Len(t, valG.Consumers, 2) assert.Len(t, valG.Producers, 4) @@ -149,10 +157,11 @@ func TestRouterCanonicalBasePath(t *testing.T) { mw := NewRouter(context, http.HandlerFunc(terminator)) recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) } func TestRouter_EscapedPath(t *testing.T) { @@ -162,22 +171,22 @@ func TestRouter_EscapedPath(t *testing.T) { mw := NewRouter(context, http.HandlerFunc(terminator)) recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets/123", nil) + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets/123", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets/abc%2Fdef", nil) + request, err = http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets/abc%2Fdef", nil) + require.NoError(t, err) mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) ri, _, _ := context.RouteInfo(request) - if assert.NotNil(t, ri) { - if assert.NotNil(t, ri.Params) { - assert.Equal(t, "abc/def", ri.Params.Get("id")) - } - } + require.NotNil(t, ri) + require.NotNil(t, ri.Params) + assert.Equal(t, "abc/def", ri.Params.Get("id")) } func TestRouterStruct(t *testing.T) { @@ -189,7 +198,7 @@ func TestRouterStruct(t *testing.T) { entry, ok := router.Lookup("delete", "/api/pets/{id}") assert.True(t, ok) - assert.NotNil(t, entry) + require.NotNil(t, entry) assert.Len(t, entry.Params, 1) assert.Equal(t, "id", entry.Params[0].Name) @@ -202,10 +211,10 @@ func TestRouterStruct(t *testing.T) { func petAPIRouterBuilder(spec *loads.Document, api *untyped.API, analyzed *analysis.Spec) *defaultRouteBuilder { builder := newDefaultRouteBuilder(spec, newRoutableUntypedAPI(spec, api, new(Context))) - builder.AddRoute("GET", "/pets", analyzed.AllPaths()["/pets"].Get) - builder.AddRoute("POST", "/pets", analyzed.AllPaths()["/pets"].Post) - builder.AddRoute("DELETE", "/pets/{id}", analyzed.AllPaths()["/pets/{id}"].Delete) - builder.AddRoute("GET", "/pets/{id}", analyzed.AllPaths()["/pets/{id}"].Get) + builder.AddRoute(http.MethodGet, "/pets", analyzed.AllPaths()["/pets"].Get) + builder.AddRoute(http.MethodPost, "/pets", analyzed.AllPaths()["/pets"].Post) + builder.AddRoute(http.MethodDelete, "/pets/{id}", analyzed.AllPaths()["/pets/{id}"].Delete) + builder.AddRoute(http.MethodGet, "/pets/{id}", analyzed.AllPaths()["/pets/{id}"].Get) return builder } @@ -223,7 +232,7 @@ func TestPathConverter(t *testing.T) { {"/{pet_id}", "/:pet_id"}, {"/{petId}", "/:petId"}, {"/{pet-id}", "/:pet-id"}, - // composit parameters tests + // compost parameters tests {"/p_{pet_id}", "/p_:pet_id"}, {"/p_{petId}.{petSubId}", "/p_:petId"}, } @@ -235,7 +244,7 @@ func TestPathConverter(t *testing.T) { } func TestExtractCompositParameters(t *testing.T) { - // name is the composite parameter's name, value is the value of this composit parameter, pattern is the pattern to be matched + // name is the composite parameter's name, value is the value of this compost parameter, pattern is the pattern to be matched cases := []struct { name string value string diff --git a/middleware/security_test.go b/middleware/security_test.go index 3218e12a..90b01bdb 100644 --- a/middleware/security_test.go +++ b/middleware/security_test.go @@ -15,11 +15,13 @@ package middleware import ( + stdcontext "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/go-openapi/runtime/internal/testing/petstore" ) @@ -30,30 +32,42 @@ func TestSecurityMiddleware(t *testing.T) { context.router = DefaultRouter(spec, context.api) mw := newSecureAPI(context, http.HandlerFunc(terminator)) - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) + t.Run("without auth", func(t *testing.T) { + recorder := httptest.NewRecorder() + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) - mw.ServeHTTP(recorder, request) - assert.Equal(t, 401, recorder.Code) + mw.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusUnauthorized, recorder.Code) + }) - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.SetBasicAuth("admin", "wrong") + t.Run("with wrong password", func(t *testing.T) { + recorder := httptest.NewRecorder() + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) + request.SetBasicAuth("admin", "wrong") - mw.ServeHTTP(recorder, request) - assert.Equal(t, 401, recorder.Code) - assert.NotEmpty(t, recorder.Header().Get("WWW-Authenticate")) + mw.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusUnauthorized, recorder.Code) + assert.NotEmpty(t, recorder.Header().Get("WWW-Authenticate")) + }) - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.SetBasicAuth("admin", "admin") + t.Run("with correct password", func(t *testing.T) { + recorder := httptest.NewRecorder() + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) + request.SetBasicAuth("admin", "admin") - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + mw.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusOK, recorder.Code) + }) - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "//apipets/1", nil) + t.Run("with unauthenticated path", func(t *testing.T) { + recorder := httptest.NewRecorder() + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "//apipets/1", nil) + require.NoError(t, err) - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + mw.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusOK, recorder.Code) + }) } diff --git a/middleware/spec.go b/middleware/spec.go index f0291429..c288a2b1 100644 --- a/middleware/spec.go +++ b/middleware/spec.go @@ -22,7 +22,6 @@ import ( // Spec creates a middleware to serve a swagger spec. // This allows for altering the spec before starting the http listener. // This can be useful if you want to serve the swagger spec from another path than /swagger.json -// func Spec(basePath string, b []byte, next http.Handler) http.Handler { if basePath == "" { basePath = "/" diff --git a/middleware/spec_test.go b/middleware/spec_test.go index 3dfc489c..2e020777 100644 --- a/middleware/spec_test.go +++ b/middleware/spec_test.go @@ -15,11 +15,13 @@ package middleware import ( + "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/internal/testing/petstore" @@ -28,29 +30,38 @@ import ( func TestServeSpecMiddleware(t *testing.T) { spec, api := petstore.NewAPI(t) ctx := NewContext(spec, api, nil) - handler := Spec("", ctx.spec.Raw(), nil) - // serves spec - request, _ := http.NewRequest("GET", "/swagger.json", nil) - request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - - // returns 404 when no next handler - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) - recorder = httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, 404, recorder.Code) - - // forwards to next handler for other url - handler = Spec("", ctx.spec.Raw(), http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) - })) - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) - recorder = httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) + + t.Run("serves spec", func(t *testing.T) { + request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/swagger.json", nil) + require.NoError(t, err) + request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) + recorder := httptest.NewRecorder() + + handler.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusOK, recorder.Code) + }) + + t.Run("returns 404 when no next handler", func(t *testing.T) { + request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) + request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) + recorder := httptest.NewRecorder() + + handler.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusNotFound, recorder.Code) + }) + + t.Run("forwards to next handler for other url", func(t *testing.T) { + handler = Spec("", ctx.spec.Raw(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { + rw.WriteHeader(http.StatusOK) + })) + request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/api/pets", nil) + require.NoError(t, err) + request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) + recorder := httptest.NewRecorder() + + handler.ServeHTTP(recorder, request) + assert.Equal(t, http.StatusOK, recorder.Code) + }) } diff --git a/middleware/string_conversion_test.go b/middleware/string_conversion_test.go index 18c3a996..d577d6e3 100644 --- a/middleware/string_conversion_test.go +++ b/middleware/string_conversion_test.go @@ -25,6 +25,7 @@ import ( "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var evaluatesAsTrue = []string{"true", "1", "yes", "ok", "y", "on", "selected", "checked", "t", "enabled"} @@ -63,7 +64,7 @@ type SomeOperationParams struct { Categories unmarshallerSlice } -func FloatParamTest(t *testing.T, fName, pName, format string, val reflect.Value, defVal, expectedDef interface{}, actual func() interface{}) { +func FloatParamTest(t *testing.T, _, pName, _ string, val reflect.Value, defVal, expectedDef interface{}, actual func() interface{}) { fld := val.FieldByName(pName) binder := &untypedParamBinder{ parameter: spec.QueryParam(pName).Typed("number", "double").WithDefault(defVal), @@ -71,15 +72,15 @@ func FloatParamTest(t *testing.T, fName, pName, format string, val reflect.Value } err := binder.setFieldValue(fld, defVal, "5", true) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 5, actual()) err = binder.setFieldValue(fld, defVal, "", true) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expectedDef, actual()) err = binder.setFieldValue(fld, defVal, "yada", true) - assert.Error(t, err) + require.Error(t, err) } func IntParamTest(t *testing.T, pName string, val reflect.Value, defVal, expectedDef interface{}, actual func() interface{}) { @@ -90,15 +91,15 @@ func IntParamTest(t *testing.T, pName string, val reflect.Value, defVal, expecte Name: pName, } err := binder.setFieldValue(fld, defVal, "5", true) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 5, actual()) err = binder.setFieldValue(fld, defVal, "", true) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expectedDef, actual()) err = binder.setFieldValue(fld, defVal, "yada", true) - assert.Error(t, err) + require.Error(t, err) } func TestParamBinding(t *testing.T) { @@ -113,11 +114,11 @@ func TestParamBinding(t *testing.T) { } err := binder.setFieldValue(fld, "some-name", "the name value", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "the name value", actual.Name) err = binder.setFieldValue(fld, "some-name", "", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "some-name", actual.Name) IntParamTest(t, "ID", val, 1, 1, func() interface{} { return actual.ID }) @@ -155,16 +156,16 @@ func TestParamBinding(t *testing.T) { for _, tv := range evaluatesAsTrue { err = binder.setFieldValue(confirmedField, true, tv, true) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, actual.Confirmed) } err = binder.setFieldValue(confirmedField, true, "", true) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, actual.Confirmed) err = binder.setFieldValue(confirmedField, true, "0", true) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, actual.Confirmed) pName = "Timestamp" @@ -177,15 +178,15 @@ func TestParamBinding(t *testing.T) { exp := strfmt.DateTime(time.Date(2014, 5, 14, 2, 9, 0, 0, time.UTC)) err = binder.setFieldValue(timeField, dt, exp.String(), true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, exp, actual.Timestamp) err = binder.setFieldValue(timeField, dt, "", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, dt, actual.Timestamp) err = binder.setFieldValue(timeField, dt, "yada", true) - assert.Error(t, err) + require.Error(t, err) ddt := strfmt.Date(time.Date(2014, 3, 19, 0, 0, 0, 0, time.UTC)) pName = "Birthdate" @@ -197,15 +198,15 @@ func TestParamBinding(t *testing.T) { expd := strfmt.Date(time.Date(2014, 5, 14, 0, 0, 0, 0, time.UTC)) err = binder.setFieldValue(dateField, ddt, expd.String(), true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expd, actual.Birthdate) err = binder.setFieldValue(dateField, ddt, "", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ddt, actual.Birthdate) err = binder.setFieldValue(dateField, ddt, "yada", true) - assert.Error(t, err) + require.Error(t, err) dt = strfmt.DateTime(time.Date(2014, 3, 19, 2, 9, 0, 0, time.UTC)) fdt := &dt @@ -219,20 +220,20 @@ func TestParamBinding(t *testing.T) { fexp := &exp err = binder.setFieldValue(ftimeField, fdt, fexp.String(), true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, fexp, actual.LastFailure) err = binder.setFieldValue(ftimeField, fdt, "", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, fdt, actual.LastFailure) err = binder.setFieldValue(ftimeField, fdt, "", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, fdt, actual.LastFailure) actual.LastFailure = nil err = binder.setFieldValue(ftimeField, fdt, "yada", true) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, actual.LastFailure) pName = "Unsupported" @@ -242,7 +243,7 @@ func TestParamBinding(t *testing.T) { Name: pName, } err = binder.setFieldValue(unsupportedField, nil, "", true) - assert.Error(t, err) + require.Error(t, err) } func TestSliceConversion(t *testing.T) { @@ -252,7 +253,7 @@ func TestSliceConversion(t *testing.T) { // prefsField := val.FieldByName("Prefs") // cData := "yada,2,3" // _, _, err := readFormattedSliceFieldValue("Prefs", prefsField, cData, "csv", nil) - // assert.Error(t, err) + // require.Error(t, err) sliced := []string{"some", "string", "values"} seps := map[string]string{"ssv": " ", "tsv": "\t", "pipes": "|", "csv": ",", "": ","} @@ -267,14 +268,14 @@ func TestSliceConversion(t *testing.T) { actual.Tags = nil cData := strings.Join(sliced, sep) tags, _, err := binder.readFormattedSliceFieldValue(cData, tagsField) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, sliced, tags) cData = strings.Join(sliced, " "+sep+" ") tags, _, err = binder.readFormattedSliceFieldValue(cData, tagsField) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, sliced, tags) tags, _, err = binder.readFormattedSliceFieldValue("", tagsField) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, tags) } @@ -288,12 +289,12 @@ func TestSliceConversion(t *testing.T) { } cData := strings.Join(sliced, ",") categories, custom, err := binder.readFormattedSliceFieldValue(cData, categoriesField) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, sliced, actual.Categories) assert.True(t, custom) assert.Empty(t, categories) categories, custom, err = binder.readFormattedSliceFieldValue("", categoriesField) - assert.Error(t, err) + require.Error(t, err) assert.True(t, custom) assert.Empty(t, categories) } diff --git a/middleware/swaggerui_oauth2_test.go b/middleware/swaggerui_oauth2_test.go index eab16396..7d3796f0 100644 --- a/middleware/swaggerui_oauth2_test.go +++ b/middleware/swaggerui_oauth2_test.go @@ -1,20 +1,23 @@ package middleware import ( + "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSwaggerUIOAuth2CallbackMiddleware(t *testing.T) { redoc := SwaggerUIOAuth2Callback(SwaggerUIOpts{}, nil) - req, _ := http.NewRequest("GET", "/docs/oauth2-callback", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs/oauth2-callback", nil) + require.NoError(t, err) recorder := httptest.NewRecorder() redoc.ServeHTTP(recorder, req) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type")) assert.Contains(t, recorder.Body.String(), "API documentation") } diff --git a/middleware/swaggerui_test.go b/middleware/swaggerui_test.go index e634ed85..0613db01 100644 --- a/middleware/swaggerui_test.go +++ b/middleware/swaggerui_test.go @@ -1,20 +1,23 @@ package middleware import ( + "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSwaggerUIMiddleware(t *testing.T) { redoc := SwaggerUI(SwaggerUIOpts{}, nil) - req, _ := http.NewRequest("GET", "/docs", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs", nil) + require.NoError(t, err) recorder := httptest.NewRecorder() redoc.ServeHTTP(recorder, req) - assert.Equal(t, 200, recorder.Code) + assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type")) assert.Contains(t, recorder.Body.String(), "API documentation") assert.Contains(t, recorder.Body.String(), "url: '\\/swagger.json',") diff --git a/middleware/untyped/api.go b/middleware/untyped/api.go index 39a85f7d..94788d26 100644 --- a/middleware/untyped/api.go +++ b/middleware/untyped/api.go @@ -197,17 +197,17 @@ func (d *API) Validate() error { // validateWith validates the registrations in this API against the provided spec analyzer func (d *API) validate() error { - var consumes []string + var consumes []string //nolint:prealloc for k := range d.consumers { consumes = append(consumes, k) } - var produces []string + var produces []string //nolint:prealloc for k := range d.producers { produces = append(produces, k) } - var authenticators []string + var authenticators []string //nolint:prealloc for k := range d.authenticators { authenticators = append(authenticators, k) } @@ -219,7 +219,7 @@ func (d *API) validate() error { } } - var definedAuths []string + var definedAuths []string //nolint:prealloc for k := range d.spec.Spec().SecurityDefinitions { definedAuths = append(definedAuths, k) } @@ -267,7 +267,7 @@ func (d *API) verify(name string, registrations []string, expectations []string) delete(expected, k) } - var unregistered []string + var unregistered []string //nolint:prealloc for k := range expected { unregistered = append(unregistered, k) } diff --git a/middleware/untyped/api_test.go b/middleware/untyped/api_test.go index 7ec50768..9c10f9a6 100644 --- a/middleware/untyped/api_test.go +++ b/middleware/untyped/api_test.go @@ -23,10 +23,10 @@ import ( "github.com/go-openapi/analysis" "github.com/go-openapi/errors" "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" swaggerspec "github.com/go-openapi/spec" "github.com/stretchr/testify/assert" - - "github.com/go-openapi/runtime" + "github.com/stretchr/testify/require" ) func stubAutenticator() runtime.Authenticator { @@ -58,8 +58,8 @@ func (s *stubOperationHandler) ParameterModel() interface{} { return nil } -func (s *stubOperationHandler) Handle(params interface{}) (interface{}, error) { - return nil, nil +func (s *stubOperationHandler) Handle(_ interface{}) (interface{}, error) { + return nil, nil //nolint:nilnil } func TestUntypedAPIRegistrations(t *testing.T) { @@ -184,11 +184,11 @@ func TestUntypedAppValidation(t *testing.T) { } }` validSpec, err := loads.Analyzed([]byte(specStr), "") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, validSpec) spec, err := loads.Analyzed([]byte(invalidSpecStr), "") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, spec) analyzed := analysis.New(spec.Spec()) @@ -200,24 +200,28 @@ func TestUntypedAppValidation(t *testing.T) { api1 := NewAPI(spec) err = api1.Validate() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "missing [application/x-yaml] consumes registrations", err.Error()) + api1.RegisterConsumer("application/x-yaml", new(stubConsumer)) err = api1.validate() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "missing [application/x-yaml] produces registrations", err.Error()) + api1.RegisterProducer("application/x-yaml", new(stubProducer)) err = api1.validate() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "missing [GET /] operation registrations", err.Error()) + api1.RegisterOperation("get", "/", new(stubOperationHandler)) err = api1.validate() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "missing [apiKey, basic] auth scheme registrations", err.Error()) + api1.RegisterAuth("basic", stubAutenticator()) api1.RegisterAuth("apiKey", stubAutenticator()) err = api1.validate() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "missing [apiKey, basic] security definitions registrations", err.Error()) api3 := NewAPI(validSpec) @@ -227,22 +231,22 @@ func TestUntypedAppValidation(t *testing.T) { api3.RegisterAuth("basic", stubAutenticator()) api3.RegisterAuth("apiKey", stubAutenticator()) err = api3.validate() - assert.NoError(t, err) + require.NoError(t, err) api3.RegisterConsumer("application/something", new(stubConsumer)) err = api3.validate() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "missing from spec file [application/something] consumes", err.Error()) api2 := NewAPI(spec) api2.RegisterConsumer("application/something", new(stubConsumer)) err = api2.validate() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "missing [application/x-yaml] consumes registrations\nmissing from spec file [application/something] consumes", err.Error()) api2.RegisterConsumer("application/x-yaml", new(stubConsumer)) delete(api2.consumers, "application/something") api2.RegisterProducer("application/something", new(stubProducer)) err = api2.validate() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "missing [application/x-yaml] produces registrations\nmissing from spec file [application/something] produces", err.Error()) delete(api2.producers, "application/something") api2.RegisterProducer("application/x-yaml", new(stubProducer)) @@ -271,7 +275,7 @@ func TestUntypedAppValidation(t *testing.T) { return data, nil }) d, err := opHandler.Handle(1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 1, d) authenticator := runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) { @@ -282,6 +286,6 @@ func TestUntypedAppValidation(t *testing.T) { }) ok, p, err := authenticator.Authenticate("hello") assert.True(t, ok) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "hello", p) } diff --git a/middleware/untyped_request_test.go b/middleware/untyped_request_test.go index f156f350..ebf570f4 100644 --- a/middleware/untyped_request_test.go +++ b/middleware/untyped_request_test.go @@ -16,6 +16,7 @@ package middleware import ( "bytes" + "context" "encoding/base64" "encoding/json" "io" @@ -26,30 +27,31 @@ import ( "testing" "time" + "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" - - "github.com/go-openapi/runtime" + "github.com/stretchr/testify/require" ) func TestUntypedFormPost(t *testing.T) { params := parametersForFormUpload() binder := NewUntypedRequestBinder(params, nil, strfmt.Default) - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=the-name&age=32`)) + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, bytes.NewBufferString(`name=the-name&age=32`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") data := make(map[string]interface{}) - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) assert.Equal(t, "the-name", data["name"]) assert.EqualValues(t, 32, data["age"]) - req, _ = http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=%3&age=32`)) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, bytes.NewBufferString(`name=%3&age=32`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) } func TestUntypedFileUpload(t *testing.T) { @@ -58,69 +60,77 @@ func TestUntypedFileUpload(t *testing.T) { body := bytes.NewBuffer(nil) writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("file", "plain-jane.txt") - assert.NoError(t, err) + require.NoError(t, err) - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) + _, err = part.Write([]byte("the file contents")) + require.NoError(t, err) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, body) + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) data := make(map[string]interface{}) - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) assert.Equal(t, "the-name", data["name"]) assert.NotNil(t, data["file"]) assert.IsType(t, runtime.File{}, data["file"]) file := data["file"].(runtime.File) - assert.NotNil(t, file.Header) + require.NotNil(t, file.Header) assert.Equal(t, "plain-jane.txt", file.Header.Filename) bb, err := io.ReadAll(file.Data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("the file contents"), bb) - req, _ = http.NewRequest("POST", urlStr, body) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, body) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json") data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - req, _ = http.NewRequest("POST", urlStr, body) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, body) + require.NoError(t, err) req.Header.Set("Content-Type", "application(") data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) body = bytes.NewBuffer(nil) writer = multipart.NewWriter(body) part, err = writer.CreateFormFile("bad-name", "plain-jane.txt") - assert.NoError(t, err) - - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) - req, _ = http.NewRequest("POST", urlStr, body) + require.NoError(t, err) + + _, err = part.Write([]byte("the file contents")) + require.NoError(t, err) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - req, _ = http.NewRequest("POST", urlStr, body) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) - _, _ = req.MultipartReader() + _, err = req.MultipartReader() + require.NoError(t, err) data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) writer = multipart.NewWriter(body) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) - req, _ = http.NewRequest("POST", urlStr, body) + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) } func TestUntypedOptionalFileUpload(t *testing.T) { @@ -128,30 +138,32 @@ func TestUntypedOptionalFileUpload(t *testing.T) { body := bytes.NewBuffer(nil) writer := multipart.NewWriter(body) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, body) + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) data := make(map[string]interface{}) - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) assert.Equal(t, "the-name", data["name"]) writer = multipart.NewWriter(body) part, err := writer.CreateFormFile("file", "plain-jane.txt") - assert.NoError(t, err) - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) - - req, _ = http.NewRequest("POST", urlStr, body) + require.NoError(t, err) + _, err = part.Write([]byte("the file contents")) + require.NoError(t, err) + require.NoError(t, writer.WriteField("name", "the-name")) + require.NoError(t, writer.Close()) + + req, err = http.NewRequestWithContext(context.Background(), http.MethodPost, testURL, body) + require.NoError(t, err) req.Header.Set("Content-Type", writer.FormDataContentType()) - assert.NoError(t, writer.Close()) + require.NoError(t, writer.Close()) data = make(map[string]interface{}) - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) + require.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) assert.Equal(t, "the-name", data["name"]) assert.NotNil(t, data["file"]) assert.IsType(t, runtime.File{}, data["file"]) @@ -176,7 +188,8 @@ func TestUntypedBindingTypesForValid(t *testing.T) { dt2 := time.Date(2014, 10, 12, 8, 5, 5, 0, time.UTC) delivered := strfmt.DateTime(dt2) picture := base64.URLEncoding.EncodeToString([]byte("hello")) - uri, _ := url.Parse("http://localhost:8002/hello/7575") + uri, err := url.Parse("http://localhost:8002/hello/7575") + require.NoError(t, err) qs := uri.Query() qs.Add("name", name) qs.Add("confirmed", "true") @@ -188,13 +201,14 @@ func TestUntypedBindingTypesForValid(t *testing.T) { qs.Add("delivered", delivered.String()) qs.Add("picture", picture) - req, _ := http.NewRequest("POST", uri.String()+"?"+qs.Encode(), bytes.NewBuffer([]byte(`{"name":"toby","age":32}`))) + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, uri.String()+"?"+qs.Encode(), bytes.NewBufferString(`{"name":"toby","age":32}`)) + require.NoError(t, err) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Request-Id", "19394858") data := make(map[string]interface{}) - err := binder.Bind(req, RouteParams([]RouteParam{{"id", "7575"}}), runtime.JSONConsumer(), &data) - assert.NoError(t, err) + err = binder.Bind(req, RouteParams([]RouteParam{{"id", "7575"}}), runtime.JSONConsumer(), &data) + require.NoError(t, err) assert.Equal(t, id, data["id"]) assert.Equal(t, name, data["name"]) assert.Equal(t, friend, data["friend"]) @@ -206,6 +220,7 @@ func TestUntypedBindingTypesForValid(t *testing.T) { assert.Equal(t, age, data["age"]) assert.Equal(t, factor, data["factor"]) assert.Equal(t, score, data["score"]) - pb, _ := base64.URLEncoding.DecodeString(picture) + pb, err := base64.URLEncoding.DecodeString(picture) + require.NoError(t, err) assert.EqualValues(t, pb, data["picture"].(strfmt.Base64)) } diff --git a/middleware/validation_test.go b/middleware/validation_test.go index b0d13504..5895055a 100644 --- a/middleware/validation_test.go +++ b/middleware/validation_test.go @@ -16,16 +16,17 @@ package middleware import ( "bytes" + stdcontext "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/go-openapi/errors" - "github.com/stretchr/testify/assert" - "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/internal/testing/petstore" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func newTestValidation(ctx *Context, next http.Handler) http.Handler { @@ -57,13 +58,13 @@ func TestContentTypeValidation(t *testing.T) { mw := newTestValidation(context, http.HandlerFunc(terminator)) recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) + request, _ := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets", nil) request.Header.Add("Accept", "*/*") mw.ServeHTTP(recorder, request) assert.Equal(t, http.StatusOK, recorder.Code) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) + request, _ = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", nil) request.Header.Add("content-type", "application(") request.Header.Add("Accept", "application/json") request.ContentLength = 1 @@ -73,7 +74,7 @@ func TestContentTypeValidation(t *testing.T) { assert.Equal(t, "application/json", recorder.Header().Get("content-type")) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) + request, _ = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", nil) request.Header.Add("Accept", "application/json") request.Header.Add("content-type", "text/html") request.ContentLength = 1 @@ -83,7 +84,7 @@ func TestContentTypeValidation(t *testing.T) { assert.Equal(t, "application/json", recorder.Header().Get("content-type")) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", strings.NewReader(`{"name":"dog"}`)) + request, _ = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", strings.NewReader(`{"name":"dog"}`)) request.Header.Add("Accept", "application/json") request.Header.Add("content-type", "text/html") request.TransferEncoding = []string{"chunked"} @@ -93,7 +94,7 @@ func TestContentTypeValidation(t *testing.T) { assert.Equal(t, "application/json", recorder.Header().Get("content-type")) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) + request, _ = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", nil) request.Header.Add("Accept", "application/json+special") request.Header.Add("content-type", "text/html") @@ -103,7 +104,7 @@ func TestContentTypeValidation(t *testing.T) { // client sends data with unsupported mime recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) + request, _ = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", nil) request.Header.Add("Accept", "application/json") // this content type is served by default by the API request.Header.Add("content-type", "application/json+special") request.ContentLength = 1 @@ -114,7 +115,7 @@ func TestContentTypeValidation(t *testing.T) { // client sends a body of data with no mime: breaks recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) + request, _ = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", nil) request.Header.Add("Accept", "application/json") request.ContentLength = 1 @@ -130,7 +131,7 @@ func TestResponseFormatValidation(t *testing.T) { mw := newTestValidation(context, http.HandlerFunc(terminator)) recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/api/pets", bytes.NewBuffer([]byte(`name: Dog`))) + request, _ := http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", bytes.NewBufferString(`name: Dog`)) request.Header.Set(runtime.HeaderContentType, "application/x-yaml") request.Header.Set(runtime.HeaderAccept, "application/x-yaml") @@ -138,7 +139,7 @@ func TestResponseFormatValidation(t *testing.T) { assert.Equal(t, 200, recorder.Code, recorder.Body.String()) recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", bytes.NewBuffer([]byte(`name: Dog`))) + request, _ = http.NewRequestWithContext(stdcontext.Background(), http.MethodPost, "/api/pets", bytes.NewBufferString(`name: Dog`)) request.Header.Set(runtime.HeaderContentType, "application/x-yaml") request.Header.Set(runtime.HeaderAccept, "application/sml") @@ -167,11 +168,11 @@ func TestValidateContentType(t *testing.T) { for _, v := range data { err := validateContentType(v.allowed, v.hdr) if v.err == nil { - assert.NoError(t, err, "input: %q", v.hdr) + require.NoError(t, err, "input: %q", v.hdr) } else { - assert.Error(t, err, "input: %q", v.hdr) + require.Error(t, err, "input: %q", v.hdr) assert.IsType(t, &errors.Validation{}, err, "input: %q", v.hdr) - assert.Equal(t, v.err.Error(), err.Error(), "input: %q", v.hdr) + require.EqualErrorf(t, err, v.err.Error(), "input: %q", v.hdr) assert.EqualValues(t, http.StatusUnsupportedMediaType, err.(*errors.Validation).Code()) } } diff --git a/request.go b/request.go index 078fda17..8c322af2 100644 --- a/request.go +++ b/request.go @@ -109,7 +109,7 @@ func (p *peekingReader) Close() error { // JSONRequest creates a new http request with json headers set func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) { - req, err := http.NewRequest(method, urlStr, body) + req, err := http.NewRequest(method, urlStr, body) //nolint:noctx if err != nil { return nil, err } diff --git a/request_test.go b/request_test.go index 7dec2aec..ac5bb552 100644 --- a/request_test.go +++ b/request_test.go @@ -17,6 +17,7 @@ package runtime import ( "bufio" "bytes" + "context" "io" "net/http" "net/url" @@ -30,7 +31,7 @@ import ( type eofReader struct{} -func (e *eofReader) Read(d []byte) (int, error) { +func (e *eofReader) Read(_ []byte) (int, error) { return 0, io.EOF } @@ -89,9 +90,8 @@ func TestPeekingReader(t *testing.T) { exp1 := []byte("original") pr1 := newPeekingReader(closeReader(bytes.NewReader(exp1))) b1, err := io.ReadAll(pr1) - if assert.NoError(t, err) { - assert.Equal(t, exp1, b1) - } + require.NoError(t, err) + assert.Equal(t, exp1, b1) // uses actual when there was some buffering exp2 := []byte("actual") @@ -100,9 +100,8 @@ func TestPeekingReader(t *testing.T) { require.NoError(t, err) require.Equal(t, "a", string(peeked)) b2, err := io.ReadAll(pr2) - if assert.NoError(t, err) { - assert.Equal(t, string(exp2), string(b2)) - } + require.NoError(t, err) + assert.Equal(t, string(exp2), string(b2)) // passes close call through to original reader cr := closeReader(closeReader(bytes.NewReader(exp2))) @@ -141,19 +140,20 @@ func TestPeekingReader(t *testing.T) { } func TestJSONRequest(t *testing.T) { - req, err := JSONRequest("GET", "/swagger.json", nil) - assert.NoError(t, err) - assert.Equal(t, "GET", req.Method) + req, err := JSONRequest(http.MethodGet, "/swagger.json", nil) + require.NoError(t, err) + assert.Equal(t, http.MethodGet, req.Method) assert.Equal(t, JSONMime, req.Header.Get(HeaderContentType)) assert.Equal(t, JSONMime, req.Header.Get(HeaderAccept)) - req, err = JSONRequest("GET", "%2", nil) - assert.Error(t, err) + req, err = JSONRequest(http.MethodGet, "%2", nil) + require.Error(t, err) assert.Nil(t, req) } func TestHasBody(t *testing.T) { - req, _ := http.NewRequest("GET", "", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "", nil) + require.NoError(t, err) assert.False(t, HasBody(req)) req.ContentLength = 123 diff --git a/security/apikey_auth_test.go b/security/apikey_auth_test.go index e48c8146..8a0c5a7e 100644 --- a/security/apikey_auth_test.go +++ b/security/apikey_auth_test.go @@ -21,18 +21,24 @@ import ( "github.com/go-openapi/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + apiToken = "token123" + apiTokenPrincipal = "admin" ) var tokenAuth = TokenAuthentication(func(token string) (interface{}, error) { - if token == "token123" { - return "admin", nil + if token == apiToken { + return apiTokenPrincipal, nil } return nil, errors.Unauthenticated("token") }) var tokenAuthCtx = TokenAuthenticationCtx(func(ctx context.Context, token string) (context.Context, interface{}, error) { - if token == "token123" { - return context.WithValue(ctx, extra, extraWisdom), "admin", nil + if token == apiToken { + return context.WithValue(ctx, extra, extraWisdom), apiTokenPrincipal, nil } return context.WithValue(ctx, reason, expReason), nil, errors.Unauthenticated("token") }) @@ -45,60 +51,66 @@ func TestValidApiKeyAuth(t *testing.T) { ta := APIKeyAuth("api_key", "query", tokenAuth) ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth) - req1, _ := http.NewRequest("GET", "/blah?api_key=token123", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token123", nil) + require.NoError(t, err) ok, usr, err := ta.Authenticate(req1) assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) + assert.Equal(t, apiTokenPrincipal, usr) + require.NoError(t, err) - req2, _ := http.NewRequest("GET", "/blah", nil) - req2.Header.Set("X-API-KEY", "token123") + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) + req2.Header.Set("X-API-KEY", apiToken) ok, usr, err = ta2.Authenticate(req2) assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) + assert.Equal(t, apiTokenPrincipal, usr) + require.NoError(t, err) } func TestInvalidApiKeyAuth(t *testing.T) { ta := APIKeyAuth("api_key", "query", tokenAuth) ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth) - req1, _ := http.NewRequest("GET", "/blah?api_key=token124", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token124", nil) + require.NoError(t, err) ok, usr, err := ta.Authenticate(req1) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2.Header.Set("X-API-KEY", "token124") ok, usr, err = ta2.Authenticate(req2) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) } func TestMissingApiKeyAuth(t *testing.T) { ta := APIKeyAuth("api_key", "query", tokenAuth) ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth) - req1, _ := http.NewRequest("GET", "/blah", nil) - req1.Header.Set("X-API-KEY", "token123") + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) + req1.Header.Set("X-API-KEY", apiToken) ok, usr, err := ta.Authenticate(req1) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) - req2, _ := http.NewRequest("GET", "/blah?api_key=token123", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token123", nil) + require.NoError(t, err) ok, usr, err = ta2.Authenticate(req2) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) } func TestInvalidApiKeyAuthInitializationCtx(t *testing.T) { @@ -109,24 +121,26 @@ func TestValidApiKeyAuthCtx(t *testing.T) { ta := APIKeyAuthCtx("api_key", "query", tokenAuthCtx) ta2 := APIKeyAuthCtx("X-API-KEY", "header", tokenAuthCtx) - req1, _ := http.NewRequest("GET", "/blah?api_key=token123", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token123", nil) + require.NoError(t, err) req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom)) ok, usr, err := ta.Authenticate(req1) assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) + assert.Equal(t, apiTokenPrincipal, usr) + require.NoError(t, err) assert.Equal(t, wisdom, req1.Context().Value(original)) assert.Equal(t, extraWisdom, req1.Context().Value(extra)) assert.Nil(t, req1.Context().Value(reason)) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom)) - req2.Header.Set("X-API-KEY", "token123") + req2.Header.Set("X-API-KEY", apiToken) ok, usr, err = ta2.Authenticate(req2) assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) + assert.Equal(t, apiTokenPrincipal, usr) + require.NoError(t, err) assert.Equal(t, wisdom, req2.Context().Value(original)) assert.Equal(t, extraWisdom, req2.Context().Value(extra)) assert.Nil(t, req2.Context().Value(reason)) @@ -136,24 +150,26 @@ func TestInvalidApiKeyAuthCtx(t *testing.T) { ta := APIKeyAuthCtx("api_key", "query", tokenAuthCtx) ta2 := APIKeyAuthCtx("X-API-KEY", "header", tokenAuthCtx) - req1, _ := http.NewRequest("GET", "/blah?api_key=token124", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token124", nil) + require.NoError(t, err) req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom)) ok, usr, err := ta.Authenticate(req1) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, wisdom, req1.Context().Value(original)) assert.Equal(t, expReason, req1.Context().Value(reason)) assert.Nil(t, req1.Context().Value(extra)) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom)) req2.Header.Set("X-API-KEY", "token124") ok, usr, err = ta2.Authenticate(req2) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, wisdom, req2.Context().Value(original)) assert.Equal(t, expReason, req2.Context().Value(reason)) assert.Nil(t, req2.Context().Value(extra)) @@ -163,24 +179,26 @@ func TestMissingApiKeyAuthCtx(t *testing.T) { ta := APIKeyAuthCtx("api_key", "query", tokenAuthCtx) ta2 := APIKeyAuthCtx("X-API-KEY", "header", tokenAuthCtx) - req1, _ := http.NewRequest("GET", "/blah", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom)) - req1.Header.Set("X-API-KEY", "token123") + req1.Header.Set("X-API-KEY", apiToken) ok, usr, err := ta.Authenticate(req1) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req1.Context().Value(original)) assert.Nil(t, req1.Context().Value(reason)) assert.Nil(t, req1.Context().Value(extra)) - req2, _ := http.NewRequest("GET", "/blah?api_key=token123", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token123", nil) + require.NoError(t, err) req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom)) ok, usr, err = ta2.Authenticate(req2) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req2.Context().Value(original)) assert.Nil(t, req2.Context().Value(reason)) assert.Nil(t, req2.Context().Value(extra)) diff --git a/security/authenticator.go b/security/authenticator.go index c3ffdac7..8653b86b 100644 --- a/security/authenticator.go +++ b/security/authenticator.go @@ -30,7 +30,7 @@ const ( ) // HttpAuthenticator is a function that authenticates a HTTP request -func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator { +func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator { //nolint:revive,stylecheck return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) { if request, ok := params.(*http.Request); ok { return handler(request) @@ -158,7 +158,7 @@ func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authe inl := strings.ToLower(in) if inl != query && inl != header { // panic because this is most likely a typo - panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\".")) + panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\".")) //nolint:revive } var getToken func(*http.Request) string @@ -186,7 +186,7 @@ func APIKeyAuthCtx(name, in string, authenticate TokenAuthenticationCtx) runtime inl := strings.ToLower(in) if inl != query && inl != header { // panic because this is most likely a typo - panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\".")) + panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\".")) //nolint:revive } var getToken func(*http.Request) string diff --git a/security/authorizer_test.go b/security/authorizer_test.go index 7f1f9b05..92eb1e36 100644 --- a/security/authorizer_test.go +++ b/security/authorizer_test.go @@ -17,12 +17,12 @@ package security import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAuthorized(t *testing.T) { authorizer := Authorized() err := authorizer.Authorize(nil, nil) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/security/basic_auth_test.go b/security/basic_auth_test.go index 213c9c12..1e5f12f5 100644 --- a/security/basic_auth_test.go +++ b/security/basic_auth_test.go @@ -21,11 +21,29 @@ import ( "github.com/go-openapi/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type secTestKey uint8 + +const ( + original secTestKey = iota + extra + reason +) + +const ( + wisdom = "The man who is swimming against the stream knows the strength of it." + extraWisdom = "Our greatest glory is not in never falling, but in rising every time we fall." + expReason = "I like the dreams of the future better than the history of the past." + authenticatedPath = "/blah" + testPassword = "123456" + basicPrincipal = "admin" ) var basicAuthHandler = UserPassAuthentication(func(user, pass string) (interface{}, error) { - if user == "admin" && pass == "123456" { - return "admin", nil + if user == basicPrincipal && pass == testPassword { + return basicPrincipal, nil } return "", errors.Unauthenticated("basic") }) @@ -33,23 +51,25 @@ var basicAuthHandler = UserPassAuthentication(func(user, pass string) (interface func TestValidBasicAuth(t *testing.T) { ba := BasicAuth(basicAuthHandler) - req, _ := http.NewRequest("GET", "/blah", nil) - req.SetBasicAuth("admin", "123456") - ok, usr, err := ba.Authenticate(req) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil) + require.NoError(t, err) - assert.NoError(t, err) + req.SetBasicAuth(basicPrincipal, testPassword) + ok, usr, err := ba.Authenticate(req) + require.NoError(t, err) assert.True(t, ok) - assert.Equal(t, "admin", usr) + assert.Equal(t, basicPrincipal, usr) } func TestInvalidBasicAuth(t *testing.T) { ba := BasicAuth(basicAuthHandler) - req, _ := http.NewRequest("GET", "/blah", nil) - req.SetBasicAuth("admin", "admin") - ok, usr, err := ba.Authenticate(req) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil) + require.NoError(t, err) + req.SetBasicAuth(basicPrincipal, basicPrincipal) - assert.Error(t, err) + ok, usr, err := ba.Authenticate(req) + require.Error(t, err) assert.True(t, ok) assert.Equal(t, "", usr) @@ -60,10 +80,11 @@ func TestInvalidBasicAuth(t *testing.T) { func TestMissingbasicAuth(t *testing.T) { ba := BasicAuth(basicAuthHandler) - req, _ := http.NewRequest("GET", "/blah", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil) + require.NoError(t, err) ok, usr, err := ba.Authenticate(req) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, ok) assert.Equal(t, nil, usr) @@ -75,29 +96,14 @@ func TestNoRequestBasicAuth(t *testing.T) { ba := BasicAuth(basicAuthHandler) ok, usr, err := ba.Authenticate("token") - - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, ok) assert.Nil(t, usr) } -type secTestKey uint8 - -const ( - original secTestKey = iota - extra - reason -) - -const ( - wisdom = "The man who is swimming against the stream knows the strength of it." - extraWisdom = "Our greatest glory is not in never falling, but in rising every time we fall." - expReason = "I like the dreams of the future better than the history of the past." -) - var basicAuthHandlerCtx = UserPassAuthenticationCtx(func(ctx context.Context, user, pass string) (context.Context, interface{}, error) { - if user == "admin" && pass == "123456" { - return context.WithValue(ctx, extra, extraWisdom), "admin", nil + if user == basicPrincipal && pass == testPassword { + return context.WithValue(ctx, extra, extraWisdom), basicPrincipal, nil } return context.WithValue(ctx, reason, expReason), "", errors.Unauthenticated("basic") }) @@ -105,14 +111,15 @@ var basicAuthHandlerCtx = UserPassAuthenticationCtx(func(ctx context.Context, us func TestValidBasicAuthCtx(t *testing.T) { ba := BasicAuthCtx(basicAuthHandlerCtx) - req, _ := http.NewRequest("GET", "/blah", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil) + require.NoError(t, err) req = req.WithContext(context.WithValue(req.Context(), original, wisdom)) - req.SetBasicAuth("admin", "123456") - ok, usr, err := ba.Authenticate(req) - assert.NoError(t, err) + req.SetBasicAuth(basicPrincipal, testPassword) + ok, usr, err := ba.Authenticate(req) + require.NoError(t, err) assert.True(t, ok) - assert.Equal(t, "admin", usr) + assert.Equal(t, basicPrincipal, usr) assert.Equal(t, wisdom, req.Context().Value(original)) assert.Equal(t, extraWisdom, req.Context().Value(extra)) assert.Nil(t, req.Context().Value(reason)) @@ -121,12 +128,13 @@ func TestValidBasicAuthCtx(t *testing.T) { func TestInvalidBasicAuthCtx(t *testing.T) { ba := BasicAuthCtx(basicAuthHandlerCtx) - req, _ := http.NewRequest("GET", "/blah", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil) + require.NoError(t, err) req = req.WithContext(context.WithValue(req.Context(), original, wisdom)) - req.SetBasicAuth("admin", "admin") - ok, usr, err := ba.Authenticate(req) + req.SetBasicAuth(basicPrincipal, basicPrincipal) - assert.Error(t, err) + ok, usr, err := ba.Authenticate(req) + require.Error(t, err) assert.True(t, ok) assert.Equal(t, "", usr) assert.Equal(t, wisdom, req.Context().Value(original)) @@ -137,10 +145,12 @@ func TestInvalidBasicAuthCtx(t *testing.T) { func TestMissingbasicAuthCtx(t *testing.T) { ba := BasicAuthCtx(basicAuthHandlerCtx) - req, _ := http.NewRequest("GET", "/blah", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil) + require.NoError(t, err) req = req.WithContext(context.WithValue(req.Context(), original, wisdom)) + ok, usr, err := ba.Authenticate(req) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, ok) assert.Equal(t, nil, usr) @@ -153,8 +163,7 @@ func TestNoRequestBasicAuthCtx(t *testing.T) { ba := BasicAuthCtx(basicAuthHandlerCtx) ok, usr, err := ba.Authenticate("token") - - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, ok) assert.Nil(t, usr) } diff --git a/security/bearer_auth_test.go b/security/bearer_auth_test.go index 53b193c1..476d35bc 100644 --- a/security/bearer_auth_test.go +++ b/security/bearer_auth_test.go @@ -12,9 +12,10 @@ import ( "github.com/go-openapi/errors" "github.com/go-openapi/runtime" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -var bearerAuth = ScopedTokenAuthentication(func(token string, requiredScopes []string) (interface{}, error) { +var bearerAuth = ScopedTokenAuthentication(func(token string, _ []string) (interface{}, error) { if token == "token123" { return "admin", nil } @@ -24,128 +25,143 @@ var bearerAuth = ScopedTokenAuthentication(func(token string, requiredScopes []s func TestValidBearerAuth(t *testing.T) { ba := BearerAuth("owners_auth", bearerAuth) - req1, _ := http.NewRequest("GET", "/blah?access_token=token123", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_token=token123", nil) + require.NoError(t, err) ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) assert.True(t, ok) assert.Equal(t, "admin", usr) - assert.NoError(t, err) - assert.Equal(t, OAuth2SchemeName(req1), "owners_auth") + require.NoError(t, err) + assert.Equal(t, "owners_auth", OAuth2SchemeName(req1)) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2.Header.Set(runtime.HeaderAuthorization, "Bearer token123") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) assert.True(t, ok) assert.Equal(t, "admin", usr) - assert.NoError(t, err) - assert.Equal(t, OAuth2SchemeName(req2), "owners_auth") + require.NoError(t, err) + assert.Equal(t, "owners_auth", OAuth2SchemeName(req2)) body := url.Values(map[string][]string{}) body.Set("access_token", "token123") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) + req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode())) + require.NoError(t, err) req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) assert.True(t, ok) assert.Equal(t, "admin", usr) - assert.NoError(t, err) - assert.Equal(t, OAuth2SchemeName(req3), "owners_auth") + require.NoError(t, err) + assert.Equal(t, "owners_auth", OAuth2SchemeName(req3)) mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_token", "token123") + err = writer.WriteField("access_token", "token123") + require.NoError(t, err) writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) + req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody) + require.NoError(t, err) req4.Header.Set("Content-Type", writer.FormDataContentType()) ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) assert.True(t, ok) assert.Equal(t, "admin", usr) - assert.NoError(t, err) - assert.Equal(t, OAuth2SchemeName(req4), "owners_auth") + require.NoError(t, err) + assert.Equal(t, "owners_auth", OAuth2SchemeName(req4)) } +//nolint:dupl func TestInvalidBearerAuth(t *testing.T) { ba := BearerAuth("owners_auth", bearerAuth) - req1, _ := http.NewRequest("GET", "/blah?access_token=token124", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_token=token124", nil) + require.NoError(t, err) ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2.Header.Set(runtime.HeaderAuthorization, "Bearer token124") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) body := url.Values(map[string][]string{}) body.Set("access_token", "token124") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) + req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode())) + require.NoError(t, err) req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_token", "token124") + require.NoError(t, writer.WriteField("access_token", "token124")) writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) + req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody) + require.NoError(t, err) req4.Header.Set("Content-Type", writer.FormDataContentType()) ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) } +//nolint:dupl func TestMissingBearerAuth(t *testing.T) { ba := BearerAuth("owners_auth", bearerAuth) - req1, _ := http.NewRequest("GET", "/blah?access_toke=token123", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_toke=token123", nil) + require.NoError(t, err) ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2.Header.Set(runtime.HeaderAuthorization, "Beare token123") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) body := url.Values(map[string][]string{}) body.Set("access_toke", "token123") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) + req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode())) + require.NoError(t, err) req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_toke", "token123") + require.NoError(t, writer.WriteField("access_toke", "token123")) writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) + req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody) + require.NoError(t, err) req4.Header.Set("Content-Type", writer.FormDataContentType()) ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) } var bearerAuthCtx = ScopedTokenAuthenticationCtx(func(ctx context.Context, token string, requiredScopes []string) (context.Context, interface{}, error) { @@ -158,114 +174,122 @@ var bearerAuthCtx = ScopedTokenAuthenticationCtx(func(ctx context.Context, token func TestValidBearerAuthCtx(t *testing.T) { ba := BearerAuthCtx("owners_auth", bearerAuthCtx) - req1, _ := http.NewRequest("GET", "/blah?access_token=token123", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_token=token123", nil) + require.NoError(t, err) req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom)) ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) assert.True(t, ok) assert.Equal(t, "admin", usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req1.Context().Value(original)) assert.Equal(t, extraWisdom, req1.Context().Value(extra)) assert.Nil(t, req1.Context().Value(reason)) - assert.Equal(t, OAuth2SchemeName(req1), "owners_auth") + assert.Equal(t, "owners_auth", OAuth2SchemeName(req1)) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom)) req2.Header.Set(runtime.HeaderAuthorization, "Bearer token123") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) assert.True(t, ok) assert.Equal(t, "admin", usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req2.Context().Value(original)) assert.Equal(t, extraWisdom, req2.Context().Value(extra)) assert.Nil(t, req2.Context().Value(reason)) - assert.Equal(t, OAuth2SchemeName(req2), "owners_auth") + assert.Equal(t, "owners_auth", OAuth2SchemeName(req2)) body := url.Values(map[string][]string{}) body.Set("access_token", "token123") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) + req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode())) + require.NoError(t, err) req3 = req3.WithContext(context.WithValue(req3.Context(), original, wisdom)) req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) assert.True(t, ok) assert.Equal(t, "admin", usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req3.Context().Value(original)) assert.Equal(t, extraWisdom, req3.Context().Value(extra)) assert.Nil(t, req3.Context().Value(reason)) - assert.Equal(t, OAuth2SchemeName(req3), "owners_auth") + assert.Equal(t, "owners_auth", OAuth2SchemeName(req3)) mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_token", "token123") + require.NoError(t, writer.WriteField("access_token", "token123")) writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) + req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody) + require.NoError(t, err) req4 = req4.WithContext(context.WithValue(req4.Context(), original, wisdom)) req4.Header.Set("Content-Type", writer.FormDataContentType()) ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) assert.True(t, ok) assert.Equal(t, "admin", usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req4.Context().Value(original)) assert.Equal(t, extraWisdom, req4.Context().Value(extra)) assert.Nil(t, req4.Context().Value(reason)) - assert.Equal(t, OAuth2SchemeName(req4), "owners_auth") + assert.Equal(t, "owners_auth", OAuth2SchemeName(req4)) } func TestInvalidBearerAuthCtx(t *testing.T) { ba := BearerAuthCtx("owners_auth", bearerAuthCtx) - req1, _ := http.NewRequest("GET", "/blah?access_token=token124", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_token=token124", nil) + require.NoError(t, err) req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom)) ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, wisdom, req1.Context().Value(original)) assert.Equal(t, expReason, req1.Context().Value(reason)) assert.Nil(t, req1.Context().Value(extra)) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom)) req2.Header.Set(runtime.HeaderAuthorization, "Bearer token124") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, wisdom, req2.Context().Value(original)) assert.Equal(t, expReason, req2.Context().Value(reason)) assert.Nil(t, req2.Context().Value(extra)) body := url.Values(map[string][]string{}) body.Set("access_token", "token124") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) + req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode())) + require.NoError(t, err) req3 = req3.WithContext(context.WithValue(req3.Context(), original, wisdom)) req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, wisdom, req3.Context().Value(original)) assert.Equal(t, expReason, req3.Context().Value(reason)) assert.Nil(t, req3.Context().Value(extra)) mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_token", "token124") + require.NoError(t, writer.WriteField("access_token", "token124")) writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) + req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody) + require.NoError(t, err) req4 = req4.WithContext(context.WithValue(req4.Context(), original, wisdom)) req4.Header.Set("Content-Type", writer.FormDataContentType()) ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) assert.True(t, ok) assert.Equal(t, nil, usr) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, wisdom, req4.Context().Value(original)) assert.Equal(t, expReason, req4.Context().Value(reason)) assert.Nil(t, req4.Context().Value(extra)) @@ -274,54 +298,59 @@ func TestInvalidBearerAuthCtx(t *testing.T) { func TestMissingBearerAuthCtx(t *testing.T) { ba := BearerAuthCtx("owners_auth", bearerAuthCtx) - req1, _ := http.NewRequest("GET", "/blah?access_toke=token123", nil) + req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_toke=token123", nil) + require.NoError(t, err) req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom)) ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req1.Context().Value(original)) assert.Nil(t, req1.Context().Value(reason)) assert.Nil(t, req1.Context().Value(extra)) - req2, _ := http.NewRequest("GET", "/blah", nil) + req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil) + require.NoError(t, err) req2.Header.Set(runtime.HeaderAuthorization, "Beare token123") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom)) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req2.Context().Value(original)) assert.Nil(t, req2.Context().Value(reason)) assert.Nil(t, req2.Context().Value(extra)) body := url.Values(map[string][]string{}) body.Set("access_toke", "token123") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) + req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode())) + require.NoError(t, err) req3 = req3.WithContext(context.WithValue(req3.Context(), original, wisdom)) req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req3.Context().Value(original)) assert.Nil(t, req3.Context().Value(reason)) assert.Nil(t, req3.Context().Value(extra)) mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_toke", "token123") - writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) + err = writer.WriteField("access_toke", "token123") + require.NoError(t, err) + require.NoError(t, writer.Close()) + req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody) + require.NoError(t, err) req4 = req4.WithContext(context.WithValue(req4.Context(), original, wisdom)) req4.Header.Set("Content-Type", writer.FormDataContentType()) ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) assert.False(t, ok) assert.Equal(t, nil, usr) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, wisdom, req4.Context().Value(original)) assert.Nil(t, req4.Context().Value(reason)) assert.Nil(t, req4.Context().Value(extra)) diff --git a/text_test.go b/text_test.go index 1c6a944b..5f2f727a 100644 --- a/text_test.go +++ b/text_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var consProdText = `The quick brown fox jumped over the lazy dog.` @@ -31,30 +32,30 @@ func TestTextConsumer(t *testing.T) { // can consume as a string var str string - err1 := cons.Consume(bytes.NewBuffer([]byte(consProdText)), &str) - assert.NoError(t, err1) + err1 := cons.Consume(bytes.NewBufferString(consProdText), &str) + require.NoError(t, err1) assert.Equal(t, consProdText, str) var tu textUnmarshalDummy // can consume as a TextUnmarshaler - err3 := cons.Consume(bytes.NewBuffer([]byte(consProdText)), &tu) - assert.NoError(t, err3) + err3 := cons.Consume(bytes.NewBufferString(consProdText), &tu) + require.NoError(t, err3) assert.Equal(t, consProdText, tu.str) // text unmarshal objects can return an error as well, this will be propagated - assert.NoError(t, cons.Consume(bytes.NewBuffer(nil), &tu)) + require.NoError(t, cons.Consume(bytes.NewBuffer(nil), &tu)) // when readers can't be read, those errors will be propogated as well - assert.Error(t, cons.Consume(new(nopReader), &tu)) + require.Error(t, cons.Consume(new(nopReader), &tu)) // readers can also not be nil - assert.Error(t, cons.Consume(nil, &tu)) + require.Error(t, cons.Consume(nil, &tu)) // can't consume nil ptr's or unsupported types - assert.Error(t, cons.Consume(bytes.NewBuffer([]byte(consProdText)), nil)) - assert.Error(t, cons.Consume(bytes.NewBuffer([]byte(consProdText)), 42)) - assert.Error(t, cons.Consume(bytes.NewBuffer([]byte(consProdText)), &struct{}{})) + require.Error(t, cons.Consume(bytes.NewBufferString(consProdText), nil)) + require.Error(t, cons.Consume(bytes.NewBufferString(consProdText), 42)) + require.Error(t, cons.Consume(bytes.NewBufferString(consProdText), &struct{}{})) } type textUnmarshalDummy struct { @@ -72,7 +73,7 @@ func (t *textUnmarshalDummy) UnmarshalText(b []byte) error { type nopReader struct{} -func (n *nopReader) Read(p []byte) (int, error) { +func (n *nopReader) Read(_ []byte) (int, error) { return 0, errors.New("nop") } @@ -80,11 +81,11 @@ func TestTextProducer(t *testing.T) { prod := TextProducer() rw := httptest.NewRecorder() err := prod.Produce(rw, consProdText) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consProdText, rw.Body.String()) rw2 := httptest.NewRecorder() err2 := prod.Produce(rw2, &consProdText) - assert.NoError(t, err2) + require.NoError(t, err2) assert.Equal(t, consProdText, rw2.Body.String()) // should always work with type aliases @@ -93,11 +94,11 @@ func TestTextProducer(t *testing.T) { aliasProdText := alias(consProdText) rw3 := httptest.NewRecorder() err3 := prod.Produce(rw3, aliasProdText) - assert.NoError(t, err3) + require.NoError(t, err3) assert.Equal(t, consProdText, rw3.Body.String()) rw4 := httptest.NewRecorder() err4 := prod.Produce(rw4, &aliasProdText) - assert.NoError(t, err4) + require.NoError(t, err4) assert.Equal(t, consProdText, rw4.Body.String()) const answer = "42" @@ -105,51 +106,51 @@ func TestTextProducer(t *testing.T) { // Should always work with objects implementing Stringer interface rw5 := httptest.NewRecorder() err5 := prod.Produce(rw5, &stringerDummy{answer}) - assert.NoError(t, err5) + require.NoError(t, err5) assert.Equal(t, answer, rw5.Body.String()) // Should always work with objects implementing TextMarshaler interface rw6 := httptest.NewRecorder() err6 := prod.Produce(rw6, &textMarshalDummy{answer}) - assert.NoError(t, err6) + require.NoError(t, err6) assert.Equal(t, answer, rw6.Body.String()) rw10 := httptest.NewRecorder() err10 := prod.Produce(rw10, errors.New(answer)) - assert.NoError(t, err10) + require.NoError(t, err10) assert.Equal(t, answer, rw10.Body.String()) rw11 := httptest.NewRecorder() err11 := prod.Produce(rw11, Error{Message: answer}) - assert.NoError(t, err11) + require.NoError(t, err11) assert.Equal(t, fmt.Sprintf(`{"message":%q}`, answer), rw11.Body.String()) rw12 := httptest.NewRecorder() err12 := prod.Produce(rw12, &Error{Message: answer}) - assert.NoError(t, err12) + require.NoError(t, err12) assert.Equal(t, fmt.Sprintf(`{"message":%q}`, answer), rw12.Body.String()) rw13 := httptest.NewRecorder() err13 := prod.Produce(rw13, []string{answer}) - assert.NoError(t, err13) + require.NoError(t, err13) assert.Equal(t, fmt.Sprintf(`[%q]`, answer), rw13.Body.String()) // should not work with anything that's not (indirectly) a string rw7 := httptest.NewRecorder() err7 := prod.Produce(rw7, 42) - assert.Error(t, err7) + require.Error(t, err7) // nil values should also be safely caught with an error rw8 := httptest.NewRecorder() err8 := prod.Produce(rw8, nil) - assert.Error(t, err8) + require.Error(t, err8) // writer can not be nil - assert.Error(t, prod.Produce(nil, &textMarshalDummy{answer})) + require.Error(t, prod.Produce(nil, &textMarshalDummy{answer})) // should not work for a textMarshaler that returns an error during marshalling rw9 := httptest.NewRecorder() err9 := prod.Produce(rw9, new(textMarshalDummy)) - assert.Error(t, err9) + require.Error(t, err9) } type Error struct { diff --git a/xml_test.go b/xml_test.go index 1f2dfd25..9da96bbe 100644 --- a/xml_test.go +++ b/xml_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var consProdXML = `Somebody1` @@ -32,8 +33,8 @@ func TestXMLConsumer(t *testing.T) { Name string `xml:"name"` ID int `xml:"id"` } - err := cons.Consume(bytes.NewBuffer([]byte(consProdXML)), &data) - assert.NoError(t, err) + err := cons.Consume(bytes.NewBufferString(consProdXML), &data) + require.NoError(t, err) assert.Equal(t, "Somebody", data.Name) assert.Equal(t, 1, data.ID) } @@ -48,6 +49,6 @@ func TestXMLProducer(t *testing.T) { rw := httptest.NewRecorder() err := prod.Produce(rw, data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consProdXML, rw.Body.String()) } diff --git a/yamlpc/yaml_test.go b/yamlpc/yaml_test.go index 22e74f80..daf5e2eb 100644 --- a/yamlpc/yaml_test.go +++ b/yamlpc/yaml_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var consProdYAML = "name: Somebody\nid: 1\n" @@ -31,8 +32,8 @@ func TestYAMLConsumer(t *testing.T) { Name string ID int } - err := cons.Consume(bytes.NewBuffer([]byte(consProdYAML)), &data) - assert.NoError(t, err) + err := cons.Consume(bytes.NewBufferString(consProdYAML), &data) + require.NoError(t, err) assert.Equal(t, "Somebody", data.Name) assert.Equal(t, 1, data.ID) } @@ -46,27 +47,27 @@ func TestYAMLProducer(t *testing.T) { rw := httptest.NewRecorder() err := prod.Produce(rw, data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consProdYAML, rw.Body.String()) } type failReaderWriter struct { } -func (f *failReaderWriter) Read(p []byte) (n int, err error) { +func (f *failReaderWriter) Read(_ []byte) (n int, err error) { return 0, errors.New("expected") } -func (f *failReaderWriter) Write(p []byte) (n int, err error) { +func (f *failReaderWriter) Write(_ []byte) (n int, err error) { return 0, errors.New("expected") } func TestFailYAMLWriter(t *testing.T) { prod := YAMLProducer() - assert.Error(t, prod.Produce(&failReaderWriter{}, nil)) + require.Error(t, prod.Produce(&failReaderWriter{}, nil)) } func TestFailYAMLReader(t *testing.T) { cons := YAMLConsumer() - assert.Error(t, cons.Consume(&failReaderWriter{}, nil)) + require.Error(t, cons.Consume(&failReaderWriter{}, nil)) }