httptest

package
v14.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause Imports: 13 Imported by: 0

README

HTTP End-To-End Testing

Overview

The httptest subpackage provides utilities for testing HTTP servers and handlers in the Iris web framework. It includes tools for creating test servers, making HTTP requests, and validating responses. This subpackage is designed to simplify the process of writing and running tests for your Iris applications.

Features

  • HTTP Status Codes: Constants for HTTP status codes as registered with IANA.
  • Test Server: Utilities for creating and managing test servers.
  • TLS Support: Functions for creating TLS listeners and certificates.
  • Request and Response Handling: Tools for making HTTP requests and validating responses.
  • Configuration Options: Customizable options for configuring the test environment.
  • Integration with httpexpect: Assertions come from the httpexpect package, so tests read as chained expectations.

Installation

To use the httptest subpackage, you need to have the Iris framework installed. You can install Iris using the following command:

go get github.com/kataras/iris/v14@latest

Creating a Test Server

The httptest subpackage provides utilities for creating and managing test servers. The NewServer function creates a new test server for an Iris application. It is rarely required for your tests but is available when you need to migrate tests from the standard Go's net/http/httptest package.

package main

import (
	"testing"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/httptest"
)

func TestMyApp(t *testing.T) {
	app := iris.New()
	// Configure your app...

	server := httptest.NewServer(t, app)
	defer server.Close()

    // Write your tests using the server...
}
Testing a Single Controller

NewController builds a throwaway application with one controller registered under a prefix and returns the same *httpexpect.Expect that New does, so a Routing value can be tested on its own, without the application or the builder chain the production code goes through. A failure answers what an application built with iris.NewBuilder answers, so the test asserts the body production sends: the path parameter type and context error handlers are installed, and rest/errors.Handler renders a bare failure status (ctx.StopWithStatus(403)) and an unknown path (404) as the rest/errors JSON envelope. A method the controller does not serve answers that 404 envelope too, not a 405: the option that turns 405 on (Options.Router.FireMethodNotAllowed) is off by default and NewController takes no options. The variadic middleware is registered on the controller's own group. Nothing else the builder chain adds is there: no CORS, no access log, no recovery, no compression. It takes no OptionSetter, because Go allows one variadic parameter and the middleware is the one a controller test needs; a test which needs httptest.URL or a non-default log level builds the application itself and calls New.

func NewController(t IrisTesty, prefix string, controller any, mw ...context.Handler) *httpexpect.Expect
func TestPlans(t *testing.T) {
	e := httptest.NewController(t, "/plans", &api.PlansController{Plans: repo})

	e.GET("/plans/1").Expect().Status(httptest.StatusOK).
		JSON().Object().HasValue("name", "starter")
}

Making HTTP Requests

The httptest subpackage integrates with the httpexpect package to provide a fluent API for making HTTP requests and validating responses.

package main

import (
	"testing"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/httptest"
)

func TestMyHandler(t *testing.T) {
	app := iris.New()
	// Configure your app...

	e := httptest.New(t, app)
	e.GET("/").Expect().Status(httptest.StatusOK).Body().IsEqual("Hello, World!")
}

TLS Support

The httptest subpackage provides functions for creating TLS listeners and certificates. The NewLocalTLSListener function creates a new TLS listener with a self-signed certificate.

package main

import (
	"testing"

	"github.com/kataras/iris/v14/httptest"
)

func TestTLS(t *testing.T) {
	listener := httptest.NewLocalTLSListener(nil)
	defer listener.Close()

	// Use the listener in your tests...
}

Configuration Options

Configuration options set up the test environment: the base URL, debug mode, and the log level.

package main

import (
	"testing"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/httptest"
)

func TestWithOptions(t *testing.T) {
	app := iris.New()
	// Configure your app...

	e := httptest.New(t, app, httptest.URL("http://localhost:8080"), httptest.Debug(true), httptest.LogLevel("debug"))
	e.GET("/").Expect().Status(httptest.StatusOK)
}

Examples

Basic Example
package main

import (
	"testing"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/httptest"
)

func TestBasic(t *testing.T) {
	app := iris.New()
	app.Get("/", func(ctx iris.Context) {
		ctx.WriteString("Hello, World!")
	})

	e := httptest.New(t, app)
	e.GET("/").Expect().Status(httptest.StatusOK).Body().IsEqual("Hello, World!")
}
Testing with Basic Authentication
package main

