diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml deleted file mode 100644 index 4c99b3e..0000000 --- a/.github/workflows/ci.yaml +++ /dev/null @@ -1,48 +0,0 @@ -name: Verify - -on: [push, pull_request] - -jobs: - 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@v2 - with: - args: --timeout=5m - - build: - runs-on: ${{ matrix.os }} - - needs: [lint] - - strategy: - matrix: - # No Windows this time. Some tests expect Unix-style paths. - os: [ ubuntu-latest, macos-latest ] - fail-fast: false - - steps: - - uses: actions/checkout@v2 - - - name: Set up Go - uses: actions/setup-go@v2 - with: - go-version: 1.19 - cache: true - - - name: Install Tools - run: go install gotest.tools/gotestsum@latest - - - name: Test - run: gotestsum -- -race -timeout=20m -coverprofile=coverage_txt -covermode=atomic ./... - - - uses: codecov/codecov-action@v3 - with: - files: coverage_txt - 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/.gitignore b/.gitignore index d69b53a..c4b1b64 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ secrets.yml vendor Godeps .idea +*.out diff --git a/.golangci.yml b/.golangci.yml index bf503e4..22f8d21 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -4,51 +4,58 @@ linters-settings: golint: min-confidence: 0 gocyclo: - min-complexity: 25 + min-complexity: 45 maligned: suggest-new: true dupl: - threshold: 100 + threshold: 200 goconst: - min-len: 3 - min-occurrences: 2 + min-len: 2 + min-occurrences: 3 linters: enable-all: true disable: - maligned + - unparam - lll - gochecknoinits - gochecknoglobals - - nlreturn - - testpackage + - funlen + - godox + - gocognit + - whitespace + - wsl - wrapcheck + - testpackage + - nlreturn - gomnd - - exhaustive - exhaustivestruct - goerr113 - - wsl - - whitespace - - gofumpt - - godot + - errorlint - nestif - - godox - - funlen - - gci - - gocognit + - godot + - gofumpt - paralleltest + - tparallel - thelper - ifshort - - gomoddirectives - - cyclop - - forcetypeassert - - ireturn - - tagliatelle - - varnamelen - - goimports - - tenv - - golint - exhaustruct - - nilnil + - varnamelen + - gci + - depguard + - errchkjson + - inamedparam - nonamedreturns + - musttag + - ireturn + - forcetypeassert + - cyclop + # deprecated linters + - deadcode + - interfacer + - scopelint + - varcheck + - structcheck + - golint - nosnakecase diff --git a/README.md b/README.md index 217f6fa..93a976c 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ -# Swag [![Build Status](https://travis-ci.org/go-openapi/swag.svg?branch=master)](https://travis-ci.org/go-openapi/swag) [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) +# Swag [![Build Status](https://github.com/go-openapi/swag/actions/workflows/go-test.yaml/badge.svg)](https://github.com/go-openapi/swag/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) +[![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/swag/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/swag?status.svg)](http://godoc.org/github.com/go-openapi/swag) [![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/swag)](https://goreportcard.com/report/github.com/go-openapi/swag) @@ -18,4 +19,4 @@ You may also use it standalone for your projects. This repo has only few dependencies outside of the standard library: -* YAML utilities depend on gopkg.in/yaml.v2 +* YAML utilities depend on gopkg.in/yaml.v3 diff --git a/convert_test.go b/convert_test.go index 77a9049..fd531e1 100644 --- a/convert_test.go +++ b/convert_test.go @@ -20,22 +20,30 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +func errMsg(f string) string { + const ( + expectedQuote = "expected '" + errSuffix = "' to generate an error" + ) + + return expectedQuote + f + errSuffix +} + // These are really dumb tests func TestConvertBool(t *testing.T) { for k := range evaluatesAsTrue { r, err := ConvertBool(k) - if assert.NoError(t, err) { - assert.True(t, r) - } + require.NoError(t, err) + assert.True(t, r) } for _, k := range []string{"a", "", "0", "false", "unchecked"} { r, err := ConvertBool(k) - if assert.NoError(t, err) { - assert.False(t, r) - } + require.NoError(t, err) + assert.False(t, r) } } @@ -45,13 +53,12 @@ func TestConvertFloat32(t *testing.T) { for _, f := range validFloats { c, err := ConvertFloat32(FormatFloat32(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidFloats { _, err := ConvertFloat32(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -61,13 +68,12 @@ func TestConvertFloat64(t *testing.T) { for _, f := range validFloats { c, err := ConvertFloat64(FormatFloat64(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidFloats { _, err := ConvertFloat64(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -77,13 +83,12 @@ func TestConvertInt8(t *testing.T) { for _, f := range validInts { c, err := ConvertInt8(FormatInt8(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidInts { _, err := ConvertInt8(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -93,13 +98,12 @@ func TestConvertInt16(t *testing.T) { for _, f := range validInts { c, err := ConvertInt16(FormatInt16(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidInts { _, err := ConvertInt16(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -109,13 +113,12 @@ func TestConvertInt32(t *testing.T) { for _, f := range validInts { c, err := ConvertInt32(FormatInt32(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidInts { _, err := ConvertInt32(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -125,13 +128,12 @@ func TestConvertInt64(t *testing.T) { for _, f := range validInts { c, err := ConvertInt64(FormatInt64(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidInts { _, err := ConvertInt64(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -141,13 +143,12 @@ func TestConvertUint8(t *testing.T) { for _, f := range validInts { c, err := ConvertUint8(FormatUint8(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidInts { _, err := ConvertUint8(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -157,13 +158,12 @@ func TestConvertUint16(t *testing.T) { for _, f := range validUints { c, err := ConvertUint16(FormatUint16(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidUints { _, err := ConvertUint16(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -173,13 +173,12 @@ func TestConvertUint32(t *testing.T) { for _, f := range validUints { c, err := ConvertUint32(FormatUint32(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidUints { _, err := ConvertUint32(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } @@ -189,13 +188,12 @@ func TestConvertUint64(t *testing.T) { for _, f := range validUints { c, err := ConvertUint64(FormatUint64(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } + require.NoError(t, err) + assert.EqualValues(t, f, c) } for _, f := range invalidUints { _, err := ConvertUint64(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") + require.Error(t, err, errMsg(f)) } } diff --git a/convert_types_test.go b/convert_types_test.go index f5c736f..0e41bc0 100644 --- a/convert_types_test.go +++ b/convert_types_test.go @@ -20,71 +20,15 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func assertSingleValue(t *testing.T, inElem, elem reflect.Value, expectPointer bool, idx int) { - if !assert.Truef(t, - (elem.Kind() == reflect.Ptr) == expectPointer, - "Unexpected expectPointer=%t value type", expectPointer) { - return - } - if inElem.Kind() == reflect.Ptr && !inElem.IsNil() { - inElem = reflect.Indirect(inElem) - } - if elem.Kind() == reflect.Ptr && !elem.IsNil() { - elem = reflect.Indirect(elem) - } - - if !assert.Truef(t, - (elem.Kind() == reflect.Ptr && elem.IsNil()) || IsZero(elem.Interface()) == - (inElem.Kind() == reflect.Ptr && inElem.IsNil()) || IsZero(inElem.Interface()), - "Unexpected nil pointer at idx %d", idx) { - return - } - - if !((elem.Kind() == reflect.Ptr && elem.IsNil()) || IsZero(elem.Interface())) { - if !assert.IsTypef(t, inElem.Interface(), elem.Interface(), "Expected in/out to match types") { - return - } - assert.EqualValuesf(t, inElem.Interface(), elem.Interface(), "Unexpected value at idx %d: %v", idx, elem.Interface()) - } -} - -// assertValues checks equivalent representation pointer vs values for single var, slices and maps -func assertValues(t *testing.T, in, out interface{}, expectPointer bool, idx int) { - vin := reflect.ValueOf(in) - vout := reflect.ValueOf(out) - switch vin.Kind() { - case reflect.Slice, reflect.Map: - if !assert.Equalf(t, vin.Kind(), vout.Kind(), "Unexpected output type at idx %d", idx) || - !assert.Equalf(t, vin.Len(), vout.Len(), "Unexpected len at idx %d", idx) { - break - } - var elem, inElem reflect.Value - for i := 0; i < vin.Len(); i++ { - if vin.Kind() == reflect.Slice { - elem = vout.Index(i) - inElem = vin.Index(i) - } else if vin.Kind() == reflect.Map { - keys := vin.MapKeys() - elem = vout.MapIndex(keys[i]) - inElem = vout.MapIndex(keys[i]) - } - assertSingleValue(t, inElem, elem, expectPointer, idx) - } - default: - inElem := vin - elem := vout - assertSingleValue(t, inElem, elem, expectPointer, idx) +func TestStringSlice(t *testing.T) { + testCasesStringSlice := [][]string{ + {"a", "b", "c", "d", "e"}, + {"a", "b", "", "", "e"}, } -} - -var testCasesStringSlice = [][]string{ - {"a", "b", "c", "d", "e"}, - {"a", "b", "", "", "e"}, -} -func TestStringSlice(t *testing.T) { for idx, in := range testCasesStringSlice { if in == nil { continue @@ -97,11 +41,11 @@ func TestStringSlice(t *testing.T) { } } -var testCasesStringValueSlice = [][]*string{ - {String("a"), String("b"), nil, String("c")}, -} - func TestStringValueSlice(t *testing.T) { + testCasesStringValueSlice := [][]*string{ + {String("a"), String("b"), nil, String("c")}, + } + for idx, in := range testCasesStringValueSlice { if in == nil { continue @@ -114,11 +58,11 @@ func TestStringValueSlice(t *testing.T) { } } -var testCasesStringMap = []map[string]string{ - {"a": "1", "b": "2", "c": "3"}, -} - func TestStringMap(t *testing.T) { + testCasesStringMap := []map[string]string{ + {"a": "1", "b": "2", "c": "3"}, + } + for idx, in := range testCasesStringMap { if in == nil { continue @@ -131,11 +75,11 @@ func TestStringMap(t *testing.T) { } } -var testCasesBoolSlice = [][]bool{ - {true, true, false, false}, -} - func TestBoolSlice(t *testing.T) { + testCasesBoolSlice := [][]bool{ + {true, true, false, false}, + } + for idx, in := range testCasesBoolSlice { if in == nil { continue @@ -148,11 +92,11 @@ func TestBoolSlice(t *testing.T) { } } -var testCasesBoolValueSlice = [][]*bool{ - {Bool(true), Bool(true), Bool(false), Bool(false)}, -} - func TestBoolValueSlice(t *testing.T) { + testCasesBoolValueSlice := [][]*bool{ + {Bool(true), Bool(true), Bool(false), Bool(false)}, + } + for idx, in := range testCasesBoolValueSlice { if in == nil { continue @@ -165,11 +109,11 @@ func TestBoolValueSlice(t *testing.T) { } } -var testCasesBoolMap = []map[string]bool{ - {"a": true, "b": false, "c": true}, -} - func TestBoolMap(t *testing.T) { + testCasesBoolMap := []map[string]bool{ + {"a": true, "b": false, "c": true}, + } + for idx, in := range testCasesBoolMap { if in == nil { continue @@ -182,11 +126,11 @@ func TestBoolMap(t *testing.T) { } } -var testCasesIntSlice = [][]int{ - {1, 2, 3, 4}, -} - func TestIntSlice(t *testing.T) { + testCasesIntSlice := [][]int{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesIntSlice { if in == nil { continue @@ -199,11 +143,11 @@ func TestIntSlice(t *testing.T) { } } -var testCasesIntValueSlice = [][]*int{ - {Int(1), Int(2), Int(3), Int(4)}, -} - func TestIntValueSlice(t *testing.T) { + testCasesIntValueSlice := [][]*int{ + {Int(1), Int(2), Int(3), Int(4)}, + } + for idx, in := range testCasesIntValueSlice { if in == nil { continue @@ -216,11 +160,11 @@ func TestIntValueSlice(t *testing.T) { } } -var testCasesIntMap = []map[string]int{ - {"a": 3, "b": 2, "c": 1}, -} - func TestIntMap(t *testing.T) { + testCasesIntMap := []map[string]int{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesIntMap { if in == nil { continue @@ -233,11 +177,11 @@ func TestIntMap(t *testing.T) { } } -var testCasesInt64Slice = [][]int64{ - {1, 2, 3, 4}, -} - func TestInt64Slice(t *testing.T) { + testCasesInt64Slice := [][]int64{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesInt64Slice { if in == nil { continue @@ -250,11 +194,11 @@ func TestInt64Slice(t *testing.T) { } } -var testCasesInt64ValueSlice = [][]*int64{ - {Int64(1), Int64(2), Int64(3), Int64(4)}, -} - func TestInt64ValueSlice(t *testing.T) { + testCasesInt64ValueSlice := [][]*int64{ + {Int64(1), Int64(2), Int64(3), Int64(4)}, + } + for idx, in := range testCasesInt64ValueSlice { if in == nil { continue @@ -267,11 +211,11 @@ func TestInt64ValueSlice(t *testing.T) { } } -var testCasesInt64Map = []map[string]int64{ - {"a": 3, "b": 2, "c": 1}, -} - func TestInt64Map(t *testing.T) { + testCasesInt64Map := []map[string]int64{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesInt64Map { if in == nil { continue @@ -284,11 +228,11 @@ func TestInt64Map(t *testing.T) { } } -var testCasesFloat32Slice = [][]float32{ - {1, 2, 3, 4}, -} - func TestFloat32Slice(t *testing.T) { + testCasesFloat32Slice := [][]float32{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesFloat32Slice { if in == nil { continue @@ -302,11 +246,11 @@ func TestFloat32Slice(t *testing.T) { } } -var testCasesFloat64Slice = [][]float64{ - {1, 2, 3, 4}, -} - func TestFloat64Slice(t *testing.T) { + testCasesFloat64Slice := [][]float64{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesFloat64Slice { if in == nil { continue @@ -319,11 +263,11 @@ func TestFloat64Slice(t *testing.T) { } } -var testCasesUintSlice = [][]uint{ - {1, 2, 3, 4}, -} - func TestUintSlice(t *testing.T) { + testCasesUintSlice := [][]uint{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesUintSlice { if in == nil { continue @@ -336,9 +280,9 @@ func TestUintSlice(t *testing.T) { } } -var testCasesUintValueSlice = [][]*uint{} - func TestUintValueSlice(t *testing.T) { + testCasesUintValueSlice := [][]*uint{} + for idx, in := range testCasesUintValueSlice { if in == nil { continue @@ -351,11 +295,11 @@ func TestUintValueSlice(t *testing.T) { } } -var testCasesUintMap = []map[string]uint{ - {"a": 3, "b": 2, "c": 1}, -} - func TestUintMap(t *testing.T) { + testCasesUintMap := []map[string]uint{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesUintMap { if in == nil { continue @@ -368,11 +312,11 @@ func TestUintMap(t *testing.T) { } } -var testCasesUint16Slice = [][]uint16{ - {1, 2, 3, 4}, -} - func TestUint16Slice(t *testing.T) { + testCasesUint16Slice := [][]uint16{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesUint16Slice { if in == nil { continue @@ -386,9 +330,9 @@ func TestUint16Slice(t *testing.T) { } } -var testCasesUint16ValueSlice = [][]*uint16{} - func TestUint16ValueSlice(t *testing.T) { + testCasesUint16ValueSlice := [][]*uint16{} + for idx, in := range testCasesUint16ValueSlice { if in == nil { continue @@ -402,11 +346,11 @@ func TestUint16ValueSlice(t *testing.T) { } } -var testCasesUint16Map = []map[string]uint16{ - {"a": 3, "b": 2, "c": 1}, -} - func TestUint16Map(t *testing.T) { + testCasesUint16Map := []map[string]uint16{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesUint16Map { if in == nil { continue @@ -420,11 +364,11 @@ func TestUint16Map(t *testing.T) { } } -var testCasesUint64Slice = [][]uint64{ - {1, 2, 3, 4}, -} - func TestUint64Slice(t *testing.T) { + testCasesUint64Slice := [][]uint64{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesUint64Slice { if in == nil { continue @@ -437,9 +381,9 @@ func TestUint64Slice(t *testing.T) { } } -var testCasesUint64ValueSlice = [][]*uint64{} - func TestUint64ValueSlice(t *testing.T) { + testCasesUint64ValueSlice := [][]*uint64{} + for idx, in := range testCasesUint64ValueSlice { if in == nil { continue @@ -452,11 +396,11 @@ func TestUint64ValueSlice(t *testing.T) { } } -var testCasesUint64Map = []map[string]uint64{ - {"a": 3, "b": 2, "c": 1}, -} - func TestUint64Map(t *testing.T) { + testCasesUint64Map := []map[string]uint64{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesUint64Map { if in == nil { continue @@ -469,9 +413,9 @@ func TestUint64Map(t *testing.T) { } } -var testCasesFloat32ValueSlice = [][]*float32{} - func TestFloat32ValueSlice(t *testing.T) { + testCasesFloat32ValueSlice := [][]*float32{} + for idx, in := range testCasesFloat32ValueSlice { if in == nil { continue @@ -485,11 +429,11 @@ func TestFloat32ValueSlice(t *testing.T) { } } -var testCasesFloat32Map = []map[string]float32{ - {"a": 3, "b": 2, "c": 1}, -} - func TestFloat32Map(t *testing.T) { + testCasesFloat32Map := []map[string]float32{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesFloat32Map { if in == nil { continue @@ -503,9 +447,9 @@ func TestFloat32Map(t *testing.T) { } } -var testCasesFloat64ValueSlice = [][]*float64{} - func TestFloat64ValueSlice(t *testing.T) { + testCasesFloat64ValueSlice := [][]*float64{} + for idx, in := range testCasesFloat64ValueSlice { if in == nil { continue @@ -518,11 +462,11 @@ func TestFloat64ValueSlice(t *testing.T) { } } -var testCasesFloat64Map = []map[string]float64{ - {"a": 3, "b": 2, "c": 1}, -} - func TestFloat64Map(t *testing.T) { + testCasesFloat64Map := []map[string]float64{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesFloat64Map { if in == nil { continue @@ -535,11 +479,11 @@ func TestFloat64Map(t *testing.T) { } } -var testCasesTimeSlice = [][]time.Time{ - {time.Now(), time.Now().AddDate(100, 0, 0)}, -} - func TestTimeSlice(t *testing.T) { + testCasesTimeSlice := [][]time.Time{ + {time.Now(), time.Now().AddDate(100, 0, 0)}, + } + for idx, in := range testCasesTimeSlice { if in == nil { continue @@ -552,11 +496,11 @@ func TestTimeSlice(t *testing.T) { } } -var testCasesTimeValueSlice = [][]*time.Time{ - {Time(time.Now()), Time(time.Now().AddDate(100, 0, 0))}, -} - func TestTimeValueSlice(t *testing.T) { + testCasesTimeValueSlice := [][]*time.Time{ + {Time(time.Now()), Time(time.Now().AddDate(100, 0, 0))}, + } + for idx, in := range testCasesTimeValueSlice { if in == nil { continue @@ -569,11 +513,11 @@ func TestTimeValueSlice(t *testing.T) { } } -var testCasesTimeMap = []map[string]time.Time{ - {"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()}, -} - func TestTimeMap(t *testing.T) { + testCasesTimeMap := []map[string]time.Time{ + {"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()}, + } + for idx, in := range testCasesTimeMap { if in == nil { continue @@ -586,11 +530,11 @@ func TestTimeMap(t *testing.T) { } } -var testCasesInt32Slice = [][]int32{ - {1, 2, 3, 4}, -} - func TestInt32Slice(t *testing.T) { + testCasesInt32Slice := [][]int32{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesInt32Slice { if in == nil { continue @@ -603,11 +547,11 @@ func TestInt32Slice(t *testing.T) { } } -var testCasesInt32ValueSlice = [][]*int32{ - {Int32(1), Int32(2), Int32(3), Int32(4)}, -} - func TestInt32ValueSlice(t *testing.T) { + testCasesInt32ValueSlice := [][]*int32{ + {Int32(1), Int32(2), Int32(3), Int32(4)}, + } + for idx, in := range testCasesInt32ValueSlice { if in == nil { continue @@ -620,11 +564,11 @@ func TestInt32ValueSlice(t *testing.T) { } } -var testCasesInt32Map = []map[string]int32{ - {"a": 3, "b": 2, "c": 1}, -} - func TestInt32Map(t *testing.T) { + testCasesInt32Map := []map[string]int32{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesInt32Map { if in == nil { continue @@ -637,11 +581,11 @@ func TestInt32Map(t *testing.T) { } } -var testCasesUint32Slice = [][]uint32{ - {1, 2, 3, 4}, -} - func TestUint32Slice(t *testing.T) { + testCasesUint32Slice := [][]uint32{ + {1, 2, 3, 4}, + } + for idx, in := range testCasesUint32Slice { if in == nil { continue @@ -654,11 +598,11 @@ func TestUint32Slice(t *testing.T) { } } -var testCasesUint32ValueSlice = [][]*uint32{ - {Uint32(1), Uint32(2), Uint32(3), Uint32(4)}, -} - func TestUint32ValueSlice(t *testing.T) { + testCasesUint32ValueSlice := [][]*uint32{ + {Uint32(1), Uint32(2), Uint32(3), Uint32(4)}, + } + for idx, in := range testCasesUint32ValueSlice { if in == nil { continue @@ -671,11 +615,11 @@ func TestUint32ValueSlice(t *testing.T) { } } -var testCasesUint32Map = []map[string]uint32{ - {"a": 3, "b": 2, "c": 1}, -} - func TestUint32Map(t *testing.T) { + testCasesUint32Map := []map[string]uint32{ + {"a": 3, "b": 2, "c": 1}, + } + for idx, in := range testCasesUint32Map { if in == nil { continue @@ -688,9 +632,9 @@ func TestUint32Map(t *testing.T) { } } -var testCasesString = []string{"a", "b", "c", "d", "e", ""} - func TestStringValue(t *testing.T) { + testCasesString := []string{"a", "b", "c", "d", "e", ""} + for idx, in := range testCasesString { out := String(in) assertValues(t, in, out, true, idx) @@ -701,9 +645,9 @@ func TestStringValue(t *testing.T) { assert.Zerof(t, StringValue(nil), "expected conversion from nil to return zero value") } -var testCasesBool = []bool{true, false} - func TestBoolValue(t *testing.T) { + testCasesBool := []bool{true, false} + for idx, in := range testCasesBool { out := Bool(in) assertValues(t, in, out, true, idx) @@ -714,9 +658,9 @@ func TestBoolValue(t *testing.T) { assert.Zerof(t, BoolValue(nil), "expected conversion from nil to return zero value") } -var testCasesInt = []int{1, 2, 3, 0} - func TestIntValue(t *testing.T) { + testCasesInt := []int{1, 2, 3, 0} + for idx, in := range testCasesInt { out := Int(in) assertValues(t, in, out, true, idx) @@ -727,9 +671,9 @@ func TestIntValue(t *testing.T) { assert.Zerof(t, IntValue(nil), "expected conversion from nil to return zero value") } -var testCasesInt32 = []int32{1, 2, 3, 0} - func TestInt32Value(t *testing.T) { + testCasesInt32 := []int32{1, 2, 3, 0} + for idx, in := range testCasesInt32 { out := Int32(in) assertValues(t, in, out, true, idx) @@ -740,9 +684,9 @@ func TestInt32Value(t *testing.T) { assert.Zerof(t, Int32Value(nil), "expected conversion from nil to return zero value") } -var testCasesInt64 = []int64{1, 2, 3, 0} - func TestInt64Value(t *testing.T) { + testCasesInt64 := []int64{1, 2, 3, 0} + for idx, in := range testCasesInt64 { out := Int64(in) assertValues(t, in, out, true, idx) @@ -753,9 +697,9 @@ func TestInt64Value(t *testing.T) { assert.Zerof(t, Int64Value(nil), "expected conversion from nil to return zero value") } -var testCasesUint = []uint{1, 2, 3, 0} - func TestUintValue(t *testing.T) { + testCasesUint := []uint{1, 2, 3, 0} + for idx, in := range testCasesUint { out := Uint(in) assertValues(t, in, out, true, idx) @@ -766,9 +710,9 @@ func TestUintValue(t *testing.T) { assert.Zerof(t, UintValue(nil), "expected conversion from nil to return zero value") } -var testCasesUint32 = []uint32{1, 2, 3, 0} - func TestUint32Value(t *testing.T) { + testCasesUint32 := []uint32{1, 2, 3, 0} + for idx, in := range testCasesUint32 { out := Uint32(in) assertValues(t, in, out, true, idx) @@ -779,9 +723,9 @@ func TestUint32Value(t *testing.T) { assert.Zerof(t, Uint32Value(nil), "expected conversion from nil to return zero value") } -var testCasesUint64 = []uint64{1, 2, 3, 0} - func TestUint64Value(t *testing.T) { + testCasesUint64 := []uint64{1, 2, 3, 0} + for idx, in := range testCasesUint64 { out := Uint64(in) assertValues(t, in, out, true, idx) @@ -792,9 +736,9 @@ func TestUint64Value(t *testing.T) { assert.Zerof(t, Uint64Value(nil), "expected conversion from nil to return zero value") } -var testCasesFloat32 = []float32{1, 2, 3, 0} - func TestFloat32Value(t *testing.T) { + testCasesFloat32 := []float32{1, 2, 3, 0} + for idx, in := range testCasesFloat32 { out := Float32(in) assertValues(t, in, out, true, idx) @@ -806,9 +750,9 @@ func TestFloat32Value(t *testing.T) { assert.Zerof(t, Float32Value(nil), "expected conversion from nil to return zero value") } -var testCasesFloat64 = []float64{1, 2, 3, 0} - func TestFloat64Value(t *testing.T) { + testCasesFloat64 := []float64{1, 2, 3, 0} + for idx, in := range testCasesFloat64 { out := Float64(in) assertValues(t, in, out, true, idx) @@ -819,11 +763,11 @@ func TestFloat64Value(t *testing.T) { assert.Zerof(t, Float64Value(nil), "expected conversion from nil to return zero value") } -var testCasesTime = []time.Time{ - time.Now().AddDate(-100, 0, 0), time.Now(), -} - func TestTimeValue(t *testing.T) { + testCasesTime := []time.Time{ + time.Now().AddDate(-100, 0, 0), time.Now(), + } + for idx, in := range testCasesTime { out := Time(in) assertValues(t, in, out, true, idx) @@ -833,3 +777,64 @@ func TestTimeValue(t *testing.T) { } assert.Zerof(t, TimeValue(nil), "expected conversion from nil to return zero value") } + +func assertSingleValue(t *testing.T, inElem, elem reflect.Value, expectPointer bool, idx int) { + require.Equalf(t, + expectPointer, (elem.Kind() == reflect.Ptr), + "unexpected expectPointer=%t value type", expectPointer, + ) + + if inElem.Kind() == reflect.Ptr && !inElem.IsNil() { + inElem = reflect.Indirect(inElem) + } + + if elem.Kind() == reflect.Ptr && !elem.IsNil() { + elem = reflect.Indirect(elem) + } + + require.Truef(t, + (elem.Kind() == reflect.Ptr && elem.IsNil()) || + IsZero(elem.Interface()) == (inElem.Kind() == reflect.Ptr && inElem.IsNil()) || + IsZero(inElem.Interface()), + "unexpected nil pointer at idx %d", idx, + ) + + if !((elem.Kind() == reflect.Ptr && elem.IsNil()) || IsZero(elem.Interface())) { + require.IsTypef(t, inElem.Interface(), elem.Interface(), "Expected in/out to match types") + assert.EqualValuesf(t, inElem.Interface(), elem.Interface(), "Unexpected value at idx %d: %v", idx, elem.Interface()) + } +} + +// assertValues checks equivalent representation pointer vs values for single var, slices and maps +func assertValues(t *testing.T, in, out interface{}, expectPointer bool, idx int) { + vin := reflect.ValueOf(in) + vout := reflect.ValueOf(out) + + switch vin.Kind() { //nolint:exhaustive + case reflect.Slice, reflect.Map: + require.Equalf(t, vin.Kind(), vout.Kind(), "Unexpected output type at idx %d", idx) + require.Equalf(t, vin.Len(), vout.Len(), "Unexpected len at idx %d", idx) + + var elem, inElem reflect.Value + for i := 0; i < vin.Len(); i++ { + switch vin.Kind() { //nolint:exhaustive + case reflect.Slice: + elem = vout.Index(i) + inElem = vin.Index(i) + case reflect.Map: + keys := vin.MapKeys() + elem = vout.MapIndex(keys[i]) + inElem = vout.MapIndex(keys[i]) + default: + } + + assertSingleValue(t, inElem, elem, expectPointer, idx) + } + + default: + inElem := vin + elem := vout + + assertSingleValue(t, inElem, elem, expectPointer, idx) + } +} diff --git a/go.mod b/go.mod index 60144c0..2c00743 100644 --- a/go.mod +++ b/go.mod @@ -14,8 +14,4 @@ require ( gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect ) -// replace github.com/golang/lint => golang.org/x/lint v0.0.0-20190409202823-959b441ac422 - -// replace sourcegraph.com/sourcegraph/go-diff => github.com/sourcegraph/go-diff v0.5.1 - -go 1.18 +go 1.19 diff --git a/post_go19.go b/initialism_index.go similarity index 100% rename from post_go19.go rename to initialism_index.go diff --git a/json_test.go b/json_test.go index 6c07d6f..266869c 100644 --- a/json_test.go +++ b/json_test.go @@ -170,13 +170,13 @@ func TestJSONConcatenation(t *testing.T) { } type SharedCounters struct { - Counter1 int64 `json:"Counter1,omitempty"` - Counter2 int64 `json:"Counter2:,omitempty"` + Counter1 int64 `json:"counter1,omitempty"` + Counter2 int64 `json:"counter2:,omitempty"` } type AggregationObject struct { SharedCounters - Count int64 `json:"Count,omitempty"` + Count int64 `json:"count,omitempty"` } func (m *AggregationObject) UnmarshalJSON(raw []byte) error { @@ -189,7 +189,7 @@ func (m *AggregationObject) UnmarshalJSON(raw []byte) error { // now for regular properties var propsAggregationObject struct { - Count int64 `json:"Count,omitempty"` + Count int64 `json:"count,omitempty"` } if err := ReadJSON(raw, &propsAggregationObject); err != nil { return err @@ -211,7 +211,7 @@ func (m AggregationObject) MarshalJSON() ([]byte, error) { // now for regular properties var propsAggregationObject struct { - Count int64 `json:"Count,omitempty"` + Count int64 `json:"count,omitempty"` } propsAggregationObject.Count = m.Count @@ -241,7 +241,7 @@ func TestIssue2350(t *testing.T) { require.NoError(t, obj11.UnmarshalJSON(rtjson)) require.Equal(t, obj, obj11) - jsons := `{"Counter1":123,"Counter2:":456,"Count":999}` + jsons := `{"counter1":123,"counter2:":456,"count":999}` var obj2 AggregationObject require.NoError(t, ReadJSON([]byte(jsons), &obj2)) require.Equal(t, AggregationObject{SharedCounters: SharedCounters{Counter1: 123, Counter2: 456}, Count: 999}, obj2) diff --git a/loading.go b/loading.go index 00038c3..714bde3 100644 --- a/loading.go +++ b/loading.go @@ -56,7 +56,7 @@ func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func( return remote } return func(pth string) ([]byte, error) { - upth, err := pathUnescape(pth) + upth, err := url.PathUnescape(pth) if err != nil { return nil, err } diff --git a/loading_test.go b/loading_test.go index dda4606..f37ee88 100644 --- a/loading_test.go +++ b/loading_test.go @@ -17,9 +17,11 @@ package swag import ( "net/http" "net/http/httptest" + "runtime" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -33,7 +35,7 @@ const ( func TestLoadFromHTTP(t *testing.T) { _, err := LoadFromFileOrHTTP("httx://12394:abd") - assert.Error(t, err) + require.Error(t, err) serv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusNotFound) @@ -41,7 +43,7 @@ func TestLoadFromHTTP(t *testing.T) { defer serv.Close() _, err = LoadFromFileOrHTTP(serv.URL) - assert.Error(t, err) + require.Error(t, err) ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusOK) @@ -50,7 +52,7 @@ func TestLoadFromHTTP(t *testing.T) { defer ts2.Close() d, err := LoadFromFileOrHTTP(ts2.URL) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("the content"), d) ts3 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { @@ -65,21 +67,21 @@ func TestLoadFromHTTP(t *testing.T) { // no auth _, err = LoadFromFileOrHTTP(ts3.URL) - assert.Error(t, err) + require.Error(t, err) // basic auth, invalide credentials LoadHTTPBasicAuthUsername = validUsername LoadHTTPBasicAuthPassword = invalidPassword _, err = LoadFromFileOrHTTP(ts3.URL) - assert.Error(t, err) + require.Error(t, err) // basic auth, valid credentials LoadHTTPBasicAuthUsername = validUsername LoadHTTPBasicAuthPassword = validPassword _, err = LoadFromFileOrHTTP(ts3.URL) - assert.NoError(t, err) + require.NoError(t, err) ts4 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { myHeaders := r.Header[sharedHeaderKey] @@ -99,12 +101,12 @@ func TestLoadFromHTTP(t *testing.T) { defer ts4.Close() _, err = LoadFromFileOrHTTP(ts4.URL) - assert.Error(t, err) + require.Error(t, err) LoadHTTPCustomHeaders[sharedHeaderKey] = sharedHeaderValue _, err = LoadFromFileOrHTTP(ts4.URL) - assert.NoError(t, err) + require.NoError(t, err) // clean up for future tests LoadHTTPBasicAuthUsername = "" @@ -114,7 +116,7 @@ func TestLoadFromHTTP(t *testing.T) { func TestLoadHTTPBytes(t *testing.T) { _, err := LoadFromFileOrHTTP("httx://12394:abd") - assert.Error(t, err) + require.Error(t, err) serv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusNotFound) @@ -122,7 +124,7 @@ func TestLoadHTTPBytes(t *testing.T) { defer serv.Close() _, err = LoadFromFileOrHTTP(serv.URL) - assert.Error(t, err) + require.Error(t, err) ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusOK) @@ -131,12 +133,11 @@ func TestLoadHTTPBytes(t *testing.T) { defer ts2.Close() d, err := LoadFromFileOrHTTP(ts2.URL) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("the content"), d) } func TestLoadStrategy(t *testing.T) { - loader := func(p string) ([]byte, error) { return []byte(yamlPetStore), nil } @@ -152,16 +153,16 @@ func TestLoadStrategy(t *testing.T) { defer serv.Close() s, err := YAMLDoc(serv.URL) - assert.NoError(t, err) - assert.NotNil(t, s) + require.NoError(t, err) + require.NotNil(t, s) - ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusNotFound) _, _ = rw.Write([]byte("\n")) })) defer ts2.Close() _, err = YAMLDoc(ts2.URL) - assert.Error(t, err) + require.Error(t, err) } func TestLoadStrategyFile(t *testing.T) { @@ -181,19 +182,26 @@ func TestLoadStrategyFile(t *testing.T) { ld := LoadStrategy("blah", loader, remLoader) - b, _ := ld("file:///a/c/myfile.yaml") + b, err := ld("file:///a/c/myfile.yaml") + require.NoError(t, err) assert.True(t, called) - assert.Equal(t, "/a/c/myfile.yaml", pth) + if runtime.GOOS == "windows" { + assert.Equal(t, `a\c\myfile.yaml`, pth) + } else { + assert.Equal(t, "/a/c/myfile.yaml", pth) + } assert.Equal(t, []byte(thisIsIt), b) called, pth = false, "" - b, _ = ld(`file://C:\a\c\myfile.yaml`) + b, err = ld(`file://C:\a\c\myfile.yaml`) + require.NoError(t, err) assert.True(t, called) assert.Equal(t, `C:\a\c\myfile.yaml`, pth) assert.Equal(t, []byte(thisIsIt), b) called, pth = false, "" - b, _ = ld(`file://C%3A%5Ca%5Cc%5Cmyfile.yaml`) + b, err = ld(`file://C%3A%5Ca%5Cc%5Cmyfile.yaml`) + require.NoError(t, err) assert.True(t, called) assert.Equal(t, `C:\a\c\myfile.yaml`, pth) assert.Equal(t, []byte(thisIsIt), b) diff --git a/net_test.go b/net_test.go index 79e5860..4130501 100644 --- a/net_test.go +++ b/net_test.go @@ -18,6 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSplitHostPort(t *testing.T) { @@ -36,9 +37,13 @@ func TestSplitHostPort(t *testing.T) { for _, e := range data { h, p, err := SplitHostPort(e.Input) - if (!e.Err && assert.NoError(t, err)) || (e.Err && assert.Error(t, err)) { - assert.Equal(t, e.Host, h) - assert.Equal(t, e.Port, p) + if !e.Err { + require.NoError(t, err) + } else { + require.Error(t, err) } + + assert.Equal(t, e.Host, h) + assert.Equal(t, e.Port, p) } } diff --git a/path_test.go b/path_test.go index e439918..281d8f6 100644 --- a/path_test.go +++ b/path_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func makeDirStructure(tgt string) (string, string, error) { @@ -99,19 +100,15 @@ func TestFindPackage(t *testing.T) { //nolint:unparam func assertPath(t testing.TB, expected, actual string) bool { fp, err := filepath.EvalSymlinks(expected) - if assert.NoError(t, err) { - return assert.Equal(t, fp, actual) - } - return true + require.NoError(t, err) + + return assert.Equal(t, fp, actual) } func TestFullGOPATH(t *testing.T) { os.Unsetenv(GOPATHKey) ngp := "/some/where:/other/place" - os.Setenv(GOPATHKey, ngp) - - ogp := os.Getenv(GOPATHKey) - defer os.Setenv(GOPATHKey, ogp) + t.Setenv(GOPATHKey, ngp) expected := ngp + ":" + runtime.GOROOT() assert.Equal(t, expected, FullGoSearchPath()) diff --git a/post_go18.go b/post_go18.go deleted file mode 100644 index f5228b8..0000000 --- a/post_go18.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build go1.8 -// +build go1.8 - -package swag - -import "net/url" - -func pathUnescape(path string) (string, error) { - return url.PathUnescape(path) -} diff --git a/pre_go18.go b/pre_go18.go deleted file mode 100644 index 2757d9b..0000000 --- a/pre_go18.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build !go1.8 -// +build !go1.8 - -package swag - -import "net/url" - -func pathUnescape(path string) (string, error) { - return url.QueryUnescape(path) -} diff --git a/pre_go19.go b/pre_go19.go deleted file mode 100644 index 0565db3..0000000 --- a/pre_go19.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build !go1.9 -// +build !go1.9 - -package swag - -import ( - "sort" - "sync" -) - -// indexOfInitialisms is a thread-safe implementation of the sorted index of initialisms. -// Before go1.9, this may be implemented with a mutex on the map. -type indexOfInitialisms struct { - getMutex *sync.Mutex - index map[string]bool -} - -func newIndexOfInitialisms() *indexOfInitialisms { - return &indexOfInitialisms{ - getMutex: new(sync.Mutex), - index: make(map[string]bool, 50), - } -} - -func (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms { - m.getMutex.Lock() - defer m.getMutex.Unlock() - for k, v := range initial { - m.index[k] = v - } - return m -} - -func (m *indexOfInitialisms) isInitialism(key string) bool { - m.getMutex.Lock() - defer m.getMutex.Unlock() - _, ok := m.index[key] - return ok -} - -func (m *indexOfInitialisms) add(key string) *indexOfInitialisms { - m.getMutex.Lock() - defer m.getMutex.Unlock() - m.index[key] = true - return m -} - -func (m *indexOfInitialisms) sorted() (result []string) { - m.getMutex.Lock() - defer m.getMutex.Unlock() - for k := range m.index { - result = append(result, k) - } - sort.Sort(sort.Reverse(byInitialism(result))) - return -} diff --git a/util.go b/util.go index d971fbe..c5322d1 100644 --- a/util.go +++ b/util.go @@ -343,7 +343,7 @@ type zeroable interface { func IsZero(data interface{}) bool { v := reflect.ValueOf(data) // check for nil data - switch v.Kind() { + switch v.Kind() { //nolint:exhaustive case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: if v.IsNil() { return true @@ -356,7 +356,7 @@ func IsZero(data interface{}) bool { } // continue with slightly more complex reflection - switch v.Kind() { + switch v.Kind() { //nolint:exhaustive case reflect.String: return v.Len() == 0 case reflect.Bool: diff --git a/util_test.go b/util_test.go index 6d2ebb2..1fd0d7a 100644 --- a/util_test.go +++ b/util_test.go @@ -16,15 +16,13 @@ package swag import ( "fmt" - "log" "strings" "testing" "time" "unicode" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type translationSample struct { @@ -79,10 +77,22 @@ func TestHighUnicode(t *testing.T) { ss := "日本語sample 2 Text" rss := []rune(ss) - log.Println("title:", unicode.IsTitle(rss[0])) require.False(t, rss[0] < unicode.MaxASCII && unicode.IsLetter(rss[0])) } +const ( + textTitle = "Text" + blankText = " text" + dashText = "-text" + uscoreText = "_text" + + sampleTitle = "Sample" + sampleString = "sample" + sampleBlank = "sample " + sampleDash = "sample-" + sampleUscore = "sample_" +) + func TestToGoName(t *testing.T) { samples := []translationSample{ {"@Type", "AtType"}, @@ -107,17 +117,17 @@ func TestToGoName(t *testing.T) { k = upper(k) samples = append(samples, - translationSample{"sample " + lower(k) + " text", "Sample" + k + "Text"}, - translationSample{"sample-" + lower(k) + "-text", "Sample" + k + "Text"}, - translationSample{"sample_" + lower(k) + "_text", "Sample" + k + "Text"}, - translationSample{"sample" + titleize(k) + "Text", "Sample" + k + "Text"}, - translationSample{"sample " + lower(k), "Sample" + k}, - translationSample{"sample-" + lower(k), "Sample" + k}, - translationSample{"sample_" + lower(k), "Sample" + k}, - translationSample{"sample" + titleize(k), "Sample" + k}, - translationSample{"sample " + titleize(k) + " text", "Sample" + k + "Text"}, - translationSample{"sample-" + titleize(k) + "-text", "Sample" + k + "Text"}, - translationSample{"sample_" + titleize(k) + "_text", "Sample" + k + "Text"}, + translationSample{sampleBlank + lower(k) + blankText, sampleTitle + k + textTitle}, + translationSample{sampleDash + lower(k) + dashText, sampleTitle + k + textTitle}, + translationSample{sampleUscore + lower(k) + uscoreText, sampleTitle + k + textTitle}, + translationSample{sampleString + titleize(k) + textTitle, sampleTitle + k + textTitle}, + translationSample{sampleBlank + lower(k), sampleTitle + k}, + translationSample{sampleDash + lower(k), sampleTitle + k}, + translationSample{sampleUscore + lower(k), sampleTitle + k}, + translationSample{sampleString + titleize(k), sampleTitle + k}, + translationSample{sampleBlank + titleize(k) + blankText, sampleTitle + k + textTitle}, + translationSample{sampleDash + titleize(k) + dashText, sampleTitle + k + textTitle}, + translationSample{sampleUscore + titleize(k) + uscoreText, sampleTitle + k + textTitle}, ) } @@ -235,7 +245,7 @@ func TestToFileName(t *testing.T) { } for _, k := range commonInitialisms.sorted() { samples = append(samples, - translationSample{"Sample" + k + "Text", "sample_" + lower(k) + "_text"}, + translationSample{sampleTitle + k + textTitle, sampleUscore + lower(k) + uscoreText}, ) } @@ -255,7 +265,7 @@ func TestToCommandName(t *testing.T) { for _, k := range commonInitialisms.sorted() { samples = append(samples, - translationSample{"Sample" + k + "Text", "sample-" + lower(k) + "-text"}, + translationSample{"Sample" + k + textTitle, sampleDash + lower(k) + dashText}, ) } @@ -274,7 +284,7 @@ func TestToHumanName(t *testing.T) { for _, k := range commonInitialisms.sorted() { samples = append(samples, - translationSample{"Sample" + k + "Text", "sample " + k + " text"}, + translationSample{"Sample" + k + textTitle, sampleBlank + k + blankText}, ) } @@ -292,7 +302,7 @@ func TestToJSONName(t *testing.T) { for _, k := range commonInitialisms.sorted() { samples = append(samples, - translationSample{"Sample" + k + "Text", "sample" + titleize(k) + "Text"}, + translationSample{sampleTitle + k + textTitle, sampleString + titleize(k) + textTitle}, ) } diff --git a/yaml.go b/yaml.go index f09ee60..3b8c1e3 100644 --- a/yaml.go +++ b/yaml.go @@ -147,7 +147,7 @@ func yamlScalar(node *yaml.Node) (interface{}, error) { case yamlTimestamp: return node.Value, nil case yamlNull: - return nil, nil + return nil, nil //nolint:nilnil default: return nil, fmt.Errorf("YAML tag %q is not supported", node.LongTag()) } @@ -319,7 +319,8 @@ func json2yaml(item interface{}) (*yaml.Node, error) { Value: strconv.FormatBool(val), }, nil } - return nil, nil + + return nil, nil //nolint:nilnil } // JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice diff --git a/yaml_test.go b/yaml_test.go index 5eb5f1a..b933bd3 100644 --- a/yaml_test.go +++ b/yaml_test.go @@ -71,9 +71,9 @@ name: a string value _ = yaml.Unmarshal([]byte(sd), &data) d, err := YAMLToJSON(data) - if assert.NoError(t, err) { - assert.Equal(t, `{"1":"the int key value","name":"a string value","y":"some value"}`, string(d)) - } + require.NoError(t, err) + require.NotNil(t, d) + assert.Equal(t, `{"1":"the int key value","name":"a string value","y":"some value"}`, string(d)) ns := []*yaml.Node{ { @@ -89,8 +89,8 @@ name: a string value } data.Content[0].Content = append(data.Content[0].Content, ns...) d, err = YAMLToJSON(data) - assert.Error(t, err) - assert.Nil(t, d) + require.Error(t, err) + require.Nil(t, d) data.Content[0].Content = data.Content[0].Content[:len(data.Content[0].Content)-2] @@ -119,7 +119,7 @@ name: a string value data.Content[0].Content = append(data.Content[0].Content, tag...) d, err = YAMLToJSON(data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, `{"1":"the int key value","name":"a string value","y":"some value","tag":{"name":"tag name"}}`, string(d)) tag[1].Content = []*yaml.Node{ @@ -136,33 +136,31 @@ name: a string value } d, err = YAMLToJSON(data) - assert.Error(t, err) - assert.Nil(t, d) + require.Error(t, err) + require.Nil(t, d) var lst []interface{} lst = append(lst, "hello") d, err = YAMLToJSON(lst) - assert.NoError(t, err) + require.NoError(t, err) + require.NotNil(t, d) assert.Equal(t, []byte(`["hello"]`), []byte(d)) lst = append(lst, data) d, err = YAMLToJSON(lst) - assert.Error(t, err) - assert.Nil(t, d) - - // _, err := yamlToJSON(failJSONMarhal{}) - // assert.Error(t, err) + require.Error(t, err) + require.Nil(t, d) _, err = BytesToYAMLDoc([]byte("- name: hello\n")) - assert.Error(t, err) + require.Error(t, err) dd, err := BytesToYAMLDoc([]byte("description: 'object created'\n")) - assert.NoError(t, err) + require.NoError(t, err) d, err = YAMLToJSON(dd) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, json.RawMessage(`{"description":"object created"}`), d) } @@ -173,32 +171,29 @@ var yamlPestoreServer = func(rw http.ResponseWriter, r *http.Request) { func TestWithYKey(t *testing.T) { doc, err := BytesToYAMLDoc([]byte(withYKey)) - if assert.NoError(t, err) { - _, err := YAMLToJSON(doc) - if assert.NoError(t, err) { - doc, err := BytesToYAMLDoc([]byte(withQuotedYKey)) - if assert.NoError(t, err) { - jsond, err := YAMLToJSON(doc) - if assert.NoError(t, err) { - var yt struct { - Definitions struct { - Viewbox struct { - Properties struct { - Y struct { - Type string `json:"type"` - } `json:"y"` - } `json:"properties"` - } `json:"viewbox"` - } `json:"definitions"` - } - if assert.NoError(t, json.Unmarshal(jsond, &yt)) { - assert.Equal(t, "integer", yt.Definitions.Viewbox.Properties.Y.Type) - } - } - } - } + require.NoError(t, err) + + _, err = YAMLToJSON(doc) + require.NoError(t, err) + doc, err = BytesToYAMLDoc([]byte(withQuotedYKey)) + require.NoError(t, err) + jsond, err := YAMLToJSON(doc) + require.NoError(t, err) + + var yt struct { + Definitions struct { + Viewbox struct { + Properties struct { + Y struct { + Type string `json:"type"` + } `json:"y"` + } `json:"properties"` + } `json:"viewbox"` + } `json:"definitions"` } + require.NoError(t, json.Unmarshal(jsond, &yt)) + assert.Equal(t, "integer", yt.Definitions.Viewbox.Properties.Y.Type) } func TestMapKeyTypes(t *testing.T) { @@ -215,7 +210,7 @@ func TestMapKeyTypes(t *testing.T) { uint64(12345678910): "uint64", } _, err := YAMLToJSON(dm) - assert.NoError(t, err) + require.NoError(t, err) } const fixtures2224 = `definitions: