Go Supertest is minimalize HTTP Client Testing only for Gin Framework

Go SuperTest

Build Status GitHub go.mod Go version Go Report Card GitHub issues GitHub closed issues GitHub contributors

Go Supertest is minimalize HTTP Client Testing only for Gin Framework, inspired by Supertest package library HTTP Client Testing for Express.js Framework.

Installation

$ go get -u github.com/restuwahyu13/go-supertest

API Reference

Important if you use http request using any method and you not returning payload, you must be use Send with nil value and Send must be added before Set or Auth please check example usage about this package is working.

  • NewSuperTest( router *gin.Engine, test *testing.T )

    Method Description
    NewSuperTest instance method for create unit testing
  • Get( url string )

    Method Description
    Get for handling request http client using GET method
  • Post( url string )

    Method Description
    Post for handling request http client using POST method
  • Delete( url string )

    Method Description
    Delete for handling request http client using Delete method
  • Put( url string )

    Method Description
    Put for handling request http client using Put method
  • Patch( url string )

    Method Description
    Patch for handling request http client using Patch method
  • Head( url string )

    Method Description
    Head for handling request http client using Head method
  • Options( url string )

    Method Description
    Options for handling request http client using Options method
  • Send( payload interface{} )

    Method Description
    Send send request data needed by client
  • End( handle func(rr *httptest.ResponseRecorder) )

    Method Description
    End receive responses from http requests
  • Set( key, value string )

    Method Description
    Set set your headers before sending http request into client
  • Auth( key, value string )

    Method Description
    Auth pass the username or password if you are using HTTP Basic authentication
  • Timeout( timeType string, value time.Duration )

    Method Description
    Timeout set delay before sending request into client

