Skip to content

Commit

Permalink
Add linter
Browse files Browse the repository at this point in the history
  • Loading branch information
Maarten van der Heijden committed Sep 21, 2023
1 parent 15b878b commit ba09195
Show file tree
Hide file tree
Showing 13 changed files with 155 additions and 31 deletions.
86 changes: 86 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
linters-settings:
gocritic:
disabled-checks:
- "paramTypeCombine"
enabled-tags:
- "performance"
- "style"
- "diagnostic"
linters:
enable:
- asasalint
- asciicheck
- bidichk
# - bodyclose # Only used in examples
- containedctx
- contextcheck
- cyclop
- decorder
- dogsled
- dupword
- durationcheck
- errcheck
- errname
- errorlint
- execinquery
- exhaustive
- exportloopref
- forbidigo
- ginkgolinter
- gocheckcompilerdirectives
- gochecknoinits
- gocognit
- goconst
- gocritic
- gocyclo
- goerr113
- gofmt
- gofumpt
- goheader
- goimports
- gomoddirectives
- gomodguard
- goprintffuncname
- gosec
- gosimple
- gosmopolitan
- govet
- grouper
- ifshort
- importas
- ineffassign
- interfacebloat
- interfacer
- ireturn
- loggercheck
- maintidx
- makezero
- mirror
- misspell
- musttag
- nakedret
- nestif
- nilerr
- nilnil
- nlreturn
- nonamedreturns
- nosprintfhostport
- paralleltest
- prealloc
- predeclared
- promlinter
- reassign
- rowserrcheck
- sqlclosecheck
- staticcheck
- tenv
- thelper
- tparallel
- typecheck
- unconvert
- unparam
- unused
- usestdlibvars
- wastedassign
- whitespace
- zerologlint
9 changes: 9 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,12 @@ test: fmt ## Run unit tests, alias: t
fmt: ## Format go code
@go mod tidy
@go fmt ./...
@gofumpt -l -w .

tools: ## Install extra tools for development
go install github.com/princjef/gomarkdoc/cmd/gomarkdoc@latest
go install mvdan.cc/gofumpt@latest
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

lint: ## Lint the code locally
golangci-lint run
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,10 @@ func TestHelloController(t *testing.T) {
## 🚀 Development

1. Clone the repository
2. Run `make t` to run unit tests
3. Run `make fmt` to format code
2. Run `make tools` to install necessary tools
3. Run `make t` to run unit tests
4. Run `make fmt` to format code
4. Run `make lint` to lint your code

You can run `make` to see a list of useful commands.

Expand Down
3 changes: 3 additions & 0 deletions await.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func EnsureCompletion(t *testing.T, wg *sync.WaitGroup, options ...EnsureOption)

if wg == nil {
t.Error("WithExpectation is nil")

return false
}

Expand All @@ -54,8 +55,10 @@ func EnsureCompletion(t *testing.T, wg *sync.WaitGroup, options ...EnsureOption)
select {
case <-channel:
return true

case <-time.After(config.timeout):
t.Errorf("tasks did not complete within: %v", config.timeout)

return false
}
}
3 changes: 2 additions & 1 deletion await_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package gintestutil