import (
	"testing"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/httptest"
	"github.com/kataras/iris/v14/middleware/basicauth"
)

func TestBasicAuth(t *testing.T) {
	app := iris.New()
	auth := basicauth.Default(map[string]string{"user": "pass"})
	app.Use(auth)
	app.Get("/", func(ctx iris.Context) {
		ctx.WriteString("Hello, Authenticated User!")
	})

	e := httptest.New(t, app)
	e.GET("/").WithBasicAuth("user", "pass").Expect().Status(httptest.StatusOK).Body().IsEqual("Hello, Authenticated User!")
	e.GET("/").Expect().Status(httptest.StatusUnauthorized)
}
Testing with JSON Requests and Responses
package main

import (
	"testing"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/httptest"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func TestJSON(t *testing.T) {
	app := iris.New()
	app.Post("/user", func(ctx iris.Context) {
		user, ok := ctx.BindJSON[User]()
		if !ok {
			return // ctx.BindJSON wrote the 400 itself.
		}
		ctx.OK(user, nil)
	})

	e := httptest.New(t, app)
	e.POST("/user").WithJSON(User{Name: "Gerasimos", Age: 31}).Expect().Status(httptest.StatusOK).JSON().Object().ValueEqual("name", "Gerasimos").ValueEqual("age", 31)
}
$ go test -v

For more examples, read the _test.go files across the Iris repository.

Documentation

Index

Constants

