Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
survivorbat committed Mar 23, 2023
0 parents commit 15b878b
Show file tree
Hide file tree
Showing 17 changed files with 1,489 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Go package

on: [push]

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
go-version: [ '1.18', '1.19', '1.20' ]
steps:
- uses: actions/checkout@v3

- name: Set up Go ${{ matrix.go-version }}
uses: actions/setup-go@v3
with:
go-version: ${{ matrix.go-version }}
cache: true

- name: Test with Go ${{ matrix.go-version }}
run: go test -json > TestResults-${{ matrix.go-version }}.json

- name: Upload Go test results for ${{ matrix.go-version }}
uses: actions/upload-artifact@v3
with:
name: Go-results-${{ matrix.go-version }}
path: TestResults-${{ matrix.go-version }}.json
15 changes: 15 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.idea/
.vscode/

# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 ING

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 15 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
MAKEFLAGS := --no-print-directory --silent

default: help

help:
@echo "Please use 'make <target>' where <target> is one of"
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z\._-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)

t: test
test: fmt ## Run unit tests, alias: t
go test ./... -timeout=30s -parallel=8

fmt: ## Format go code
@go mod tidy
@go fmt ./...
122 changes: 122 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# 🦁 Gin Test Utils

[![Go package](https://github.com/ing-bank/gintestutil/actions/workflows/test.yaml/badge.svg)](https://github.com/ing-bank/gintestutil/actions/workflows/test.yaml)
![GitHub](https://img.shields.io/github/license/ing-bank/gintestutil)
![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/ing-bank/gintestutil)

Small utility functions for testing Gin-related code.
Such as the creation of a gin context and wait groups with callbacks.

## ⬇️ Installation

`go get github.com/ing-bank/gintestutil`

## 📋 Usage

### Context creation

```go
package main

import (
"net/http"
"testing"
"github.com/ing-bank/gintestutil"
)

type TestObject struct {
Name string
}

func TestProductController_Post_CreatesProducts(t *testing.T) {
// Arrange
context, writer := gintestutil.PrepareRequest(t,
gintestutil.WithJsonBody(t, TestObject{Name: "test"}),
gintestutil.WithMethod(http.MethodPost),
gintestutil.WithUrl("https://my-website.com"),
gintestutil.WithUrlParams(map[string]any{"category": "barbecue"}),
gintestutil.WithQueryParams(map[string]any{"force": "true"}))

// [...]
}
```

### Response Assertions

```go
package main

import (
"github.com/stretchr/testify/assert"
"net/http"
"testing"
"github.com/ing-bank/gintestutil"
)

type TestObject struct {
Name string
}

func TestProductController_Index_ReturnsAllProducts(t *testing.T) {
// Arrange
context, writer := gintestutil.PrepareRequest(t)

// [...]

// Assert
var actual []TestObject
if gintestutil.Response(t, &actual, http.StatusOK, writer.Result()) {
assert.Equal(t, []TestObject{}, actual)
}
}
```

### Hooks

```go
package main

import (
"github.com/gin-gonic/gin"
"github.com/ing-bank/gintestutil"
"net/http"
"net/http/httptest"
"time"
"testing"
)

func TestHelloController(t *testing.T) {
// Arrange
ginContext := gin.Default()

// create expectation
expectation := gintestutil.ExpectCalled(t, ginContext, "/hello-world")

ginContext.GET("/hello-world", func(context *gin.Context) {
context.Status(http.StatusOK)
})

// create webserver
ts := httptest.NewServer(ginContext)

// Send request to webserver path
_, _ = http.Get(fmt.Sprintf("%s/hello-world", ts.URL))

// Wait for expectation in bounded time
if ok := gintestutil.EnsureCompletion(t, expectation); !ok {
// do something
}
}
```

## 🚀 Development

1. Clone the repository
2. Run `make t` to run unit tests
3. Run `make fmt` to format code

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

## 🔭 Future Plans

Nothing here yet!
61 changes: 61 additions & 0 deletions await.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package gintestutil

import (
"sync"
"testing"
"time"
)

const (
// defaultTimeout is the default value for EnsureCompletion's config
defaultTimeout = 30 * time.Second
)

// EnsureOption allows various options to be supplied to EnsureCompletion
type EnsureOption func(*ensureConfig)

// WithTimeout is used to set a timeout for EnsureCompletion
func WithTimeout(timeout time.Duration) EnsureOption {
return func(config *ensureConfig) {
config.timeout = timeout
}
}

type ensureConfig struct {
timeout time.Duration
}

// EnsureCompletion ensures that the waitgroup completes within a specified duration or else fails
func EnsureCompletion(t *testing.T, wg *sync.WaitGroup, options ...EnsureOption) bool {
t.Helper()

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

config := &ensureConfig{
timeout: defaultTimeout,
}

for _, option := range options {
option(config)
}

// Run waitgroup in goroutine
channel := make(chan struct{})
go func() {
t.Helper()
defer close(channel)
wg.Wait()
}()

// Select first response (waitgroup completion or time.After)
select {
case <-channel:
return true
case <-time.After(config.timeout):
t.Errorf("tasks did not complete within: %v", config.timeout)
return false
}
}
86 changes: 86 additions & 0 deletions await_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package gintestutil

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

func TestEnsure_NilWaitGroupFails(t *testing.T) {
t.Parallel()
// Arrange
testingObject := new(testing.T)

// Act
ok := EnsureCompletion(testingObject, nil)

// Assert
assert.False(t, ok)
}

func TestEnsure_NegativeDurationFails(t *testing.T) {
t.Parallel()
// Arrange
testingObject := new(testing.T)

expectation := &sync.WaitGroup{}
expectation.Add(1)
go func() {
timeout := time.After(1 * time.Second)

<-timeout
expectation.Done()
}()

// Act
ok := EnsureCompletion(testingObject, expectation, WithTimeout(-1*time.Second))

// Assert
assert.True(t, testingObject.Failed())
assert.False(t, ok)
}

func TestEnsure_LongerTaskTimeThanEnsureDurationFails(t *testing.T) {
t.Parallel()
// Arrange
testingObject := new(testing.T)

expectation := &sync.WaitGroup{}
expectation.Add(1)
go func() {
timeout := time.After(5 * time.Second)

<-timeout
expectation.Done()
}()

// Act
ok := EnsureCompletion(testingObject, expectation, WithTimeout(1*time.Second))

// Assert
assert.True(t, testingObject.Failed())
assert.False(t, ok)
}

func TestEnsure_ShortTaskTimeThanEnsureDurationSucceeds(t *testing.T) {
t.Parallel()
// Arrange
testingObject := new(testing.T)

expectation := &sync.WaitGroup{}
expectation.Add(1)
go func() {
timeout := time.After(1 * time.Second)

<-timeout
expectation.Done()
}()

// Act
ok := EnsureCompletion(testingObject, expectation, WithTimeout(3*time.Second))

// Assert
assert.False(t, testingObject.Failed())
assert.True(t, ok)
}
Loading

0 comments on commit 15b878b

Please sign in to comment.