import (
"github.com/stretchr/testify/assert"
"sync"
"testing"
"time"

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

func TestEnsure_NilWaitGroupFails(t *testing.T) {
Expand Down
10 changes: 7 additions & 3 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"io"
"net/http"
"net/http/httptest"
"net/url"

"github.com/gin-gonic/gin"
)

// RequestOption are functions used in PrepareRequest to configure a request using the Functional Option pattern.
Expand All @@ -35,10 +36,12 @@ func applyQueryParams(params map[string]any, query url.Values, keyPrefix string)
switch resultValue := value.(type) {
case string:
query.Add(newKey, resultValue)

case []string:
for _, valueString := range resultValue {
query.Add(newKey, valueString)
}

case fmt.Stringer:
query.Add(newKey, resultValue.String())

Expand Down Expand Up @@ -68,6 +71,7 @@ func PrepareRequest(t TestingT, options ...RequestOption) (*gin.Context, *httpte
var err error
if context.Request, err = http.NewRequest(config.method, config.url, config.body); err != nil {
t.Error(err)

return context, writer
}

Expand Down Expand Up @@ -101,9 +105,9 @@ func WithMethod(method string) RequestOption {
}

// WithUrl specifies the url to use, defaults to https://example.com
func WithUrl(url string) RequestOption {
func WithUrl(reqUrl string) RequestOption {
return func(config *requestConfig) {
config.url = url
config.url = reqUrl
}
}

Expand Down
7 changes: 5 additions & 2 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ package gintestutil
import (
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"io"
"net/http"
"net/url"
"testing"

"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)

type testStringer struct {
Expand Down Expand Up @@ -103,6 +104,7 @@ func TestPrepareRequest_CreatesExpectedContext(t *testing.T) {
"expected error on nonsensical request": {
options: []RequestOption{WithUrl("://://::::///::::")},

//nolint:goerr113 // Not relevant
expectedError: &url.Error{Op: "parse", URL: "://://::::///::::", Err: errors.New("missing protocol scheme")},
},
}
Expand All @@ -122,6 +124,7 @@ func TestPrepareRequest_CreatesExpectedContext(t *testing.T) {

if testData.expectedError != nil {
assert.Equal(t, testData.expectedError, mockT.ErrorCalls[0])

return
}

Expand Down
7 changes: 6 additions & 1 deletion controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@ func statusHasBody(status int) bool {
switch {
case status >= http.StatusContinue && status <= 199:
return false

case status == http.StatusNoContent:
return false

case status == http.StatusNotModified:
return false
}

return true
}

Expand All @@ -26,13 +29,14 @@ func Response(t TestingT, result any, code int, res *http.Response) bool {

if code != res.StatusCode {
t.Errorf("Status code %d is not %d", res.StatusCode, code)

return false
}

response, err := io.ReadAll(res.Body)

if err != nil {
t.Errorf("failed to read body of response")

return false
}

Expand All @@ -43,6 +47,7 @@ func Response(t TestingT, result any, code int, res *http.Response) bool {

if err := json.Unmarshal(response, &result); err != nil {
t.Errorf("Failed to unmarshall '%s' into '%T': %v", response, result, err)

return false
}

Expand Down
4 changes: 3 additions & 1 deletion controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ func TestSuccessResponse_FailsOnNoBody(t *testing.T) {
// Arrange
testingObject := new(mockT)
response := &http.Response{
//nolint:mirror // Used for a test
Body: io.NopCloser(bytes.NewBuffer([]byte(""))),
StatusCode: http.StatusOK,
}
Expand All @@ -126,7 +127,8 @@ func TestSuccessResponse_FailsOnUnmarshall(t *testing.T) {
testingObject := new(mockT)
response := &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBuffer([]byte("test"))),
//nolint:mirror // Used for a test
Body: io.NopCloser(bytes.NewBuffer([]byte("test"))),
}

var result testObject
Expand Down
6 changes: 4 additions & 2 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package gintestutil

import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)

type MyObject struct {
Expand Down Expand Up @@ -50,6 +51,7 @@ func ExampleResponse() {
myController := &MyController{}

context, writer := PrepareRequest(t)
defer writer.Result().Body.Close()

// Act
myController.Get(context)
Expand Down
21 changes: 12 additions & 9 deletions expect.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package gintestutil

import (
"github.com/gin-gonic/gin"
"sync"

"github.com/gin-gonic/gin"
)

// ExpectOption allows various options to be supplied to Expect* functions
Expand Down Expand Up @@ -36,6 +37,7 @@ func ExpectCalled(t TestingT, context *gin.Engine, path string, options ...Expec

if context == nil {
t.Errorf("context cannot be nil")

return nil
}

Expand All @@ -55,15 +57,16 @@ func ExpectCalled(t TestingT, context *gin.Engine, path string, options ...Expec
var timesCalled int
context.Use(func(c *gin.Context) {
c.Next()
if c.FullPath() == path {
timesCalled++
if timesCalled <= config.Times {
config.Expectation.Done()
} else {
t.Errorf("%s hook asserts called %d times but called at least %d times\n", path, config.Times, timesCalled)
return
}
if c.FullPath() != path {
return
}

timesCalled++
if timesCalled <= config.Times {
config.Expectation.Done()
}

t.Errorf("%s hook asserts called %d times but called at least %d times\n", path, config.Times, timesCalled)
})

return config.Expectation
Expand Down
Loading

0 comments on commit ba09195

Please sign in to comment.