httpservertest

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2025 License: MIT Imports: 7 Imported by: 0

README

httpservertest

This is lightweight package to handle HTTP-request stubs.

It's somewhat similar to WireMock , but much less flexible.

Simple usage:

func TestServer_Stub_NotMatched(t *testing.T) {
	server := httpservertest.Start(t)

	absentStub := server.
		Stub(
			httpservertest.OnGet("/test-url"),
			httpservertest.ResponseBody("not found").
				With(httpservertest.ResponseStatus(404)),
		)

	gotResp, gotErr := http.Get(server.Resolve("/test-url-other"))
	require.NoError(t, gotErr)
	defer gotResp.Body.Close()

	assert.Zero(t, absentStub())
}

More examples in tests.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Start

func Start(t *testing.T) *server

Start httptest.NewServer tied to testing.T life-cycle. Later it might be used to validate calls to it.

Types

type Matcher

type Matcher func(*http.Request) bool

Matcher simple wrapper wo implement request matching.

func OnBody

func OnBody(reader io.Reader) Matcher

OnBody matches body of the request.

func OnGet

func OnGet(uri string) Matcher

OnGet matches uri with GET mathod.

func OnHeader

func OnHeader(name, value string) Matcher

OnHeader matches one header. Does not check if it's the only header.

func OnMethod

func OnMethod(method, uri string) Matcher

OnMethod mathes uri with arbitrary method & uri.

func OnPost

func OnPost(uri string) Matcher

OnPost matches uri with POST mathod.

func (Matcher) And

func (m Matcher) And(other Matcher) Matcher

And is a conjunction for matchers.

type Responder

type Responder func(http.ResponseWriter)

Responder is a simple way to define response. Just a wrapper around a function.

func Response

func Response() Responder

Response empty resonse.

func ResponseBody

func ResponseBody(body string) Responder

ResponseBody specifies body of the response as a string.

func ResponseHeader

func ResponseHeader(name, value string) Responder

ResponseHeader specifies header in the reponse.

func ResponseStatus

func ResponseStatus(statusCode int) Responder

ResponseStatus specifies status code. this method must be called first due to the http.ResponseWriter. Otherwise we will always get 200.

func (Responder) With

func (r Responder) With(other Responder) Responder

With allows you to combine responses as you wish.

Jump to

Keyboard shortcuts

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