tester

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2025 License: MIT Imports: 13 Imported by: 0

README

tester

Simple testing package for restful APIs. Uses mux router for routing and direct http.Handler for handling requests.

Usage

Tester provides a simple way to test restful APIs. It is based on the testing package and provides a simple way to test APIs. You need to call WithAPI function with dependencies and then you provide closure where API will be available.


var (
    router = mux.NewRouter()
)

func init() {
    // create a health check endpoint
    router.HandleFunc("/api/v1/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        if err := json.NewEncoder(w).Encode(HealthResponse{
			Status: "ok",
        }); err != nil {
            panic(err)
        }
    }).Methods(http.MethodGet).Name("api:v1:health")
}

type HealthResponse struct {
    Status string `json:"status"`
}

func TestHealthHandler(t *testing.T) {// 
    tester.WithAPI(t, &Deps{
        Router: router,
        Handler: router,
    }, func(api *API) {
        var status string
        
        // unmarshal key from json object to value
        api.Get(t, api.ReverseURL(t, "api:v1:health")).
            Do(context.Background()).
            AssertStatus(t, http.StatusOK).
            Unmarshal(t, 
                APIObject(t, "status", &status),
            )
        assert.Equal(t, "ok", status)

        // direct unmarshal to struct
        response := HealthResponse{}
        api.Get(t, api.ReverseURL(t, "api:v1:health")).
            Do(context.Background()).
            AssertStatus(t, http.StatusOK).
            Unmarshal(t, &response)

        // assert json equals
        api.Get(t, api.ReverseURL(t, "api:v1:health")).
            Do(context.Background()).
            AssertStatus(t, http.StatusOK).
            AssertJsonEquals(t, HealthResponse{
                Status: "ok",	
            })
		
        // assert object key
        api.Get(t, api.ReverseURL(t, "api:v1:health")).
            Do(context.Background()).
            AssertStatus(t, http.StatusOK).
            AssertJsonKeyEquals(t, "status", "ok")
		
    })
}

Author

Peter Vrba phonkee@phonkee.eu

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIObject

func APIObject(t *testing.T, kv ...any) any

APIObject gives ability to unmarshall json object into multiple fields

func WithAPI

func WithAPI(t *testing.T, deps *Deps, fn func(APIClient))

WithAPI runs the given function with a new APIClient instance

Types

type APIClient

type APIClient interface {
	// Delete does a DELETE response to the APIClient
	Delete(t *testing.T, path string) APIRequest

	// Get does a GET response to the APIClient
	Get(t *testing.T, path string) APIRequest

	// Post does a POST response to the APIClient
	Post(t *testing.T, path string) APIRequest

	// Put does a PUT response to the APIClient
	Put(t *testing.T, path string) APIRequest

	// Request does a response to the APIClient
	Request(t *testing.T, method string, path string) APIRequest

	// ReverseURL creates a path by given url name and url arguments
	ReverseURL(t *testing.T, name string, vars ...string) string
}

APIClient is the interface for testing the rest APIClient

type APIRequest

type APIRequest interface {
	// Body sets the body of the request
	Body(t *testing.T, body any) APIRequest
	// Do perform the request and returns the response
	Do(t *testing.T, ctx context.Context) APIResponse
	// Header sets the header of the request
	Header(t *testing.T, key, value string) APIRequest
	// Query sets the query of the request
	Query(t *testing.T, key, value string) APIRequest
}

APIRequest is the interface for testing the rest APIClient response

type APIResponse

type APIResponse interface {
	// AssertJsonEquals asserts that response body is equal to given json
	AssertJsonEquals(t *testing.T, what any) APIResponse

	// AssertJsonKeyEquals asserts that response body key is equal to given value
	AssertJsonKeyEquals(t *testing.T, key string, what any) APIResponse

	// AssertStatus asserts that response status is equal to given status
	AssertStatus(t *testing.T, status int) APIResponse

	// Unmarshal json unmarshalls whole response body into given value
	Unmarshal(t *testing.T, v any) APIResponse
}

APIResponse is the interface for testing the rest APIClient response

type Deps

type Deps struct {
	// Router - currently required
	Router *mux.Router
	// If the Handler is nil, Router will be used as the handler
	Handler http.Handler
}

Deps is the dependencies for the APIClient

func (*Deps) Validate

func (d *Deps) Validate(t *testing.T)

Validate deps

Jump to

Keyboard shortcuts

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