Skip to content

Commit

Permalink
new: enable some linters (staticcheck, ineffassign, govet, errcheck, …
Browse files Browse the repository at this point in the history
…revive, unparam)
  • Loading branch information
lansfy committed Jan 7, 2025
1 parent 4507057 commit 21e2335
Show file tree
Hide file tree
Showing 30 changed files with 113 additions and 147 deletions.
15 changes: 6 additions & 9 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -65,34 +64,32 @@ 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
#- goconst
#- gocritic
- gofmt
- goimports
#- gosec
- gosimple
#- govet
#- ineffassign
- govet
- ineffassign
- lll
- misspell
- nakedret
#- revive
#- staticcheck
- revive
- staticcheck
#- stylecheck
- typecheck
- unconvert
#- unparam
- unparam
- unused
- whitespace

Expand Down
8 changes: 0 additions & 8 deletions checker/response_db/response_db.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
3 changes: 1 addition & 2 deletions colorize/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 1 addition & 2 deletions examples/mock-based-on-request/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions examples/mock-field-json-str/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log"
"net/http"
"os"
Expand All @@ -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\"}"))
Expand Down
4 changes: 2 additions & 2 deletions examples/traffic-lights-demo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log"
"net/http"
"sync"
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions examples/with-cases-example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log"
"net/http"
)
Expand Down Expand Up @@ -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" {
Expand Down
26 changes: 10 additions & 16 deletions mocks/constraint_query_regexp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package mocks
import (
"net/http"
"net/url"
"reflect"
"testing"

"github.com/stretchr/testify/require"
)

func Test_newQueryRegexpConstraint(t *testing.T) {
Expand Down Expand Up @@ -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)
})
}
}
Expand Down Expand Up @@ -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)
})
}
}
26 changes: 12 additions & 14 deletions mocks/definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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
}
Expand All @@ -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()
Expand Down
13 changes: 1 addition & 12 deletions mocks/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)}
}
12 changes: 6 additions & 6 deletions mocks/getters.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"

"github.com/lansfy/gonkex/compare"
Expand Down Expand Up @@ -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
}
8 changes: 4 additions & 4 deletions mocks/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,27 +104,27 @@ 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)
case "methodVary":
*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")
}
Expand Down
4 changes: 1 addition & 3 deletions mocks/mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
6 changes: 2 additions & 4 deletions mocks/service_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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
}
6 changes: 3 additions & 3 deletions mocks/strategy_based_on_request_reply.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Loading

0 comments on commit 21e2335

Please sign in to comment.