From 5a61832a971aac60ee506d6367850c5cc12ce6e2 Mon Sep 17 00:00:00 2001 From: Frederic BIDON Date: Wed, 6 Dec 2023 11:14:44 +0100 Subject: [PATCH] chore: relinted, updated * updated go version to go1.19 * updated linting rules * updated dependencies, upgraded yaml.v2 to yaml.v3 * relinted code * doc: updated links and badges in README * ci: updated github actions Signed-off-by: Frederic BIDON --- .github/workflows/ci.yaml | 47 ---- .github/workflows/go-test.yml | 50 ++++ .golangci.yml | 56 +++-- README.md | 8 +- debug_test.go | 3 +- default_validator.go | 2 - default_validator_test.go | 17 +- doc_test.go | 6 +- example_validator.go | 4 +- example_validator_test.go | 12 +- go.mod | 13 +- go.sum | 12 +- helpers.go | 6 +- helpers_test.go | 12 +- items_validator_test.go | 53 +++-- jsonschema_test.go | 21 +- messages_test.go | 9 +- object_validator_test.go | 8 +- parameter_validator_test.go | 48 ++-- post/defaulter_test.go | 16 +- post/prune_test.go | 7 +- result.go | 12 +- result_test.go | 22 +- rexp_test.go | 9 +- schema_test.go | 16 +- spec.go | 3 - spec_test.go | 23 +- swagger_test.go | 7 +- type.go | 2 +- type_test.go | 6 +- validator.go | 2 - values.go | 8 +- values_test.go | 430 +++++++++++++--------------------- 33 files changed, 453 insertions(+), 497 deletions(-) delete mode 100644 .github/workflows/ci.yaml create mode 100644 .github/workflows/go-test.yml diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml deleted file mode 100644 index 7e0dab5..0000000 --- a/.github/workflows/ci.yaml +++ /dev/null @@ -1,47 +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 - - - 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 - - lint: - runs-on: ${{ matrix.os }} - - strategy: - matrix: - os: [ ubuntu-latest, macos-latest, windows-latest ] - fail-fast: false - - steps: - - uses: actions/checkout@v2 - - uses: golangci/golangci-lint-action@v3 - with: - version: v1.53 - args: --timeout=5m diff --git a/.github/workflows/go-test.yml b/.github/workflows/go-test.yml new file mode 100644 index 0000000..e1a95c7 --- /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/.golangci.yml b/.golangci.yml index 348b9b4..22f8d21 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,12 +1,14 @@ linters-settings: govet: check-shadowing: true + golint: + min-confidence: 0 gocyclo: - min-complexity: 50 + min-complexity: 45 maligned: suggest-new: true dupl: - threshold: 100 + threshold: 200 goconst: min-len: 2 min-occurrences: 3 @@ -15,41 +17,45 @@ linters: enable-all: true disable: - 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 - - tparallel + - gofumpt - paralleltest - - cyclop # because we have gocyclo already - - depguard # we do not add a config for this - # TODO: review the linters below. We disabled them to make the CI pass first. - - nonamedreturns + - tparallel + - thelper + - ifshort - exhaustruct - - nosnakecase - - nolintlint - - ireturn - varnamelen + - gci + - depguard + - errchkjson + - inamedparam + - nonamedreturns + - musttag + - ireturn - forcetypeassert - - thelper - # Disable deprecated linters. - # They will be removed from golangci-lint in future. + - cyclop + # deprecated linters + - deadcode - interfacer - - golint \ No newline at end of file + - scopelint + - varcheck + - structcheck + - golint + - nosnakecase diff --git a/README.md b/README.md index ea2d68c..e8e1bb2 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,5 @@ -# Validation helpers -[![Build Status](https://travis-ci.org/go-openapi/validate.svg?branch=master)](https://travis-ci.org/go-openapi/validate) -[![Build status](https://ci.appveyor.com/api/projects/status/d6epy6vipueyh5fs/branch/master?svg=true)](https://ci.appveyor.com/project/fredbi/validate/branch/master) -[![codecov](https://codecov.io/gh/go-openapi/validate/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/validate) +# Validation helpers [![Build Status](https://github.com/go-openapi/validate/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/validate/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/validate/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/validate) + [![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/validate/master/LICENSE) [![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/validate.svg)](https://pkg.go.dev/github.com/go-openapi/validate) @@ -24,7 +22,7 @@ Reference can be found here: https://github.com/OAI/OpenAPI-Specification/blob/m * Minimum, Maximum, MultipleOf * FormatOf -[Documentation](https://godoc.org/github.com/go-openapi/validate) +[Documentation](https://pkg.go.dev/github.com/go-openapi/validate) ## FAQ diff --git a/debug_test.go b/debug_test.go index aede3f5..0cac02e 100644 --- a/debug_test.go +++ b/debug_test.go @@ -15,7 +15,6 @@ package validate import ( - "io/ioutil" "os" "sync" "testing" @@ -32,7 +31,7 @@ func TestDebug(t *testing.T) { skipNotify(t) t.SkipNow() } - tmpFile, _ := ioutil.TempFile("", "debug-test") + tmpFile, _ := os.CreateTemp("", "debug-test") tmpName := tmpFile.Name() defer func() { Debug = false diff --git a/default_validator.go b/default_validator.go index 670a177..7f7fd0b 100644 --- a/default_validator.go +++ b/default_validator.go @@ -170,7 +170,6 @@ func (d *defaultValidator) validateDefaultInResponse(resp *spec.Response, respon responseName, responseCodeAsStr := responseHelp.responseMsgVariants(responseType, responseCode) - //nolint: dupl if response.Headers != nil { // Safeguard for nm, h := range response.Headers { // reset explored schemas to get depth-first recursive-proof exploration @@ -263,7 +262,6 @@ func (d *defaultValidator) validateDefaultValueSchemaAgainstSchema(path, in stri // TODO: Temporary duplicated code. Need to refactor with examples -// nolint: dupl func (d *defaultValidator) validateDefaultValueItemsAgainstSchema(path, in string, root interface{}, items *spec.Items) *Result { res := new(Result) s := d.SpecValidator diff --git a/default_validator_test.go b/default_validator_test.go index d2384fb..fc56a23 100644 --- a/default_validator_test.go +++ b/default_validator_test.go @@ -26,6 +26,13 @@ import ( "github.com/stretchr/testify/require" ) +const ( + jsonExt = ".json" + hasErrorMsg = " should have errors" + noErrorMsg = " should not have errors" + hasWarningMsg = " should have warnings" +) + func TestDefault_ValidatePetStore(t *testing.T) { doc, _ := loads.Analyzed(PetStoreJSONMessage, "") validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default) @@ -72,14 +79,14 @@ func TestDefault_ValidateDefaults(t *testing.T) { } for _, tt := range tests { - path := filepath.Join("fixtures", "validation", "default", "valid-default-value-"+tt+".json") + path := filepath.Join("fixtures", "validation", "default", "valid-default-value-"+tt+jsonExt) if DebugTest { t.Logf("Testing valid default values for: %s", path) } validator := makeSpecValidator(t, path) myDefaultValidator := &defaultValidator{SpecValidator: validator} res := myDefaultValidator.Validate() - assert.Empty(t, res.Errors, tt+" should not have errors") + assert.Empty(t, res.Errors, tt+noErrorMsg) // Special case: warning only if tt == "parameter-required" { @@ -87,7 +94,7 @@ func TestDefault_ValidateDefaults(t *testing.T) { assert.Contains(t, warns, "limit in query has a default value and is required as parameter") } - path = filepath.Join("fixtures", "validation", "default", "invalid-default-value-"+tt+".json") + path = filepath.Join("fixtures", "validation", "default", "invalid-default-value-"+tt+jsonExt) if DebugTest { t.Logf("Testing invalid default values for: %s", path) } @@ -95,13 +102,13 @@ func TestDefault_ValidateDefaults(t *testing.T) { validator = makeSpecValidator(t, path) myDefaultValidator = &defaultValidator{SpecValidator: validator} res = myDefaultValidator.Validate() - assert.NotEmpty(t, res.Errors, tt+" should have errors") + assert.NotEmpty(t, res.Errors, tt+hasErrorMsg) // Update: now we have an additional message to explain it's all about a default value // Example: // - default value for limit in query does not validate its Schema // - limit in query must be of type integer: "string"] - assert.True(t, len(res.Errors) >= 1, tt+" should have at least 1 error") + assert.NotEmptyf(t, res.Errors, tt+" should have at least 1 error") } } diff --git a/doc_test.go b/doc_test.go index 1eee213..d206376 100644 --- a/doc_test.go +++ b/doc_test.go @@ -17,7 +17,7 @@ package validate_test import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" @@ -196,7 +196,7 @@ func Test_Issue102_Circular(t *testing.T) { filepath.Join("fixtures", "bugs", "123-validate", "fixture-123.json"), } { t.Run(fixture, func(t *testing.T) { - filebytes, err := ioutil.ReadFile(fixture) + filebytes, err := os.ReadFile(fixture) require.NoError(t, err) openAPIv2Doc := json.RawMessage(filebytes) @@ -207,7 +207,7 @@ func Test_Issue102_Circular(t *testing.T) { validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default) validator.SetContinueOnErrors(true) res, _ := validator.Validate(doc) - require.Lenf(t, res.Errors, 0, "unexpected validation erorrs: %v", res.Errors) + require.Emptyf(t, res.Errors, "unexpected validation erorrs: %v", res.Errors) }) } } diff --git a/example_validator.go b/example_validator.go index 930b47e..d5d4b88 100644 --- a/example_validator.go +++ b/example_validator.go @@ -145,7 +145,6 @@ func (ex *exampleValidator) validateExampleInResponse(resp *spec.Response, respo responseName, responseCodeAsStr := responseHelp.responseMsgVariants(responseType, responseCode) - // nolint: dupl if response.Headers != nil { // Safeguard for nm, h := range response.Headers { // reset explored schemas to get depth-first recursive-proof exploration @@ -250,7 +249,8 @@ func (ex *exampleValidator) validateExampleValueSchemaAgainstSchema(path, in str } // TODO: Temporary duplicated code. Need to refactor with examples -// nolint: dupl +// + func (ex *exampleValidator) validateExampleValueItemsAgainstSchema(path, in string, root interface{}, items *spec.Items) *Result { res := new(Result) s := ex.SpecValidator diff --git a/example_validator_test.go b/example_validator_test.go index 09bdf64..f3a7a41 100644 --- a/example_validator_test.go +++ b/example_validator_test.go @@ -69,7 +69,7 @@ func TestExample_ValidateExamples(t *testing.T) { validator := makeSpecValidator(t, path) myExampleValidator := &exampleValidator{SpecValidator: validator} res := myExampleValidator.Validate() - assert.Empty(t, res.Errors, tt+" should not have errors") + assert.Empty(t, res.Errors, tt+noErrorMsg) /* // Special case: warning only if tt == "parameter-required" { @@ -90,17 +90,17 @@ func TestExample_ValidateExamples(t *testing.T) { switch tt { case "header-badpattern": // This fixture exhibits real errors besides example values - assert.NotEmpty(t, res.Errors, tt+" should have errors") - assert.NotEmpty(t, res.Warnings, tt+" should have warnings") + assert.NotEmpty(t, res.Errors, tt+hasErrorMsg) + assert.NotEmpty(t, res.Warnings, tt+hasWarningMsg) default: - assert.Empty(t, res.Errors, tt+" should not have errors") - assert.NotEmpty(t, res.Warnings, tt+" should have warnings") + assert.Empty(t, res.Errors, tt+noErrorMsg) + assert.NotEmpty(t, res.Warnings, tt+hasWarningMsg) } // Update: now we have an additional message to explain it's all about a default value // Example: // - default value for limit in query does not validate its Schema // - limit in query must be of type integer: "string"] - assert.True(t, len(res.Warnings) >= 1, tt+" should have at least 1 warning") + assert.NotEmptyf(t, res.Warnings, tt+" should have at least 1 warning") debugTest(t, path, res) if DebugTest && t.Failed() { diff --git a/go.mod b/go.mod index 1e1d402..b849dfb 100644 --- a/go.mod +++ b/go.mod @@ -1,17 +1,15 @@ module github.com/go-openapi/validate -go 1.18 - require ( github.com/go-openapi/analysis v0.21.4 github.com/go-openapi/errors v0.20.4 github.com/go-openapi/jsonpointer v0.20.0 github.com/go-openapi/loads v0.21.2 - github.com/go-openapi/spec v0.20.9 - github.com/go-openapi/strfmt v0.21.7 + 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/stretchr/testify v1.8.4 - gopkg.in/yaml.v2 v2.4.0 + gopkg.in/yaml.v3 v3.0.1 ) require ( @@ -24,6 +22,7 @@ require ( github.com/oklog/ulid v1.3.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect - go.mongodb.org/mongo-driver v1.12.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect + go.mongodb.org/mongo-driver v1.13.0 // indirect ) + +go 1.19 diff --git a/go.sum b/go.sum index 7f65a3b..1b731fc 100644 --- a/go.sum +++ b/go.sum @@ -21,11 +21,11 @@ github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En 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.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= -github.com/go-openapi/spec v0.20.9 h1:xnlYNQAwKd2VQRRfwTEI0DcK+2cbuvI/0c7jx3gA8/8= -github.com/go-openapi/spec v0.20.9/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= +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= @@ -84,8 +84,8 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= 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.12.0 h1:aPx33jmn/rQuJXPQLZQ8NtfPQG8CaqgLThFtqRb0PiE= -go.mongodb.org/mongo-driver v1.12.0/go.mod h1:AZkxhPnFJUoH7kZlFkVKucV20K387miPfm7oimrSmK0= +go.mongodb.org/mongo-driver v1.13.0 h1:67DgFFjYOCMWdtTEmKFpV3ffWlFnh+CYZ8ZS/tXWUfY= +go.mongodb.org/mongo-driver v1.13.0/go.mod h1:/rGBTebI3XYboVmgz+Wv3Bcbl3aD0QF9zl6kDDw18rQ= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 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= diff --git a/helpers.go b/helpers.go index dc376f7..fc7500c 100644 --- a/helpers.go +++ b/helpers.go @@ -157,7 +157,7 @@ func (h *valueHelper) asInt64(val interface{}) int64 { // Number conversion function for int64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) - switch v.Kind() { + switch v.Kind() { //nolint:exhaustive case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: @@ -174,7 +174,7 @@ func (h *valueHelper) asUint64(val interface{}) uint64 { // Number conversion function for uint64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) - switch v.Kind() { + switch v.Kind() { //nolint:exhaustive case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return uint64(v.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: @@ -192,7 +192,7 @@ func (h *valueHelper) asFloat64(val interface{}) float64 { // Number conversion function for float64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) - switch v.Kind() { + switch v.Kind() { //nolint:exhaustive case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return float64(v.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: diff --git a/helpers_test.go b/helpers_test.go index 110353e..ec10cca 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -19,11 +19,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestHelpers_addPointerError(t *testing.T) { res := new(Result) r := errorHelp.addPointerError(res, fmt.Errorf("my error"), "my ref", "path") + require.NotEmpty(t, r.Errors) msg := r.Errors[0].Error() assert.Contains(t, msg, "could not resolve reference in path to $ref my ref: my error") } @@ -55,7 +57,7 @@ func TestHelpers_asInt64(t *testing.T) { if assert.NotPanics(t, func() { valueHelp.asInt64("123") }) { - assert.Equal(t, valueHelp.asInt64("123"), (int64)(0)) + assert.Equal(t, int64(0), valueHelp.asInt64("123")) } } @@ -69,20 +71,22 @@ func TestHelpers_asUint64(t *testing.T) { if assert.NotPanics(t, func() { valueHelp.asUint64("123") }) { - assert.Equal(t, valueHelp.asUint64("123"), (uint64)(0)) + assert.Equal(t, uint64(0), valueHelp.asUint64("123")) } } // Test cases in private method asFloat64() func TestHelpers_asFloat64(t *testing.T) { + const epsilon = 1e-9 + for _, v := range integerFactory(3) { - assert.Equal(t, float64(3), valueHelp.asFloat64(v)) + assert.InDelta(t, float64(3), valueHelp.asFloat64(v), epsilon) } // Non numeric if assert.NotPanics(t, func() { valueHelp.asFloat64("123") }) { - assert.Equal(t, valueHelp.asFloat64("123"), (float64)(0)) + assert.InDelta(t, float64(0), valueHelp.asFloat64("123"), epsilon) } } diff --git a/items_validator_test.go b/items_validator_test.go index 0cc4bad..863336d 100644 --- a/items_validator_test.go +++ b/items_validator_test.go @@ -17,8 +17,8 @@ package validate import ( "encoding/json" "fmt" - "io/ioutil" "log" + "os" "path/filepath" "testing" @@ -26,6 +26,7 @@ import ( "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( @@ -38,7 +39,7 @@ var ( func init() { petstoreFixture := filepath.Join("fixtures", "petstore", "swagger.json") - petstore, err := ioutil.ReadFile(petstoreFixture) + petstore, err := os.ReadFile(petstoreFixture) if err != nil { log.Fatalf("could not initialize fixture: %s: %v", petstoreFixture, err) } @@ -122,14 +123,16 @@ func TestNumberItemsValidation(t *testing.T) { // MultipleOf err := validator.Validate(i, v[0]) assert.True(t, err.HasErrors()) - assert.EqualError(t, multipleOfErrorItems(path, validator.in, items, v[0]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, multipleOfErrorItems(path, validator.in, items, v[0]), err.Errors[0].Error()) // Maximum err = validator.Validate(i, v[1]) assert.True(t, err == nil || err.IsValid()) err = validator.Validate(i, v[2]) assert.True(t, err.HasErrors()) - assert.EqualError(t, maxErrorItems(path, validator.in, items, v[2]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, maxErrorItems(path, validator.in, items, v[2]), err.Errors[0].Error()) // ExclusiveMaximum items.ExclusiveMaximum = true @@ -137,14 +140,16 @@ func TestNumberItemsValidation(t *testing.T) { validator = newItemsValidator(parent.Name, parent.In, items, parent, strfmt.Default) err = validator.Validate(i, v[1]) assert.True(t, err.HasErrors()) - assert.EqualError(t, maxErrorItems(path, validator.in, items, v[1]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, maxErrorItems(path, validator.in, items, v[1]), err.Errors[0].Error()) // Minimum err = validator.Validate(i, v[3]) assert.True(t, err == nil || err.IsValid()) err = validator.Validate(i, v[4]) assert.True(t, err.HasErrors()) - assert.EqualError(t, minErrorItems(path, validator.in, items, v[4]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minErrorItems(path, validator.in, items, v[4]), err.Errors[0].Error()) // ExclusiveMinimum items.ExclusiveMinimum = true @@ -152,12 +157,14 @@ func TestNumberItemsValidation(t *testing.T) { validator = newItemsValidator(parent.Name, parent.In, items, parent, strfmt.Default) err = validator.Validate(i, v[3]) assert.True(t, err.HasErrors()) - assert.EqualError(t, minErrorItems(path, validator.in, items, v[3]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minErrorItems(path, validator.in, items, v[3]), err.Errors[0].Error()) // Enum err = validator.Validate(i, v[5]) assert.True(t, err.HasErrors()) - assert.EqualError(t, enumFailItems(path, validator.in, items, v[5]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, enumFailItems(path, validator.in, items, v[5]), err.Errors[0].Error()) // Valid passes err = validator.Validate(i, v[6]) @@ -177,31 +184,36 @@ func TestStringItemsValidation(t *testing.T) { data := "" err := validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, minLengthErrorItems(path, validator.in, items, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minLengthErrorItems(path, validator.in, items, data), err.Errors[0].Error()) // MaxLength data = "abcdef" err = validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, maxLengthErrorItems(path, validator.in, items, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, maxLengthErrorItems(path, validator.in, items, data), err.Errors[0].Error()) // MinLength data = "a" err = validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, minLengthErrorItems(path, validator.in, items, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minLengthErrorItems(path, validator.in, items, data), err.Errors[0].Error()) // Pattern data = "a394" err = validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, patternFailItems(path, validator.in, items, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, patternFailItems(path, validator.in, items, data), err.Errors[0].Error()) // Enum data = "abcde" err = validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, enumFailItems(path, validator.in, items, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, enumFailItems(path, validator.in, items, data), err.Errors[0].Error()) // Valid passes err = validator.Validate(1, "bbb") @@ -219,22 +231,26 @@ func TestArrayItemsValidation(t *testing.T) { data := []string{} err := validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, minItemsErrorItems(path, validator.in, items, len(data)), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minItemsErrorItems(path, validator.in, items, len(data)), err.Errors[0].Error()) // MaxItems data = []string{"a", "b", "c", "d", "e", "f"} err = validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, maxItemsErrorItems(path, validator.in, items, len(data)), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, maxItemsErrorItems(path, validator.in, items, len(data)), err.Errors[0].Error()) // UniqueItems err = validator.Validate(1, []string{"a", "a"}) assert.True(t, err.HasErrors()) - assert.EqualError(t, duplicatesErrorItems(path, validator.in), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, duplicatesErrorItems(path, validator.in), err.Errors[0].Error()) // Enum data = []string{"a", "b", "c"} err = validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, enumFailItems(path, validator.in, items, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, enumFailItems(path, validator.in, items, data), err.Errors[0].Error()) // Items strItems := spec.NewItems().WithMinLength(3).WithMaxLength(5).WithPattern(`^[a-z]+$`).Typed(stringType, "") @@ -244,5 +260,6 @@ func TestArrayItemsValidation(t *testing.T) { data = []string{"aa", "bbb", "ccc"} err = validator.Validate(1, data) assert.True(t, err.HasErrors()) - assert.EqualError(t, minLengthErrorItems(path+".0", parent.In, strItems, data[0]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minLengthErrorItems(path+".0", parent.In, strItems, data[0]), err.Errors[0].Error()) } diff --git a/jsonschema_test.go b/jsonschema_test.go index 77a3671..b8af57e 100644 --- a/jsonschema_test.go +++ b/jsonschema_test.go @@ -16,7 +16,6 @@ package validate import ( "encoding/json" - "io/ioutil" "net/http" "os" "path/filepath" @@ -120,7 +119,7 @@ func TestJSONSchemaSuite(t *testing.T) { } }() - files, err := ioutil.ReadDir(jsonSchemaFixturesPath) + files, err := os.ReadDir(jsonSchemaFixturesPath) if err != nil { t.Fatal(err) } @@ -138,14 +137,14 @@ func TestJSONSchemaSuite(t *testing.T) { return } t.Log("Running " + specName) - b, _ := ioutil.ReadFile(filepath.Join(jsonSchemaFixturesPath, fileName)) + b, _ := os.ReadFile(filepath.Join(jsonSchemaFixturesPath, fileName)) doTestSchemaSuite(t, b) }) } } func TestSchemaFixtures(t *testing.T) { - files, err := ioutil.ReadDir(schemaFixturesPath) + files, err := os.ReadDir(schemaFixturesPath) if err != nil { t.Fatal(err) } @@ -159,7 +158,7 @@ func TestSchemaFixtures(t *testing.T) { t.Parallel() specName := strings.TrimSuffix(fileName, filepath.Ext(fileName)) t.Log("Running " + specName) - b, _ := ioutil.ReadFile(filepath.Join(schemaFixturesPath, fileName)) + b, _ := os.ReadFile(filepath.Join(schemaFixturesPath, fileName)) doTestSchemaSuite(t, b) }) } @@ -175,7 +174,7 @@ func expandOpts(base string) *spec.ExpandOptions { func TestOptionalJSONSchemaSuite(t *testing.T) { jsonOptionalSchemaFixturesPath := filepath.Join(jsonSchemaFixturesPath, "optional") - files, err := ioutil.ReadDir(jsonOptionalSchemaFixturesPath) + files, err := os.ReadDir(jsonOptionalSchemaFixturesPath) if err != nil { t.Fatal(err) } @@ -193,7 +192,7 @@ func TestOptionalJSONSchemaSuite(t *testing.T) { return } t.Log("Running [optional] " + specName) - b, _ := ioutil.ReadFile(filepath.Join(jsonOptionalSchemaFixturesPath, fileName)) + b, _ := os.ReadFile(filepath.Join(jsonOptionalSchemaFixturesPath, fileName)) doTestSchemaSuite(t, b) }) } @@ -201,7 +200,7 @@ func TestOptionalJSONSchemaSuite(t *testing.T) { // Further testing with all formats recognized by strfmt func TestFormat_JSONSchemaExtended(t *testing.T) { - files, err := ioutil.ReadDir(formatFixturesPath) + files, err := os.ReadDir(formatFixturesPath) if err != nil { t.Fatal(err) } @@ -219,7 +218,7 @@ func TestFormat_JSONSchemaExtended(t *testing.T) { return } t.Log("Running [extended formats] " + specName) - b, _ := ioutil.ReadFile(filepath.Join(formatFixturesPath, fileName)) + b, _ := os.ReadFile(filepath.Join(formatFixturesPath, fileName)) doTestSchemaSuite(t, b) }) } @@ -233,8 +232,8 @@ func doTestSchemaSuite(t *testing.T, doc []byte) { for _, testDescription := range testDescriptions { b, _ := testDescription.Schema.MarshalJSON() - tmpFile, err := ioutil.TempFile(os.TempDir(), "validate-test") - assert.NoError(t, err) + tmpFile, err := os.CreateTemp(os.TempDir(), "validate-test") + require.NoError(t, err) _, _ = tmpFile.Write(b) tmpFile.Close() defer func() { _ = os.Remove(tmpFile.Name()) }() diff --git a/messages_test.go b/messages_test.go index f1e04bd..eb73b3f 100644 --- a/messages_test.go +++ b/messages_test.go @@ -16,7 +16,6 @@ package validate import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -28,7 +27,7 @@ import ( "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) var ( @@ -86,7 +85,7 @@ func Test_MessageQualityStopOnErrors_Issue44(t *testing.T) { } func loadTestConfig(t *testing.T, fp string) ExpectedMap { - expectedConfig, err := ioutil.ReadFile(fp) + expectedConfig, err := os.ReadFile(fp) require.NoErrorf(t, err, "cannot read expected messages config file: %v", err) tested := make(ExpectedMap, 200) @@ -192,7 +191,7 @@ func expectValid(t *testing.T, path string, thisTest *ExpectedFixture, continueO validator.SetContinueOnErrors(continueOnErrors) res, warn := validator.Validate(doc) assert.True(t, res.IsValid(), "expected this spec to be valid") - assert.Lenf(t, res.Errors, 0, "expected no returned errors") + assert.Emptyf(t, res.Errors, "expected no returned errors") // check warnings errs := verifyErrors(t, warn, thisTest.ExpectedWarnings, "warning", continueOnErrors) @@ -316,7 +315,7 @@ func verifyErrorsVsWarnings(t *testing.T, res, warn *Result) int { // First verification of result conventions: results are redundant, just a matter of presentation w := len(warn.Errors) if !assert.Len(t, res.Warnings, w) || - !assert.Len(t, warn.Warnings, 0) || + !assert.Empty(t, warn.Warnings) || !assert.Subset(t, res.Warnings, warn.Errors) || !assert.Subset(t, warn.Errors, res.Warnings) { t.Log("Result equivalence errors vs warnings not verified") diff --git a/object_validator_test.go b/object_validator_test.go index 9f38cb7..bace41a 100644 --- a/object_validator_test.go +++ b/object_validator_test.go @@ -29,18 +29,18 @@ func itemsFixture() map[string]interface{} { func expectAllValid(t *testing.T, ov EntityValidator, dataValid, dataInvalid map[string]interface{}) { res := ov.Validate(dataValid) - assert.Equal(t, 0, len(res.Errors)) + assert.Empty(t, res.Errors) res = ov.Validate(dataInvalid) - assert.Equal(t, 0, len(res.Errors)) + assert.Empty(t, res.Errors) } func expectOnlyInvalid(t *testing.T, ov EntityValidator, dataValid, dataInvalid map[string]interface{}) { res := ov.Validate(dataValid) - assert.Equal(t, 0, len(res.Errors)) + assert.Empty(t, res.Errors) res = ov.Validate(dataInvalid) - assert.NotEqual(t, 0, len(res.Errors)) + assert.NotEmpty(t, res.Errors) } func TestItemsMustBeTypeArray(t *testing.T) { diff --git a/parameter_validator_test.go b/parameter_validator_test.go index fb14d4a..6eeaeff 100644 --- a/parameter_validator_test.go +++ b/parameter_validator_test.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // common validations: enum, allOf, anyOf, oneOf, not, definitions @@ -71,7 +72,8 @@ func TestNumberParameterValidation(t *testing.T) { // MultipleOf err := validator.Validate(v[0]) assert.True(t, err.HasErrors()) - assert.EqualError(t, multipleOfError(factorParam, v[0]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, multipleOfError(factorParam, v[0]), err.Errors[0].Error()) // Maximum err = validator.Validate(v[1]) @@ -82,7 +84,8 @@ func TestNumberParameterValidation(t *testing.T) { err = validator.Validate(v[2]) assert.True(t, err.HasErrors()) - assert.EqualError(t, maxError(factorParam, v[1]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, maxError(factorParam, v[1]), err.Errors[0].Error()) // ExclusiveMaximum factorParam.ExclusiveMaximum = true @@ -90,14 +93,15 @@ func TestNumberParameterValidation(t *testing.T) { validator = NewParamValidator(factorParam, strfmt.Default) err = validator.Validate(v[1]) assert.True(t, err.HasErrors()) - assert.EqualError(t, maxError(factorParam, v[1]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, maxError(factorParam, v[1]), err.Errors[0].Error()) // Minimum err = validator.Validate(v[3]) assert.True(t, err == nil || err.IsValid()) err = validator.Validate(v[4]) assert.True(t, err.HasErrors()) - assert.EqualError(t, minError(factorParam, v[4]), err.Errors[0].Error()) + require.EqualError(t, minError(factorParam, v[4]), err.Errors[0].Error()) // ExclusiveMinimum factorParam.ExclusiveMinimum = true @@ -105,12 +109,14 @@ func TestNumberParameterValidation(t *testing.T) { validator = NewParamValidator(factorParam, strfmt.Default) err = validator.Validate(v[3]) assert.True(t, err.HasErrors()) - assert.EqualError(t, minError(factorParam, v[3]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minError(factorParam, v[3]), err.Errors[0].Error()) // Enum err = validator.Validate(v[5]) assert.True(t, err.HasErrors()) - assert.EqualError(t, enumFail(factorParam, v[5]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, enumFail(factorParam, v[5]), err.Errors[0].Error()) err = validator.Validate(v[6]) assert.True(t, err == nil || err.IsValid()) @@ -149,28 +155,33 @@ func TestStringParameterValidation(t *testing.T) { data := "" err := validator.Validate(data) assert.True(t, err.HasErrors()) - assert.EqualError(t, requiredError(nameParam, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, requiredError(nameParam, data), err.Errors[0].Error()) // MaxLength data = "abcdef" err = validator.Validate(data) assert.True(t, err.HasErrors()) - assert.EqualError(t, maxLengthError(nameParam, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, maxLengthError(nameParam, data), err.Errors[0].Error()) // MinLength data = "a" err = validator.Validate(data) assert.True(t, err.HasErrors()) - assert.EqualError(t, minLengthError(nameParam, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minLengthError(nameParam, data), err.Errors[0].Error()) // Pattern data = "a394" err = validator.Validate(data) assert.True(t, err.HasErrors()) - assert.EqualError(t, patternFail(nameParam, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, patternFail(nameParam, data), err.Errors[0].Error()) // Enum data = "abcde" err = validator.Validate(data) assert.True(t, err.HasErrors()) - assert.EqualError(t, enumFail(nameParam, data), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, enumFail(nameParam, data), err.Errors[0].Error()) // Valid passes err = validator.Validate("bbb") @@ -203,21 +214,25 @@ func TestArrayParameterValidation(t *testing.T) { data := []string{} err := validator.Validate(data) assert.True(t, err.HasErrors()) - assert.EqualError(t, minItemsError(tagsParam, len(data)), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minItemsError(tagsParam, len(data)), err.Errors[0].Error()) // MaxItems data = []string{"a", "b", "c", "d", "e", "f"} err = validator.Validate(data) assert.True(t, err.HasErrors()) - assert.EqualError(t, maxItemsError(tagsParam, len(data)), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, maxItemsError(tagsParam, len(data)), err.Errors[0].Error()) // UniqueItems err = validator.Validate([]string{"a", "a"}) assert.True(t, err.HasErrors()) - assert.EqualError(t, duplicatesError(tagsParam), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, duplicatesError(tagsParam), err.Errors[0].Error()) // Enum err = validator.Validate([]string{"a", "b", "c"}) assert.True(t, err.HasErrors()) - assert.EqualError(t, enumFail(tagsParam, []string{"a", "b", "c"}), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, enumFail(tagsParam, []string{"a", "b", "c"}), err.Errors[0].Error()) // Items strItems := spec.NewItems().WithMinLength(3).WithMaxLength(5).WithPattern(`^[a-z]+$`).Typed(stringType, "") @@ -226,7 +241,8 @@ func TestArrayParameterValidation(t *testing.T) { data = []string{"aa", "bbb", "ccc"} err = validator.Validate(data) assert.True(t, err.HasErrors()) - assert.EqualError(t, minLengthErrorItems("tags.0", tagsParam.In, strItems, data[0]), err.Errors[0].Error()) + require.NotEmpty(t, err.Errors) + require.EqualError(t, minLengthErrorItems("tags.0", tagsParam.In, strItems, data[0]), err.Errors[0].Error()) // Not required in a parameter or items // Additional items diff --git a/post/defaulter_test.go b/post/defaulter_test.go index 67a6909..889eb6e 100644 --- a/post/defaulter_test.go +++ b/post/defaulter_test.go @@ -17,22 +17,22 @@ package post import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" - "github.com/stretchr/testify/assert" - "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" "github.com/go-openapi/validate" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var defaulterFixturesPath = filepath.Join("..", "fixtures", "defaulting") func TestDefaulter(t *testing.T) { schema, err := defaulterFixture() - assert.NoError(t, err) + require.NoError(t, err) validator := validate.NewSchemaValidator(schema, nil, "", strfmt.Default) x := defaulterFixtureInput() @@ -54,7 +54,7 @@ func TestDefaulter(t *testing.T) { "any": {"foo": 42}, "one": {"bar": 42} }`), &expected) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, x) } @@ -88,7 +88,7 @@ func TestDefaulterSimple(t *testing.T) { "int": 42, "str": "Hello" }`), &expected) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, x) } @@ -96,7 +96,7 @@ func BenchmarkDefaulting(b *testing.B) { b.ReportAllocs() schema, err := defaulterFixture() - assert.NoError(b, err) + require.NoError(b, err) for n := 0; n < b.N; n++ { validator := validate.NewSchemaValidator(schema, nil, "", strfmt.Default) @@ -119,7 +119,7 @@ func defaulterFixtureInput() map[string]interface{} { func defaulterFixture() (*spec.Schema, error) { fname := filepath.Join(defaulterFixturesPath, "schema.json") - b, err := ioutil.ReadFile(fname) + b, err := os.ReadFile(fname) if err != nil { return nil, err } diff --git a/post/prune_test.go b/post/prune_test.go index e95a407..81b3452 100644 --- a/post/prune_test.go +++ b/post/prune_test.go @@ -17,11 +17,12 @@ package post import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" @@ -32,7 +33,7 @@ var pruneFixturesPath = filepath.Join("..", "fixtures", "pruning") func TestPrune(t *testing.T) { schema, err := pruningFixture() - assert.NoError(t, err) + require.NoError(t, err) x := map[string]interface{}{ "foo": 42, @@ -111,7 +112,7 @@ func TestPrune(t *testing.T) { func pruningFixture() (*spec.Schema, error) { fname := filepath.Join(pruneFixturesPath, "schema.json") - b, err := ioutil.ReadFile(fname) + b, err := os.ReadFile(fname) if err != nil { return nil, err } diff --git a/result.go b/result.go index 8f5f935..cd14ec3 100644 --- a/result.go +++ b/result.go @@ -132,7 +132,8 @@ func (r *Result) RootObjectSchemata() []*spec.Schema { } // FieldSchemata returns the schemata which apply to fields in objects. -// nolint: dupl +// + func (r *Result) FieldSchemata() map[FieldKey][]*spec.Schema { if r.cachedFieldSchemta != nil { return r.cachedFieldSchemta @@ -152,7 +153,8 @@ func (r *Result) FieldSchemata() map[FieldKey][]*spec.Schema { } // ItemSchemata returns the schemata which apply to items in slices. -// nolint: dupl +// + func (r *Result) ItemSchemata() map[ItemKey][]*spec.Schema { if r.cachedItemSchemata != nil { return r.cachedItemSchemata @@ -177,7 +179,8 @@ func (r *Result) resetCaches() { } // mergeForField merges other into r, assigning other's root schemata to the given Object and field name. -// nolint: unparam +// +//nolint:unparam func (r *Result) mergeForField(obj map[string]interface{}, field string, other *Result) *Result { if other == nil { return r @@ -199,7 +202,8 @@ func (r *Result) mergeForField(obj map[string]interface{}, field string, other * } // mergeForSlice merges other into r, assigning other's root schemata to the given slice and index. -// nolint: unparam +// +//nolint:unparam func (r *Result) mergeForSlice(slice reflect.Value, i int, other *Result) *Result { if other == nil { return r diff --git a/result_test.go b/result_test.go index af31fbd..9bdccab 100644 --- a/result_test.go +++ b/result_test.go @@ -40,7 +40,7 @@ func TestResult_AddError(t *testing.T) { func TestResult_AddNilError(t *testing.T) { r := Result{} r.AddErrors(nil) - assert.Len(t, r.Errors, 0) + assert.Empty(t, r.Errors) errArray := []error{fmt.Errorf("one Error"), nil, fmt.Errorf("another error")} r.AddErrors(errArray...) @@ -51,7 +51,7 @@ func TestResult_AddWarnings(t *testing.T) { r := Result{} r.AddErrors(fmt.Errorf("one Error")) assert.Len(t, r.Errors, 1) - assert.Len(t, r.Warnings, 0) + assert.Empty(t, r.Warnings) r.AddWarnings(fmt.Errorf("one Warning")) assert.Len(t, r.Errors, 1) @@ -65,7 +65,7 @@ func TestResult_Merge(t *testing.T) { r.Inc() assert.Len(t, r.Errors, 1) assert.Len(t, r.Warnings, 1) - assert.Equal(t, r.MatchCount, 1) + assert.Equal(t, 1, r.MatchCount) // Merge with same r2 := Result{} @@ -77,7 +77,7 @@ func TestResult_Merge(t *testing.T) { assert.Len(t, r.Errors, 1) assert.Len(t, r.Warnings, 1) - assert.Equal(t, r.MatchCount, 2) + assert.Equal(t, 2, r.MatchCount) // Merge with new r3 := Result{} @@ -89,7 +89,7 @@ func TestResult_Merge(t *testing.T) { assert.Len(t, r.Errors, 2) assert.Len(t, r.Warnings, 2) - assert.Equal(t, r.MatchCount, 3) + assert.Equal(t, 3, r.MatchCount) } func errorFixture() (Result, Result, Result) { @@ -116,26 +116,26 @@ func TestResult_MergeAsErrors(t *testing.T) { r, r2, r3 := errorFixture() assert.Len(t, r.Errors, 1) assert.Len(t, r.Warnings, 1) - assert.Equal(t, r.MatchCount, 1) + assert.Equal(t, 1, r.MatchCount) r.MergeAsErrors(&r2, &r3) assert.Len(t, r.Errors, 4) // One Warning added to Errors assert.Len(t, r.Warnings, 1) - assert.Equal(t, r.MatchCount, 3) + assert.Equal(t, 3, r.MatchCount) } func TestResult_MergeAsWarnings(t *testing.T) { r, r2, r3 := errorFixture() assert.Len(t, r.Errors, 1) assert.Len(t, r.Warnings, 1) - assert.Equal(t, r.MatchCount, 1) + assert.Equal(t, 1, r.MatchCount) r.MergeAsWarnings(&r2, &r3) assert.Len(t, r.Errors, 1) // One Warning added to Errors assert.Len(t, r.Warnings, 4) - assert.Equal(t, r.MatchCount, 3) + assert.Equal(t, 3, r.MatchCount) } func TestResult_IsValid(t *testing.T) { @@ -193,11 +193,11 @@ func TestResult_keepRelevantErrors(t *testing.T) { func TestResult_AsError(t *testing.T) { r := Result{} - assert.Nil(t, r.AsError()) + require.NoError(t, r.AsError()) r.AddErrors(fmt.Errorf("one Error")) r.AddErrors(fmt.Errorf("additional Error")) res := r.AsError() - require.NotNil(t, res) + require.Error(t, res) assert.Contains(t, res.Error(), "validation failure list:") // Expected from pkg errors assert.Contains(t, res.Error(), "one Error") // Expected from pkg errors diff --git a/rexp_test.go b/rexp_test.go index 580b397..7009c7f 100644 --- a/rexp_test.go +++ b/rexp_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Save repeated regexp compilation @@ -26,16 +27,16 @@ func Test_compileRegexp(t *testing.T) { vrex := new(re.Regexp) rex, err := compileRegexp(".*TestRegexp.*") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, rex) assert.IsType(t, vrex, rex) rex, err = compileRegexp(".*TestRegexp.*") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, rex) irex, ierr := compileRegexp(".[*InvalidTestRegexp.*") - assert.Error(t, ierr) + require.Error(t, ierr) assert.Nil(t, irex) assert.IsType(t, vrex, irex) } @@ -69,7 +70,7 @@ func TestRace_compileRegexp(t *testing.T) { comp := func(pattern string) { rex, err := compileRegexp(pattern) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, rex) assert.IsType(t, vrex, rex) } diff --git a/schema_test.go b/schema_test.go index 51df670..0bb0240 100644 --- a/schema_test.go +++ b/schema_test.go @@ -55,11 +55,11 @@ func TestSchemaValidator_Validate_Pattern(t *testing.T) { var inputJSON = `{"name": "Ivan"}` require.NoError(t, json.Unmarshal([]byte(inputJSON), &input)) - assert.NoError(t, AgainstSchema(schema, input, strfmt.Default)) + require.NoError(t, AgainstSchema(schema, input, strfmt.Default)) input["place"] = json.Number("10") - assert.Error(t, AgainstSchema(schema, input, strfmt.Default)) + require.Error(t, AgainstSchema(schema, input, strfmt.Default)) } @@ -93,16 +93,16 @@ func TestSchemaValidator_PatternProperties(t *testing.T) { // ok var inputJSON = `{"name": "Ivan","address-1": "sesame street"}` require.NoError(t, json.Unmarshal([]byte(inputJSON), &input)) - assert.NoError(t, AgainstSchema(schema, input, strfmt.Default)) + require.NoError(t, AgainstSchema(schema, input, strfmt.Default)) // fail pattern regexp input["address-1"] = "1, Sesame Street" - assert.Error(t, AgainstSchema(schema, input, strfmt.Default)) + require.Error(t, AgainstSchema(schema, input, strfmt.Default)) // fail patternProperties regexp inputJSON = `{"name": "Ivan","address-1": "sesame street","address-A": "address"}` require.NoError(t, json.Unmarshal([]byte(inputJSON), &input)) - assert.Error(t, AgainstSchema(schema, input, strfmt.Default)) + require.Error(t, AgainstSchema(schema, input, strfmt.Default)) } @@ -203,7 +203,7 @@ func TestSchemaValidator_SchemaOptions(t *testing.T) { var input map[string]interface{} var inputJSON = `{"spec": {"items": ["foo", "bar"], "replicas": 1}}` - assert.NoError(t, json.Unmarshal([]byte(inputJSON), &input)) + require.NoError(t, json.Unmarshal([]byte(inputJSON), &input)) // ok s := NewSchemaValidator(schema, nil, "", strfmt.Default, EnableObjectArrayTypeCheck(false)) @@ -230,8 +230,8 @@ func TestSchemaValidator_TypeArray_Issue83(t *testing.T) { require.NoError(t, json.Unmarshal([]byte(inputJSON), &input)) // default behavior: jsonschema - assert.NoError(t, AgainstSchema(schema, input, strfmt.Default)) + require.NoError(t, AgainstSchema(schema, input, strfmt.Default)) // swagger behavior - assert.Error(t, AgainstSchema(schema, input, strfmt.Default, SwaggerSchema(true))) + require.Error(t, AgainstSchema(schema, input, strfmt.Default, SwaggerSchema(true))) } diff --git a/spec.go b/spec.go index 5b867dd..71a7bac 100644 --- a/spec.go +++ b/spec.go @@ -455,7 +455,6 @@ func (s *SpecValidator) validateReferenced() *Result { return &res } -// nolint: dupl func (s *SpecValidator) validateReferencedParameters() *Result { // Each referenceable definition should have references. params := s.spec.Spec().Parameters @@ -481,7 +480,6 @@ func (s *SpecValidator) validateReferencedParameters() *Result { return result } -// nolint: dupl func (s *SpecValidator) validateReferencedResponses() *Result { // Each referenceable definition should have references. responses := s.spec.Spec().Responses @@ -507,7 +505,6 @@ func (s *SpecValidator) validateReferencedResponses() *Result { return result } -// nolint: dupl func (s *SpecValidator) validateReferencedDefinitions() *Result { // Each referenceable definition must have references. defs := s.spec.Spec().Definitions diff --git a/spec_test.go b/spec_test.go index d996a5d..896e1e8 100644 --- a/spec_test.go +++ b/spec_test.go @@ -17,7 +17,7 @@ package validate import ( "encoding/json" "flag" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -104,7 +104,7 @@ func TestSpec_ExpandResponseRecursive(t *testing.T) { // Spec with no path func TestSpec_Issue52(t *testing.T) { fp := filepath.Join("fixtures", "bugs", "52", "swagger.json") - jstext, _ := ioutil.ReadFile(fp) + jstext, _ := os.ReadFile(fp) // as json schema var sch spec.Schema @@ -113,7 +113,8 @@ func TestSpec_Issue52(t *testing.T) { schemaValidator := NewSchemaValidator(spec.MustLoadSwagger20Schema(), nil, "", strfmt.Default) res := schemaValidator.Validate(&sch) assert.False(t, res.IsValid()) - assert.EqualError(t, res.Errors[0], ".paths in body is required") + require.NotEmpty(t, res.Errors) + require.EqualError(t, res.Errors[0], ".paths in body is required") // as swagger spec: path is set to nil // Here, validation stops as paths is initialized to empty @@ -128,7 +129,7 @@ func TestSpec_Issue52(t *testing.T) { func TestSpec_Issue53(t *testing.T) { fp := filepath.Join("fixtures", "bugs", "53", "noswagger.json") - jstext, _ := ioutil.ReadFile(fp) + jstext, _ := os.ReadFile(fp) // as json schema var sch spec.Schema @@ -137,12 +138,14 @@ func TestSpec_Issue53(t *testing.T) { schemaValidator := NewSchemaValidator(spec.MustLoadSwagger20Schema(), nil, "", strfmt.Default) res := schemaValidator.Validate(&sch) assert.False(t, res.IsValid()) - assert.EqualError(t, res.Errors[0], ".swagger in body is required") + require.NotEmpty(t, res.Errors) + require.EqualError(t, res.Errors[0], ".swagger in body is required") // as swagger despec res, _ = loadAndValidate(t, fp, false) require.False(t, res.IsValid()) - assert.EqualError(t, res.Errors[0], ".swagger in body is required") + require.NotEmpty(t, res.Errors) + require.EqualError(t, res.Errors[0], ".swagger in body is required") } func TestSpec_Issue62(t *testing.T) { @@ -580,7 +583,7 @@ func TestSpec_ValidDoc(t *testing.T) { doc2, err := loads.Spec(fp) require.NoError(t, err) err = Spec(doc2, strfmt.Default) - assert.NoError(t, err) + require.NoError(t, err) } // Check higher level behavior on invalid spec doc @@ -588,7 +591,7 @@ func TestSpec_InvalidDoc(t *testing.T) { doc, err := loads.Spec(filepath.Join("fixtures", "validation", "default", "invalid-default-value-parameter.json")) require.NoError(t, err) err = Spec(doc, strfmt.Default) - assert.Error(t, err) + require.Error(t, err) } func TestSpec_Validate_InvalidInterface(t *testing.T) { @@ -718,12 +721,12 @@ func TestItemsProperty_Issue43(t *testing.T) { fp := filepath.Join("fixtures", "bugs", "43", "fixture-43-fail.yaml") res, _ := loadAndValidate(t, fp) assert.Falsef(t, res.IsValid(), "expected spec to be invalid") - assert.True(t, len(res.Errors) > 3) + assert.Greater(t, len(res.Errors), 3) fp = filepath.Join("fixtures", "validation", "fixture-1171.yaml") res, _ = loadAndValidate(t, fp) assert.Falsef(t, res.IsValid(), "expected spec to be invalid") - assert.True(t, len(res.Errors) > 3) + assert.Greater(t, len(res.Errors), 3) found := false for _, e := range res.Errors { found = strings.Contains(e.Error(), "array requires items definition") diff --git a/swagger_test.go b/swagger_test.go index 6bdc293..3c9908d 100644 --- a/swagger_test.go +++ b/swagger_test.go @@ -25,6 +25,7 @@ import ( "github.com/go-openapi/loads/fmts" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func init() { @@ -145,10 +146,10 @@ func testGoSwaggerSpecs(t *testing.T, path string, expectToFail, expectToFailOnL doc, err := loads.Spec(path) if shouldNotLoad { - assert.Errorf(t, err, "expected this spec not to load: %s", path) + require.Errorf(t, err, "expected this spec not to load: %s", path) return } - assert.NoErrorf(t, err, "expected this spec to load without error: %s", path) + require.NoErrorf(t, err, "expected this spec to load without error: %s", path) if haltOnErrors && t.Failed() { assert.FailNow(t, "test Halted: stop on error mode") @@ -176,7 +177,7 @@ func testGoSwaggerSpecs(t *testing.T, path string, expectToFail, expectToFailOnL }) return nil }) - assert.NoErrorf(t, err, "walk: %v", err) + require.NoErrorf(t, err, "walk: %v", err) if t.Failed() { log.Printf("A change in expected validation status has been detected") } diff --git a/type.go b/type.go index 8764675..c7abf38 100644 --- a/type.go +++ b/type.go @@ -90,7 +90,7 @@ func (t *typeValidator) schemaInfoForType(data interface{}) (string, string) { default: val := reflect.ValueOf(data) tpe := val.Type() - switch tpe.Kind() { + switch tpe.Kind() { //nolint:exhaustive case reflect.Bool: return booleanType, "" case reflect.String: diff --git a/type_test.go b/type_test.go index 7a72394..41febbf 100644 --- a/type_test.go +++ b/type_test.go @@ -265,11 +265,13 @@ func TestType_schemaInfoForType(t *testing.T) { v := &typeValidator{} for _, x := range testTypes { - jsonType, swaggerFormat := v.schemaInfoForType(x.value) + value := x.value + + jsonType, swaggerFormat := v.schemaInfoForType(value) assert.Equal(t, x.expectedJSONType, jsonType) assert.Equal(t, x.expectedSwaggerFormat, swaggerFormat) - jsonType, swaggerFormat = v.schemaInfoForType(&x.value) + jsonType, swaggerFormat = v.schemaInfoForType(&value) assert.Equal(t, x.expectedJSONType, jsonType) assert.Equal(t, x.expectedSwaggerFormat, swaggerFormat) } diff --git a/validator.go b/validator.go index ee01f2a..ab4f718 100644 --- a/validator.go +++ b/validator.go @@ -548,7 +548,6 @@ func (n *numberValidator) Validate(val interface{}) *Result { } } - // nolint: dupl if n.Maximum != nil { // Is the constraint specifier within the range of the specific numeric type and format? resMaximum.AddErrors(IsValueValidAgainstRange(*n.Maximum, n.Type, n.Format, "Maximum boundary", n.Path)) @@ -565,7 +564,6 @@ func (n *numberValidator) Validate(val interface{}) *Result { } } - // nolint: dupl if n.Minimum != nil { // Is the constraint specifier within the range of the specific numeric type and format? resMinimum.AddErrors(IsValueValidAgainstRange(*n.Minimum, n.Type, n.Format, "Minimum boundary", n.Path)) diff --git a/values.go b/values.go index 080fe21..5f6f5ee 100644 --- a/values.go +++ b/values.go @@ -315,7 +315,7 @@ func FormatOf(path, in, format, data string, registry strfmt.Registry) *errors.V // TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free func MaximumNativeType(path, in string, val interface{}, max float64, exclusive bool) *errors.Validation { kind := reflect.ValueOf(val).Type().Kind() - switch kind { + switch kind { //nolint:exhaustive case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value := valueHelp.asInt64(val) return MaximumInt(path, in, value, int64(max), exclusive) @@ -345,7 +345,7 @@ func MaximumNativeType(path, in string, val interface{}, max float64, exclusive // TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free func MinimumNativeType(path, in string, val interface{}, min float64, exclusive bool) *errors.Validation { kind := reflect.ValueOf(val).Type().Kind() - switch kind { + switch kind { //nolint:exhaustive case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value := valueHelp.asInt64(val) return MinimumInt(path, in, value, int64(min), exclusive) @@ -375,7 +375,7 @@ func MinimumNativeType(path, in string, val interface{}, min float64, exclusive // TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free func MultipleOfNativeType(path, in string, val interface{}, multipleOf float64) *errors.Validation { kind := reflect.ValueOf(val).Type().Kind() - switch kind { + switch kind { //nolint:exhaustive case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value := valueHelp.asInt64(val) return MultipleOfInt(path, in, value, int64(multipleOf)) @@ -399,7 +399,7 @@ func IsValueValidAgainstRange(val interface{}, typeName, format, prefix, path st // What is the string representation of val var stringRep string - switch kind { + switch kind { //nolint:exhaustive case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: stringRep = swag.FormatUint64(valueHelp.asUint64(val)) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: diff --git a/values_test.go b/values_test.go index cb25465..d17e332 100644 --- a/values_test.go +++ b/values_test.go @@ -22,47 +22,40 @@ import ( "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValues_ValidateIntEnum(t *testing.T) { enumValues := []interface{}{1, 2, 3} - err := Enum("test", "body", int64(5), enumValues) - assert.Error(t, err) - err = Enum("test", "body", int64(1), enumValues) - assert.Nil(t, err) + require.Error(t, Enum("test", "body", int64(5), enumValues)) + require.Nil(t, Enum("test", "body", int64(1), enumValues)) } func TestValues_ValidateEnum(t *testing.T) { enumValues := []string{"aa", "bb", "cc"} - err := Enum("test", "body", "a", enumValues) - assert.Error(t, err) - err = Enum("test", "body", "bb", enumValues) - assert.Nil(t, err) + require.Error(t, Enum("test", "body", "a", enumValues)) + require.Nil(t, Enum("test", "body", "bb", enumValues)) type CustomString string - err = Enum("test", "body", CustomString("a"), enumValues) - assert.Error(t, err) - err = Enum("test", "body", CustomString("bb"), enumValues) - assert.Nil(t, err) + require.Error(t, Enum("test", "body", CustomString("a"), enumValues)) + require.Nil(t, Enum("test", "body", CustomString("bb"), enumValues)) } func TestValues_ValidateNilEnum(t *testing.T) { enumValues := []string{"aa", "bb", "cc"} - err := Enum("test", "body", nil, enumValues) - assert.Error(t, err) + require.Error(t, Enum("test", "body", nil, enumValues)) } // Check edge cases in Enum func TestValues_Enum_EdgeCases(t *testing.T) { enumValues := "aa, bb, cc" - err := Enum("test", "body", int64(1), enumValues) // No validation occurs: enumValues is not a slice - assert.Nil(t, err) + require.Nil(t, Enum("test", "body", int64(1), enumValues)) // TODO(TEST): edge case: value is not a concrete type // It's really a go internals challenge @@ -73,33 +66,22 @@ func TestValues_Enum_EdgeCases(t *testing.T) { func TestValues_ValidateEnumCaseInsensitive(t *testing.T) { enumValues := []string{"aa", "bb", "cc"} - err := EnumCase("test", "body", "a", enumValues, true) - assert.Error(t, err) - err = EnumCase("test", "body", "bb", enumValues, true) - assert.Nil(t, err) - err = EnumCase("test", "body", "BB", enumValues, true) - assert.Error(t, err) - - err = EnumCase("test", "body", "a", enumValues, false) - assert.Error(t, err) - err = EnumCase("test", "body", "bb", enumValues, false) - assert.Nil(t, err) - err = EnumCase("test", "body", "BB", enumValues, false) - assert.Nil(t, err) - err = EnumCase("test", "body", int64(1), enumValues, false) - assert.Error(t, err) + require.Error(t, EnumCase("test", "body", "a", enumValues, true)) + require.Nil(t, EnumCase("test", "body", "bb", enumValues, true)) + require.Error(t, EnumCase("test", "body", "BB", enumValues, true)) + require.Error(t, EnumCase("test", "body", "a", enumValues, false)) + require.Nil(t, EnumCase("test", "body", "bb", enumValues, false)) + require.Nil(t, EnumCase("test", "body", "BB", enumValues, false)) + require.Error(t, EnumCase("test", "body", int64(1), enumValues, false)) } func TestValues_ValidateUniqueItems(t *testing.T) { - var err error - itemsNonUnique := []interface{}{ []int32{1, 2, 3, 4, 4, 5}, []string{"aa", "bb", "cc", "cc", "dd"}, } for _, v := range itemsNonUnique { - err = UniqueItems("test", "body", v) - assert.Error(t, err) + require.Error(t, UniqueItems("test", "body", v)) } itemsUnique := []interface{}{ @@ -113,31 +95,27 @@ func TestValues_ValidateUniqueItems(t *testing.T) { nil, } for _, v := range itemsUnique { - err = UniqueItems("test", "body", v) - assert.Nil(t, err) + require.Nil(t, UniqueItems("test", "body", v)) } } func TestValues_ValidateMinLength(t *testing.T) { - var minLength int64 = 5 - err := MinLength("test", "body", "aa", minLength) - assert.Error(t, err) - err = MinLength("test", "body", "aaaaa", minLength) - assert.Nil(t, err) + const minLength = int64(5) + require.Error(t, MinLength("test", "body", "aa", minLength)) + require.Nil(t, MinLength("test", "body", "aaaaa", minLength)) } func TestValues_ValidateMaxLength(t *testing.T) { - var maxLength int64 = 5 - err := MaxLength("test", "body", "bbbbbb", maxLength) - assert.Error(t, err) - err = MaxLength("test", "body", "aa", maxLength) - assert.Nil(t, err) + const maxLength = int64(5) + require.Error(t, MaxLength("test", "body", "bbbbbb", maxLength)) + require.Nil(t, MaxLength("test", "body", "aa", maxLength)) } func TestValues_ReadOnly(t *testing.T) { - var err error - path := "test" - in := "body" + const ( + path = "test" + in = "body" + ) ReadOnlySuccess := []interface{}{ "", @@ -157,43 +135,38 @@ func TestValues_ReadOnly(t *testing.T) { // readonly should not have any effect ctx := context.Background() for _, v := range ReadOnlySuccess { - err = ReadOnly(ctx, path, in, v) - assert.Nil(t, err) + require.Nil(t, ReadOnly(ctx, path, in, v)) } for _, v := range ReadOnlyFail { - err = ReadOnly(ctx, path, in, v) - assert.Nil(t, err) + require.Nil(t, ReadOnly(ctx, path, in, v)) } }) t.Run("operationType request", func(t *testing.T) { ctx := WithOperationRequest(context.Background()) for _, v := range ReadOnlySuccess { - err = ReadOnly(ctx, path, in, v) - assert.Nil(t, err) + require.Nil(t, ReadOnly(ctx, path, in, v)) } for _, v := range ReadOnlyFail { - err = ReadOnly(ctx, path, in, v) - assert.Error(t, err) + require.Error(t, ReadOnly(ctx, path, in, v)) } }) t.Run("operationType response", func(t *testing.T) { ctx := WithOperationResponse(context.Background()) for _, v := range ReadOnlySuccess { - err = ReadOnly(ctx, path, in, v) - assert.Nil(t, err) + require.Nil(t, ReadOnly(ctx, path, in, v)) } for _, v := range ReadOnlyFail { - err = ReadOnly(ctx, path, in, v) - assert.Nil(t, err) + require.Nil(t, ReadOnly(ctx, path, in, v)) } }) } func TestValues_ValidateRequired(t *testing.T) { - var err error - path := "test" - in := "body" + const ( + path = "test" + in = "body" + ) RequiredFail := []interface{}{ "", @@ -202,8 +175,7 @@ func TestValues_ValidateRequired(t *testing.T) { } for _, v := range RequiredFail { - err = Required(path, in, v) - assert.Error(t, err) + require.Error(t, Required(path, in, v)) } RequiredSuccess := []interface{}{ @@ -214,87 +186,57 @@ func TestValues_ValidateRequired(t *testing.T) { } for _, v := range RequiredSuccess { - err = Required(path, in, v) - assert.Nil(t, err) + require.Nil(t, Required(path, in, v)) } } func TestValues_ValidateRequiredNumber(t *testing.T) { - err := RequiredNumber("test", "body", 0) - assert.Error(t, err) - err = RequiredNumber("test", "body", 1) - assert.Nil(t, err) + require.Error(t, RequiredNumber("test", "body", 0)) + require.Nil(t, RequiredNumber("test", "body", 1)) } func TestValuMultipleOf(t *testing.T) { - // positive - - err := MultipleOf("test", "body", 9, 3) - assert.Nil(t, err) - - err = MultipleOf("test", "body", 9.3, 3.1) - assert.Nil(t, err) - - err = MultipleOf("test", "body", 9.1, 0.1) - assert.Nil(t, err) - - err = MultipleOf("test", "body", 3, 0.3) - assert.Nil(t, err) - - err = MultipleOf("test", "body", 6, 0.3) - assert.Nil(t, err) - - err = MultipleOf("test", "body", 1, 0.25) - assert.Nil(t, err) - - err = MultipleOf("test", "body", 8, 0.2) - assert.Nil(t, err) + require.Nil(t, MultipleOf("test", "body", 9, 3)) + require.Nil(t, MultipleOf("test", "body", 9.3, 3.1)) + require.Nil(t, MultipleOf("test", "body", 9.1, 0.1)) + require.Nil(t, MultipleOf("test", "body", 3, 0.3)) + require.Nil(t, MultipleOf("test", "body", 6, 0.3)) + require.Nil(t, MultipleOf("test", "body", 1, 0.25)) + require.Nil(t, MultipleOf("test", "body", 8, 0.2)) // zero - err = MultipleOf("test", "body", 9, 0) - assert.Error(t, err) - - err = MultipleOf("test", "body", 9.1, 0) - assert.Error(t, err) + require.Error(t, MultipleOf("test", "body", 9, 0)) + require.Error(t, MultipleOf("test", "body", 9.1, 0)) // negative - - err = MultipleOf("test", "body", 3, 0.4) - assert.Error(t, err) - - err = MultipleOf("test", "body", 9.1, 0.2) - assert.Error(t, err) - - err = MultipleOf("test", "body", 9.34, 0.1) - assert.Error(t, err) + require.Error(t, MultipleOf("test", "body", 3, 0.4)) + require.Error(t, MultipleOf("test", "body", 9.1, 0.2)) + require.Error(t, MultipleOf("test", "body", 9.34, 0.1)) // error on negative factor - err = MultipleOf("test", "body", 9.34, -0.1) - assert.Error(t, err) + require.Error(t, MultipleOf("test", "body", 9.34, -0.1)) } // Test edge case for Pattern (in regular spec, no invalid regexp should reach there) func TestValues_Pattern_Edgecases(t *testing.T) { - var err *errors.Validation - err = Pattern("path", "in", "pick-a-boo", `.*-[a-z]-.*`) - assert.Nil(t, err) + require.Nil(t, Pattern("path", "in", "pick-a-boo", `.*-[a-z]-.*`)) - // Invalid regexp - err = Pattern("path", "in", "pick-a-boo", `.*-[a(-z]-^).*`) - if assert.NotNil(t, err) { + t.Run("with invalid regexp", func(t *testing.T) { + err := Pattern("path", "in", "pick-a-boo", `.*-[a(-z]-^).*`) + require.Error(t, err) assert.Equal(t, int(err.Code()), int(errors.PatternFailCode)) assert.Contains(t, err.Error(), "pattern is invalid") - } + }) - // Valid regexp, invalid pattern - err = Pattern("path", "in", "pick-8-boo", `.*-[a-z]-.*`) - if assert.NotNil(t, err) { + t.Run("with valid regexp, invalid pattern", func(t *testing.T) { + err := Pattern("path", "in", "pick-8-boo", `.*-[a-z]-.*`) + require.Error(t, err) assert.Equal(t, int(err.Code()), int(errors.PatternFailCode)) assert.NotContains(t, err.Error(), "pattern is invalid") assert.Contains(t, err.Error(), "should match") - } + }) } // Test edge cases in FormatOf @@ -303,211 +245,173 @@ func TestValues_FormatOf_EdgeCases(t *testing.T) { var err *errors.Validation err = FormatOf("path", "in", "bugz", "", nil) - if assert.NotNil(t, err) { - assert.Equal(t, int(err.Code()), int(errors.InvalidTypeCode)) - assert.Contains(t, err.Error(), "bugz is an invalid type name") - } + require.Error(t, err) + assert.Equal(t, int(err.Code()), int(errors.InvalidTypeCode)) + assert.Contains(t, err.Error(), "bugz is an invalid type name") err = FormatOf("path", "in", "bugz", "", strfmt.Default) - if assert.NotNil(t, err) { - assert.Equal(t, int(err.Code()), int(errors.InvalidTypeCode)) - assert.Contains(t, err.Error(), "bugz is an invalid type name") - } + require.Error(t, err) + assert.Equal(t, int(err.Code()), int(errors.InvalidTypeCode)) + assert.Contains(t, err.Error(), "bugz is an invalid type name") } // Test edge cases in MaximumNativeType // not easily exercised with full specs func TestValues_MaximumNative(t *testing.T) { - assert.Nil(t, MaximumNativeType("path", "in", int(5), 10, false)) - assert.Nil(t, MaximumNativeType("path", "in", uint(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", int8(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", uint8(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", int16(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", uint16(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", int32(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", uint32(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", int64(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", uint64(5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", float32(5.5), 10, true)) - assert.Nil(t, MaximumNativeType("path", "in", float64(5.5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", int(5), 10, false)) + require.Nil(t, MaximumNativeType("path", "in", uint(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", int8(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", uint8(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", int16(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", uint16(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", int32(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", uint32(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", int64(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", uint64(5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", float32(5.5), 10, true)) + require.Nil(t, MaximumNativeType("path", "in", float64(5.5), 10, true)) var err *errors.Validation err = MaximumNativeType("path", "in", int32(10), 10, true) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, errors.MaxFailCode) - } + require.Error(t, err) + code := int(err.Code()) + assert.Equal(t, errors.MaxFailCode, code) err = MaximumNativeType("path", "in", uint(10), 10, true) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, errors.MaxFailCode) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, errors.MaxFailCode, code) err = MaximumNativeType("path", "in", int64(12), 10, false) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, errors.MaxFailCode) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, errors.MaxFailCode, code) err = MaximumNativeType("path", "in", float32(12.6), 10, false) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MaxFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MaxFailCode), code) err = MaximumNativeType("path", "in", float64(12.6), 10, false) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MaxFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MaxFailCode), code) err = MaximumNativeType("path", "in", uint(5), -10, true) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MaxFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MaxFailCode), code) } // Test edge cases in MinimumNativeType // not easily exercised with full specs func TestValues_MinimumNative(t *testing.T) { - assert.Nil(t, MinimumNativeType("path", "in", int(5), 0, false)) - assert.Nil(t, MinimumNativeType("path", "in", uint(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", int8(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", uint8(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", int16(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", uint16(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", int32(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", uint32(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", int64(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", uint64(5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", float32(5.5), 0, true)) - assert.Nil(t, MinimumNativeType("path", "in", float64(5.5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", int(5), 0, false)) + require.Nil(t, MinimumNativeType("path", "in", uint(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", int8(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", uint8(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", int16(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", uint16(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", int32(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", uint32(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", int64(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", uint64(5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", float32(5.5), 0, true)) + require.Nil(t, MinimumNativeType("path", "in", float64(5.5), 0, true)) var err *errors.Validation err = MinimumNativeType("path", "in", uint(10), 10, true) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MinFailCode)) - } + require.Error(t, err) + code := int(err.Code()) + assert.Equal(t, int(errors.MinFailCode), code) err = MinimumNativeType("path", "in", uint(10), 10, true) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MinFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MinFailCode), code) err = MinimumNativeType("path", "in", int64(8), 10, false) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MinFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MinFailCode), code) err = MinimumNativeType("path", "in", float32(12.6), 20, false) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MinFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MinFailCode), code) err = MinimumNativeType("path", "in", float64(12.6), 20, false) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MinFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MinFailCode), code) - err = MinimumNativeType("path", "in", uint(5), -10, true) - assert.Nil(t, err) + require.Nil(t, MinimumNativeType("path", "in", uint(5), -10, true)) } // Test edge cases in MaximumNativeType // not easily exercised with full specs func TestValues_MultipleOfNative(t *testing.T) { - assert.Nil(t, MultipleOfNativeType("path", "in", int(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", uint(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", int8(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", uint8(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", int16(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", uint16(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", int32(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", uint32(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", int64(5), 1)) - assert.Nil(t, MultipleOfNativeType("path", "in", uint64(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", int(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", uint(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", int8(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", uint8(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", int16(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", uint16(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", int32(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", uint32(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", int64(5), 1)) + require.Nil(t, MultipleOfNativeType("path", "in", uint64(5), 1)) var err *errors.Validation err = MultipleOfNativeType("path", "in", int64(5), 0) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MultipleOfMustBePositiveCode)) - } + require.Error(t, err) + code := int(err.Code()) + assert.Equal(t, int(errors.MultipleOfMustBePositiveCode), code) err = MultipleOfNativeType("path", "in", uint64(5), 0) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MultipleOfMustBePositiveCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MultipleOfMustBePositiveCode), code) err = MultipleOfNativeType("path", "in", int64(5), -1) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MultipleOfMustBePositiveCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MultipleOfMustBePositiveCode), code) err = MultipleOfNativeType("path", "in", int64(11), 5) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MultipleOfFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MultipleOfFailCode), code) err = MultipleOfNativeType("path", "in", uint64(11), 5) - if assert.NotNil(t, err) { - code := int(err.Code()) - assert.Equal(t, code, int(errors.MultipleOfFailCode)) - } + require.Error(t, err) + code = int(err.Code()) + assert.Equal(t, int(errors.MultipleOfFailCode), code) } // Test edge cases in IsValueValidAgainstRange -// not easily exercised with full specs +// not easily exercised with full specs: we did not simulate these formats in full specs func TestValues_IsValueValidAgainstRange(t *testing.T) { - var err error - - // We did not simulate these formats in full specs - err = IsValueValidAgainstRange(float32(123.45), "number", "float32", "prefix", "path") - assert.NoError(t, err) - - err = IsValueValidAgainstRange(float64(123.45), "number", "float32", "prefix", "path") - assert.NoError(t, err) - - err = IsValueValidAgainstRange(int64(123), "number", "float", "prefix", "path") - assert.NoError(t, err) - - err = IsValueValidAgainstRange(int64(123), "integer", "", "prefix", "path") - assert.NoError(t, err) - - err = IsValueValidAgainstRange(int64(123), "integer", "int64", "prefix", "path") - assert.NoError(t, err) - - err = IsValueValidAgainstRange(int64(123), "integer", "uint64", "prefix", "path") - assert.NoError(t, err) + require.NoError(t, IsValueValidAgainstRange(float32(123.45), "number", "float32", "prefix", "path")) + require.NoError(t, IsValueValidAgainstRange(float64(123.45), "number", "float32", "prefix", "path")) + require.NoError(t, IsValueValidAgainstRange(int64(123), "number", "float", "prefix", "path")) + require.NoError(t, IsValueValidAgainstRange(int64(123), "integer", "", "prefix", "path")) + require.NoError(t, IsValueValidAgainstRange(int64(123), "integer", "int64", "prefix", "path")) + require.NoError(t, IsValueValidAgainstRange(int64(123), "integer", "uint64", "prefix", "path")) + require.NoError(t, IsValueValidAgainstRange(int64(2147483647), "integer", "int32", "prefix", "path")) + require.NoError(t, IsValueValidAgainstRange(int64(2147483647), "integer", "uint32", "prefix", "path")) + var err error // Error case (do not occur in normal course of a validation) err = IsValueValidAgainstRange(float64(math.MaxFloat64), "integer", "", "prefix", "path") - if assert.Error(t, err) { - assert.Contains(t, err.Error(), "must be of type integer (default format)") - } + require.Error(t, err) + assert.Contains(t, err.Error(), "must be of type integer (default format)") // Checking a few limits err = IsValueValidAgainstRange("123", "number", "", "prefix", "path") - if assert.Error(t, err) { - assert.Contains(t, err.Error(), "called with invalid (non numeric) val type") - } - - err = IsValueValidAgainstRange(int64(2147483647), "integer", "int32", "prefix", "path") - assert.NoError(t, err) - - err = IsValueValidAgainstRange(int64(2147483647), "integer", "uint32", "prefix", "path") - assert.NoError(t, err) + require.Error(t, err) + assert.Contains(t, err.Error(), "called with invalid (non numeric) val type") }