goat

package module
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 15, 2022 License: MIT Imports: 8 Imported by: 0

README

goat

goat is golang API testing library.

Usage

using gin

If you are using gin-gonic/gin, set *gin.Engine to goat.New().

package example_test

import (
	"io"
	"net/http"
	"testing"

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

func TestExample(t *testing.T) {
	goat.New(handler()).Run(t, []goat.TestCase{
		{
			Name:     "example test case",
			SetUp:    func(*testing.T) {},
			TearDown: func(*testing.T) {},
			Request:  goat.GetJsonRequest("/example"),
			Response: goat.JsonResponse(http.StatusOK, `{"ping":"pong"}`),
		},
	})
}

func handler() *gin.Engine {
	gin.DefaultWriter = io.Discard
	r := gin.Default()
	r.GET("/example", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"ping": "pong"})
	})
	return r
}

using echo

If you are using labstack/echo, set *echo.Echo to goat.New().

package example_test

import (
	"net/http"
	"testing"

	"github.com/labstack/echo"
	"github.com/masakurapa/goat"
)

func TestExample(t *testing.T) {
	goat.New(handler()).Run(t, []goat.TestCase{
		{
			Name:     "example test case",
			SetUp:    func(*testing.T) {},
			TearDown: func(*testing.T) {},
			Request:  goat.GetJsonRequest("/example"),
			Response: goat.JsonResponse(http.StatusOK, `{"ping":"pong"}`),
		},
	})
}

func handler() *echo.Echo {
	e := echo.New()
	e.GET("/example", func(c echo.Context) error {
		return c.JSON(http.StatusOK, echo.Map{"ping": "pong"})
	})
	return e
}

using net/http package

If you are using net/http, set http.Handler to goat.New().

package example_test

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/masakurapa/goat"
)

func TestExample(t *testing.T) {
	goat.New(handler()).Run(t, []goat.TestCase{
		{
			Name:     "example test case",
			SetUp:    func(*testing.T) {},
			TearDown: func(*testing.T) {},
			Request:  goat.GetJsonRequest("/example"),
			Response: goat.JsonResponse(http.StatusOK, `{"ping":"pong"}`),
		},
	})
}

func handler() http.Handler {
	mux := http.NewServeMux()
	mux.Handle("/example", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Add("Content-Type", "application/json; charset=utf-8")
		rw.WriteHeader(http.StatusOK)
		fmt.Fprint(rw, `{"ping":"pong"}`)
	}))
	return mux
}

SetUp and TearDown

Use SetUp and TearDown if you want the process to run before or after the test is executed.

Use SetUpBeforeTest and TearDownAfterTest if you want to run the process before and after all test cases are executed.

Example

package example_test

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/masakurapa/goat"
)

func TestExample(t *testing.T) {
	tt := goat.New(handler())

	tt.SetUpBeforeTest(func(t *testing.T) { fmt.Println("run SetUpBeforeTest") })
	tt.TearDownAfterTest(func(t *testing.T) { fmt.Println("run TearDownAfterTest") })

	tt.Run(t, []goat.TestCase{
		{
			Name:     "test1",
			SetUp:    func(*testing.T) { fmt.Println("run SetUp test1") },
			TearDown: func(*testing.T) { fmt.Println("run TearDown test1") },
			Request:  goat.GetJsonRequest("/ok"),
			Response: goat.JsonResponse(http.StatusOK, `{"status":"ok"}`),
		},
		{
			Name:     "test2",
			SetUp:    func(*testing.T) { fmt.Println("run SetUp test2") },
			TearDown: func(*testing.T) { fmt.Println("run TearDown test2") },
			Request:  goat.GetJsonRequest("/ok"),
			Response: goat.JsonResponse(http.StatusOK, `{"status":"ok"}`),
		},
	})
}

func handler() http.Handler {
	mux := http.NewServeMux()
	mux.Handle("/example", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Add("Content-Type", "application/json; charset=utf-8")
		rw.WriteHeader(http.StatusOK)
		fmt.Fprint(rw, `{"ping":"pong"}`)
	}))
	return mux
}

The result of running this test will look like this.

$ go test example_test.go -v
=== RUN   TestExample
run SetUpBeforeTest
=== RUN   TestExample/test1
run SetUp test1
run TearDown test1
=== RUN   TestExample/test2
run SetUp test2
run TearDown test2
run TearDownAfterTest
--- PASS: TestExample (0.00s)
    --- PASS: TestExample/test1 (0.00s)
    --- PASS: TestExample/test2 (0.00s)
PASS
ok      command-line-arguments  0.251s

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CustomTestFunc added in v0.2.0

type CustomTestFunc struct {
	Name string
	Func func(t *testing.T, res *http.Response)
}

CustomTestFunc is a type of function that implements its own validation

type H

type H struct {
	Key   string
	Value string
}

