routest

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2020 License: MIT Imports: 7 Imported by: 0

README

routest

Fast and easy way of testing your http api. Works with the stdlibs testing pkg.

go.dev reference

install

$ go get github.com/karlpokus/routest/v2

usage

Test a route

import (
	// ...
	"github.com/karlpokus/routest/v2"
)

func hi(s string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Etag", "abc")
		fmt.Fprintf(w, "hi %s", s)
	}
}

func TestRoute(t *testing.T) {
	routest.Test(t, nil, []routest.Data{
		{
			Name: "hi from route",
			Path: "/",
			Handler: hi("bob"),
			Status: 200,
			ResponseBody: []byte("hi bob"),
			ResponseHeader: http.Header{
				"Etag": []string{"abc"},
			},
		},
	})
}

Test registered routes

import (
	// ...
	"github.com/karlpokus/routest/v2"
	"github.com/julienschmidt/httprouter"
)

func Greet(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())
	fmt.Fprintf(w, "hello %s", params.ByName("user"))
}

func TestRouter(t *testing.T) {
	routest.Test(t, func() http.Handler {
		router := httprouter.New()
		router.HandlerFunc("GET", "/greet/:user", Greet)
		return router
	}, []routest.Data{
		{
			Name: "Greet from router",
			Method: "GET",
			Path: "/greet/bob",
			Status: 200,
			ResponseBody: []byte("hello bob"),
		},
	})
}

todos

  • allow for custom server/router to register as handler
  • fix v2 module path
  • Add http.Header to Data
  • Make some Data fields optional

license

MIT

Documentation

Overview

Package routest provides a quick and easy way of testing your http api

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Test

func Test(t *testing.T, fn RegisterFunc, data []Data)

Test runs assertion tests on data and reports to t

Types

type Data

type Data struct {
	Name, Method, Path string
	RequestBody        io.Reader
	RequestHeader      http.Header
	Handler            http.Handler
	Status             int
	ResponseBody       []byte
	ResponseHeader     http.Header
}

Only Name, Method and Path are required. All other fields are optional. A non-nil RegisterFunc overrides Handler.

type RegisterFunc

type RegisterFunc func() http.Handler

Jump to

Keyboard shortcuts

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