Example Usage

  • Main Setup

    package main
    
    import (
      "net/http"
    
      "github.com/gin-gonic/gin"
    )
    
    type User struct {
      Name string `json:"name"`
    }
    
    func GetMethod(ctx *gin.Context) {
      ctx.JSON(http.StatusOK, gin.H{
        "statusCode": 200,
        "method":     http.MethodGet,
        "message":    "fetch request using get method",
        "data":       nil,
      })
    }
    
    func PostMethod(ctx *gin.Context) {
      var input User
      ctx.ShouldBindJSON(&input)
    
      ctx.JSON(http.StatusOK, gin.H{
        "statusCode": 200,
        "method":     http.MethodPost,
        "message":    "fetch request using post method",
        "data":       input,
      })
    }
    
    func DeleteMethod(ctx *gin.Context) {
    
      userId := ctx.Param("id")
      userData := make(map[string]string, 5)
    
      userData["name-1"] = "john doe"
      userData["name-2"] = "jane doe"
      userData["name-3"] = "james bond"
      userData["name-4"] = "curt cobain"
      userData["name-5"] = "rorona zoro"
    
      delete(userData, "name-"+userId)
    
      ctx.JSON(http.StatusOK, gin.H{
        "statusCode": 200,
        "method":     http.MethodPost,
        "message":    "fetch request using delete method",
        "data":       userData,
      })
    }
    
    func PutMethod(ctx *gin.Context) {
    
      var input User
    
      userId := ctx.Param("id")
      ctx.ShouldBindJSON(&input)
    
      userData := make(map[string]string, 5)
    
      userData["name-1"] = "john doe"
      userData["name-2"] = "jane doe"
      userData["name-3"] = "james bond"
      userData["name-4"] = "curt cobain"
      userData["name-5"] = "rorona zoro"
    
      userData["name-"+userId] = input.Name
    
      ctx.JSON(http.StatusOK, gin.H{
        "statusCode": 200,
        "method":     http.MethodPost,
        "message":    "fetch request using put method",
        "data":       userData,
      })
    }
    
    func main() {
      router := SetupRouter()
      router.Run()
    }
    
    func SetupRouter() *gin.Engine {
      router := gin.Default()
      gin.SetMode(gin.TestMode)
    
      router.GET("/", GetMethod)
      router.POST("/", PostMethod)
      router.DELETE("/:id", DeleteMethod)
      router.PUT("/:id", PutMethod)
    
      return router
    }
  • Test Setup

    package main
    
    import (
      "encoding/json"
      "fmt"
      "net/http"
      "net/http/httptest"
      "testing"
    
      "github.com/gin-gonic/gin"
      "github.com/go-playground/assert/v2"
      "github.com/restuwahyu13/go-supertest/supertest"
    )
    
    type Response struct {
      StatusCode int `json:"statusCode"`
      Method     string `json:"method"`
      Message    string  `json:"message"`
      Data     interface{} `json:"data"`
    }
    
    var router = SetupRouter()
    
    func TestGetMethod(t *testing.T) {
      test := supertest.NewSuperTest(router, t)
    
      test.Get("/")
      test.Send(nil)
      test.Set("Content-Type", "application/json")
      test.End(func(req *http.Request, rr *httptest.ResponseRecorder) {
    
        var response Response
        json.Unmarshal(rr.Body.Bytes(), &response)
    
        assert.Equal(t, http.StatusOK, rr.Code)
        assert.Equal(t, req.Method, req.Method)
        assert.Equal(t, "fetch request using get method", response.Message)
      })
    }
    
    func TestPostMethod(t *testing.T) {
      test := supertest.NewSuperTest(router, t)
    
      payload := gin.H{
        "name": "restu wahyu saputra",
      }
    
      test.Post("/")
      test.Send(payload)
      test.Set("Content-Type", "application/json")
      test.End(func(req *http.Request, rr *httptest.ResponseRecorder) {
    
        var response Response
        json.Unmarshal(rr.Body.Bytes(), &response)
    
        assert.Equal(t, http.StatusOK, rr.Code)
        assert.Equal(t, req.Method, req.Method)
        assert.Equal(t, "fetch request using post method", response.Message)
      })
    }
    
    func TestDeleteMethod(t *testing.T) {
      test := supertest.NewSuperTest(router, t)
    
      test.Delete("/" + fmt.Sprintf("%v", 5))
      test.Send(nil)
      test.Set("Content-Type", "application/json")
      test.End(func(req *http.Request, rr *httptest.ResponseRecorder) {
    
        var response Response
        json.Unmarshal(rr.Body.Bytes(), &response)
    
        assert.Equal(t, http.StatusOK, rr.Code)
        assert.Equal(t, req.Method, req.Method)
        assert.Equal(t, "fetch request using delete method", response.Message)
    
        encoded, _ := json.Marshal(response.Data)
    
        var mapping map[string]interface{}
        json.Unmarshal(encoded, &mapping)
    
        assert.Equal(t, 4, len(mapping))
      })
    }
    
    func TestPutMethod(t *testing.T) {
      test := supertest.NewSuperTest(router, t)
    
      payload := gin.H{
        "name": "restu wahyu saputra",
      }
    
      test.Put("/" + fmt.Sprintf("%v", 1))
      test.Send(payload)
      test.Set("Content-Type", "application/json")
      test.End(func(req *http.Request, rr *httptest.ResponseRecorder) {
    
    
        var response Response
        json.Unmarshal(rr.Body.Bytes(), &response)
    
        assert.Equal(t, http.StatusOK, rr.Code)
        assert.Equal(t, req.Method, req.Method)
        assert.Equal(t, "fetch request using put method", response.Message)
    
        encoded, _ := json.Marshal(response.Data)
    
        var mapping map[string]interface{}
        json.Unmarshal(encoded, &mapping)
    
        assert.Equal(t, "restu wahyu saputra", mapping["name-1"])
      })
    }

API Status Reference

Name Ready Description
Get yes for handling request http client using GET method
Post yes for handling request http client using POST method
Delete yes for handling request http client using Delete method
Put yes for handling request http client using Put method
Patch yes for handling request http client using Patch method
Head yes for handling request http client using Head method
Options yes for handling request http client using Options method
Send yes send request data needed by client
End yes receive responses from http requests
Set yes set your headers before sending http request into client
Auth yes pass the username or password if you are using HTTP Basic authentication
Timeout yes set delay before sending request into client
Attach no handle requests from files or image uploads if you are using multipart/form-data
Field no handle data submitted from form/field if you are using multipart/form-data

Testing

$ go test ./supertest/... || make gotest

Bugs

For information on bugs related to package libraries, please visit here

Contributing

Want to make Go Supertest more perfect ? Let's contribute and follow the contribution guide.

License

