diff --git a/.golangci.yml b/.golangci.yml index 835d55e..22f8d21 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -11,7 +11,7 @@ linters-settings: threshold: 200 goconst: min-len: 2 - min-occurrences: 2 + min-occurrences: 3 linters: enable-all: true @@ -40,3 +40,22 @@ linters: - tparallel - thelper - ifshort + - exhaustruct + - varnamelen + - gci + - depguard + - errchkjson + - inamedparam + - nonamedreturns + - musttag + - ireturn + - forcetypeassert + - cyclop + # deprecated linters + - deadcode + - interfacer + - scopelint + - varcheck + - structcheck + - golint + - nosnakecase diff --git a/circular_test.go b/circular_test.go index 90bc6d2..3dbb45a 100644 --- a/circular_test.go +++ b/circular_test.go @@ -219,7 +219,7 @@ func TestExpandCircular_SpecExpansion(t *testing.T) { func TestExpandCircular_RemoteCircularID(t *testing.T) { go func() { - err := http.ListenAndServe("localhost:1234", http.FileServer(http.Dir("fixtures/more_circulars/remote"))) + err := http.ListenAndServe("localhost:1234", http.FileServer(http.Dir("fixtures/more_circulars/remote"))) //#nosec if err != nil { panic(err.Error()) } @@ -232,7 +232,7 @@ func TestExpandCircular_RemoteCircularID(t *testing.T) { assertRefResolve(t, jazon, "", root, &ExpandOptions{RelativeBase: fixturePath}) assertRefExpand(t, jazon, "", root, &ExpandOptions{RelativeBase: fixturePath}) - assert.NoError(t, ExpandSchemaWithBasePath(root, nil, &ExpandOptions{})) + require.NoError(t, ExpandSchemaWithBasePath(root, nil, &ExpandOptions{})) jazon = asJSON(t, root) diff --git a/contact_info_test.go b/contact_info_test.go index 3ca2315..fedd81a 100644 --- a/contact_info_test.go +++ b/contact_info_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const contactInfoJSON = `{ @@ -36,13 +37,11 @@ var contactInfo = ContactInfo{ContactInfoProps: ContactInfoProps{ func TestIntegrationContactInfo(t *testing.T) { b, err := json.MarshalIndent(contactInfo, "", "\t") - if assert.NoError(t, err) { - assert.Equal(t, contactInfoJSON, string(b)) - } + require.NoError(t, err) + assert.Equal(t, contactInfoJSON, string(b)) actual := ContactInfo{} err = json.Unmarshal([]byte(contactInfoJSON), &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, contactInfo, actual) - } + require.NoError(t, err) + assert.EqualValues(t, contactInfo, actual) } diff --git a/expander.go b/expander.go index d4ea889..012a462 100644 --- a/expander.go +++ b/expander.go @@ -27,7 +27,6 @@ import ( // all relative $ref's will be resolved from there. // // PathLoader injects a document loading method. By default, this resolves to the function provided by the SpecLoader package variable. -// type ExpandOptions struct { RelativeBase string // the path to the root document to expand. This is a file, not a directory SkipSchemas bool // do not expand schemas, just paths, parameters and responses diff --git a/expander_test.go b/expander_test.go index 471b567..b044e71 100644 --- a/expander_test.go +++ b/expander_test.go @@ -353,7 +353,7 @@ func TestExpand_ContinueOnError(t *testing.T) { // missing $ref in spec missingRefDoc, err := jsonDoc(specPath) - assert.NoError(t, err) + require.NoError(t, err) testCase := struct { Input *Swagger `json:"input"` @@ -367,7 +367,7 @@ func TestExpand_ContinueOnError(t *testing.T) { } require.NoError(t, ExpandSpec(testCase.Input, opts)) - assert.Equal(t, testCase.Input, testCase.Expected, "Should continue expanding spec when a definition can't be found.") + assert.Equal(t, testCase.Expected, testCase.Input, "Should continue expanding spec when a definition can't be found.") // missing $ref in items doc, err := jsonDoc("fixtures/expansion/missingItemRef.json") @@ -791,7 +791,7 @@ func resolutionContextServer() *httptest.Server { ctnt["id"] = servedAt rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) + rw.WriteHeader(http.StatusOK) bb, _ := json.Marshal(ctnt) _, _ = rw.Write(bb) return @@ -803,7 +803,6 @@ func resolutionContextServer() *httptest.Server { ctnt["id"] = servedAt rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) bb, _ := json.Marshal(ctnt) _, _ = rw.Write(bb) return @@ -811,7 +810,6 @@ func resolutionContextServer() *httptest.Server { if req.URL.Path == "/boolProp.json" { rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) b, _ := json.Marshal(map[string]interface{}{ "type": "boolean", }) @@ -821,7 +819,6 @@ func resolutionContextServer() *httptest.Server { if req.URL.Path == "/deeper/stringProp.json" { rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) b, _ := json.Marshal(map[string]interface{}{ "type": "string", }) @@ -831,7 +828,6 @@ func resolutionContextServer() *httptest.Server { if req.URL.Path == "/deeper/arrayProp.json" { rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) b, _ := json.Marshal(map[string]interface{}{ "type": "array", "items": map[string]interface{}{ diff --git a/header_test.go b/header_test.go index 19d08cc..67a893a 100644 --- a/header_test.go +++ b/header_test.go @@ -20,8 +20,11 @@ import ( "github.com/go-openapi/swag" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +const epsilon = 1e-9 + func float64Ptr(f float64) *float64 { return &f } @@ -83,9 +86,8 @@ const headerJSON = `{ func TestIntegrationHeader(t *testing.T) { var actual Header - if assert.NoError(t, json.Unmarshal([]byte(headerJSON), &actual)) { - assert.EqualValues(t, actual, header) - } + require.NoError(t, json.Unmarshal([]byte(headerJSON), &actual)) + assert.EqualValues(t, actual, header) assertParsesJSON(t, headerJSON, header) } @@ -93,37 +95,38 @@ func TestIntegrationHeader(t *testing.T) { func TestJSONLookupHeader(t *testing.T) { var def string res, err := header.JSONLookup("default") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, def, res) { - t.FailNow() - return - } - def = res.(string) + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, def, res) + + var ok bool + def, ok = res.(string) + require.True(t, ok) assert.Equal(t, "8", def) var x *interface{} res, err = header.JSONLookup("x-framework") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, x, res) { - t.FailNow() - return - } + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, x, res) - x = res.(*interface{}) + x, ok = res.(*interface{}) + require.True(t, ok) assert.EqualValues(t, "swagger-go", *x) res, err = header.JSONLookup("unknown") - if !assert.Error(t, err) || !assert.Nil(t, res) { - t.FailNow() - return - } + require.Error(t, err) + require.Nil(t, res) var max *float64 res, err = header.JSONLookup("maximum") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, max, res) { - t.FailNow() - return - } - max = res.(*float64) - assert.Equal(t, float64(100), *max) + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, max, res) + + max, ok = res.(*float64) + require.True(t, ok) + assert.InDelta(t, float64(100), *max, epsilon) } func TestResponseHeaueder(t *testing.T) { diff --git a/helpers_spec_test.go b/helpers_spec_test.go index 40fa75b..4dd12c5 100644 --- a/helpers_spec_test.go +++ b/helpers_spec_test.go @@ -71,7 +71,7 @@ func assertRefInJSONRegexp(t testing.TB, jazon, match string) { // assertRefExpand ensures that all $ref in some json doc expand properly against a root document. // // "exclude" is a regexp pattern to ignore certain $ref (e.g. some specs may embed $ref that are not processed, such as extensions). -func assertRefExpand(t *testing.T, jazon, exclude string, root interface{}, opts ...*spec.ExpandOptions) { +func assertRefExpand(t *testing.T, jazon, _ string, root interface{}, opts ...*spec.ExpandOptions) { if len(opts) > 0 { assertRefWithFunc(t, "expand-with-base", jazon, "", func(t *testing.T, match string) { ref := spec.RefSchema(match) diff --git a/helpers_test.go b/helpers_test.go index 0d54150..f16a4dd 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -105,7 +105,7 @@ func assertNoRef(t testing.TB, jazon string) { // assertRefExpand ensures that all $ref in some json doc expand properly against a root document. // // "exclude" is a regexp pattern to ignore certain $ref (e.g. some specs may embed $ref that are not processed, such as extensions). -func assertRefExpand(t *testing.T, jazon, exclude string, root interface{}, opts ...*ExpandOptions) { +func assertRefExpand(t *testing.T, jazon, _ string, root interface{}, opts ...*ExpandOptions) { assertRefWithFunc(t, jazon, "", func(t *testing.T, match string) { ref := RefSchema(match) if len(opts) > 0 { diff --git a/info_test.go b/info_test.go index 5ecf1bb..a8e3fbe 100644 --- a/info_test.go +++ b/info_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const infoJSON = `{ @@ -57,25 +58,19 @@ var info = Info{ func TestIntegrationInfo_Serialize(t *testing.T) { b, err := json.MarshalIndent(info, "", "\t") - if assert.NoError(t, err) { - assert.Equal(t, infoJSON, string(b)) - } + require.NoError(t, err) + assert.Equal(t, infoJSON, string(b)) } func TestIntegrationInfo_Deserialize(t *testing.T) { actual := Info{} - err := json.Unmarshal([]byte(infoJSON), &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, info, actual) - } + require.NoError(t, json.Unmarshal([]byte(infoJSON), &actual)) + assert.EqualValues(t, info, actual) } func TestInfoGobEncoding(t *testing.T) { var src, dst Info - if assert.NoError(t, json.Unmarshal([]byte(infoJSON), &src)) { - assert.EqualValues(t, src, info) - } else { - t.FailNow() - } + require.NoError(t, json.Unmarshal([]byte(infoJSON), &src)) + assert.EqualValues(t, src, info) doTestAnyGobEncoding(t, &src, &dst) } diff --git a/items_test.go b/items_test.go index edd75c2..4d4e458 100644 --- a/items_test.go +++ b/items_test.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var items = Items{ @@ -74,9 +75,8 @@ const itemsJSON = `{ func TestIntegrationItems(t *testing.T) { var actual Items - if assert.NoError(t, json.Unmarshal([]byte(itemsJSON), &actual)) { - assert.EqualValues(t, actual, items) - } + require.NoError(t, json.Unmarshal([]byte(itemsJSON), &actual)) + assert.EqualValues(t, actual, items) assertParsesJSON(t, itemsJSON, items) } @@ -152,38 +152,38 @@ func TestItemsBuilder(t *testing.T) { func TestJSONLookupItems(t *testing.T) { res, err := items.JSONLookup("$ref") - if !assert.NoError(t, err) { - t.FailNow() - return - } - if assert.IsType(t, &Ref{}, res) { - ref := res.(*Ref) - assert.EqualValues(t, MustCreateRef("Dog"), *ref) - } + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, &Ref{}, res) + + var ok bool + ref, ok := res.(*Ref) + require.True(t, ok) + assert.EqualValues(t, MustCreateRef("Dog"), *ref) var max *float64 res, err = items.JSONLookup("maximum") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, max, res) { - t.FailNow() - return - } - max = res.(*float64) - assert.Equal(t, float64(100), *max) + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, max, res) + + max, ok = res.(*float64) + require.True(t, ok) + assert.InDelta(t, float64(100), *max, epsilon) var f string res, err = items.JSONLookup("collectionFormat") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, f, res) { - t.FailNow() - return - } - f = res.(string) + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, f, res) + + f, ok = res.(string) + require.True(t, ok) assert.Equal(t, "csv", f) res, err = items.JSONLookup("unknown") - if !assert.Error(t, err) || !assert.Nil(t, res) { - t.FailNow() - return - } + require.Error(t, err) + require.Nil(t, res) } func TestItemsWithValidation(t *testing.T) { diff --git a/license_test.go b/license_test.go index 407df73..398f0d8 100644 --- a/license_test.go +++ b/license_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var license = License{ @@ -36,13 +37,11 @@ func TestIntegrationLicense(t *testing.T) { // const licenseYAML = "name: the name\nurl: the url\n" b, err := json.MarshalIndent(license, "", "\t") - if assert.NoError(t, err) { - assert.Equal(t, licenseJSON, string(b)) - } + require.NoError(t, err) + assert.Equal(t, licenseJSON, string(b)) actual := License{} err = json.Unmarshal([]byte(licenseJSON), &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, license, actual) - } + require.NoError(t, err) + assert.EqualValues(t, license, actual) } diff --git a/normalizer_nonwindows.go b/normalizer_nonwindows.go index 2df0723..f19f1a8 100644 --- a/normalizer_nonwindows.go +++ b/normalizer_nonwindows.go @@ -40,5 +40,5 @@ func repairURI(in string) (*url.URL, string) { return u, "" } -func fixWindowsURI(u *url.URL, in string) { +func fixWindowsURI(_ *url.URL, _ string) { } diff --git a/normalizer_test.go b/normalizer_test.go index b152297..66f30bf 100644 --- a/normalizer_test.go +++ b/normalizer_test.go @@ -245,6 +245,7 @@ func TestNormalizer_NormalizeBase(t *testing.T) { if runtime.GOOS == windowsOS { cwd = "/" + strings.ToLower(filepath.ToSlash(cwd)) } + const fileScheme = "file:///" for _, toPin := range []struct { Base, Expected string @@ -317,7 +318,7 @@ func TestNormalizer_NormalizeBase(t *testing.T) { { // path clean Base: "///folder//subfolder///file.json/", - Expected: "file:///" + currentDriveLetter + ":/folder/subfolder/file.json", + Expected: fileScheme + currentDriveLetter + ":/folder/subfolder/file.json", Windows: true, }, { @@ -344,18 +345,18 @@ func TestNormalizer_NormalizeBase(t *testing.T) { { // handling dots (3/6): valid, cleaned to /c:/ on windows Base: "/..", - Expected: "file:///" + currentDriveLetter + ":", + Expected: fileScheme + currentDriveLetter + ":", Windows: true, }, { // handling dots (4/6): dodgy specification - resolved to / Base: `file:/.`, - Expected: "file:///", + Expected: fileScheme, }, { // handling dots (5/6): dodgy specification - resolved to / Base: `file:/..`, - Expected: "file:///", + Expected: fileScheme, }, { // handling dots (6/6) @@ -377,7 +378,7 @@ func TestNormalizer_NormalizeBase(t *testing.T) { // windows-only cases { Base: "/base/sub/file.json", - Expected: "file:///" + currentDriveLetter + ":/base/sub/file.json", // on windows, filepath.Abs("/a/b") prepends the "c:" drive + Expected: fileScheme + currentDriveLetter + ":/base/sub/file.json", // on windows, filepath.Abs("/a/b") prepends the "c:" drive Windows: true, }, { diff --git a/operation.go b/operation.go index 995ce6a..a69cca8 100644 --- a/operation.go +++ b/operation.go @@ -217,9 +217,12 @@ func (o *Operation) AddParam(param *Parameter) *Operation { for i, p := range o.Parameters { if p.Name == param.Name && p.In == param.In { - params := append(o.Parameters[:i], *param) + params := make([]Parameter, 0, len(o.Parameters)+1) + params = append(params, o.Parameters[:i]...) + params = append(params, *param) params = append(params, o.Parameters[i+1:]...) o.Parameters = params + return o } } diff --git a/operation_test.go b/operation_test.go index 812cdda..495f609 100644 --- a/operation_test.go +++ b/operation_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var operation = Operation{ @@ -82,30 +83,28 @@ func TestSuccessResponse(t *testing.T) { resp, n, f := ope.SuccessResponse() assert.Nil(t, resp) assert.Equal(t, 0, n) - assert.Equal(t, false, f) + assert.False(t, f) resp, n, f = operation.SuccessResponse() - if assert.NotNil(t, resp) { - assert.Equal(t, "void response", resp.Description) - } + require.NotNil(t, resp) + assert.Equal(t, "void response", resp.Description) + assert.Equal(t, 0, n) - assert.Equal(t, false, f) + assert.False(t, f) + + require.NoError(t, json.Unmarshal([]byte(operationJSON), ope)) - err := json.Unmarshal([]byte(operationJSON), ope) - if !assert.Nil(t, err) { - t.FailNow() - } ope = ope.RespondsWith(301, &Response{ ResponseProps: ResponseProps{ Description: "failure", }, }) resp, n, f = ope.SuccessResponse() - if assert.NotNil(t, resp) { - assert.Equal(t, "void response", resp.Description) - } + require.NotNil(t, resp) + assert.Equal(t, "void response", resp.Description) + assert.Equal(t, 0, n) - assert.Equal(t, false, f) + assert.False(t, f) ope = ope.RespondsWith(200, &Response{ ResponseProps: ResponseProps{ @@ -114,11 +113,11 @@ func TestSuccessResponse(t *testing.T) { }) resp, n, f = ope.SuccessResponse() - if assert.NotNil(t, resp) { - assert.Equal(t, "success", resp.Description) - } + require.NotNil(t, resp) + assert.Equal(t, "success", resp.Description) + assert.Equal(t, 200, n) - assert.Equal(t, true, f) + assert.True(t, f) } func TestOperationBuilder(t *testing.T) { @@ -146,7 +145,9 @@ func TestOperationBuilder(t *testing.T) { WithSummary("my summary"). WithExternalDocs("some doc", "https://www.example.com") - jazon, _ := json.MarshalIndent(ope, "", " ") + jazon, err := json.MarshalIndent(ope, "", " ") + require.NoError(t, err) + assert.JSONEq(t, `{ "operationId": "operationID", "description": "test operation", @@ -201,8 +202,11 @@ func TestOperationBuilder(t *testing.T) { // check token lookup token, err := ope.JSONLookup("responses") - assert.NoError(t, err) - jazon, _ = json.MarshalIndent(token, "", " ") + require.NoError(t, err) + + jazon, err = json.MarshalIndent(token, "", " ") + require.NoError(t, err) + assert.JSONEq(t, `{ "200": { "description": "success" @@ -219,7 +223,9 @@ func TestOperationBuilder(t *testing.T) { RemoveParam("fakeParam", "query"). Undeprecate(). WithExternalDocs("", "") - jazon, _ = json.MarshalIndent(ope, "", " ") + jazon, err = json.MarshalIndent(ope, "", " ") + require.NoError(t, err) + assert.JSONEq(t, `{ "security": [ { @@ -252,9 +258,8 @@ func TestOperationBuilder(t *testing.T) { func TestIntegrationOperation(t *testing.T) { var actual Operation - if assert.NoError(t, json.Unmarshal([]byte(operationJSON), &actual)) { - assert.EqualValues(t, actual, operation) - } + require.NoError(t, json.Unmarshal([]byte(operationJSON), &actual)) + assert.EqualValues(t, actual, operation) assertParsesJSON(t, operationJSON, operation) } @@ -263,21 +268,19 @@ func TestSecurityProperty(t *testing.T) { // Ensure we omit security key when unset securityNotSet := OperationProps{} jsonResult, err := json.Marshal(securityNotSet) - if assert.NoError(t, err) { - assert.NotContains(t, string(jsonResult), "security", "security key should be omitted when unset") - } + require.NoError(t, err) + assert.NotContains(t, string(jsonResult), "security", "security key should be omitted when unset") // Ensure we preserve the security key when it contains an empty (zero length) slice securityContainsEmptyArray := OperationProps{ Security: []map[string][]string{}, } jsonResult, err = json.Marshal(securityContainsEmptyArray) - if assert.NoError(t, err) { - var props OperationProps - if assert.NoError(t, json.Unmarshal(jsonResult, &props)) { - assert.Equal(t, securityContainsEmptyArray, props) - } - } + require.NoError(t, err) + + var props OperationProps + require.NoError(t, json.Unmarshal(jsonResult, &props)) + assert.Equal(t, securityContainsEmptyArray, props) } func TestOperationGobEncoding(t *testing.T) { @@ -346,10 +349,7 @@ func TestOperationGobEncoding(t *testing.T) { func doTestOperationGobEncoding(t *testing.T, fixture string) { var src, dst Operation - - if !assert.NoError(t, json.Unmarshal([]byte(fixture), &src)) { - t.FailNow() - } + require.NoError(t, json.Unmarshal([]byte(fixture), &src)) doTestAnyGobEncoding(t, &src, &dst) } @@ -359,18 +359,12 @@ func doTestAnyGobEncoding(t *testing.T, src, dst interface{}) { var b bytes.Buffer err := gob.NewEncoder(&b).Encode(src) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) err = gob.NewDecoder(&b).Decode(dst) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) jazon, err := json.MarshalIndent(dst, "", " ") - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) assert.JSONEq(t, string(expectedJSON), string(jazon)) } diff --git a/parameter.go b/parameter.go index 2b2b89b..bd4f1cd 100644 --- a/parameter.go +++ b/parameter.go @@ -84,27 +84,27 @@ type ParamProps struct { // Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). // // There are five possible parameter types. -// * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part -// of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, -// the path parameter is `itemId`. -// * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. -// * Header - Custom headers that are expected as part of the request. -// * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be -// _one_ body parameter. The name of the body parameter has no effect on the parameter itself and is used for -// documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist -// together for the same operation. -// * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or -// `multipart/form-data` are used as the content type of the request (in Swagger's definition, -// the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used -// to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be -// declared together with a body parameter for the same operation. Form parameters have a different format based on -// the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4). -// * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. -// For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple -// parameters that are being transferred. -// * `multipart/form-data` - each parameter takes a section in the payload with an internal header. -// For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is -// `submit-name`. This type of form parameters is more commonly used for file transfers. +// - Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part +// of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, +// the path parameter is `itemId`. +// - Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +// - Header - Custom headers that are expected as part of the request. +// - Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be +// _one_ body parameter. The name of the body parameter has no effect on the parameter itself and is used for +// documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist +// together for the same operation. +// - Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or +// `multipart/form-data` are used as the content type of the request (in Swagger's definition, +// the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used +// to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be +// declared together with a body parameter for the same operation. Form parameters have a different format based on +// the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4). +// - `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. +// For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple +// parameters that are being transferred. +// - `multipart/form-data` - each parameter takes a section in the payload with an internal header. +// For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is +// `submit-name`. This type of form parameters is more commonly used for file transfers. // // For more information: http://goo.gl/8us55a#parameterObject type Parameter struct { diff --git a/parameters_test.go b/parameters_test.go index 0f5ad3c..702d867 100644 --- a/parameters_test.go +++ b/parameters_test.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var parameter = Parameter{ @@ -92,9 +93,8 @@ var parameterJSON = `{ func TestIntegrationParameter(t *testing.T) { var actual Parameter - if assert.NoError(t, json.Unmarshal([]byte(parameterJSON), &actual)) { - assert.EqualValues(t, actual, parameter) - } + require.NoError(t, json.Unmarshal([]byte(parameterJSON), &actual)) + assert.EqualValues(t, actual, parameter) assertParsesJSON(t, parameterJSON, parameter) } @@ -158,9 +158,7 @@ func TestParameterSerialization(t *testing.T) { func TestParameterGobEncoding(t *testing.T) { var src, dst Parameter - if !assert.NoError(t, json.Unmarshal([]byte(parameterJSON), &src)) { - t.FailNow() - } + require.NoError(t, json.Unmarshal([]byte(parameterJSON), &src)) doTestAnyGobEncoding(t, &src, &dst) } diff --git a/path_item_test.go b/path_item_test.go index 3c78e90..c3507a0 100644 --- a/path_item_test.go +++ b/path_item_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var pathItem = PathItem{ @@ -73,9 +74,8 @@ const pathItemJSON = `{ func TestIntegrationPathItem(t *testing.T) { var actual PathItem - if assert.NoError(t, json.Unmarshal([]byte(pathItemJSON), &actual)) { - assert.EqualValues(t, actual, pathItem) - } + require.NoError(t, json.Unmarshal([]byte(pathItemJSON), &actual)) + assert.EqualValues(t, actual, pathItem) assertParsesJSON(t, pathItemJSON, pathItem) } diff --git a/paths_test.go b/paths_test.go index ff5626a..4592818 100644 --- a/paths_test.go +++ b/paths_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var paths = Paths{ @@ -34,9 +35,8 @@ const pathsJSON = `{"x-framework":"go-swagger","/":{"$ref":"cats"}}` func TestIntegrationPaths(t *testing.T) { var actual Paths - if assert.NoError(t, json.Unmarshal([]byte(pathsJSON), &actual)) { - assert.EqualValues(t, actual, paths) - } + require.NoError(t, json.Unmarshal([]byte(pathsJSON), &actual)) + assert.EqualValues(t, actual, paths) assertParsesJSON(t, pathsJSON, paths) diff --git a/ref_test.go b/ref_test.go index 7dc2f59..6f4c0de 100644 --- a/ref_test.go +++ b/ref_test.go @@ -21,27 +21,24 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // pin pointing go-swagger/go-swagger#1816 issue with cloning ref's func TestCloneRef(t *testing.T) { var b bytes.Buffer src := MustCreateRef("#/definitions/test") - err := gob.NewEncoder(&b).Encode(&src) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, + gob.NewEncoder(&b).Encode(&src), + ) var dst Ref - err = gob.NewDecoder(&b).Decode(&dst) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, + gob.NewDecoder(&b).Decode(&dst), + ) jazon, err := json.Marshal(dst) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) assert.Equal(t, `{"$ref":"#/definitions/test"}`, string(jazon)) } diff --git a/resolver_test.go b/resolver_test.go index 21df897..7f59135 100644 --- a/resolver_test.go +++ b/resolver_test.go @@ -189,7 +189,7 @@ func TestResolveRemoteRef_FromInvalidFragment(t *testing.T) { require.NoError(t, err) resolver := defaultSchemaLoader(rootDoc, nil, nil, nil) - assert.Error(t, resolver.Resolve(&ref, &tgt, "")) + require.Error(t, resolver.Resolve(&ref, &tgt, "")) } /* This next test will have to wait until we do full $ID analysis for every subschema on every file that is referenced */ diff --git a/response_test.go b/response_test.go index 71578ab..d03720c 100644 --- a/response_test.go +++ b/response_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var response = Response{ @@ -45,48 +46,46 @@ const responseJSON = `{ func TestIntegrationResponse(t *testing.T) { var actual Response - if assert.NoError(t, json.Unmarshal([]byte(responseJSON), &actual)) { - assert.EqualValues(t, actual, response) - } + require.NoError(t, json.Unmarshal([]byte(responseJSON), &actual)) + assert.EqualValues(t, actual, response) assertParsesJSON(t, responseJSON, response) } func TestJSONLookupResponse(t *testing.T) { res, err := response.JSONLookup("$ref") - if !assert.NoError(t, err) { - t.FailNow() - return - } - if assert.IsType(t, &Ref{}, res) { - ref := res.(*Ref) - assert.EqualValues(t, MustCreateRef("Dog"), *ref) - } + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, &Ref{}, res) + + var ok bool + ref, ok := res.(*Ref) + require.True(t, ok) + assert.EqualValues(t, MustCreateRef("Dog"), *ref) var def string res, err = response.JSONLookup("description") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, def, res) { - t.FailNow() - return - } - def = res.(string) + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, def, res) + + def, ok = res.(string) + require.True(t, ok) assert.Equal(t, "Dog exists", def) var x *interface{} res, err = response.JSONLookup("x-go-name") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, x, res) { - t.FailNow() - return - } + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, x, res) - x = res.(*interface{}) + x, ok = res.(*interface{}) + require.True(t, ok) assert.EqualValues(t, "PutDogExists", *x) res, err = response.JSONLookup("unknown") - if !assert.Error(t, err) || !assert.Nil(t, res) { - t.FailNow() - return - } + require.Error(t, err) + require.Nil(t, res) } func TestResponseBuild(t *testing.T) { @@ -95,7 +94,9 @@ func TestResponseBuild(t *testing.T) { WithSchema(new(Schema).Typed("object", "")). AddHeader("x-header", ResponseHeader().Typed("string", "")). AddExample("application/json", `{"key":"value"}`) - jazon, _ := json.MarshalIndent(resp, "", " ") + jazon, err := json.MarshalIndent(resp, "", " ") + require.NoError(t, err) + assert.JSONEq(t, `{ "description": "some response", "schema": { diff --git a/responses_test.go b/responses_test.go index 746575f..fc626bf 100644 --- a/responses_test.go +++ b/responses_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var responses = Responses{ @@ -59,54 +60,48 @@ const responsesJSON = `{ func TestIntegrationResponses(t *testing.T) { var actual Responses - if assert.NoError(t, json.Unmarshal([]byte(responsesJSON), &actual)) { - assert.EqualValues(t, actual, responses) - } + require.NoError(t, json.Unmarshal([]byte(responsesJSON), &actual)) + assert.EqualValues(t, actual, responses) assertParsesJSON(t, responsesJSON, responses) } func TestJSONLookupResponses(t *testing.T) { resp200, ok := responses.StatusCodeResponses[200] - if !assert.True(t, ok) { - t.FailNow() - return - } + require.True(t, ok) res, err := resp200.JSONLookup("$ref") - if !assert.NoError(t, err) { - t.FailNow() - return - } - if assert.IsType(t, &Ref{}, res) { - ref := res.(*Ref) - assert.EqualValues(t, MustCreateRef("Dog"), *ref) - } + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, &Ref{}, res) + + ref, ok := res.(*Ref) + require.True(t, ok) + assert.EqualValues(t, MustCreateRef("Dog"), *ref) var def string res, err = resp200.JSONLookup("description") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, def, res) { - t.FailNow() - return - } - def = res.(string) + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, def, res) + + def, ok = res.(string) + require.True(t, ok) assert.Equal(t, "Dog exists", def) var x *interface{} res, err = responses.JSONLookup("x-go-name") - if !assert.NoError(t, err) || !assert.NotNil(t, res) || !assert.IsType(t, x, res) { - t.FailNow() - return - } + require.NoError(t, err) + require.NotNil(t, res) + require.IsType(t, x, res) - x = res.(*interface{}) + x, ok = res.(*interface{}) + require.True(t, ok) assert.EqualValues(t, "PutDogExists", *x) res, err = responses.JSONLookup("unknown") - if !assert.Error(t, err) || !assert.Nil(t, res) { - t.FailNow() - return - } + require.Error(t, err) + require.Nil(t, res) } func TestResponsesBuild(t *testing.T) { diff --git a/schema_test.go b/schema_test.go index 110764e..038284c 100644 --- a/schema_test.go +++ b/schema_test.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var schema = Schema{ @@ -153,56 +154,56 @@ func TestSchema(t *testing.T) { expected := map[string]interface{}{} _ = json.Unmarshal([]byte(schemaJSON), &expected) b, err := json.Marshal(schema) - if assert.NoError(t, err) { - var actual map[string]interface{} - _ = json.Unmarshal(b, &actual) - assert.Equal(t, expected, actual) - } + require.NoError(t, err) + + var actual map[string]interface{} + require.NoError(t, json.Unmarshal(b, &actual)) + assert.Equal(t, expected, actual) actual2 := Schema{} - if assert.NoError(t, json.Unmarshal([]byte(schemaJSON), &actual2)) { - assert.Equal(t, schema.Ref, actual2.Ref) - assert.Equal(t, schema.Description, actual2.Description) - assert.Equal(t, schema.Maximum, actual2.Maximum) - assert.Equal(t, schema.Minimum, actual2.Minimum) - assert.Equal(t, schema.ExclusiveMinimum, actual2.ExclusiveMinimum) - assert.Equal(t, schema.ExclusiveMaximum, actual2.ExclusiveMaximum) - assert.Equal(t, schema.MaxLength, actual2.MaxLength) - assert.Equal(t, schema.MinLength, actual2.MinLength) - assert.Equal(t, schema.Pattern, actual2.Pattern) - assert.Equal(t, schema.MaxItems, actual2.MaxItems) - assert.Equal(t, schema.MinItems, actual2.MinItems) - assert.True(t, actual2.UniqueItems) - assert.Equal(t, schema.MultipleOf, actual2.MultipleOf) - assert.Equal(t, schema.Enum, actual2.Enum) - assert.Equal(t, schema.Type, actual2.Type) - assert.Equal(t, schema.Format, actual2.Format) - assert.Equal(t, schema.Title, actual2.Title) - assert.Equal(t, schema.MaxProperties, actual2.MaxProperties) - assert.Equal(t, schema.MinProperties, actual2.MinProperties) - assert.Equal(t, schema.Required, actual2.Required) - assert.Equal(t, schema.Items, actual2.Items) - assert.Equal(t, schema.AllOf, actual2.AllOf) - assert.Equal(t, schema.Properties, actual2.Properties) - assert.Equal(t, schema.Discriminator, actual2.Discriminator) - assert.Equal(t, schema.ReadOnly, actual2.ReadOnly) - assert.Equal(t, schema.XML, actual2.XML) - assert.Equal(t, schema.ExternalDocs, actual2.ExternalDocs) - assert.Equal(t, schema.AdditionalProperties, actual2.AdditionalProperties) - assert.Equal(t, schema.Extensions, actual2.Extensions) - examples := actual2.Example.([]interface{}) - expEx := schema.Example.([]interface{}) - ex1 := examples[0].(map[string]interface{}) - ex2 := examples[1].(map[string]interface{}) - exp1 := expEx[0].(map[string]interface{}) - exp2 := expEx[1].(map[string]interface{}) - - assert.EqualValues(t, exp1["id"], ex1["id"]) - assert.Equal(t, exp1["name"], ex1["name"]) - assert.EqualValues(t, exp2["id"], ex2["id"]) - assert.Equal(t, exp2["name"], ex2["name"]) - } + require.NoError(t, json.Unmarshal([]byte(schemaJSON), &actual2)) + + assert.Equal(t, schema.Ref, actual2.Ref) + assert.Equal(t, schema.Description, actual2.Description) + assert.Equal(t, schema.Maximum, actual2.Maximum) + assert.Equal(t, schema.Minimum, actual2.Minimum) + assert.Equal(t, schema.ExclusiveMinimum, actual2.ExclusiveMinimum) + assert.Equal(t, schema.ExclusiveMaximum, actual2.ExclusiveMaximum) + assert.Equal(t, schema.MaxLength, actual2.MaxLength) + assert.Equal(t, schema.MinLength, actual2.MinLength) + assert.Equal(t, schema.Pattern, actual2.Pattern) + assert.Equal(t, schema.MaxItems, actual2.MaxItems) + assert.Equal(t, schema.MinItems, actual2.MinItems) + assert.True(t, actual2.UniqueItems) + assert.Equal(t, schema.MultipleOf, actual2.MultipleOf) + assert.Equal(t, schema.Enum, actual2.Enum) + assert.Equal(t, schema.Type, actual2.Type) + assert.Equal(t, schema.Format, actual2.Format) + assert.Equal(t, schema.Title, actual2.Title) + assert.Equal(t, schema.MaxProperties, actual2.MaxProperties) + assert.Equal(t, schema.MinProperties, actual2.MinProperties) + assert.Equal(t, schema.Required, actual2.Required) + assert.Equal(t, schema.Items, actual2.Items) + assert.Equal(t, schema.AllOf, actual2.AllOf) + assert.Equal(t, schema.Properties, actual2.Properties) + assert.Equal(t, schema.Discriminator, actual2.Discriminator) + assert.Equal(t, schema.ReadOnly, actual2.ReadOnly) + assert.Equal(t, schema.XML, actual2.XML) + assert.Equal(t, schema.ExternalDocs, actual2.ExternalDocs) + assert.Equal(t, schema.AdditionalProperties, actual2.AdditionalProperties) + assert.Equal(t, schema.Extensions, actual2.Extensions) + + examples := actual2.Example.([]interface{}) + expEx := schema.Example.([]interface{}) + ex1 := examples[0].(map[string]interface{}) + ex2 := examples[1].(map[string]interface{}) + exp1 := expEx[0].(map[string]interface{}) + exp2 := expEx[1].(map[string]interface{}) + assert.EqualValues(t, exp1["id"], ex1["id"]) + assert.Equal(t, exp1["name"], ex1["name"]) + assert.EqualValues(t, exp2["id"], ex2["id"]) + assert.Equal(t, exp2["name"], ex2["name"]) } func BenchmarkSchemaUnmarshal(b *testing.B) { diff --git a/spec.go b/spec.go index 7d38b6e..b388503 100644 --- a/spec.go +++ b/spec.go @@ -26,7 +26,7 @@ import ( const ( // SwaggerSchemaURL the url for the swagger 2.0 schema to validate specs SwaggerSchemaURL = "http://swagger.io/v2/schema.json#" - // JSONSchemaURL the url for the json schema schema + // JSONSchemaURL the url for the json schema JSONSchemaURL = "http://json-schema.org/draft-04/schema#" ) diff --git a/structs_test.go b/structs_test.go index d4b87f4..7b076b4 100644 --- a/structs_test.go +++ b/structs_test.go @@ -28,7 +28,7 @@ func assertSerializeJSON(t testing.TB, actual interface{}, expected string) bool if err != nil { return assert.Fail(t, "unable to marshal to json (%s): %#v", err, actual) } - return assert.Equal(t, string(ser), expected) + return assert.Equal(t, expected, string(ser)) } func assertSerializeYAML(t testing.TB, actual interface{}, expected string) bool { @@ -36,7 +36,7 @@ func assertSerializeYAML(t testing.TB, actual interface{}, expected string) bool if err != nil { return assert.Fail(t, "unable to marshal to yaml (%s): %#v", err, actual) } - return assert.Equal(t, string(ser), expected) + return assert.Equal(t, expected, string(ser)) } func derefTypeOf(expected interface{}) (tpe reflect.Type) { @@ -65,7 +65,7 @@ func assertParsesJSON(t testing.TB, actual string, expected interface{}) bool { if !isPointed(expected) { act = reflect.Indirect(parsed).Interface() } - return assert.Equal(t, act, expected) + return assert.Equal(t, expected, act) } func assertParsesYAML(t testing.TB, actual string, expected interface{}) bool { diff --git a/swagger_test.go b/swagger_test.go index 23aa509..cb288e6 100644 --- a/swagger_test.go +++ b/swagger_test.go @@ -107,7 +107,6 @@ const specJSON = `{ "x-schemes": ["unix","amqp"] }` -// // func verifySpecSerialize(specJSON []byte, spec Swagger) { // expected := map[string]interface{}{} // json.Unmarshal(specJSON, &expected) @@ -120,96 +119,96 @@ const specJSON = `{ // } /* -// assertEquivalent is currently unused -func assertEquivalent(t testing.TB, actual, expected interface{}) bool { - if actual == nil || expected == nil || reflect.DeepEqual(actual, expected) { - return true - } - - actualType := reflect.TypeOf(actual) - expectedType := reflect.TypeOf(expected) - if reflect.TypeOf(actual).ConvertibleTo(expectedType) { - expectedValue := reflect.ValueOf(expected) - if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { + // assertEquivalent is currently unused + func assertEquivalent(t testing.TB, actual, expected interface{}) bool { + if actual == nil || expected == nil || reflect.DeepEqual(actual, expected) { return true } - // Attempt comparison after type conversion - if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { + actualType := reflect.TypeOf(actual) + expectedType := reflect.TypeOf(expected) + if reflect.TypeOf(actual).ConvertibleTo(expectedType) { + expectedValue := reflect.ValueOf(expected) + if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { + return true + } + + // Attempt comparison after type conversion + if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { + return true + } + } + + // Last ditch effort + if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { return true } + errFmt := "Expected: '%[1]T(%[1]#v)'\nActual: '%[2]T(%[2]#v)'\n(Should be equivalent)!" + return assert.Fail(t, errFmt, expected, actual) } - // Last ditch effort - if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { - return true - } - errFmt := "Expected: '%T(%#v)'\nActual: '%T(%#v)'\n(Should be equivalent)!" - return assert.Fail(t, errFmt, expected, expected, actual, actual) -} + // ShouldBeEquivalentTo is currently unused + func ShouldBeEquivalentTo(actual interface{}, expecteds ...interface{}) string { + expected := expecteds[0] + if actual == nil || expected == nil { + return "" + } -// ShouldBeEquivalentTo is currently unused -func ShouldBeEquivalentTo(actual interface{}, expecteds ...interface{}) string { - expected := expecteds[0] - if actual == nil || expected == nil { - return "" - } + if reflect.DeepEqual(expected, actual) { + return "" + } - if reflect.DeepEqual(expected, actual) { - return "" - } + actualType := reflect.TypeOf(actual) + expectedType := reflect.TypeOf(expected) + if reflect.TypeOf(actual).ConvertibleTo(expectedType) { + expectedValue := reflect.ValueOf(expected) + if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { + return "" + } - actualType := reflect.TypeOf(actual) - expectedType := reflect.TypeOf(expected) - if reflect.TypeOf(actual).ConvertibleTo(expectedType) { - expectedValue := reflect.ValueOf(expected) - if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { - return "" + // Attempt comparison after type conversion + if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { + return "" + } } - // Attempt comparison after type conversion - if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { + // Last ditch effort + if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { return "" } + errFmt := "Expected: '%[1]T(%[1]#v)'\nActual: '%[2]T(%[2]#v)'\n(Should be equivalent)!" + return fmt.Sprintf(errFmt, expected, actual) } - // Last ditch effort - if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { - return "" - } - errFmt := "Expected: '%T(%#v)'\nActual: '%T(%#v)'\n(Should be equivalent)!" - return fmt.Sprintf(errFmt, expected, expected, actual, actual) - -} - -// assertSpecMaps is currently unused -func assertSpecMaps(t testing.TB, actual, expected map[string]interface{}) bool { - res := true - if id, ok := expected["id"]; ok { - res = assert.Equal(t, id, actual["id"]) + // assertSpecMaps is currently unused + func assertSpecMaps(t testing.TB, actual, expected map[string]interface{}) bool { + res := true + if id, ok := expected["id"]; ok { + res = assert.Equal(t, id, actual["id"]) + } + res = res && assert.Equal(t, expected["consumes"], actual["consumes"]) + res = res && assert.Equal(t, expected["produces"], actual["produces"]) + res = res && assert.Equal(t, expected["schemes"], actual["schemes"]) + res = res && assert.Equal(t, expected["swagger"], actual["swagger"]) + res = res && assert.Equal(t, expected["info"], actual["info"]) + res = res && assert.Equal(t, expected["host"], actual["host"]) + res = res && assert.Equal(t, expected["basePath"], actual["basePath"]) + res = res && assert.Equal(t, expected["paths"], actual["paths"]) + res = res && assert.Equal(t, expected["definitions"], actual["definitions"]) + res = res && assert.Equal(t, expected["responses"], actual["responses"]) + res = res && assert.Equal(t, expected["securityDefinitions"], actual["securityDefinitions"]) + res = res && assert.Equal(t, expected["tags"], actual["tags"]) + res = res && assert.Equal(t, expected["externalDocs"], actual["externalDocs"]) + res = res && assert.Equal(t, expected["x-some-extension"], actual["x-some-extension"]) + res = res && assert.Equal(t, expected["x-schemes"], actual["x-schemes"]) + + return res } - res = res && assert.Equal(t, expected["consumes"], actual["consumes"]) - res = res && assert.Equal(t, expected["produces"], actual["produces"]) - res = res && assert.Equal(t, expected["schemes"], actual["schemes"]) - res = res && assert.Equal(t, expected["swagger"], actual["swagger"]) - res = res && assert.Equal(t, expected["info"], actual["info"]) - res = res && assert.Equal(t, expected["host"], actual["host"]) - res = res && assert.Equal(t, expected["basePath"], actual["basePath"]) - res = res && assert.Equal(t, expected["paths"], actual["paths"]) - res = res && assert.Equal(t, expected["definitions"], actual["definitions"]) - res = res && assert.Equal(t, expected["responses"], actual["responses"]) - res = res && assert.Equal(t, expected["securityDefinitions"], actual["securityDefinitions"]) - res = res && assert.Equal(t, expected["tags"], actual["tags"]) - res = res && assert.Equal(t, expected["externalDocs"], actual["externalDocs"]) - res = res && assert.Equal(t, expected["x-some-extension"], actual["x-some-extension"]) - res = res && assert.Equal(t, expected["x-schemes"], actual["x-schemes"]) - - return res -} */ + func assertSpecs(t testing.TB, actual, expected Swagger) bool { expected.Swagger = "2.0" - return assert.Equal(t, actual, expected) + return assert.Equal(t, expected, actual) } /* @@ -233,7 +232,7 @@ func assertSpecJSON(t testing.TB, specJSON []byte) bool { if !assert.NoError(t, json.Unmarshal(cb, &actual)) { return false } - return assertSpecMaps(t, actual, expected) + return assertSpecMaps(t, expected, actual ) } */ @@ -241,48 +240,41 @@ func TestSwaggerSpec_Serialize(t *testing.T) { expected := make(map[string]interface{}) _ = json.Unmarshal([]byte(specJSON), &expected) b, err := json.MarshalIndent(spec, "", " ") - if assert.NoError(t, err) { - var actual map[string]interface{} - err := json.Unmarshal(b, &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, actual, expected) - } - } + require.NoError(t, err) + var actual map[string]interface{} + require.NoError(t, json.Unmarshal(b, &actual)) + assert.EqualValues(t, actual, expected) } func TestSwaggerSpec_Deserialize(t *testing.T) { var actual Swagger - err := json.Unmarshal([]byte(specJSON), &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, actual, spec) - } + require.NoError(t, json.Unmarshal([]byte(specJSON), &actual)) + assert.EqualValues(t, actual, spec) } func TestVendorExtensionStringSlice(t *testing.T) { var actual Swagger - err := json.Unmarshal([]byte(specJSON), &actual) - if assert.NoError(t, err) { - schemes, ok := actual.Extensions.GetStringSlice("x-schemes") - if assert.True(t, ok) { - assert.EqualValues(t, []string{"unix", "amqp"}, schemes) - } - notSlice, ok := actual.Extensions.GetStringSlice("x-some-extension") - assert.Nil(t, notSlice) - assert.False(t, ok) - - actual.AddExtension("x-another-ext", 100) - notString, ok := actual.Extensions.GetStringSlice("x-another-ext") - assert.Nil(t, notString) - assert.False(t, ok) - - actual.AddExtension("x-another-slice-ext", []interface{}{100, 100}) - notStringSlice, ok := actual.Extensions.GetStringSlice("x-another-slice-ext") - assert.Nil(t, notStringSlice) - assert.False(t, ok) - - _, ok = actual.Extensions.GetStringSlice("x-notfound-ext") - assert.False(t, ok) - } + require.NoError(t, json.Unmarshal([]byte(specJSON), &actual)) + schemes, ok := actual.Extensions.GetStringSlice("x-schemes") + require.True(t, ok) + assert.EqualValues(t, []string{"unix", "amqp"}, schemes) + + notSlice, ok := actual.Extensions.GetStringSlice("x-some-extension") + assert.Nil(t, notSlice) + assert.False(t, ok) + + actual.AddExtension("x-another-ext", 100) + notString, ok := actual.Extensions.GetStringSlice("x-another-ext") + assert.Nil(t, notString) + assert.False(t, ok) + + actual.AddExtension("x-another-slice-ext", []interface{}{100, 100}) + notStringSlice, ok := actual.Extensions.GetStringSlice("x-another-slice-ext") + assert.Nil(t, notStringSlice) + assert.False(t, ok) + + _, ok = actual.Extensions.GetStringSlice("x-notfound-ext") + assert.False(t, ok) } func TestOptionalSwaggerProps_Serialize(t *testing.T) { @@ -307,26 +299,25 @@ func TestOptionalSwaggerProps_Serialize(t *testing.T) { var minimalSpec Swagger err := json.Unmarshal(minimalJSONSpec, &minimalSpec) - if assert.NoError(t, err) { - bytes, err := json.Marshal(&minimalSpec) - if assert.NoError(t, err) { - var ms map[string]interface{} - if err := json.Unmarshal(bytes, &ms); assert.NoError(t, err) { - assert.NotContains(t, ms, "consumes") - assert.NotContains(t, ms, "produces") - assert.NotContains(t, ms, "schemes") - assert.NotContains(t, ms, "host") - assert.NotContains(t, ms, "basePath") - assert.NotContains(t, ms, "definitions") - assert.NotContains(t, ms, "parameters") - assert.NotContains(t, ms, "responses") - assert.NotContains(t, ms, "securityDefinitions") - assert.NotContains(t, ms, "security") - assert.NotContains(t, ms, "tags") - assert.NotContains(t, ms, "externalDocs") - } - } - } + require.NoError(t, err) + bytes, err := json.Marshal(&minimalSpec) + require.NoError(t, err) + + var ms map[string]interface{} + require.NoError(t, json.Unmarshal(bytes, &ms)) + + assert.NotContains(t, ms, "consumes") + assert.NotContains(t, ms, "produces") + assert.NotContains(t, ms, "schemes") + assert.NotContains(t, ms, "host") + assert.NotContains(t, ms, "basePath") + assert.NotContains(t, ms, "definitions") + assert.NotContains(t, ms, "parameters") + assert.NotContains(t, ms, "responses") + assert.NotContains(t, ms, "securityDefinitions") + assert.NotContains(t, ms, "security") + assert.NotContains(t, ms, "tags") + assert.NotContains(t, ms, "externalDocs") } var minimalJSONSpec = []byte(`{ @@ -376,16 +367,15 @@ var minimalJSONSpec = []byte(`{ func TestSecurityRequirements(t *testing.T) { var minimalSpec Swagger - err := json.Unmarshal(minimalJSONSpec, &minimalSpec) - if assert.NoError(t, err) { - sec := minimalSpec.Paths.Paths["/"].Get.Security - require.Len(t, sec, 3) - assert.Contains(t, sec[0], "basic") - assert.Contains(t, sec[0], "apiKey") - assert.NotNil(t, sec[1]) - assert.Empty(t, sec[1]) - assert.Contains(t, sec[2], "queryKey") - } + require.NoError(t, json.Unmarshal(minimalJSONSpec, &minimalSpec)) + + sec := minimalSpec.Paths.Paths["/"].Get.Security + require.Len(t, sec, 3) + assert.Contains(t, sec[0], "basic") + assert.Contains(t, sec[0], "apiKey") + assert.NotNil(t, sec[1]) + assert.Empty(t, sec[1]) + assert.Contains(t, sec[2], "queryKey") } func TestSwaggerGobEncoding(t *testing.T) { @@ -396,10 +386,7 @@ func TestSwaggerGobEncoding(t *testing.T) { func doTestSwaggerGobEncoding(t *testing.T, fixture string) { var src, dst Swagger - - if !assert.NoError(t, json.Unmarshal([]byte(fixture), &src)) { - t.FailNow() - } + require.NoError(t, json.Unmarshal([]byte(fixture), &src)) doTestAnyGobEncoding(t, &src, &dst) } diff --git a/validations_test.go b/validations_test.go index b62f82e..993547c 100644 --- a/validations_test.go +++ b/validations_test.go @@ -75,7 +75,6 @@ func TestValidations(t *testing.T) { expectedSV.PatternProperties = nil expectedSV.MinProperties = nil expectedSV.MaxProperties = nil - val = mkVal() val = mkVal() cv.SetValidations(val) diff --git a/xml_object_test.go b/xml_object_test.go index da616a9..8573e82 100644 --- a/xml_object_test.go +++ b/xml_object_test.go @@ -19,14 +19,14 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestXmlObject_Serialize(t *testing.T) { obj1 := XMLObject{} actual, err := json.Marshal(obj1) - if assert.NoError(t, err) { - assert.Equal(t, "{}", string(actual)) - } + require.NoError(t, err) + assert.Equal(t, "{}", string(actual)) obj2 := XMLObject{ Name: "the name", @@ -37,24 +37,22 @@ func TestXmlObject_Serialize(t *testing.T) { } actual, err = json.Marshal(obj2) - if assert.NoError(t, err) { - var ad map[string]interface{} - if assert.NoError(t, json.Unmarshal(actual, &ad)) { - assert.Equal(t, obj2.Name, ad["name"]) - assert.Equal(t, obj2.Namespace, ad["namespace"]) - assert.Equal(t, obj2.Prefix, ad["prefix"]) - assert.True(t, ad["attribute"].(bool)) - assert.True(t, ad["wrapped"].(bool)) - } - } + require.NoError(t, err) + + var ad map[string]interface{} + require.NoError(t, json.Unmarshal(actual, &ad)) + assert.Equal(t, obj2.Name, ad["name"]) + assert.Equal(t, obj2.Namespace, ad["namespace"]) + assert.Equal(t, obj2.Prefix, ad["prefix"]) + assert.True(t, ad["attribute"].(bool)) + assert.True(t, ad["wrapped"].(bool)) } func TestXmlObject_Deserialize(t *testing.T) { expected := XMLObject{} actual := XMLObject{} - if assert.NoError(t, json.Unmarshal([]byte("{}"), &actual)) { - assert.Equal(t, expected, actual) - } + require.NoError(t, json.Unmarshal([]byte("{}"), &actual)) + assert.Equal(t, expected, actual) completed := `{"name":"the name","namespace":"the namespace","prefix":"the prefix","attribute":true,"wrapped":true}` expected = XMLObject{ @@ -64,8 +62,8 @@ func TestXmlObject_Deserialize(t *testing.T) { Attribute: true, Wrapped: true, } + actual = XMLObject{} - if assert.NoError(t, json.Unmarshal([]byte(completed), &actual)) { - assert.Equal(t, expected, actual) - } + require.NoError(t, json.Unmarshal([]byte(completed), &actual)) + assert.Equal(t, expected, actual) }