From 21e2335ed16e3ec63d3fea6ddda2e133f979eac9 Mon Sep 17 00:00:00 2001 From: lansfy <5764541+lansfy@users.noreply.github.com> Date: Mon, 6 Jan 2025 11:57:31 -0700 Subject: [PATCH] new: enable some linters (staticcheck, ineffassign, govet, errcheck, revive, unparam) --- .golangci.yml | 15 +++++------- checker/response_db/response_db.go | 8 ------- colorize/error.go | 3 +-- examples/mock-based-on-request/main.go | 3 +-- examples/mock-field-json-str/main.go | 4 ++-- examples/traffic-lights-demo/main.go | 4 ++-- examples/with-cases-example/main.go | 4 ++-- mocks/constraint_query_regexp_test.go | 26 ++++++++------------ mocks/definition.go | 26 ++++++++++---------- mocks/error.go | 13 +--------- mocks/getters.go | 12 +++++----- mocks/loader.go | 8 +++---- mocks/mocks.go | 4 +--- mocks/service_mock.go | 6 ++--- mocks/strategy_based_on_request_reply.go | 6 ++--- mocks/strategy_constant_reply.go | 6 ++--- mocks/strategy_constant_reply_test.go | 6 ++--- mocks/strategy_drop_request.go | 6 ++--- mocks/strategy_template_reply.go | 2 +- output/allure/allure.go | 10 ++++---- output/terminal/terminal.go | 6 ++--- runner/request.go | 3 +-- runner/runner.go | 4 ++-- runner/runner_upload_file_test.go | 4 ++-- storage/addons/sqldb/fixtures.go | 16 +++++++++---- storage/addons/sqldb/tojson.go | 6 +++-- testloader/yaml_file/parser.go | 4 ++-- testloader/yaml_file/test_test.go | 30 ++++++++---------------- testloader/yaml_file/yaml_file.go | 13 ++++++---- variables/response_parser.go | 2 +- 30 files changed, 113 insertions(+), 147 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 533ea8c..2756f0b 100755 --- a/.golangci.yml +++ b/.golangci.yml @@ -46,7 +46,6 @@ linters-settings: - name: error-return - name: error-strings - name: errorf - - name: exported - name: identical-branches - name: if-return - name: import-shadowing @@ -65,14 +64,13 @@ linters-settings: - name: unreachable-code #- name: unhandled-error - name: var-declaration - - name: var-naming linters: disable-all: true enable: - bodyclose - dogsled - #- errcheck + - errcheck - exportloopref #- funlen - gochecknoinits @@ -80,19 +78,18 @@ linters: #- gocritic - gofmt - goimports - #- gosec - gosimple - #- govet - #- ineffassign + - govet + - ineffassign - lll - misspell - nakedret - #- revive - #- staticcheck + - revive + - staticcheck #- stylecheck - typecheck - unconvert - #- unparam + - unparam - unused - whitespace diff --git a/checker/response_db/response_db.go b/checker/response_db/response_db.go index 6ca0b73..86dd069 100644 --- a/checker/response_db/response_db.go +++ b/checker/response_db/response_db.go @@ -135,14 +135,6 @@ func compareDbResponseLength(expected, actual []string, query interface{}) error len(expected), len(actual), ).AddParts(tail...) - - return colorize.NewError( - "quantity of items in database do not match (-expected: %s +actual: %s)\n test query:\n%s\n result diff:\n%s", - colorize.Cyan(len(expected)), - colorize.Cyan(len(actual)), - colorize.Cyan(query), - colorize.Cyan(pretty.Compare(expected, actual)), - ) } func newQuery(dbQuery string, db storage.StorageInterface) ([]string, error) { diff --git a/colorize/error.go b/colorize/error.go index d867bd6..c471e7d 100644 --- a/colorize/error.go +++ b/colorize/error.go @@ -38,8 +38,7 @@ func (e *Error) AddParts(values ...Part) *Error { } func (e *Error) SetSubError(err error) *Error { - e.AddParts(SubError(err)) - return e + return e.AddParts(SubError(err)) } func (e *Error) Error() string { diff --git a/examples/mock-based-on-request/main.go b/examples/mock-based-on-request/main.go index fd08c08..ccd52d3 100755 --- a/examples/mock-based-on-request/main.go +++ b/examples/mock-based-on-request/main.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "log" "net/http" "net/url" @@ -45,7 +44,7 @@ func Do(w http.ResponseWriter, r *http.Request) { if res.StatusCode != http.StatusOK { return 0, fmt.Errorf("backend response status code %d", res.StatusCode) } - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) _ = res.Body.Close() if err != nil { return 0, fmt.Errorf("cannot read response body: %w", err) diff --git a/examples/mock-field-json-str/main.go b/examples/mock-field-json-str/main.go index c034cb6..97b2a33 100644 --- a/examples/mock-field-json-str/main.go +++ b/examples/mock-field-json-str/main.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "log" "net/http" "os" @@ -20,7 +20,7 @@ func initServer() { } func ProxyRequest(w http.ResponseWriter, r *http.Request) { - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { log.Print(err) w.Write([]byte("{\"status\": \"error\"}")) diff --git a/examples/traffic-lights-demo/main.go b/examples/traffic-lights-demo/main.go index 0113a64..c93c5f8 100644 --- a/examples/traffic-lights-demo/main.go +++ b/examples/traffic-lights-demo/main.go @@ -3,7 +3,7 @@ package main import ( "encoding/json" "fmt" - "io/ioutil" + "io" "log" "net/http" "sync" @@ -54,7 +54,7 @@ func initServer() { lights.mutex.Lock() defer lights.mutex.Unlock() - request, err := ioutil.ReadAll(r.Body) + request, err := io.ReadAll(r.Body) if err != nil { log.Fatal(err) } diff --git a/examples/with-cases-example/main.go b/examples/with-cases-example/main.go index ea0d576..f320cd1 100644 --- a/examples/with-cases-example/main.go +++ b/examples/with-cases-example/main.go @@ -3,7 +3,7 @@ package main import ( "encoding/json" "fmt" - "io/ioutil" + "io" "log" "net/http" ) @@ -34,7 +34,7 @@ func Do(w http.ResponseWriter, r *http.Request) { return } - jsonRequest, _ := ioutil.ReadAll(r.Body) + jsonRequest, _ := io.ReadAll(r.Body) request := buildRequest(jsonRequest) if request.Name == "a" { diff --git a/mocks/constraint_query_regexp_test.go b/mocks/constraint_query_regexp_test.go index f7136f7..311b616 100644 --- a/mocks/constraint_query_regexp_test.go +++ b/mocks/constraint_query_regexp_test.go @@ -3,8 +3,9 @@ package mocks import ( "net/http" "net/url" - "reflect" "testing" + + "github.com/stretchr/testify/require" ) func Test_newQueryRegexpConstraint(t *testing.T) { @@ -34,19 +35,14 @@ func Test_newQueryRegexpConstraint(t *testing.T) { want: queryRegexpConstraint{expectedQuery: map[string][]string{"a": {"1", "3"}, "b": {"$matchRegexp(\\d+)"}}}, }, } + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := newQueryRegexpConstraint(tt.query) - if err != nil { - t.Errorf("newQueryRegexpConstraint() error = %v", err) - return - } - if got == nil { - t.Fatalf("unexpected. got nil instead of queryRegexpConstraint") - } - if !reflect.DeepEqual(*got, tt.want) { - t.Errorf("newQueryRegexpConstraint() = %v, want %v", *got, tt.want) - } + + require.NoError(t, err) + require.NotNil(t, got) + require.Equal(t, tt.want, *got) }) } } @@ -101,16 +97,14 @@ func Test_queryRegexpConstraint_Verify(t *testing.T) { wantErrors: 1, }, } + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { c := &queryRegexpConstraint{ expectedQuery: tt.expQuery, } - if gotErrors := c.Verify(tt.req); len(gotErrors) != tt.wantErrors { - t.Errorf("unexpected amount of errors. Got %v, want %v. Errors are: '%v'", - len(gotErrors), tt.wantErrors, gotErrors, - ) - } + gotErrors := c.Verify(tt.req) + require.Equal(t, tt.wantErrors, len(gotErrors), "unexpected amount of errors. Got %v, want %v. Errors: '%v'", len(gotErrors), tt.wantErrors, gotErrors) }) } } diff --git a/mocks/definition.go b/mocks/definition.go index 1e7f735..e75037e 100644 --- a/mocks/definition.go +++ b/mocks/definition.go @@ -37,11 +37,11 @@ func (d *Definition) Execute(w http.ResponseWriter, r *http.Request) []error { d.calls++ d.mutex.Unlock() - errors := verifyRequestConstraints(d.requestConstraints, r) + errs := verifyRequestConstraints(d.requestConstraints, r) if d.replyStrategy != nil { - errors = append(errors, d.replyStrategy.HandleRequest(w, r)...) + errs = append(errs, d.replyStrategy.HandleRequest(w, r)...) } - return errors + return errs } func (d *Definition) ResetRunningContext() { @@ -61,11 +61,9 @@ func (d *Definition) EndRunningContext() []error { errs = s.EndRunningContext() } if d.callsConstraint != CallsNoConstraint && d.calls != d.callsConstraint { - err := colorize.NewEntityError("at path %s", d.path) - err.SetSubError( + errs = append(errs, colorize.NewEntityError("at path %s", d.path).SetSubError( colorize.NewNotEqualError("number of %s does not match:", "calls", d.callsConstraint, d.calls), - ) - errs = append(errs, err) + )) } return errs } @@ -80,17 +78,17 @@ func verifyRequestConstraints(requestConstraints []verifier, r *http.Request) [] requestDump = []byte(fmt.Sprintf("dump request: %v", err)) } - var errors []error + var errs []error for _, c := range requestConstraints { - errs := c.Verify(r) - for _, e := range errs { - err := colorize.NewEntityError("request constraint %s", c.GetName()).SetSubError(e) - err.AddParts(colorize.None(", request was:\n\n"), colorize.None(string(requestDump))) - errors = append(errors, err) + for _, e := range c.Verify(r) { + errs = append(errs, colorize.NewEntityError("request constraint %s", c.GetName()).SetSubError(e).AddParts( + colorize.None(", request was:\n\n"), + colorize.None(string(requestDump)), + )) } } - return errors + return errs } func (d *Definition) ExecuteWithoutVerifying(w http.ResponseWriter, r *http.Request) []error { d.mutex.Lock() diff --git a/mocks/error.go b/mocks/error.go index 8c4eb6b..633cb1b 100644 --- a/mocks/error.go +++ b/mocks/error.go @@ -6,21 +6,10 @@ import ( "net/http/httputil" ) -type RequestConstraintError struct { - error - Constraint verifier - RequestDump []byte -} - -func (e *RequestConstraintError) Error() string { - kind := e.Constraint.GetName() - return fmt.Sprintf("request constraint %q: %s, request was:\n%s", kind, e.error.Error(), e.RequestDump) -} - func unhandledRequestError(r *http.Request) []error { requestContent, err := httputil.DumpRequest(r, true) if err != nil { - return []error{fmt.Errorf("Gonkex internal error during request dump: %s\n", err)} + return []error{fmt.Errorf("gonkex internal error during request dump: %s", err)} } return []error{fmt.Errorf("unhandled request to mock:\n%s", requestContent)} } diff --git a/mocks/getters.go b/mocks/getters.go index 7976ff6..61018ce 100644 --- a/mocks/getters.go +++ b/mocks/getters.go @@ -4,7 +4,7 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" + "io" "net/http" "github.com/lansfy/gonkex/compare" @@ -116,22 +116,22 @@ func readCompareParams(def map[interface{}]interface{}) (compare.Params, error) return params, wrap(wrongTypeError(skey, "bool")) } - if pbval, ok := mapping[skey]; ok { - *pbval = bval - } else { + pbval, ok := mapping[skey] + if !ok { return params, wrap(fmt.Errorf("unexpected key '%s' (allowed only %v)", skey, allowedKeys)) } + *pbval = bval } return params, nil } func getBodyCopy(r *http.Request) ([]byte, error) { - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { return nil, err } // write body for future reusing - r.Body = ioutil.NopCloser(bytes.NewReader(body)) + r.Body = io.NopCloser(bytes.NewReader(body)) return body, nil } diff --git a/mocks/loader.go b/mocks/loader.go index ac5c45c..48f6fa5 100644 --- a/mocks/loader.go +++ b/mocks/loader.go @@ -104,19 +104,19 @@ func (l *loaderImpl) loadStrategy(path, strategyName string, definition map[inte return NewNopReply(), nil case "constant": *ak = append(*ak, "body", "statusCode", "headers") - return l.loadConstantStrategy(path, definition) + return l.loadConstantStrategy(definition) case "sequence": *ak = append(*ak, "sequence") return l.loadSequenceReplyStrategy(path, definition) case "template": *ak = append(*ak, "body", "statusCode", "headers") - return l.loadTemplateReplyStrategy(path, definition) + return l.loadTemplateReplyStrategy(definition) case "basedOnRequest": *ak = append(*ak, "basePath", "uris") return l.loadBasedOnRequestReplyStrategy(path, definition) case "file": *ak = append(*ak, "filename", "statusCode", "headers") - return l.loadFileStrategy(path, definition) + return l.loadFileStrategy(definition) case "uriVary": *ak = append(*ak, "basePath", "uris") return l.loadUriVaryReplyStrategy(path, definition) @@ -124,7 +124,7 @@ func (l *loaderImpl) loadStrategy(path, strategyName string, definition map[inte *ak = append(*ak, "methods") return l.loadMethodVaryStrategy(path, definition) case "dropRequest": - return l.loadDropRequestStrategy(path, definition) + return l.loadDropRequestStrategy() default: return nil, errors.New("unknown strategy") } diff --git a/mocks/mocks.go b/mocks/mocks.go index 964fa2a..66a9df1 100644 --- a/mocks/mocks.go +++ b/mocks/mocks.go @@ -109,9 +109,7 @@ func (m *Mocks) LoadDefinitions(loader Loader, definitions map[string]interface{ def, err := loader.LoadDefinition(definition) if err != nil { - perr := colorize.NewEntityError("load definition for %s", serviceName) - perr.SetSubError(err) - return perr + return colorize.NewEntityError("load definition for %s", serviceName).SetSubError(err) } service.SetDefinition(def) } diff --git a/mocks/service_mock.go b/mocks/service_mock.go index ee8faac..52a4559 100644 --- a/mocks/service_mock.go +++ b/mocks/service_mock.go @@ -42,7 +42,7 @@ func (m *ServiceMock) StartServerWithAddr(addr string) error { } m.listener = ln m.server = &http.Server{Addr: addr, Handler: m} - go m.server.Serve(ln) + go m.server.Serve(ln) // nolint:errcheck return nil } @@ -95,9 +95,7 @@ func (m *ServiceMock) EndRunningContext() []error { errs := append(m.errors, m.mock.EndRunningContext()...) for i, e := range errs { - err := colorize.NewEntityError("mock %s", m.ServiceName) - err.SetSubError(e) - errs[i] = err + errs[i] = colorize.NewEntityError("mock %s", m.ServiceName).SetSubError(e) } return errs } diff --git a/mocks/strategy_based_on_request_reply.go b/mocks/strategy_based_on_request_reply.go index c7bdeec..253124a 100644 --- a/mocks/strategy_based_on_request_reply.go +++ b/mocks/strategy_based_on_request_reply.go @@ -47,15 +47,15 @@ func (s *basedOnRequestReply) HandleRequest(w http.ResponseWriter, r *http.Reque s.mutex.Lock() defer s.mutex.Unlock() - var errors []error + var allerrors []error for _, def := range s.variants { errs := verifyRequestConstraints(def.requestConstraints, r) if len(errs) == 0 { return def.ExecuteWithoutVerifying(w, r) } - errors = append(errors, errs...) + allerrors = append(allerrors, errs...) } - return append(errors, unhandledRequestError(r)...) + return append(allerrors, unhandledRequestError(r)...) } func (s *basedOnRequestReply) ResetRunningContext() { diff --git a/mocks/strategy_constant_reply.go b/mocks/strategy_constant_reply.go index 527541b..b772d15 100644 --- a/mocks/strategy_constant_reply.go +++ b/mocks/strategy_constant_reply.go @@ -5,7 +5,7 @@ import ( "os" ) -func (l *loaderImpl) loadFileStrategy(path string, def map[interface{}]interface{}) (ReplyStrategy, error) { +func (l *loaderImpl) loadFileStrategy(def map[interface{}]interface{}) (ReplyStrategy, error) { filename, err := getRequiredStringKey(def, "filename", false) if err != nil { return nil, err @@ -25,7 +25,7 @@ func (l *loaderImpl) loadFileStrategy(path string, def map[interface{}]interface return NewConstantReplyWithCode(content, statusCode, headers), nil } -func (l *loaderImpl) loadConstantStrategy(path string, def map[interface{}]interface{}) (ReplyStrategy, error) { +func (l *loaderImpl) loadConstantStrategy(def map[interface{}]interface{}) (ReplyStrategy, error) { body, err := getRequiredStringKey(def, "body", true) if err != nil { return nil, err @@ -60,6 +60,6 @@ func (s *constantReply) HandleRequest(w http.ResponseWriter, r *http.Request) [] w.Header().Add(k, v) } w.WriteHeader(s.statusCode) - w.Write(s.replyBody) + w.Write(s.replyBody) // nolint:errcheck return nil } diff --git a/mocks/strategy_constant_reply_test.go b/mocks/strategy_constant_reply_test.go index 40a3e8b..b22ccad 100644 --- a/mocks/strategy_constant_reply_test.go +++ b/mocks/strategy_constant_reply_test.go @@ -1,7 +1,7 @@ package mocks import ( - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -63,7 +63,7 @@ body: "Multi-header test"`, err := yaml.Unmarshal([]byte(tt.content), &def) require.NoError(t, err) - reply, err := loader.loadConstantStrategy("$", def) + reply, err := loader.loadConstantStrategy(def) require.NoError(t, err) // Mock request and response @@ -98,7 +98,7 @@ func Test_ConstantReplyStrategy(t *testing.T) { require.NoError(t, err) require.Equal(t, 200, res.StatusCode) - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) res.Body.Close() require.Equal(t, "somebodycontent", string(body)) } diff --git a/mocks/strategy_drop_request.go b/mocks/strategy_drop_request.go index c6ba0ba..eb197d7 100644 --- a/mocks/strategy_drop_request.go +++ b/mocks/strategy_drop_request.go @@ -5,7 +5,7 @@ import ( "net/http" ) -func (l *loaderImpl) loadDropRequestStrategy(path string, _ map[interface{}]interface{}) (ReplyStrategy, error) { +func (l *loaderImpl) loadDropRequestStrategy() (ReplyStrategy, error) { return NewDropRequestReply(), nil } @@ -18,11 +18,11 @@ type dropRequestReply struct{} func (s *dropRequestReply) HandleRequest(w http.ResponseWriter, r *http.Request) []error { hj, ok := w.(http.Hijacker) if !ok { - return []error{fmt.Errorf("Gonkex internal error during drop request: webserver doesn't support hijacking")} + return []error{fmt.Errorf("gonkex internal error during drop request: webserver does not support hijacking")} } conn, _, err := hj.Hijack() if err != nil { - return []error{fmt.Errorf("Gonkex internal error during connection hijacking: %w", err)} + return []error{fmt.Errorf("gonkex internal error during connection hijacking: %w", err)} } conn.Close() return nil diff --git a/mocks/strategy_template_reply.go b/mocks/strategy_template_reply.go index 0f97bf0..b19c083 100644 --- a/mocks/strategy_template_reply.go +++ b/mocks/strategy_template_reply.go @@ -9,7 +9,7 @@ import ( "text/template" ) -func (l *loaderImpl) loadTemplateReplyStrategy(path string, def map[interface{}]interface{}) (ReplyStrategy, error) { +func (l *loaderImpl) loadTemplateReplyStrategy(def map[interface{}]interface{}) (ReplyStrategy, error) { body, err := getRequiredStringKey(def, "body", true) if err != nil { return nil, err diff --git a/output/allure/allure.go b/output/allure/allure.go index 5bab069..f3a5923 100644 --- a/output/allure/allure.go +++ b/output/allure/allure.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/xml" "errors" - "io/ioutil" + "os" "path/filepath" "time" @@ -79,10 +79,10 @@ func (a *Allure) CreateStep(name string, stepFunc func()) { func (a *Allure) StartStep(stepName string, start time.Time) { var ( // FIXME: step is overwritten below - step = beans.NewStep(stepName, start) + // step = beans.NewStep(stepName, start) suite = a.GetCurrentSuite() ) - step = currentStep[suite] + step := currentStep[suite] step.Parent.AddStep(step) currentStep[suite] = step } @@ -119,7 +119,7 @@ func getBufferInfo(buf bytes.Buffer, typ string) (string, string) { func writeBuffer(pathDir string, buf bytes.Buffer, ext string) (string, error) { fileName := uuid.New().String() + `-attachment.` + ext - err := ioutil.WriteFile(filepath.Join(pathDir, fileName), buf.Bytes(), 0o644) + err := os.WriteFile(filepath.Join(pathDir, fileName), buf.Bytes(), 0o644) return fileName, err } @@ -129,7 +129,7 @@ func writeSuite(pathDir string, suite *beans.Suite) error { if err != nil { return err } - err = ioutil.WriteFile(filepath.Join(pathDir, uuid.New().String()+`-testsuite.xml`), b, 0o644) + err = os.WriteFile(filepath.Join(pathDir, uuid.New().String()+`-testsuite.xml`), b, 0o644) if err != nil { return err } diff --git a/output/terminal/terminal.go b/output/terminal/terminal.go index 50ffeaf..cc45dc8 100644 --- a/output/terminal/terminal.go +++ b/output/terminal/terminal.go @@ -68,7 +68,7 @@ func (o *Output) Process(_ models.TestInterface, result *models.Result) error { if err != nil { return err } - o.fprintf(o.opts.CustomWriter, "%s", text) + _, _ = o.fprintf(o.opts.CustomWriter, "%s", text) } return nil @@ -87,7 +87,7 @@ func renderResult(result *models.Result, policy ColorPolicy) (string, error) { } func (o *Output) ShowSummary(summary *models.Summary) { - o.fprintf( + _, _ = o.fprintf( o.opts.CustomWriter, "\nsuccess %d, failed %d, skipped %d, broken %d, total %d\n", summary.Total-summary.Broken-summary.Failed-summary.Skipped, @@ -99,7 +99,7 @@ func (o *Output) ShowSummary(summary *models.Summary) { } func getTemplateFuncMap(policy ColorPolicy, showHeaders bool) template.FuncMap { - funcMap := template.FuncMap{} + var funcMap template.FuncMap if policy == PolicyForceColor { funcMap = template.FuncMap{ "green": color.GreenString, diff --git a/runner/request.go b/runner/request.go index 0c92de5..6008213 100644 --- a/runner/request.go +++ b/runner/request.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "fmt" "io" - "io/ioutil" "mime/multipart" "net/http" "net/url" @@ -179,7 +178,7 @@ func request(test models.TestInterface, b *bytes.Buffer, host string) (*http.Req func actualRequestBody(req *http.Request) string { if req.Body != nil { reqBodyStream, _ := req.GetBody() - reqBody, _ := ioutil.ReadAll(reqBodyStream) + reqBody, _ := io.ReadAll(reqBodyStream) return string(reqBody) } diff --git a/runner/runner.go b/runner/runner.go index 8da25d9..bfa820f 100644 --- a/runner/runner.go +++ b/runner/runner.go @@ -3,7 +3,7 @@ package runner import ( "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" @@ -168,7 +168,7 @@ func (r *Runner) executeTest(v models.TestInterface) (*models.Result, error) { return nil, err } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) _ = resp.Body.Close() diff --git a/runner/runner_upload_file_test.go b/runner/runner_upload_file_test.go index 7abcf62..13cf22e 100644 --- a/runner/runner_upload_file_test.go +++ b/runner/runner_upload_file_test.go @@ -2,7 +2,7 @@ package runner import ( "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" "path/filepath" @@ -54,7 +54,7 @@ func formFile(t *testing.T, r *http.Request, field string) (string, string) { defer func() { _ = file.Close() }() - contents, err := ioutil.ReadAll(file) + contents, err := io.ReadAll(file) require.NoError(t, err) return header.Filename, string(contents) diff --git a/storage/addons/sqldb/fixtures.go b/storage/addons/sqldb/fixtures.go index 3a27181..2c07cd7 100644 --- a/storage/addons/sqldb/fixtures.go +++ b/storage/addons/sqldb/fixtures.go @@ -182,9 +182,9 @@ func (ctx *loadContext) loadYml(location string, data []byte) error { func (ctx *loadContext) generateTestFixtures() ([]byte, error) { tables := []tableContent{} for _, lt := range ctx.tables { - items, err := ctx.processTableContent(lt.name, lt.rows) + items, err := ctx.processTableContent(lt.rows) if err != nil { - return nil, err + return nil, fmt.Errorf("processing table %s: %w", lt.name, err) } // append rows to global tables found := false @@ -203,7 +203,10 @@ func (ctx *loadContext) generateTestFixtures() ([]byte, error) { yamlTables := yaml.MapSlice{} for _, t := range tables { - yamlTables = append(yamlTables, yaml.MapItem{t.name, t.items}) + yamlTables = append(yamlTables, yaml.MapItem{ + Key: t.name, + Value: t.items, + }) } out, err := yaml.Marshal(yamlTables) @@ -219,7 +222,7 @@ type tableContent struct { items []yaml.MapSlice } -func (ctx *loadContext) processTableContent(tableName string, rows table) ([]yaml.MapSlice, error) { +func (ctx *loadContext) processTableContent(rows table) ([]yaml.MapSlice, error) { // $extend keyword allows to import values from a named row for i, row := range rows { if _, ok := row[actionExtend]; !ok { @@ -263,7 +266,10 @@ func loadRow(row tableRow) (yaml.MapSlice, error) { if err != nil { return values, err } - values = append(values, yaml.MapItem{name, val}) + values = append(values, yaml.MapItem{ + Key: name, + Value: val, + }) } return values, nil } diff --git a/storage/addons/sqldb/tojson.go b/storage/addons/sqldb/tojson.go index dd90844..5f84e99 100644 --- a/storage/addons/sqldb/tojson.go +++ b/storage/addons/sqldb/tojson.go @@ -21,12 +21,14 @@ func ExecuteQuery(_ SQLType, db *sql.DB, query string) ([]json.RawMessage, error defer rows.Close() for rows.Next() { - j, err := convertResultToJson(rows) + var j interface{} + j, err = convertResultToJson(rows) if err != nil { return nil, err } - data, err := json.Marshal(j) + var data []byte + data, err = json.Marshal(j) if err != nil { return nil, err } diff --git a/testloader/yaml_file/parser.go b/testloader/yaml_file/parser.go index 5a11399..ffc010f 100644 --- a/testloader/yaml_file/parser.go +++ b/testloader/yaml_file/parser.go @@ -3,7 +3,7 @@ package yaml_file import ( "bytes" "fmt" - "io/ioutil" + "os" "regexp" "strings" "text/template" @@ -21,7 +21,7 @@ const ( var gonkexProtectTemplate = regexp.MustCompile(`{{\s*\$`) func parseTestDefinitionFile(absPath string) ([]Test, error) { - data, err := ioutil.ReadFile(absPath) + data, err := os.ReadFile(absPath) if err != nil { return nil, fmt.Errorf("failed to read file %s:\n%s", absPath, err) } diff --git a/testloader/yaml_file/test_test.go b/testloader/yaml_file/test_test.go index f3954d0..9ede6d5 100644 --- a/testloader/yaml_file/test_test.go +++ b/testloader/yaml_file/test_test.go @@ -1,8 +1,9 @@ package yaml_file import ( - "reflect" "testing" + + "github.com/stretchr/testify/require" ) func TestNewTestWithCases(t *testing.T) { @@ -53,31 +54,20 @@ func TestNewTestWithCases(t *testing.T) { } tests, err := makeTestFromDefinition("cases/example.yaml", data) - - if err != nil { - t.Fatal(err) - } - if len(tests) != 2 { - t.Errorf("wait len(tests) == 2, got len(tests) == %d", len(tests)) - } + require.NoError(t, err) + require.Len(t, tests, 2, "expected 2 tests") reqData, err := tests[0].ToJSON() - if !reflect.DeepEqual(reqData, []byte(`{"foo": "bar", "hello": "world" }`)) { - t.Errorf("want request %s, got %s", `{"foo": "bar", "hello": "world" }`, reqData) - } + require.NoError(t, err) + require.JSONEq(t, `{"foo": "bar", "hello": "world" }`, string(reqData), "unexpected request JSON") filename := tests[0].GetFileName() - if !reflect.DeepEqual(filename, "cases/example.yaml") { - t.Errorf("want filename %s, got %s", "cases/example.yaml", filename) - } + require.Equal(t, "cases/example.yaml", filename, "unexpected filename") reqData, err = tests[1].ToJSON() - if !reflect.DeepEqual(reqData, []byte(`{"foo": "bar", "hello": "world2" }`)) { - t.Errorf("want request %s, got %s", `{"foo": "bar", "hello": "world2" }`, reqData) - } + require.NoError(t, err) + require.JSONEq(t, `{"foo": "bar", "hello": "world2" }`, string(reqData), "unexpected request JSON") filename = tests[1].GetFileName() - if !reflect.DeepEqual(filename, "cases/example.yaml") { - t.Errorf("want filename %s, got %s", "cases/example.yaml", filename) - } + require.Equal(t, "cases/example.yaml", filename, "unexpected filename") } diff --git a/testloader/yaml_file/yaml_file.go b/testloader/yaml_file/yaml_file.go index 69d91aa..2d48556 100644 --- a/testloader/yaml_file/yaml_file.go +++ b/testloader/yaml_file/yaml_file.go @@ -1,7 +1,6 @@ package yaml_file import ( - "io/ioutil" "os" "strings" @@ -56,15 +55,21 @@ func (l *YamlFileLoader) lookupPath(path string, fi os.FileInfo) ([]Test, error) return parseTestDefinitionFile(path) } - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { return nil, err } var tests []Test - for _, fi := range files { - if !fi.IsDir() && !isYmlFile(fi.Name()) { + for _, entry := range files { + if !entry.IsDir() && !isYmlFile(entry.Name()) { continue } + + fi, err := entry.Info() + if err != nil { + return nil, err + } + moreTests, err := l.lookupPath(path+"/"+fi.Name(), fi) if err != nil { return nil, err diff --git a/variables/response_parser.go b/variables/response_parser.go index f92f2ab..dc42117 100644 --- a/variables/response_parser.go +++ b/variables/response_parser.go @@ -33,7 +33,7 @@ func fromJSON(names, paths []string, body string) (*Variables, error) { for n, res := range results { if !res.Exists() { return nil, - fmt.Errorf("path '%s' doesn't exist in given json", paths[n]) + fmt.Errorf("path '%s' does not exist in given json", paths[n]) } vars.Add(NewVariable(names[n], res.String()))