gosette

package module
v0.0.0-...-808ecfe Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2024 License: MIT Imports: 5 Imported by: 0

README

Go Reference Coverage

Gosette

A HTTP server implementation which can be used to mock HTTP responses and spy on incoming HTTP requests and outgoing HTTP responses. The primary goal of this package is to provide an easy way to perform local end-to-end tests of HTTP clients against a local HTTP server.

Features

  • Built on top of http and httptest packages.
  • Easily add predefined HTTP responses.
  • Responses are served in a FIFO fashion until there is only one left: If only one response is available, it is served indefinitly. The server returns an empty 404 response when no predefined responses are available.
  • The server records HTTP requests, body and HTTP response in a FIFO fashion. These records can be extracted from the test server to spy on exchanged requests and responses.
  • In case the server encounter an error while processing the request or serving the predefined response, the server will reply with a 500 response with a text body that is the string representation of the error. The server will also add a record to its queue. The added record will have its ServerError set with an error which wraps the error that has occured.
  • Helper functions are available to clear responses and records.
  • Pluggable httptest.Server. The server handler will be overriden by the framework. The underlying httptest.Server is accessible so more experienced users can build more complex test cases (like shutting down client connections, testing with TLS, ...).

Basic usage

// Build HTTP Server with default options and start it
testsrv := NewHTTPTestServer(nil)
testsrv.Start()

// Configure a predefined response that will be served indefinitly
testsrv.PushPredefinedServerResponse(&PredefinedServerResponse{
	Status: http.StatusOK,
	Headers: map[string][]string{
		"Content-Type": []string{"application/json"},
	},
	Body: []byte(`{"test": "success"}`),
})

// Get a http.Client which trusts the server certificate if TLS is enabled
client := testsrv.Client()

// Send a request to the http test server
resp, err := client.Get(testsrv.GetBaseURL())
...

// Pop recorded request, request body and recorded response
record := testsrv.PopServerRecord()

// Inspect recorded http.Request
host := record.Request.Host
method := record.Request.Method
path := record.Request.URL.String()
...

// Inspect recorded request body
recReqBody, err := io.ReadAll(record.RequestBody)
...

// Inspect recorded http.Response
recResp := record.Response.Result()
...

Advanced usage and integration with ther testing framework

More advanced usage of the gosette.HTTPTestServer can be seen in the test file. Tests also show how gosette.HTTPTestServer can be used in combination with the basic Golang testing utilities as well as the stretchr/testify testing framework.

Documentation

Overview

Description

The package provides a HTTP server implementation which can be used to mock HTTP responses and spy on incoming requests and outgoing responses. The primary goal of this package is to provide an easy way to perform local end-to-end tests of HTTP clients against a local HTTP server.

Features

  • Built on top of http and httptest packages.
  • Easily add predefined HTTP responses.
  • Responses are served in a FIFO fashion until there is only one left: If only one response is available, it is served indefinitly. The server returns an empty 404 response when no predefined responses are available.
  • The server records HTTP requests, body and HTTP response in a FIFO fashion. These records can be extracted from the test server to spy on exchanged requests and responses.
  • In case the server encounter an error while processing the request or serving the predefined response, the server will reply with a 500 response with a text body that is the string representation of the error. The server will also add a record to its queue. The added record will have its ServerError set with an error which wraps the error that has occured.
  • Helper functions are available to clear responses and records.
  • Pluggable httptest.Server. The server handler will be overriden by the framework. The underlying httptest.Server is accessible so more experienced users can build more complex test cases (like shutting down client connections, testing with TLS, ...).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HTTPTestServer

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

HTTP test server used to mock real HTTP servers.

Predefined responses and recorded requests are voluntary left public to allow users to navigate and manage their data.

func NewHTTPTestServer

func NewHTTPTestServer(server *httptest.Server) *HTTPTestServer

Description

Factory to create a new, unstarted HTTPTestServer. The underlying httptest.Server can be provided by the user in case specific server cofnigurations (TLS, ...) must be used.

Inputs

  • server: The underlying httptest.Server to be used by the HTTPTestServer. In case it is nil, a new unstarted httptest.Server with default settings will be created.

func (*HTTPTestServer) Clear

func (hts *HTTPTestServer) Clear()

Clear all server predefined responses & records

func (*HTTPTestServer) ClearPredefinedServerResponses

func (hts *HTTPTestServer) ClearPredefinedServerResponses()

Clear all predefined responses configured for the http test server

func (*HTTPTestServer) ClearServerRecords

func (hts *HTTPTestServer) ClearServerRecords()

Clear all test server records

func (*HTTPTestServer) Client

func (hts *HTTPTestServer) Client() *http.Client

func (*HTTPTestServer) Close

func (hts *HTTPTestServer) Close()

Close the http test server

func (*HTTPTestServer) GetBaseURL

func (hts *HTTPTestServer) GetBaseURL() string

Return the test server base URL of form http://ipaddr:port with no trailing slash.

func (*HTTPTestServer) GetUnderlyingHTTPTestServer

func (hts *HTTPTestServer) GetUnderlyingHTTPTestServer() *httptest.Server

Get the underlying httptest.Server used by this HTTPTestServer.

func (*HTTPTestServer) PopServerRecord

func (hts *HTTPTestServer) PopServerRecord() *ServerRecord

Pop a server record (received request and response) if any. Server records are recorded and provided in a FIFO fashion. The returned record will be nil if no record is available.

func (*HTTPTestServer) PushPredefinedServerResponse

func (hts *HTTPTestServer) PushPredefinedServerResponse(resp *PredefinedServerResponse)

Push a predefined response to the server.

func (*HTTPTestServer) ServeHTTP

func (srv *HTTPTestServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

The test server handler which records incoming requests, request body and outgoing responses.

Predefined responses are served once in a FIFO fashion. When there is only one response left in predefined response the queue, this response is served indefinitly. When no responses are available, the test server replies with an empty 404 response.

func (*HTTPTestServer) Start

func (hts *HTTPTestServer) Start()

Start the test server.

func (*HTTPTestServer) StartTLS

func (hts *HTTPTestServer) StartTLS()

Start the test server with TLS activated.

type PredefinedServerResponse

type PredefinedServerResponse struct {
	// HTTP status code to return
	Status int
	// Headers to return
	Headers http.Header
	// Body to return
	Body []byte
}

Data of a predefined server response

type ServerRecord

type ServerRecord struct {
	// The HTTP request received by the test server.
	//
	// The body of the request is closed by the test server. Use the RequestBody in the record to
	// get a copy of the body of the HTTP request.
	Request *http.Request
	// A recorder used to record the HTTP response sent by the test server. Never nil.
	Response *httptest.ResponseRecorder
	// A copy of the request body. Will be empty in case request has no body. Never nil.
	RequestBody *bytes.Buffer
	// This member will be non-nil only in case an error has occured while handling the incoming
	// request. The member will contain an error which wraps the error that has occured.
	ServerError error
}

Data of a server record. The server save in a record each incoming request and the corresponding HTTP response. The server also save a copy of the request body if any.

In case the test server failed to process

Jump to

Keyboard shortcuts

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