BACK TO TOP

Owner
Restu Wahyu Saputra
A bright future will come, just waiting times, someday I will definitely become a software engineer
Restu Wahyu Saputra
Similar Resources

Http-conection - A simple example of how to establish a HTTP connection using Golang

A simple example of how to establish a HTTP connection using Golang

Feb 1, 2022

Full-featured, plugin-driven, extensible HTTP client toolkit for Go

gentleman Full-featured, plugin-driven, middleware-oriented toolkit to easily create rich, versatile and composable HTTP clients in Go. gentleman embr

Dec 23, 2022

An enhanced http client for Golang

An enhanced http client for Golang

go-http-client An enhanced http client for Golang Documentation on go.dev 🔗 This package provides you a http client package for your http requests. Y

Dec 23, 2022

An enhanced HTTP client for Go

An enhanced HTTP client for Go

Heimdall Description Installation Usage Making a simple GET request Creating a hystrix-like circuit breaker Creating a hystrix-like circuit breaker wi

Jan 9, 2023

Enriches the standard go http client with retry functionality.

httpRetry Enriches the standard go http client with retry functionality using a wrapper around the Roundtripper interface. The advantage of this libra

Dec 10, 2022

http client for golang

http client for golang

Request HTTP client for golang, Inspired by Javascript-axios Python-request. If you have experience about axios or requests, you will love it. No 3rd

Dec 18, 2022

Simple HTTP and REST client library for Go

Resty Simple HTTP and REST client library for Go (inspired by Ruby rest-client) Features section describes in detail about Resty capabilities Resty Co

Jan 1, 2023

A nicer interface for golang stdlib HTTP client

rq A nicer interface for golang stdlib HTTP client Documents rq: here client: here jar: here Why? Because golang HTTP client is a pain in the a... Fea

Dec 12, 2022

A Go HTTP client library for creating and sending API requests

A Go HTTP client library for creating and sending API requests

Sling Sling is a Go HTTP client library for creating and sending API requests. Slings store HTTP Request properties to simplify sending requests and d

Jan 7, 2023
fhttp is a fork of net/http that provides an array of features pertaining to the fingerprint of the golang http client.

fhttp The f stands for flex. fhttp is a fork of net/http that provides an array of features pertaining to the fingerprint of the golang http client. T

Jan 1, 2023
HTTP Load Testing And Benchmarking Tool

GBench HTTP Load Testing And Benchmarking Tool inspired by Apache Benchmark and Siege. Requirements You need Golang installed and ready on your system

Jan 2, 2020
HTTP/HTTPS load testing and benchmarking tool

Introduction I wrote that code because: (the obvious reason::I love to write code in Go) We are working so hard to optimize our servers - why shouldn'

Dec 5, 2022
Replacement of ApacheBench(ab), support for transactional requests, support for command line and package references to HTTP stress testing tool.

stress stress is an HTTP stress testing tool. Through this tool, you can do a stress test on the HTTP service and get detailed test results. It is ins

Aug 23, 2022
An HTTP performance testing tool written in GoLang

Gonce A HTTP API performance testing tool written in GoLang Description Installation Usage Description A performance testing tool written in GoLang. S

Jan 28, 2022
Nap is a file-based framework for automating the execution of config-driven HTTP requests and scripts.

Nap Nap is a file-based framework for automating the execution of config-driven HTTP requests and scripts. Installation Options Using go get $ go inst

Nov 17, 2022
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

fasthttp Fast HTTP implementation for Go. Currently fasthttp is successfully used by VertaMedia in a production serving up to 200K rps from more than

Jan 2, 2023
Speak HTTP like a local. (the simple, intuitive HTTP console, golang version)

http-gonsole This is the Go port of the http-console. Speak HTTP like a local Talking to an HTTP server with curl can be fun, but most of the time it'

Jul 14, 2021
NATS HTTP Round Tripper - This is a Golang http.RoundTripper that uses NATS as a transport.

This is a Golang http.RoundTripper that uses NATS as a transport. Included is a http.RoundTripper for clients, a server that uses normal HTTP Handlers and any existing http handler mux and a Caddy Server transport.

Dec 6, 2022
Simple HTTP package that wraps net/http

Simple HTTP package that wraps net/http

Jan 17, 2022