View Source
const (
	StatusContinue             = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols   = 101 // RFC 7231, 6.2.2
	StatusProcessing           = 102 // RFC 2518, 10.1
	StatusEarlyHints           = 103 // RFC 8297
	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes as registered with IANA. See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Raw Copy from the future(tip) net/http std package in order to reduce the import path of "net/http" for the users.

Variables

View Source
var (
	// URL if set then it sets the httptest's BaseURL.
	// Defaults to empty string "".
	URL = func(schemeAndHost string) OptionSet {
		return func(c *Configuration) {
			c.URL = schemeAndHost
		}
	}

	// Domain if set then it sets the httptest's BaseURL to a specific internal URL (https://iris-go.com) which enables the cookies for this domain.
	Domain = URL("https://iris-go.com")

	// Debug if true then debug messages from the httpexpect will be shown when a test runs
	// Defaults to false.
	Debug = func(val bool) OptionSet {
		return func(c *Configuration) {
			c.Debug = val
		}
	}

	// LogLevel sets the application's log level.
	// Defaults to disabled when testing.
	LogLevel = func(level string) OptionSet {
		return func(c *Configuration) {
			c.LogLevel = level
		}
	}

	// Strict sets the Strict configuration field to "val".
	// Applies the NewRequireReporter instead of the default one.
	// Use this if you want the test to fail on first error, before all checks have been done.
	Strict = func(val bool) OptionSet {
		return func(c *Configuration) {
			c.Strict = val
		}
	}
)
View Source
var (
	NewRecorder = httptest.NewRecorder
	NewRequest  = httptest.NewRequest
)

Aliases for "net/http/httptest" package. See `Do` package-level function.

Functions

func Do

func Do(w http.ResponseWriter, r *http.Request, handler iris.Handler, irisConfigurators ...iris.Configurator)

Do is a simple helper which can be used to test handlers individually with the "net/http/httptest" package. This package contains aliases for `NewRequest` and `NewRecorder` too.

For a more efficient testing please use the `New` function instead.

func LocalhostCert

func LocalhostCert() []byte

LocalhostCert returns a PEM-encoded, self-signed ECDSA P-256 TLS certificate with subjectAltNames for "localhost", 127.0.0.1 and ::1. It is generated once per process on first use and stays valid for a year, so it passes modern hostname verification when added to a client's root pool.

func LocalhostKey

func LocalhostKey() []byte

LocalhostKey returns the PEM-encoded private key for `LocalhostCert`.

func New

func New(t IrisTesty, app *iris.Application, setters ...OptionSetter) *httpexpect.Expect

New Prepares and returns a new test framework based on the "app". Usage:

httptest.New(t, app)

With options:

httptest.New(t, app, httptest.URL(...), httptest.Debug(true), httptest.LogLevel("debug"), httptest.Strict(true))

Example: https://github.com/kataras/iris/tree/main/_examples/14-testing/iris-httptest

func NewController

func NewController(t IrisTesty, prefix string, controller any, mw ...context.Handler) *httpexpect.Expect

NewController builds a throwaway application with the given controller registered under prefix and returns what New returns, so a Routing value or any other controller can be tested on its own, without the Server type or the builder chain the production code goes through.

The middleware is registered on the controller's own group, so it runs for its routes and not for the 404 and 405 chains.

A failure answers what an application built with iris.NewBuilder answers, so a controller test asserts the body production sends:

  • the path parameter type error handler and the context error handler, so a bad path parameter and a failed response write render the rest/errors body;
  • rest/errors.Handler before the router, so a bare failure status (ctx.StopWithStatus(403), a middleware that rejects with 401) renders the rest/errors envelope instead of an empty body;
  • rest/errors.Handler as the 404 handler, so an unknown path renders the envelope too. So does a method the controller does not serve: it answers 404, not 405, because the option that turns 405 on (Options.Router.FireMethodNotAllowed) is off by default and NewController takes no options.

Nothing else the builder chain adds is here: no CORS, no access log, no recovery, no compression.

It takes an IrisTesty rather than a *testing.T for the same reason New does, so ginkgo and the other testing shims keep working. It takes no OptionSetter: Go allows one variadic parameter and the middleware is the one a controller test needs; a test which needs httptest.URL or a non-default log level builds the application itself and calls New.

Usage:

e := httptest.NewController(t, "/plans", &api.PlansController{Plans: repo})
e.GET("/plans/1").Expect().Status(httptest.StatusOK)

func NewInsecure

func NewInsecure(t IrisTesty, setters ...OptionSetter) *httpexpect.Expect

NewInsecure same as New but receives a single host instead of the whole framework. Useful for testing running TLS servers.

func NewLocalListener

func NewLocalListener() net.Listener

NewLocalListener returns a new ipv4 "127.0.0.1:0" or tcp6 "[::1]:0" tcp listener.

func NewLocalTLSListener

func NewLocalTLSListener(tcpListener net.Listener) net.Listener

NewLocalTLSListener returns a new tls listener based on the "tcpListener", if "tcpListener" is nil it make use of the `NewLocalListener`. Cert and Key are `LocalhostCert` and `LocalhostKey` respectfully.

func NewServer

func NewServer(t IrisTesty, app *iris.Application) *httptest.Server

NewServer is just a helper to create a new standard httptest.Server instance.

Types

type Configuration

type Configuration struct {
	// URL the base url.
	// Defaults to empty string "".
	URL string
	// Debug if true then debug messages from the httpexpect will be shown when a test runs
	// Defaults to false.
	Debug bool
	// LogLevel sets the application's log level.
	// Defaults to "disable" when testing.
	LogLevel string

	// If true then the underline httpexpect report will be acquired by the NewRequireReporter
	// call instead of the default NewAssertReporter.
	// Defaults to false.
	Strict bool // Note: if more reports are available in the future then add a Reporter interface as a field.
}

Configuration httptest configuration

func DefaultConfiguration

func DefaultConfiguration() *Configuration

DefaultConfiguration returns the default configuration for the httptest.

func (Configuration) Set

func (c Configuration) Set(main *Configuration)

Set implements the OptionSetter for the Configuration itself

type ContentOpts

type ContentOpts = httpexpect.ContentOpts

ContentOpts alias.

type Expect

type Expect = httpexpect.Expect

Expect type alias.

type IrisTesty

type IrisTesty interface {
	Cleanup(func())
	Error(args ...any)
	Errorf(format string, args ...any)
	Fail()
	FailNow()
	Failed() bool
	Fatal(args ...any)
	Fatalf(format string, args ...any)
	Helper()
	Log(args ...any)
	Logf(format string, args ...any)
	Name() string
	Setenv(key, value string)
	Skip(args ...any)
	SkipNow()
	Skipf(format string, args ...any)
	Skipped() bool
	TempDir() string
}

IrisTesty is an interface which all testing package should implement. The `httptest` standard package and `ginkgo` third-party module do implement this interface indeed.

See the `New` package-level function for more.

type OptionSet

type OptionSet func(c *Configuration)

OptionSet implements the OptionSetter

func (OptionSet) Set

func (o OptionSet) Set(c *Configuration)

Set is the func which makes the OptionSet an OptionSetter, this is used mostly

type OptionSetter

type OptionSetter interface {
	// Set receives a pointer to the Configuration type and does the job of filling it
	Set(c *Configuration)
}

OptionSetter sets a configuration field to the configuration

type Request

type Request = httpexpect.Request

Request type alias.

Jump to

Keyboard shortcuts

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