H is the type of the request and response headers

type Request

type Request struct {
	// Method is the request method
	//
	// see https://github.com/golang/go/blob/master/src/net/http/method.go for available methods.
	Method string
	// Path is the request path.
	//
	// since we will be using an internally started test server, the scheme, domain, and port are not necessary.
	Path string
	// Headers is the request headers
	Headers []H
	// Body is the request body
	Body string
}

Request is the type for manage request parameters.

func ConnectRequest

func ConnectRequest(path string, headers ...H) Request

ConnectRequest is the helper that returns the configuration for sending a CONNECT request

func DeleteJsonRequest

func DeleteJsonRequest(path, body string, headers ...H) Request

DeleteJsonRequest is the helper that returns the configuration for sending a DELETE request with a JSON format body.

func DeleteRequest

func DeleteRequest(path, body string, headers ...H) Request

DeleteRequest is the helper that returns the configuration for sending a DELETE request

func GetJsonRequest

func GetJsonRequest(path string, headers ...H) Request

GetJsonRequest is the helper that returns the configuration for sending a GET request with a JSON format body.

func GetRequest

func GetRequest(path string, headers ...H) Request

GetRequest is the helper that returns the configuration for sending a GET request

func HeadRequest

func HeadRequest(path string, headers ...H) Request

HeadRequest is the helper that returns the configuration for sending a HEAD request

func OptionsRequest

func OptionsRequest(path string, headers ...H) Request

OptionsRequest is the helper that returns the configuration for sending a OPTIONS request

func PatchJsonRequest

func PatchJsonRequest(path, body string, headers ...H) Request

PatchJsonRequest is the helper that returns the configuration for sending a PATCH request with a JSON format body.

func PatchRequest

func PatchRequest(path, body string, headers ...H) Request

PatchRequest is the helper that returns the configuration for sending a PATCH request

func PostJsonRequest

func PostJsonRequest(path, body string, headers ...H) Request

PostRequest is the helper that returns the configuration for sending a POST request with a JSON format body.

func PostRequest

func PostRequest(path, body string, headers ...H) Request

PostRequest is the helper that returns the configuration for sending a POST request

func PutJsonRequest

func PutJsonRequest(path, body string, headers ...H) Request

PutJsonRequest is the helper that returns the configuration for sending a PUT request with a JSON format body.

func PutRequest

func PutRequest(path, body string, headers ...H) Request

PutRequest is the helper that returns the configuration for sending a PUT request

func TraceRequest

func TraceRequest(path string, headers ...H) Request

TraceRequest is the helper that returns the configuration for sending a TRACE request

type Response

type Response struct {
	// Status is the response status code
	Status int
	// Headers is the response headers
	Headers []H
	// Body is the response body
	Body string
}

Response is the type for manage response parameters.

func JsonResponse

func JsonResponse(status int, body string, headers ...H) Response

JsonResponse returns the structure of the expected value of the JSON response. charset is specified as utf-8.

func JsonResponseWithoutCharset

func JsonResponseWithoutCharset(status int, body, charset string, headers ...H) Response

JsonResponse returns the structure of the expected value of the JSON response. No charset is specified.

func NoContent

func NoContent(headers ...H) Response

NoContent returns the structure of the expected value of 204(No Content)

type T

type T struct {
	// contains filtered or unexported fields
}

T is the type for manage API tests.

func New

func New(handler http.Handler) *T

New returns a client for API testing

func (*T) Run

func (r *T) Run(t *testing.T, testCases []TestCase)

Run executes the test case

func (*T) SetUpBeforeTest

func (r *T) SetUpBeforeTest(f func(*testing.T))

SetUpBeforeTest set up a function that all test cases will run before execution

func (*T) TearDownAfterTest

func (r *T) TearDownAfterTest(f func(*testing.T))

TearDownAfterTest set up a function that all test cases will run after execution

type TestCase

type TestCase struct {
	// Name is the name of the test case
	Name string
	// SetUp is the function that runs before the API is executed.
	//
	// This function performs preprocessing such as migration, test data creation, etc.
	SetUp func(*testing.T)
	// TearDown is the function that runs after the API is executed
	//
	// This function perform post-processing such as deleting test data, deleting tables, etc.
	TearDown func(*testing.T)
	// CustomTestFuncs is a set of functions used when you want to perform validation other
	// than HTTP status, response header, and response body validation.
	//
	// Each `CustomTestFunc` works in series.
	//
	// If you use `t.Fatal()`, `t.Fail()`, etc. in a `CustomTestFunc`,
	// the process will be interrupted and the subsequent `CustomTestFunc` will not be processed.
	CustomTestFuncs []CustomTestFunc
	// Request is the request parameter of the API
	Request Request
	// Response is the response parameter of the API
	Response Response
}

TestCase is the type for manage API test cases

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL