httpexpect

package module
v2.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2023 License: MIT Imports: 52 Imported by: 123

README

httpexpect GoDev Build Coveralls GitHub release Discord

Concise, declarative, and easy to use end-to-end HTTP and REST API testing for Go (golang).

Basically, httpexpect is a set of chainable builders for HTTP requests and assertions for HTTP responses and payload, on top of net/http and several utility packages.

Workflow:

  • Incrementally build HTTP requests.
  • Inspect HTTP responses.
  • Inspect response payload recursively.

Features

Request builder
Response assertions
  • Response status, predefined status ranges.
  • Headers, cookies, payload: JSON, JSONP, forms, text.
  • Round-trip time.
  • Custom reusable response matchers.
Payload assertions
  • Type-specific assertions, supported types: object, array, string, number, boolean, null, datetime.
  • Regular expressions.
  • Simple JSON queries (using subset of JSONPath), provided by jsonpath package.
  • JSON Schema validation, provided by gojsonschema package.
WebSocket support (thanks to @tyranron)
  • Upgrade an HTTP connection to a WebSocket connection (we use gorilla/websocket internally).
  • Interact with the WebSocket server.
  • Inspect WebSocket connection parameters and WebSocket messages.
Pretty printing
  • Verbose error messages.
  • JSON diff is produced on failure using gojsondiff package.
  • Failures are reported using testify (assert or require package) or standard testing package.
  • JSON values are pretty-printed using encoding/json, Go values are pretty-printed using litter.
  • Dumping requests and responses in various formats, using httputil, http2curl, or simple compact logger.
  • Color support using fatih/color.
Tuning
  • Tests can communicate with server via real HTTP client or invoke net/http or fasthttp handler directly.
  • User can provide custom HTTP client, WebSocket dialer, HTTP request factory (e.g. from the Google App Engine testing).
  • User can configure formatting options or provide custom templates based on text/template engine.
  • Custom handlers may be provided for logging, printing requests and responses, handling succeeded and failed assertions.

Versions

The versions are selected according to the semantic versioning scheme. Every new major version gets its own stable branch with a backwards compatibility promise. Releases are tagged from stable branches.

The current stable branch is v2. Previous branches are still maintained, but no new features are added.

If you're using go.mod, use a versioned import path:

import "github.com/gavv/httpexpect/v2"

Otherwise, use gopkg.in import path:

import "gopkg.in/gavv/httpexpect.v2"

Documentation

Documentation is available on pkg.go.dev. It contains an overview and reference.

Community

Community forum and Q&A board is right on GitHub in discussions tab.

For more interactive discussion, you can join discord chat.

Contributing

Feel free to report bugs, suggest improvements, and send pull requests! Please add documentation and tests for new features.

This project highly depends on contributors. Thank you all for your amazing work!

If you would like to submit code, see HACKING.md.

Donating

If you would like to support my open-source work, you can do it here:

Thanks!

Examples

See _examples directory for complete standalone examples.

  • fruits_test.go

    Testing a simple CRUD server made with bare net/http.

  • iris_test.go

    Testing a server made with iris framework. Example includes JSON queries and validation, URL and form parameters, basic auth, sessions, and streaming. Tests invoke the http.Handler directly.

  • echo_test.go

    Testing a server with JWT authentication made with echo framework. Tests use either HTTP client or invoke the http.Handler directly.

  • gin_test.go

    Testing a server utilizing the gin web framework. Tests invoke the http.Handler directly.

  • fasthttp_test.go

    Testing a server made with fasthttp package. Tests invoke the fasthttp.RequestHandler directly.

  • websocket_test.go

    Testing a WebSocket server based on gorilla/websocket. Tests invoke the http.Handler or fasthttp.RequestHandler directly.

  • oauth2_test.go

    Testing a OAuth2 server with oauth2.

  • gae_test.go

    Testing a server running under the Google App Engine.

  • formatter_test.go

    Testing with custom formatter for assertion messages.

Quick start

Hello, world!
package example

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gavv/httpexpect/v2"
)

func TestFruits(t *testing.T) {
	// create http.Handler
	handler := FruitsHandler()

	// run server using httptest
	server := httptest.NewServer(handler)
	defer server.Close()

	// create httpexpect instance
	e := httpexpect.Default(t, server.URL)

	// is it working?
	e.GET("/fruits").
		Expect().
		Status(http.StatusOK).JSON().Array().IsEmpty()
}
JSON
orange := map[string]interface{}{
	"weight": 100,
}

e.PUT("/fruits/orange").WithJSON(orange).
	Expect().
	Status(http.StatusNoContent).NoContent()

e.GET("/fruits/orange").
	Expect().
	Status(http.StatusOK).
	JSON().Object().ContainsKey("weight").HasValue("weight", 100)

apple := map[string]interface{}{
	"colors": []interface{}{"green", "red"},
	"weight": 200,
}

e.PUT("/fruits/apple").WithJSON(apple).
	Expect().
	Status(http.StatusNoContent).NoContent()

obj := e.GET("/fruits/apple").
	Expect().
	Status(http.StatusOK).JSON().Object()

obj.Keys().ContainsOnly("colors", "weight")

obj.Value("colors").Array().ConsistsOf("green", "red")
obj.Value("colors").Array().Value(0).String().IsEqual("green")
obj.Value("colors").Array().Value(1).String().IsEqual("red")
obj.Value("colors").Array().First().String().IsEqual("green")
obj.Value("colors").Array().Last().String().IsEqual("red")
JSON Schema and JSON Path
schema := `{
	"type": "array",
	"items": {
		"type": "object",
		"properties": {
			...
			"private": {
				"type": "boolean"
			}
		}
	}
}`

repos := e.GET("/repos/octocat").
	Expect().
	Status(http.StatusOK).JSON()

// validate JSON schema
repos.Schema(schema)

// run JSONPath query and iterate results
for _, private := range repos.Path("$..private").Array().Iter() {
	private.Boolean().IsFalse()
}
JSON decoding
type User struct {
	Name   string `json:"name"`
	Age    int    `json:"age"`
	Gender string `json:"gender"`
}

var user User
e.GET("/user").
	Expect().
	Status(http.StatusOK).
	JSON().
	Decode(&user)
	
if user.Name != "octocat" {
	t.Fail()
}
Forms
// post form encoded from struct or map
e.POST("/form").WithForm(structOrMap).
	Expect().
	Status(http.StatusOK)

// set individual fields
e.POST("/form").WithFormField("foo", "hello").WithFormField("bar", 123).
	Expect().
	Status(http.StatusOK)

// multipart form
e.POST("/form").WithMultipart().
	WithFile("avatar", "./john.png").WithFormField("username", "john").
	Expect().
	Status(http.StatusOK)
URL construction
// construct path using ordered parameters
e.GET("/repos/{user}/{repo}", "octocat", "hello-world").
	Expect().
	Status(http.StatusOK)

// construct path using named parameters
e.GET("/repos/{user}/{repo}").
	WithPath("user", "octocat").WithPath("repo", "hello-world").
	Expect().
	Status(http.StatusOK)

// set query parameters
e.GET("/repos/{user}", "octocat").WithQuery("sort", "asc").
	Expect().
	Status(http.StatusOK)    // "/repos/octocat?sort=asc"
Headers
// set If-Match
e.POST("/users/john").WithHeader("If-Match", etag).WithJSON(john).
	Expect().
	Status(http.StatusOK)

// check ETag
e.GET("/users/john").
	Expect().
	Status(http.StatusOK).Header("ETag").NotEmpty()

// check Date
t := time.Now()

e.GET("/users/john").
	Expect().
	Status(http.StatusOK).Header("Date").AsDateTime().InRange(t, time.Now())
Cookies
// set cookie
t := time.Now()

e.POST("/users/john").WithCookie("session", sessionID).WithJSON(john).
	Expect().
	Status(http.StatusOK)

// check cookies
c := e.GET("/users/john").
	Expect().
	Status(http.StatusOK).Cookie("session")

c.Value().IsEqual(sessionID)
c.Domain().IsEqual("example.com")
c.Path().IsEqual("/")
c.Expires().InRange(t, t.Add(time.Hour * 24))
Regular expressions
// simple match
e.GET("/users/john").
	Expect().
	Header("Location").
	Match("http://(.+)/users/(.+)").Values("example.com", "john")

// check capture groups by index or name
m := e.GET("/users/john").
	Expect().
	Header("Location").Match("http://(?P<host>.+)/users/(?P<user>.+)")

m.Index(0).IsEqual("http://example.com/users/john")
m.Index(1).IsEqual("example.com")
m.Index(2).IsEqual("john")

m.Name("host").IsEqual("example.com")
m.Name("user").IsEqual("john")
Redirection support
e.POST("/path").
	WithRedirectPolicy(httpexpect.FollowAllRedirects).
	WithMaxRedirects(5).
	Expect().
	Status(http.StatusOK)

e.POST("/path").
	WithRedirectPolicy(httpexpect.DontFollowRedirects).
	Expect().
	Status(http.StatusPermanentRedirect)
Retry support
// default retry policy
e.POST("/path").
	WithMaxRetries(5).
	Expect().
	Status(http.StatusOK)

// custom retry policy
e.POST("/path").
	WithMaxRetries(5).
	WithRetryPolicy(httpexpect.RetryAllErrors).
	Expect().
	Status(http.StatusOK)

// custom retry delays
e.POST("/path").
	WithMaxRetries(5).
	WithRetryDelay(time.Second, time.Minute).
	Expect().
	Status(http.StatusOK)
Subdomains and per-request URL
e.GET("/path").WithURL("http://example.com").
	Expect().
	Status(http.StatusOK)

e.GET("/path").WithURL("http://subdomain.example.com").
	Expect().
	Status(http.StatusOK)
WebSocket support
ws := e.GET("/mysocket").WithWebsocketUpgrade().
	Expect().
	Status(http.StatusSwitchingProtocols).
	Websocket()
defer ws.Disconnect()

ws.WriteText("some request").
	Expect().
	TextMessage().Body().IsEqual("some response")

ws.CloseWithText("bye").
	Expect().
	CloseMessage().NoContent()
Reusable builders
e := httpexpect.Default(t, "http://example.com")

r := e.POST("/login").WithForm(Login{"ford", "betelgeuse7"}).
	Expect().
	Status(http.StatusOK).JSON().Object()

token := r.Value("token").String().Raw()

auth := e.Builder(func (req *httpexpect.Request) {
	req.WithHeader("Authorization", "Bearer "+token)
})

auth.GET("/restricted").
	Expect().
	Status(http.StatusOK)

e.GET("/restricted").
	Expect().
	Status(http.StatusUnauthorized)
Reusable matchers
e := httpexpect.Default(t, "http://example.com")

// every response should have this header
m := e.Matcher(func (resp *httpexpect.Response) {
	resp.Header("API-Version").NotEmpty()
})

m.GET("/some-path").
	Expect().
	Status(http.StatusOK)

m.GET("/bad-path").
	Expect().
	Status(http.StatusNotFound)
Request transformers
e := httpexpect.Default(t, "http://example.com")

myTranform := func(r* http.Request) {
	// modify the underlying http.Request
}

// apply transformer to a single request
e.POST("/some-path").
	WithTransformer(myTranform).
	Expect().
	Status(http.StatusOK)

// create a builder that applies transfromer to every request
myBuilder := e.Builder(func (req *httpexpect.Request) {
	req.WithTransformer(myTranform)
})

myBuilder.POST("/some-path").
	Expect().
	Status(http.StatusOK)
Shared environment
e := httpexpect.Default(t, "http://example.com")

t.Run("/users", func(t *testing.T) {
	obj := e.GET("/users").
		Expect().
		Status(http.StatusOK).JSON().Object()

	// store user id for next tests
	userID := obj.Path("$.users[1].id").String().Raw()
	e.Env().Put("user1.id", userID)
})

t.Run("/user/{userId}", func(t *testing.T) {
	// read user id from previous tests
	userID := e.Env().GetString("user1.id")

	e.GET("/user/{userId}").
		WithPath("userId", userID)
		Expect().
		Status(http.StatusOK)
})
Custom config
e := httpexpect.WithConfig(httpexpect.Config{
	// include test name in failures (optional)
	TestName: t.Name(),

	// prepend this url to all requests
	BaseURL: "http://example.com",

	// use http.Client with a cookie jar and timeout
	Client: &http.Client{
		Jar:     httpexpect.NewCookieJar(),
		Timeout: time.Second * 30,
	},

	// use fatal failures
	Reporter: httpexpect.NewRequireReporter(t),

	// print all requests and responses
	Printers: []httpexpect.Printer{
		httpexpect.NewDebugPrinter(t, true),
	},
})
Use HTTP handler directly
// invoke http.Handler directly using httpexpect.Binder
var handler http.Handler = myHandler()

e := httpexpect.WithConfig(httpexpect.Config{
	// prepend this url to all requests, required for cookies
	// to be handled correctly
	BaseURL: "http://example.com",
	Reporter: httpexpect.NewAssertReporter(t),
	Client: &http.Client{
		Transport: httpexpect.NewBinder(handler),
		Jar:       httpexpect.NewCookieJar(),
	},
})

// invoke fasthttp.RequestHandler directly using httpexpect.FastBinder
var handler fasthttp.RequestHandler = myHandler()

e := httpexpect.WithConfig(httpexpect.Config{
	// prepend this url to all requests, required for cookies
	// to be handled correctly
	BaseURL: "http://example.com",
	Reporter: httpexpect.NewAssertReporter(t),
	Client: &http.Client{
		Transport: httpexpect.NewFastBinder(handler),
		Jar:       httpexpect.NewCookieJar(),
	},
})
Per-request client or handler
e := httpexpect.Default(t, server.URL)

client := &http.Client{
	Transport: &http.Transport{
		DisableCompression: true,
	},
}

// overwrite client
e.GET("/path").WithClient(client).
	Expect().
	Status(http.StatusOK)

// construct client that invokes a handler directly and overwrite client
e.GET("/path").WithHandler(handler).
	Expect().
	Status(http.StatusOK)
WebSocket dialer
// invoke http.Handler directly using websocket.Dialer
var handler http.Handler = myHandler()

e := httpexpect.WithConfig(httpexpect.Config{
	BaseURL:         "http://example.com",
	Reporter:        httpexpect.NewAssertReporter(t),
	WebsocketDialer: httpexpect.NewWebsocketDialer(handler),
})

// invoke fasthttp.RequestHandler directly using websocket.Dialer
var handler fasthttp.RequestHandler = myHandler()

e := httpexpect.WithConfig(httpexpect.Config{
	BaseURL:         "http://example.com",
	Reporter:        httpexpect.NewAssertReporter(t),
	WebsocketDialer: httpexpect.NewFastWebsocketDialer(handler),
})
Session support
// cookie jar is used to store cookies from server
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpexpect.NewAssertReporter(t),
	Client: &http.Client{
		Jar: httpexpect.NewCookieJar(), // used by default if Client is nil
	},
})

// cookies are disabled
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpexpect.NewAssertReporter(t),
	Client: &http.Client{
		Jar: nil,
	},
})
TLS support
// use TLS with http.Transport
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpexpect.NewAssertReporter(t),
	Client: &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				// accept any certificate; for testing only!
				InsecureSkipVerify: true,
			},
		},
	},
})

// use TLS with http.Handler
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpexpect.NewAssertReporter(t),
	Client: &http.Client{
		Transport: &httpexpect.Binder{
			Handler: myHandler,
			TLS:     &tls.ConnectionState{},
		},
	},
})
Proxy support
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpexpect.NewAssertReporter(t),
	Client: &http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyURL("http://proxy.example.com"),
		},
	},
})
Global time-out/cancellation
handler := FruitsHandler()

server := httptest.NewServer(handler)
defer server.Close()

ctx, cancel := context.WithCancel(context.Background())

e := WithConfig(Config{
	BaseURL:  server.URL,
	Reporter: httpexpect.NewAssertReporter(t),
	Context:  ctx,
})

go func() {
	time.Sleep(time.Duration(5)*time.Second)
	cancel()
}()

e.GET("/fruits").
	Expect().
	Status(http.StatusOK)
Per-request time-out/cancellation
// per-request context
e.GET("/fruits").
	WithContext(context.TODO()).
	Expect().
	Status(http.StatusOK)

// per-request timeout
e.GET("/fruits").
	WithTimeout(time.Duration(5)*time.Second).
	Expect().
	Status(http.StatusOK)

// timeout combined with retries (timeout applies to each try)
e.POST("/fruits").
	WithMaxRetries(5).
	WithTimeout(time.Duration(10)*time.Second).
	Expect().
	Status(http.StatusOK)
Support for aliases in failure messages
// when the tests fails, assertion path in the failure message is:
//   Request("GET").Expect().JSON().Array().IsEmpty()
e.GET("/fruits").
	Expect().
	Status(http.StatusOK).JSON().Array().IsEmpty()


// assign alias "fruits" to the Array variable
fruits := e.GET("/fruits").
	Expect().
	Status(http.StatusOK).JSON().Array().Alias("fruits")

// assertion path in the failure message is now:
//   fruits.IsEmpty()
fruits.IsEmpty()
Printing requests and responses
// print requests in short form, don't print responses
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpexpect.NewAssertReporter(t),
	Printers: []httpexpect.Printer{
		httpexpect.NewCompactPrinter(t),
	},
})

// print requests as curl commands that can be inserted into terminal
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpexpect.NewAssertReporter(t),
	Printers: []httpexpect.Printer{
		httpexpect.NewCurlPrinter(t),
	},
})

// print requests and responses in verbose form
// also print all incoming and outgoing websocket messages
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpexpect.NewAssertReporter(t),
	Printers: []httpexpect.Printer{
		httpexpect.NewDebugPrinter(t, true),
	},
})
Customize failure formatting
// customize formatting options
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter:  httpexpect.NewAssertReporter(t),
	Formatter: &httpexpect.DefaultFormatter{
		DisablePaths: true,
		DisableDiffs: true,
		FloatFormat:  httpexpect.FloatFormatScientific,
		ColorMode:    httpexpect.ColorModeNever,
		LineWidth:    80,
	},
})

// customize formatting template
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter:  httpexpect.NewAssertReporter(t),
	Formatter: &httpexpect.DefaultFormatter{
		SuccessTemplate: "...",
		FailureTemplate: "...",
		TemplateFuncs:   template.FuncMap{ ... },
	},
})

// provide custom formatter
e := httpexpect.WithConfig(httpexpect.Config{
	Reporter:  httpexpect.NewAssertReporter(t),
	Formatter: &MyFormatter{},
})
Customize assertion handling
// enable printing of succeeded assertions
e := httpexpect.WithConfig(httpexpect.Config{
	AssertionHandler: &httpexpect.DefaultAssertionHandler{
		Formatter: &httpexpect.DefaultFormatter{},
		Reporter:  httpexpect.NewAssertReporter(t),
		Logger:    t, // specify logger to enable printing of succeeded assertions
	},
})

// provide custom assertion handler
// here you can implement custom handling of succeeded and failed assertions
// this may be useful for integrating httpexpect with other testing libs
// if desired, you can completely ignore builtin Formatter, Reporter, and Logger
e := httpexpect.WithConfig(httpexpect.Config{
	AssertionHandler: &MyAssertionHandler{},
})

Similar packages

License

MIT

Documentation

Overview

Package httpexpect helps with end-to-end HTTP and REST API testing.

Usage examples

See example directory:

Communication mode

There are two common ways to test API with httpexpect:

  • start HTTP server and instruct httpexpect to use HTTP client for communication
  • don't start server and instruct httpexpect to invoke http handler directly

The second approach works only if the server is a Go module and its handler can be imported in tests.

Concrete behaviour is determined by Client implementation passed to Config struct. If you're using http.Client, set its Transport field (http.RoundTriper) to one of the following:

  1. default (nil) - use HTTP transport from net/http (you should start server)
  2. httpexpect.Binder - invoke given http.Handler directly
  3. httpexpect.FastBinder - invoke given fasthttp.RequestHandler directly

Note that http handler can be usually obtained from http framework you're using. E.g., echo framework provides either http.Handler or fasthttp.RequestHandler.

You can also provide your own implementation of RequestFactory (creates http.Request), or Client (gets http.Request and returns http.Response).

If you're starting server from tests, it's very handy to use net/http/httptest.

Value equality

Whenever values are checked for equality in httpexpect, they are converted to "canonical form":

  • structs are converted to map[string]interface{}
  • type aliases are removed
  • numeric types are converted to float64
  • non-nil interfaces pointing to nil slices and maps are replaced with nil interfaces

This is equivalent to subsequently json.Marshal() and json.Unmarshal() the value and currently is implemented so.

Failure handling

When some check fails, failure is reported. If non-fatal failures are used (see Reporter interface), execution is continued and instance that was checked is marked as failed.

If specific instance is marked as failed, all subsequent checks are ignored for this instance and for any child instances retrieved after failure.

Example:

array := NewArray(NewAssertReporter(t), []interface{}{"foo", 123})

e0 := array.Value(0)  // success
e1 := array.Value(1)  // success

s0 := e0.String()  // success
s1 := e1.String()  // failure; e1 and s1 are marked as failed, e0 and s0 are not

s0.IsEqual("foo")    // success
s1.IsEqual("bar")    // this check is ignored because s1 is marked as failed

Assertion handling

If you want to be informed about every asserion made, successful or failed, you can use AssertionHandler interface.

Default implementation of this interface ignores successful assertions and reports failed assertions using Formatter and Reporter objects.

Custom AssertionHandler can handle all assertions (e.g. dump them in JSON format) and is free to use or not to use Formatter and Reporter in its sole discretion.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewCookieJar added in v2.9.0

func NewCookieJar() http.CookieJar

NewCookieJar returns a new http.CookieJar.

Returned jar is implemented in net/http/cookiejar. PublicSuffixList is implemented in golang.org/x/net/publicsuffix.

Note that this jar ignores cookies when request url is empty.

func NewFastWebsocketDialer

func NewFastWebsocketDialer(handler fasthttp.RequestHandler) *websocket.Dialer

NewFastWebsocketDialer produces new websocket.Dialer which dials to bound fasthttp.RequestHandler without creating a real net.Conn.

func NewJar deprecated

func NewJar() http.CookieJar

Deprecated: use NewCookieJar instead.

func NewWebsocketDialer

func NewWebsocketDialer(handler http.Handler) *websocket.Dialer

NewWebsocketDialer produces new websocket.Dialer which dials to bound http.Handler without creating a real net.Conn.

Types

type Array

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

Array provides methods to inspect attached []interface{} object (Go representation of JSON array).

func NewArray

func NewArray(reporter Reporter, value []interface{}) *Array

NewArray returns a new Array instance.

If reporter is nil, the function panics. If value is nil, failure is reported.

Example:

array := NewArray(t, []interface{}{"foo", 123})

func NewArrayC added in v2.9.0

func NewArrayC(config Config, value []interface{}) *Array

NewArrayC returns a new Array instance with config.

Requirements for config are same as for WithConfig function. If value is nil, failure is reported.

Example:

array := NewArrayC(config, []interface{}{"foo", 123})

func (*Array) Alias added in v2.10.0

func (a *Array) Alias(name string) *Array

Alias is similar to Value.Alias.

func (*Array) ConsistsOf added in v2.10.0

func (a *Array) ConsistsOf(values ...interface{}) *Array

ConsistsOf succeeds if array contains all given elements, in given order, and only them. Before comparison, array and all elements are converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.ConsistsOf("foo", 123)

These calls are equivalent:

array.ConsistsOf("a", "b")
array.IsEqual([]interface{}{"a", "b"})

func (*Array) Contains deprecated

func (a *Array) Contains(values ...interface{}) *Array

Deprecated: use ContainsAll or ContainsAny instead.

func (*Array) ContainsAll added in v2.10.0

func (a *Array) ContainsAll(values ...interface{}) *Array

ContainsAll succeeds if array contains all given elements (in any order). Before comparison, array and all elements are converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.ContainsAll(123, "foo")

func (*Array) ContainsAny added in v2.7.0

func (a *Array) ContainsAny(values ...interface{}) *Array

ContainsAny succeeds if array contains at least one element from the given elements. Before comparison, array and all elements are converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123, 123})
array.ContainsAny(123, "foo", "FOO") // success
array.ContainsAny("FOO") // failure

func (*Array) ContainsOnly

func (a *Array) ContainsOnly(values ...interface{}) *Array

ContainsOnly succeeds if array contains all given elements, in any order, and only them, ignoring duplicates. Before comparison, array and all elements are converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123, 123})
array.ContainsOnly(123, "foo")

These calls are equivalent:

array.ContainsOnly("a", "b")
array.ContainsOnly("b", "a")

func (*Array) Decode added in v2.10.0

func (a *Array) Decode(target interface{}) *Array

Decode unmarshals the underlying value attached to the Array to a target variable. target should be one of these:

  • pointer to an empty interface
  • pointer to a slice of any type

Example:

type S struct{
	Foo int `json:foo`
}
value := []interface{}{
	map[string]interface{}{
		"foo": 123,
	},
	map[string]interface{}{
		"foo": 456,
	},
}
array := NewArray(t, value)

var target []S
arr.Decode(&target)

assert.Equal(t, []S{{123}, {456}}, target)

func (*Array) Element deprecated

func (a *Array) Element(index int) *Value

Deprecated: use Value instead.

func (*Array) Elements deprecated

func (a *Array) Elements(values ...interface{}) *Array

Deprecated: use ConsistsOf instead.

func (*Array) Empty deprecated

func (a *Array) Empty() *Array

Deprecated: use IsEmpty instead.

func (*Array) Equal deprecated

func (a *Array) Equal(value interface{}) *Array

Deprecated: use IsEqual instead.

func (*Array) EqualUnordered deprecated added in v2.6.0

func (a *Array) EqualUnordered(value interface{}) *Array

Deprecated: use IsEqualUnordered instead.

func (*Array) Every added in v2.7.0

func (a *Array) Every(fn func(index int, value *Value)) *Array

Every runs the passed function on all the elements in the array.

If assertion inside function fails, the original Array is marked failed.

Every will execute the function for all values in the array irrespective of assertion failures for some values in the array.

Example:

array := NewArray(t, []interface{}{"foo", "bar"})

array.Every(func(index int, value *httpexpect.Value) {
	value.String().NotEmpty()
})

func (*Array) Filter added in v2.7.0

func (a *Array) Filter(fn func(index int, value *Value) bool) *Array

Filter accepts a function that returns a boolean. The function is ran over the array elements. If the function returns true, the element passes the filter and is added to the new array of filtered elements. If false, the element is skipped (or in other words filtered out). After iterating through all the elements of the original array, the new filtered array is returned.

If there are any failed assertions in the filtering function, the element is omitted without causing test failure.

Example:

array := NewArray(t, []interface{}{1, 2, "foo", "bar"})
filteredArray := array.Filter(func(index int, value *httpexpect.Value) bool {
	value.String().NotEmpty()		//fails on 1 and 2
	return value.Raw() != "bar"		//fails on "bar"
})
filteredArray.IsEqual([]interface{}{"foo"})	//succeeds

func (*Array) Find added in v2.9.0

func (a *Array) Find(fn func(index int, value *Value) bool) *Value

Find accepts a function that returns a boolean, runs it over the array elements, and returns the first element on which it returned true.

If there are any failed assertions in the predicate function, the element is skipped without causing test failure.

If no elements were found, a failure is reported.

Example:

array := NewArray(t, []interface{}{1, "foo", 101, "bar", 201})
foundValue := array.Find(func(index int, value *httpexpect.Value) bool {
	num := value.Number()    // skip if element is not a number
	return num.Raw() > 100   // check element value
})
foundValue.IsEqual(101) // succeeds

func (*Array) FindAll added in v2.9.0

func (a *Array) FindAll(fn func(index int, value *Value) bool) []*Value

FindAll accepts a function that returns a boolean, runs it over the array elements, and returns all the elements on which it returned true.

If there are any failed assertions in the predicate function, the element is skipped without causing test failure.

If no elements were found, empty slice is returned without reporting error.

Example:

array := NewArray(t, []interface{}{1, "foo", 101, "bar", 201})
foundValues := array.FindAll(func(index int, value *httpexpect.Value) bool {
	num := value.Number()   // skip if element is not a number
	return num.Raw() > 100  // check element value
})

assert.Equal(t, len(foundValues), 2)
foundValues[0].IsEqual(101)
foundValues[1].IsEqual(201)

func (*Array) First deprecated

func (a *Array) First() *Value

Deprecated: use Value or HasValue instead.

func (*Array) HasValue added in v2.13.0

func (a *Array) HasValue(index int, value interface{}) *Array

HasValue succeeds if array's value at the given index is equal to given value.

Before comparison, both values are converted to canonical form. value should be map[string]interface{} or struct.

Example:

array := NewArray(t, []interface{}{"foo", "123"})
array.HasValue(1, 123)

func (*Array) InList added in v2.11.0

func (a *Array) InList(values ...interface{}) *Array

InList succeeds if the whole array is equal to one of the values from given list of arrays. Before comparison, both array and each value are converted to canonical form.

Each value should be a slice of any type. If at least one value has wrong type, failure is reported.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.InList([]interface{}{"foo", 123}, []interface{}{"bar", "456"})

func (*Array) IsEmpty added in v2.11.0

func (a *Array) IsEmpty() *Array

IsEmpty succeeds if array is empty.

Example:

array := NewArray(t, []interface{}{})
array.IsEmpty()

func (*Array) IsEqual added in v2.11.0

func (a *Array) IsEqual(value interface{}) *Array

IsEqual succeeds if array is equal to given value. Before comparison, both array and value are converted to canonical form.

value should be a slice of any type.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.IsEqual([]interface{}{"foo", 123})

array := NewArray(t, []interface{}{"foo", "bar"})
array.IsEqual([]string{}{"foo", "bar"})

array := NewArray(t, []interface{}{123, 456})
array.IsEqual([]int{}{123, 456})

func (*Array) IsEqualUnordered added in v2.11.0

func (a *Array) IsEqualUnordered(value interface{}) *Array

IsEqualUnordered succeeds if array is equal to another array, ignoring element order. Before comparison, both arrays are converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.IsEqualUnordered([]interface{}{123, "foo"})

func (*Array) IsOrdered added in v2.9.0

func (a *Array) IsOrdered(less ...func(x, y *Value) bool) *Array

IsOrdered succeeds if every element is not less than the previous element as defined on the given `less` comparator function. For default, it will use built-in comparator function for each data type. Built-in comparator requires all elements in the array to have same data type. Array with 0 or 1 element will always succeed

Example:

array := NewArray(t, []interface{}{100, 101, 102})
array.IsOrdered() // succeeds
array.IsOrdered(func(x, y *httpexpect.Value) bool {
	return x.Number().Raw() < y.Number().Raw()
}) // succeeds

func (*Array) Iter

func (a *Array) Iter() []Value

Iter returns a new slice of Values attached to array elements.

Example:

strings := []interface{}{"foo", "bar"}
array := NewArray(t, strings)

for index, value := range array.Iter() {
	value.String().IsEqual(strings[index])
}

func (*Array) Last deprecated

func (a *Array) Last() *Value

Deprecated: use Value or HasValue instead.

func (*Array) Length

func (a *Array) Length() *Number

Length returns a new Number instance with array length.

Example:

array := NewArray(t, []interface{}{1, 2, 3})
array.Length().IsEqual(3)

func (*Array) NotConsistsOf added in v2.10.0

func (a *Array) NotConsistsOf(values ...interface{}) *Array

NotConsistsOf is opposite to ConsistsOf.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.NotConsistsOf("foo")
array.NotConsistsOf("foo", 123, 456)
array.NotConsistsOf(123, "foo")

These calls are equivalent:

array.NotConsistsOf("a", "b")
array.NotEqual([]interface{}{"a", "b"})

func (*Array) NotContains deprecated

func (a *Array) NotContains(values ...interface{}) *Array

Deprecated: use NotContainsAll or NotContainsAny instead.

func (*Array) NotContainsAll added in v2.10.0

func (a *Array) NotContainsAll(values ...interface{}) *Array

NotContainsAll succeeds if array does not contain at least one of the elements. Before comparison, array and all elements are converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.NotContainsAll("bar")         // success
array.NotContainsAll(123, "foo")    // failure

func (*Array) NotContainsAny added in v2.7.0

func (a *Array) NotContainsAny(values ...interface{}) *Array

NotContainsAny succeeds if none of the given elements are in the array. Before comparison, array and all elements are converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.NotContainsAny("bar", 124) // success
array.NotContainsAny(123) // failure

func (*Array) NotContainsOnly added in v2.6.0

func (a *Array) NotContainsOnly(values ...interface{}) *Array

NotContainsOnly is opposite to ContainsOnly.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.NotContainsOnly(123)
array.NotContainsOnly(123, "foo", "bar")

These calls are equivalent:

array.NotContainsOnly("a", "b")
array.NotContainsOnly("b", "a")

func (*Array) NotElements deprecated added in v2.6.0

func (a *Array) NotElements(values ...interface{}) *Array

Deprecated: use NotConsistsOf instead.

func (*Array) NotEmpty

func (a *Array) NotEmpty() *Array

NotEmpty succeeds if array is non-empty.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.NotEmpty()

func (*Array) NotEqual

func (a *Array) NotEqual(value interface{}) *Array

NotEqual succeeds if array is not equal to given value. Before comparison, both array and value are converted to canonical form.

value should be a slice of any type.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.NotEqual([]interface{}{123, "foo"})

func (*Array) NotEqualUnordered added in v2.6.0

func (a *Array) NotEqualUnordered(value interface{}) *Array

NotEqualUnordered succeeds if array is not equal to another array, ignoring element order. Before comparison, both arrays are converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.NotEqualUnordered([]interface{}{123, "foo", "bar"})

func (*Array) NotFind added in v2.9.0

func (a *Array) NotFind(fn func(index int, value *Value) bool) *Array

NotFind accepts a function that returns a boolean, runs it over the array elelements, and checks that it does not return true for any of the elements.

If there are any failed assertions in the predicate function, the element is skipped without causing test failure.

If the predicate function did not fail and returned true for at least one element, a failure is reported.

Example:

array := NewArray(t, []interface{}{1, "foo", 2, "bar"})
array.NotFind(func(index int, value *httpexpect.Value) bool {
	num := value.Number()    // skip if element is not a number
	return num.Raw() > 100   // check element value
}) // succeeds

func (*Array) NotHasValue added in v2.13.0

func (a *Array) NotHasValue(index int, value interface{}) *Array

NotHasValue succeeds if array's value at the given index is not equal to given value.

Before comparison, both values are converted to canonical form. value should be map[string]interface{} or struct.

Example:

array := NewArray(t, []interface{}{"foo", "123"})
array.NotHasValue(1, 234)

func (*Array) NotInList added in v2.11.0

func (a *Array) NotInList(values ...interface{}) *Array

NotInList succeeds if the whole array is not equal to any of the values from given list of arrays. Before comparison, both array and each value are converted to canonical form.

Each value should be a slice of any type. If at least one value has wrong type, failure is reported.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.NotInList([]interface{}{"bar", 456}, []interface{}{"baz", "foo"})

func (*Array) NotOrdered added in v2.9.0

func (a *Array) NotOrdered(less ...func(x, y *Value) bool) *Array

NotOrdered succeeds if at least one element is less than the previous element as defined on the given `less` comparator function. For default, it will use built-in comparator function for each data type. Built-in comparator requires all elements in the array to have same data type. Array with 0 or 1 element will always succeed

Example:

array := NewArray(t, []interface{}{102, 101, 100})
array.NotOrdered() // succeeds
array.NotOrdered(func(x, y *httpexpect.Value) bool {
	return x.Number().Raw() < y.Number().Raw()
}) // succeeds

func (*Array) Path

func (a *Array) Path(path string) *Value

Path is similar to Value.Path.

func (*Array) Raw

func (a *Array) Raw() []interface{}

Raw returns underlying value attached to Array. This is the value originally passed to NewArray, converted to canonical form.

Example:

array := NewArray(t, []interface{}{"foo", 123})
assert.Equal(t, []interface{}{"foo", 123.0}, array.Raw())

func (*Array) Schema

func (a *Array) Schema(schema interface{}) *Array

Schema is similar to Value.Schema.

func (*Array) Transform added in v2.7.0

func (a *Array) Transform(fn func(index int, value interface{}) interface{}) *Array

Transform runs the passed function on all the elements in the array and returns a new array without effeecting original array.

Example:

array := NewArray(t, []interface{}{"foo", "bar"})
transformedArray := array.Transform(
	func(index int, value interface{}) interface{} {
		return strings.ToUpper(value.(string))
	})
transformedArray.IsEqual([]interface{}{"FOO", "BAR"})

func (*Array) Value added in v2.13.0

func (a *Array) Value(index int) *Value

Value returns a new Value instance with array element for given index.

If index is out of array bounds, Value reports failure and returns empty (but non-nil) instance.

Example:

array := NewArray(t, []interface{}{"foo", 123})
array.Value(0).String().IsEqual("foo")
array.Value(1).Number().IsEqual(123)

type AssertReporter

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

AssertReporter implements Reporter interface using `testify/assert' package. Failures are non-fatal with this reporter.

func NewAssertReporter

func NewAssertReporter(t assert.TestingT) *AssertReporter

NewAssertReporter returns a new AssertReporter object.

func (*AssertReporter) Errorf

func (r *AssertReporter) Errorf(message string, args ...interface{})

Errorf implements Reporter.Errorf.

type AssertionContext added in v2.5.0

type AssertionContext struct {
	// Name of the running test
	// Usually comes from testing.T
	TestName string

	// Name of request being sent
	// Comes from Request.WithName()
	RequestName string

	// Chain of nested assertion names
	// Example value:
	//   {`Request("GET")`, `Expect()`, `JSON()`, `NotNull()`}
	Path []string

	// Chain of nested assertion names starting from alias
	// When alias is not set, AliasedPath has the same value as Path
	// Example value:
	//   {`foo`, `NotNull()`} // alias named foo
	AliasedPath []string

	// Request being sent
	// May be nil if request was not yet sent
	Request *Request

	// Response being matched
	// May be nil if response was not yet received
	Response *Response

	// Environment shared between tests
	// Comes from Expect instance
	Environment *Environment

	// Whether reporter is known to output to testing.TB
	// For example, true when reporter is testing.T or testify-based reporter.
	TestingTB bool
}

AssertionContext provides context where the assetion happened.

type AssertionFailure added in v2.5.0

type AssertionFailure struct {
	// Type of failed assertion
	Type AssertionType

	// Severity of failure
	Severity AssertionSeverity

	// Deprecated: use Severity
	IsFatal bool

	// List of error messages
	Errors []error

	// Actually observed value
	Actual *AssertionValue

	// Expected value
	Expected *AssertionValue

	// Reference value
	Reference *AssertionValue

	// Allowed delta between actual and expected
	Delta *AssertionValue

	// Stacktrace of the failure
	Stacktrace []StacktraceEntry
}

AssertionFailure provides detailed information about failed assertion.

[Type] and [Errors] fields are set for all assertions. [Actual], [Expected], [Reference], and [Delta] fields are set only for certain assertion types.

The value itself is stored in [Actual.Value], [Expected.Value], etc. It allows to distinguish whether the value is not present at all, or is present but is nil.

[Actual] stores the value being examined.

Exact meaning of [Expected] depends on assertion type. It may be the value to which [Actual] was compared, or range to which [Actual] should belong, or pattern with which [Actual] should match, or element which [Actual] should contain, and so on.

If [Reference] is set, it stores the value from which the check originated. For example, the user asked to check for unordered equality of arrays A and B. During comparison, a check failed that array A contains element E from array B. In this case [Actual] will be set to A (actually observed array), [Expected] will be set to E (expected but missing element), and [Reference] will be set to B (reference array that originated the check).

If [Delta] is set, it stores maximum allowed difference between [Actual] and [Expected] values.

For further details, see comments for corresponding AssertionType constant.

type AssertionHandler added in v2.5.0

type AssertionHandler interface {
	// Invoked every time when an assertion succeeded.
	// May ignore failure, or log it, e.g. using t.Logf().
	Success(*AssertionContext)

	// Invoked every time when an assertion failed.
	// Handling depends on Failure.Severity field:
	//  - for SeverityError, reports failure to testing suite, e.g. using t.Errorf()
	//  - for SeverityLog, ignores failure, or logs it, e.g. using t.Logf()
	Failure(*AssertionContext, *AssertionFailure)
}

AssertionHandler takes care of formatting and reporting test Failure or Success.

You can log every performed assertion, or report only failures. You can implement custom formatting, for example, provide a JSON output for ulterior processing.

Usually you don't need to implement AssertionHandler; instead you can implement Reporter, which is much simpler, and use it with DefaultAssertionHandler.

type AssertionList added in v2.5.0

type AssertionList []interface{}

AssertionList holds list of allowed values

type AssertionRange added in v2.5.0

type AssertionRange struct {
	Min interface{}
	Max interface{}
}

AssertionRange holds inclusive range for allowed values

type AssertionSeverity added in v2.7.0

type AssertionSeverity uint

AssertionSeverity defines how assertion failure should be treated.

const (
	// This assertion failure should mark current test as failed.
	// Typically handler will call t.Errorf().
	// This severity is used for most assertions.
	SeverityError AssertionSeverity = iota

	// This assertion failure is informational only, it can be logged,
	// but should not cause test failure.
	// Typically handler will call t.Logf(), or just ignore assertion.
	// This severity is used for assertions issued inside predicate functions,
	// e.g. in Array.Filter and Object.Filter.
	SeverityLog
)

func (AssertionSeverity) String added in v2.7.0

func (i AssertionSeverity) String() string

type AssertionType added in v2.5.0

type AssertionType uint

AssertionType defines type of performed assertion.

const (
	// Check if the invocation is correct
	AssertUsage AssertionType = iota

	// Check if the operation succeeded
	AssertOperation

	// Check expression: [Actual] has appropriate type
	AssertType
	AssertNotType

	// Check expression: [Actual] has valid value
	AssertValid
	AssertNotValid

	// Check expression: [Actual] is nil
	AssertNil
	AssertNotNil

	// Check expression: [Actual] is empty
	AssertEmpty
	AssertNotEmpty

	// Check expression: [Actual] is equal to [Expected]
	// If [Delta] is set, it specifies allowed difference between values
	AssertEqual
	AssertNotEqual

	// Check expression: [Actual] < [Expected]
	AssertLt
	// Check expression: [Actual] <= [Expected]
	AssertLe
	// Check expression: [Actual] > [Expected]
	AssertGt
	// Check expression: [Actual] >= [Expected]
	AssertGe

	// Check expression: [Actual] belongs to inclusive range [Expected]
	// [Expected] stores AssertionRange with Min and Max values
	AssertInRange
	AssertNotInRange

	// Check expression: [Actual] matches json schema [Expected]
	// [Expected] stores map with parsed schema or string with schema uri
	AssertMatchSchema
	AssertNotMatchSchema

	// Check expression: [Actual] matches json path [Expected]
	// [Expected] stores a string with json path
	AssertMatchPath
	AssertNotMatchPath

	// Check expression: [Actual] matches regex [Expected]
	// [Expected] stores a string with regular expression
	AssertMatchRegexp
	AssertNotMatchRegexp

	// Check expression: [Actual] matches format [Expected]
	// [Expected] stores expected format or format list (AssertionList)
	AssertMatchFormat
	AssertNotMatchFormat

	// Check expression: [Actual] contains key [Expected]
	AssertContainsKey
	AssertNotContainsKey

	// Check expression: [Actual] contains element [Expected]
	AssertContainsElement
	AssertNotContainsElement

	// Check expression: [Actual] contains subset [Expected]
	AssertContainsSubset
	AssertNotContainsSubset

	// Check expression: [Actual] belongs to list [Expected]
	// [Expected] stores AssertionList with allowed values
	AssertBelongs
	AssertNotBelongs
)

func (AssertionType) String added in v2.5.0

func (i AssertionType) String() string

type AssertionValue added in v2.5.0

type AssertionValue struct {
	Value interface{}
}

AssertionValue holds expected or actual value

type Binder

type Binder struct {
	// HTTP handler invoked for every request.
	Handler http.Handler
	// TLS connection state used for https:// requests.
	TLS *tls.ConnectionState
}

Binder implements networkless http.RoundTripper attached directly to http.Handler.

Binder emulates network communication by invoking given http.Handler directly. It passes httptest.ResponseRecorder as http.ResponseWriter to the handler, and then constructs http.Response from recorded data.

func NewBinder

func NewBinder(handler http.Handler) Binder

NewBinder returns a new Binder given a http.Handler.

Example:

client := &http.Client{
	Transport: NewBinder(handler),
}

func (Binder) RoundTrip

func (binder Binder) RoundTrip(origReq *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.RoundTrip.

type Boolean

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

Boolean provides methods to inspect attached bool value (Go representation of JSON boolean).

func NewBoolean

func NewBoolean(reporter Reporter, value bool) *Boolean

NewBoolean returns a new Boolean instance.

If reporter is nil, the function panics.

Example:

boolean := NewBoolean(t, true)
boolean.IsTrue()

func NewBooleanC added in v2.9.0

func NewBooleanC(config Config, value bool) *Boolean

NewBooleanC returns a new Boolean instance with config.

Requirements for config are same as for WithConfig function.

Example:

boolean := NewBooleanC(config, true)
boolean.IsTrue()

func (*Boolean) Alias added in v2.10.0

func (b *Boolean) Alias(name string) *Boolean

Alias is similar to Value.Alias.

func (*Boolean) Decode added in v2.10.0

func (b *Boolean) Decode(target interface{}) *Boolean

Decode unmarshals the underlying value attached to the Boolean to a target variable. target should be one of these:

  • pointer to an empty interface
  • pointer to a boolean

Example:

value := NewBoolean(t, true)

var target bool
value.Decode(&target)

assert.Equal(t, true, target)

func (*Boolean) Equal deprecated

func (b *Boolean) Equal(value bool) *Boolean

Deprecated: use IsEqual instead.

func (*Boolean) False deprecated

func (b *Boolean) False() *Boolean

Deprecated: use IsFalse instead.

func (*Boolean) InList added in v2.11.0

func (b *Boolean) InList(values ...bool) *Boolean

InList succeeds if boolean is equal to one of the values from given list of booleans.

Example:

boolean := NewBoolean(t, true)
boolean.InList(true, false)

func (*Boolean) IsEqual added in v2.11.0

func (b *Boolean) IsEqual(value bool) *Boolean

IsEqual succeeds if boolean is equal to given value.

Example:

boolean := NewBoolean(t, true)
boolean.IsEqual(true)

func (*Boolean) IsFalse added in v2.12.0

func (b *Boolean) IsFalse() *Boolean

IsFalse succeeds if boolean is false.

Example:

boolean := NewBoolean(t, false)
boolean.IsFalse()

func (*Boolean) IsTrue added in v2.12.0

func (b *Boolean) IsTrue() *Boolean

IsTrue succeeds if boolean is true.

Example:

boolean := NewBoolean(t, true)
boolean.IsTrue()

func (*Boolean) NotEqual

func (b *Boolean) NotEqual(value bool) *Boolean

NotEqual succeeds if boolean is not equal to given value.

Example:

boolean := NewBoolean(t, true)
boolean.NotEqual(false)

func (*Boolean) NotInList added in v2.11.0

func (b *Boolean) NotInList(values ...bool) *Boolean

NotInList succeeds if boolean is not equal to any of the values from given list of booleans.

Example:

boolean := NewBoolean(t, true)
boolean.NotInList(true, false) // failure

func (*Boolean) Path

func (b *Boolean) Path(path string) *Value

Path is similar to Value.Path.

func (*Boolean) Raw

func (b *Boolean) Raw() bool

Raw returns underlying value attached to Boolean. This is the value originally passed to NewBoolean.

Example:

boolean := NewBoolean(t, true)
assert.Equal(t, true, boolean.Raw())

func (*Boolean) Schema

func (b *Boolean) Schema(schema interface{}) *Boolean

Schema is similar to Value.Schema.

func (*Boolean) True deprecated

func (b *Boolean) True() *Boolean

Deprecated: use IsTrue instead.

type Client

type Client interface {
	// Do sends request and returns response.
	Do(*http.Request) (*http.Response, error)
}

Client is used to send http.Request and receive http.Response. http.Client implements this interface.

Binder and FastBinder may be used to obtain this interface implementation.

Example:

httpBinderClient := &http.Client{
  Transport: httpexpect.NewBinder(HTTPHandler),
}
fastBinderClient := &http.Client{
  Transport: httpexpect.NewFastBinder(FastHTTPHandler),
}

type ClientFunc added in v2.15.0

type ClientFunc func(req *http.Request) (*http.Response, error)

ClientFunc is an adapter that allows a function to be used as the Client

Example:

e := httpexpect.WithConfig(httpexpect.Config{
	Client: httpextect.ClientFunc(
		func(req *http.Request) (*http.Response, error) {
			// client code here
		}),
})

func (ClientFunc) Do added in v2.15.0

func (f ClientFunc) Do(req *http.Request) (*http.Response, error)

type ColorMode added in v2.15.0

type ColorMode int

ColorMode defines how the text color is enabled.

const (
	// Automatically enable colors if ALL of the following is true:
	//  - stdout is a tty / console
	//  - AssertionHandler is known to output to testing.T
	//  - testing.Verbose() is true
	//
	// Colors are forcibly enabled if FORCE_COLOR environment variable
	// is set to a positive integer.
	//
	// Colors are forcibly disabled if TERM is "dumb" or NO_COLOR
	// environment variable is set to non-empty string.
	ColorModeAuto ColorMode = iota

	// Unconditionally enable colors.
	ColorModeAlways

	// Unconditionally disable colors.
	ColorModeNever
)

type CompactPrinter

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

CompactPrinter implements Printer. Prints requests in compact form. Does not print responses.

func NewCompactPrinter

func NewCompactPrinter(logger Logger) CompactPrinter

NewCompactPrinter returns a new CompactPrinter given a logger.

func (CompactPrinter) Request

func (p CompactPrinter) Request(req *http.Request)

Request implements Printer.Request.

func (CompactPrinter) Response

Response implements Printer.Response.

type Config

type Config struct {
	// TestName defines the name of the currently running test.
	// May be empty.
	//
	// If non-empty, it will be included in failure report.
	// Normally you set this value to t.Name().
	TestName string

	// BaseURL is a URL to prepended to all requests.
	// May be empty.
	//
	// If non-empty, trailing slash is allowed (but not required) and is appended
	// automatically.
	BaseURL string

	// RequestFactory is used to pass in a custom *http.Request generation func.
	// May be nil.
	//
	// If nil, DefaultRequestFactory is used, which just calls http.NewRequest.
	//
	// You can use DefaultRequestFactory, or provide custom implementation.
	// Useful for Google App Engine testing for example.
	RequestFactory RequestFactory

	// Client is used to send http.Request and receive http.Response.
	// May be nil.
	//
	// If nil, set to a default client with a non-nil Jar:
	//  &http.Client{
	//      Jar: httpexpect.NewCookieJar(),
	//  }
	//
	// You can use http.DefaultClient or your own http.Client, or provide
	// custom implementation.
	Client Client

	// WebsocketDialer is used to establish websocket.Conn and receive http.Response
	// of handshake result.
	// May be nil.
	//
	// If nil, set to a default dialer:
	//  &websocket.Dialer{}
	//
	// You can use websocket.DefaultDialer or websocket.Dialer, or provide
	// custom implementation.
	WebsocketDialer WebsocketDialer

	// Context is passed to all requests. It is typically used for request cancellation,
	// either explicit or after a time-out.
	// May be nil.
	//
	// You can use the Request.WithContext for per-request context and Request.WithTimeout
	// for per-request timeout.
	Context context.Context

	// Reporter is used to report formatted failure messages.
	// Should NOT be nil, unless custom AssertionHandler is used.
	//
	// Config.Reporter is used by DefaultAssertionHandler, which is automatically
	// constructed when AssertionHandler is nil.
	//
	// You can use:
	//  - AssertReporter / RequireReporter
	//    (non-fatal / fatal failures using testify package)
	//  - testing.T / FatalReporter
	//    (non-fatal / fatal failures using standard testing package)
	//  - PanicReporter
	//    (failures that panic to be used in multithreaded tests)
	//  - custom implementation
	Reporter Reporter

	// Formatter is used to format success and failure messages.
	// May be nil.
	//
	// If nil, DefaultFormatter is used.
	//
	// Config.Formatter is used by DefaultAssertionHandler, which is automatically
	// constructed when AssertionHandler is nil.
	//
	// Usually you don't need custom formatter. Implementing one is a
	// relatively big task.
	Formatter Formatter

	// AssertionHandler handles successful and failed assertions.
	// May be nil.
	//
	// Every time an assertion is made, AssertionHandler is invoked with detailed
	// info about the assertion. On failure, AssertionHandler is responsible to
	// format error and report it to the test suite.
	//
	// If AssertionHandler is nil, DefaultAssertionHandler is constructed, with
	// Formatter set to Config.Formatter, Reporter set to Config.Reporter, and
	// Logger set to nil. DefaultAssertionHandler will just delegate formatting
	// and reporting to Formatter and Reporter.
	//
	// If you're happy with DefaultAssertionHandler, but want to enable logging
	// of successful assertions and non-fatal failures, you can manually construct
	// DefaultAssertionHandler and set its Logger field to a non-nil value.
	//
	// Usually you don't need custom AssertionHandler and it's enough just to
	// set Reporter. Use AssertionHandler for more precise control of reports.
	AssertionHandler AssertionHandler

	// Printers are used to print requests and responses.
	// May be nil.
	//
	// If printer implements WebsocketPrinter interface, it will be also used
	// to print Websocket messages.
	//
	// You can use CompactPrinter, DebugPrinter, CurlPrinter, or provide
	// custom implementation.
	//
	// You can also use builtin printers with alternative Logger if you're happy
	// with their format, but want to send logs somewhere else than *testing.T.
	Printers []Printer

	// Environment provides a container for arbitrary data shared between tests.
	// May be nil.
	//
	// Environment is not used by httpexpect itself, but can be used by tests to
	// store and load arbitrary values. Tests can access Environment via
	// Expect.Env(). It is also accessible in AssertionHandler via AssertionContext.
	//
	// If Environment is nil, a new empty environment is automatically created
	// when Expect instance is constructed.
	Environment *Environment
}

Config contains various settings.

type ContentOpts

type ContentOpts struct {
	// The media type Content-Type part, e.g. "application/json"
	MediaType string
	// The character set Content-Type part, e.g. "utf-8"
	Charset string
}

ContentOpts define parameters for matching the response content parameters.

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

Cookie provides methods to inspect attached http.Cookie value.

func NewCookie

func NewCookie(reporter Reporter, value *http.Cookie) *Cookie

NewCookie returns a new Cookie instance.

If reporter is nil, the function panics. If value is nil, failure is reported.

Example:

cookie := NewCookie(t, &http.Cookie{...})

cookie.Domain().IsEqual("example.com")
cookie.Path().IsEqual("/")
cookie.Expires().InRange(time.Now(), time.Now().Add(time.Hour * 24))

func NewCookieC added in v2.9.0

func NewCookieC(config Config, value *http.Cookie) *Cookie

NewCookieC returns a new Cookie instance with config.

Requirements for config are same as for WithConfig function. If value is nil, failure is reported.

See NewCookie for usage example.

func (*Cookie) Alias added in v2.10.0

func (c *Cookie) Alias(name string) *Cookie

Alias is similar to Value.Alias.

func (*Cookie) Domain

func (c *Cookie) Domain() *String

Domain returns a new String instance with cookie domain.

Example:

cookie := NewCookie(t, &http.Cookie{...})
cookie.Domain().IsEqual("example.com")

func (*Cookie) Expires

func (c *Cookie) Expires() *DateTime

Expires returns a new DateTime instance with cookie expiration date.

Example:

cookie := NewCookie(t, &http.Cookie{...})
cookie.Expires().InRange(time.Now(), time.Now().Add(time.Hour * 24))

func (*Cookie) HasMaxAge added in v2.10.0

func (c *Cookie) HasMaxAge() *Cookie

HasMaxAge succeeds if cookie has Max-Age field.

In particular, if Max-Age is present and is zero (which means delete cookie now), method succeeds.

Example:

cookie := NewCookie(t, &http.Cookie{...})
cookie.HasMaxAge()

func (*Cookie) HaveMaxAge deprecated added in v2.6.0

func (c *Cookie) HaveMaxAge() *Cookie

Deprecated: use HasMaxAge instead.

func (*Cookie) MaxAge

func (c *Cookie) MaxAge() *Duration

MaxAge returns a new Duration instance with cookie Max-Age field.

If Max-Age is not present, method fails.

If Max-Age is present and is zero (which means delete cookie now), methods succeeds and the returned Duration is equal to zero.

Example:

cookie := NewCookie(t, &http.Cookie{...})
cookie.HasMaxAge()
cookie.MaxAge().InRange(time.Minute, time.Minute*10)

func (*Cookie) Name

func (c *Cookie) Name() *String

Name returns a new String instance with cookie name.

Example:

cookie := NewCookie(t, &http.Cookie{...})
cookie.Name().IsEqual("session")

func (*Cookie) NotHasMaxAge added in v2.10.0

func (c *Cookie) NotHasMaxAge() *Cookie

NotHasMaxAge succeeds if cookie does not have Max-Age field.

In particular, if Max-Age is present and is zero (which means delete cookie now), method fails.

Example:

cookie := NewCookie(t, &http.Cookie{...})
cookie.NotHasMaxAge()

func (*Cookie) NotHaveMaxAge deprecated added in v2.6.0

func (c *Cookie) NotHaveMaxAge() *Cookie

Deprecated: use NotHasMaxAge instead.

func (*Cookie) Path

func (c *Cookie) Path() *String

Path returns a new String instance with cookie path.

Example:

cookie := NewCookie(t, &http.Cookie{...})
cookie.Path().IsEqual("/foo")

func (*Cookie) Raw

func (c *Cookie) Raw() *http.Cookie

Raw returns underlying http.Cookie value attached to Cookie. This is the value originally passed to NewCookie.

Example:

cookie := NewCookie(t, c)
assert.Equal(t, c, cookie.Raw())

func (*Cookie) Value

func (c *Cookie) Value() *String

Value returns a new String instance with cookie value.

Example:

cookie := NewCookie(t, &http.Cookie{...})
cookie.Value().IsEqual("gH6z7Y")

type CurlPrinter

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

CurlPrinter implements Printer. Uses http2curl to dump requests as curl commands that can be inserted into terminal.

func NewCurlPrinter

func NewCurlPrinter(logger Logger) CurlPrinter

NewCurlPrinter returns a new CurlPrinter given a logger.

func (CurlPrinter) Request

func (p CurlPrinter) Request(req *http.Request)

Request implements Printer.Request.

func (CurlPrinter) Response

func (CurlPrinter) Response(*http.Response, time.Duration)

Response implements Printer.Response.

type DateTime

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

DateTime provides methods to inspect attached time.Time value.

func NewDateTime

func NewDateTime(reporter Reporter, value time.Time) *DateTime

NewDateTime returns a new DateTime instance.

If reporter is nil, the function panics.

Example:

dt := NewDateTime(t, time.Now())
dt.Le(time.Now())

time.Sleep(time.Second)
dt.Lt(time.Now())

func NewDateTimeC added in v2.9.0

func NewDateTimeC(config Config, value time.Time) *DateTime

NewDateTimeC returns a new DateTime instance with config.

Requirements for config are same as for WithConfig function.

See NewDateTime for usage example.

func (*DateTime) Alias added in v2.10.0

func (dt *DateTime) Alias(name string) *DateTime

Alias is similar to Value.Alias.

func (*DateTime) AsLocal added in v2.9.0

func (dt *DateTime) AsLocal() *DateTime

AsLocal returns a new DateTime instance in Local timeZone.

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.AsLocal().Zone().IsEqual("IST")

func (*DateTime) AsUTC added in v2.9.0

func (dt *DateTime) AsUTC() *DateTime

AsUTC returns a new DateTime instance in UTC timeZone.

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.AsUTC().Zone().IsEqual("UTC")

func (*DateTime) Day added in v2.10.0

func (dt *DateTime) Day() *Number

Day returns the day of the month specified datetime, in the range [1,31].

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.Day().IsEqual(30)

func (*DateTime) Equal deprecated

func (dt *DateTime) Equal(value time.Time) *DateTime

Deprecated: use IsEqual instead.

func (*DateTime) Ge

func (dt *DateTime) Ge(value time.Time) *DateTime

Ge succeeds if DateTime is greater than or equal to given value.

Example:

dt := NewDateTime(t, time.Unix(0, 2))
dt.Ge(time.Unix(0, 1))

func (*DateTime) GetDay deprecated added in v2.9.0

func (dt *DateTime) GetDay() *Number

Deprecated: use Day instead.

func (*DateTime) GetHour deprecated added in v2.9.0

func (dt *DateTime) GetHour() *Number

Deprecated: use Hour instead.

func (*DateTime) GetMinute deprecated added in v2.9.0

func (dt *DateTime) GetMinute() *Number

Deprecated: use Minute instead.

func (*DateTime) GetMonth deprecated added in v2.9.0

func (dt *DateTime) GetMonth() *Number

Deprecated: use Month instead.

func (*DateTime) GetNanosecond deprecated added in v2.9.0

func (dt *DateTime) GetNanosecond() *Number

Deprecated: use Nanosecond instead.

func (*DateTime) GetSecond deprecated added in v2.9.0

func (dt *DateTime) GetSecond() *Number

Deprecated: use Second instead.

func (*DateTime) GetWeekDay deprecated added in v2.9.0

func (dt *DateTime) GetWeekDay() *Number

Deprecated: use WeekDay instead.

func (*DateTime) GetYear deprecated added in v2.9.0

func (dt *DateTime) GetYear() *Number

Deprecated: use Year instead.

func (*DateTime) GetYearDay deprecated added in v2.9.0

func (dt *DateTime) GetYearDay() *Number

Deprecated: use YearDay instead.

func (*DateTime) GetZone deprecated added in v2.9.0

func (dt *DateTime) GetZone() *String

Deprecated: use Zone instead.

func (*DateTime) Gt

func (dt *DateTime) Gt(value time.Time) *DateTime

Gt succeeds if DateTime is greater than given value.

Example:

dt := NewDateTime(t, time.Unix(0, 2))
dt.Gt(time.Unix(0, 1))

func (*DateTime) Hour added in v2.10.0

func (dt *DateTime) Hour() *Number

Hour returns the hour within the day specified by datetime, in the range [0, 23].

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.Hour().IsEqual(15)

func (*DateTime) InList added in v2.11.0

func (dt *DateTime) InList(values ...time.Time) *DateTime

InList succeeds if DateTime is equal to one of the values from given list of time.Time.

Example:

dt := NewDateTime(t, time.Unix(0, 2))
dt.InRange(time.Unix(0, 1), time.Unix(0, 2))

func (*DateTime) InRange

func (dt *DateTime) InRange(min, max time.Time) *DateTime

InRange succeeds if DateTime is within given range [min; max].

Example:

dt := NewDateTime(t, time.Unix(0, 2))
dt.InRange(time.Unix(0, 1), time.Unix(0, 3))
dt.InRange(time.Unix(0, 2), time.Unix(0, 2))

func (*DateTime) IsEqual added in v2.11.0

func (dt *DateTime) IsEqual(value time.Time) *DateTime

IsEqual succeeds if DateTime is equal to given value.

Example:

dt := NewDateTime(t, time.Unix(0, 1))
dt.IsEqual(time.Unix(0, 1))

func (*DateTime) Le

func (dt *DateTime) Le(value time.Time) *DateTime

Le succeeds if DateTime is lesser than or equal to given value.

Example:

dt := NewDateTime(t, time.Unix(0, 1))
dt.Le(time.Unix(0, 2))

func (*DateTime) Lt

func (dt *DateTime) Lt(value time.Time) *DateTime

Lt succeeds if DateTime is lesser than given value.

Example:

dt := NewDateTime(t, time.Unix(0, 1))
dt.Lt(time.Unix(0, 2))

func (*DateTime) Minute added in v2.10.0

func (dt *DateTime) Minute() *Number

Minute returns the minute offset within the hour specified by datetime, in the range [0, 59].

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.Minute().IsEqual(4)

func (*DateTime) Month added in v2.10.0

func (dt *DateTime) Month() *Number

Month returns the month of the year specified by datetime, in the range [1,12].

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.Month().IsEqual(12)

func (*DateTime) Nanosecond added in v2.10.0

func (dt *DateTime) Nanosecond() *Number

Nanosecond returns the nanosecond offset within the second specified by datetime, in the range [0, 999999999].

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.Nanosecond().IsEqual(0)

func (*DateTime) NotEqual

func (dt *DateTime) NotEqual(value time.Time) *DateTime

NotEqual succeeds if DateTime is not equal to given value.

Example:

dt := NewDateTime(t, time.Unix(0, 1))
dt.NotEqual(time.Unix(0, 2))

func (*DateTime) NotInList added in v2.11.0

func (dt *DateTime) NotInList(values ...time.Time) *DateTime

NotInList succeeds if DateTime is not equal to any of the values from given list of time.Time.

Example:

dt := NewDateTime(t, time.Unix(0, 2))
dt.InRange(time.Unix(0, 1), time.Unix(0, 3))

func (*DateTime) NotInRange added in v2.6.0

func (dt *DateTime) NotInRange(min, max time.Time) *DateTime

NotInRange succeeds if DateTime is not within given range [min; max].

Example:

dt := NewDateTime(t, time.Unix(0, 10))
dt.NotInRange(time.Unix(0, 1), time.Unix(0, 9))
dt.NotInRange(time.Unix(0, 11), time.Unix(0, 20))

func (*DateTime) Raw

func (dt *DateTime) Raw() time.Time

Raw returns underlying time.Time value attached to DateTime. This is the value originally passed to NewDateTime.

Example:

dt := NewDateTime(t, timestamp)
assert.Equal(t, timestamp, dt.Raw())

func (*DateTime) Second added in v2.10.0

func (dt *DateTime) Second() *Number

Second returns the second offset within the minute specified by datetime, in the range [0, 59].

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.Second().IsEqual(5)

func (*DateTime) WeekDay added in v2.10.0

func (dt *DateTime) WeekDay() *Number

Weekday returns the day of the week specified by datetime, in the range [0, 6], 0 corresponds to Sunday

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.WeekDay().IsEqual(time.Friday)

func (*DateTime) Year added in v2.10.0

func (dt *DateTime) Year() *Number

Year returns the year in which datetime occurs, in the range [0, 9999]

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.Year().IsEqual(2022)

func (*DateTime) YearDay added in v2.10.0

func (dt *DateTime) YearDay() *Number

YearDay returns the day of the year specified by datetime, in the range [1,365] for non-leap years, and [1,366] in leap years.

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.YearDay().IsEqual(364)

func (*DateTime) Zone added in v2.10.0

func (dt *DateTime) Zone() *String

Zone returns a new String instance with datetime zone.

Example:

tm, _ := time.Parse(time.UnixDate, "Fri Dec 30 15:04:05 IST 2022")
dt := NewDateTime(t, tm)
dt.Zone().IsEqual("IST")

type DebugPrinter

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

DebugPrinter implements Printer and WebsocketPrinter. Uses net/http/httputil to dump both requests and responses. Also prints all websocket messages.

func NewDebugPrinter

func NewDebugPrinter(logger Logger, body bool) DebugPrinter

NewDebugPrinter returns a new DebugPrinter given a logger and body flag. If body is true, request and response body is also printed.

func (DebugPrinter) Request

func (p DebugPrinter) Request(req *http.Request)

Request implements Printer.Request.

func (DebugPrinter) Response

func (p DebugPrinter) Response(resp *http.Response, duration time.Duration)

Response implements Printer.Response.

func (DebugPrinter) WebsocketRead

func (p DebugPrinter) WebsocketRead(typ int, content []byte, closeCode int)

WebsocketRead implements WebsocketPrinter.WebsocketRead.

func (DebugPrinter) WebsocketWrite

func (p DebugPrinter) WebsocketWrite(typ int, content []byte, closeCode int)

WebsocketWrite implements WebsocketPrinter.WebsocketWrite.

type DefaultAssertionHandler added in v2.5.0

type DefaultAssertionHandler struct {
	Formatter Formatter
	Reporter  Reporter
	Logger    Logger
}

DefaultAssertionHandler is default implementation for AssertionHandler.

  • Formatter is used to format success and failure messages
  • Reporter is used to report formatted fatal failure messages
  • Logger is used to print formatted success and non-fatal failure messages

Formatter and Reporter are required. Logger is optional. By default httpexpect creates DefaultAssertionHandler without Logger.

func (*DefaultAssertionHandler) Failure added in v2.5.0

func (h *DefaultAssertionHandler) Failure(
	ctx *AssertionContext, failure *AssertionFailure,
)

Failure implements AssertionHandler.Failure.

func (*DefaultAssertionHandler) Success added in v2.5.0

func (h *DefaultAssertionHandler) Success(ctx *AssertionContext)

Success implements AssertionHandler.Success.

type DefaultFormatter added in v2.5.0

type DefaultFormatter struct {
	// Exclude test name and request name from failure report.
	DisableNames bool

	// Exclude assertion path from failure report.
	DisablePaths bool

	// Exclude aliased assertion path from failure report.
	DisableAliases bool

	// Exclude diff from failure report.
	DisableDiffs bool

	// Exclude HTTP request from failure report.
	DisableRequests bool

	// Exclude HTTP response from failure report.
	DisableResponses bool

	// Thousand separator.
	// Default is DigitSeparatorUnderscore.
	DigitSeparator DigitSeparator

	// Float printing format.
	// Default is FloatFormatAuto.
	FloatFormat FloatFormat

	// Defines whether to print stacktrace on failure and in what format.
	// Default is StacktraceModeDisabled.
	StacktraceMode StacktraceMode

	// Colorization mode.
	// Default is ColorModeAuto.
	ColorMode ColorMode

	// Wrap text to keep lines below given width.
	// Use zero for default width, and negative value to disable wrapping.
	LineWidth int

	// If not empty, used to format success messages.
	// If empty, default template is used.
	SuccessTemplate string

	// If not empty, used to format failure messages.
	// If empty, default template is used.
	FailureTemplate string

	// When SuccessTemplate or FailureTemplate is set, this field
	// defines the function map passed to template engine.
	// May be nil.
	TemplateFuncs template.FuncMap
}

DefaultFormatter is the default Formatter implementation.

DefaultFormatter gathers values from AssertionContext and AssertionFailure, converts them to strings, and creates FormatData struct. Then it passes FormatData to the template engine (text/template) to format message.

You can control what is included and what is excluded from messages via several public fields.

If desired, you can provide custom templates and function map. This may be easier than creating your own formatter from scratch.

func (*DefaultFormatter) FormatFailure added in v2.5.0

func (f *DefaultFormatter) FormatFailure(
	ctx *AssertionContext, failure *AssertionFailure,
) string

FormatFailure implements Formatter.FormatFailure.

func (*DefaultFormatter) FormatSuccess added in v2.5.0

func (f *DefaultFormatter) FormatSuccess(ctx *AssertionContext) string

FormatSuccess implements Formatter.FormatSuccess.

type DefaultRequestFactory

type DefaultRequestFactory struct{}

DefaultRequestFactory is the default RequestFactory implementation which just calls http.NewRequest.

func (DefaultRequestFactory) NewRequest

func (DefaultRequestFactory) NewRequest(
	method, url string, body io.Reader,
) (*http.Request, error)

NewRequest implements RequestFactory.NewRequest.

type DigitSeparator added in v2.15.0

type DigitSeparator int

DigitSeparator defines the separator used to format integers and floats.

const (
	// Separate using underscore
	DigitSeparatorUnderscore DigitSeparator = iota

	// Separate using comma
	DigitSeparatorComma

	// Separate using apostrophe
	DigitSeparatorApostrophe

	// Do not separate
	DigitSeparatorNone
)

type Duration

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

Duration provides methods to inspect attached time.Duration value.

func NewDuration

func NewDuration(reporter Reporter, value time.Duration) *Duration

NewDuration returns a new Duration instance.

If reporter is nil, the function panics.

Example:

d := NewDuration(t, time.Second)
d.Le(time.Minute)

func NewDurationC added in v2.9.0

func NewDurationC(config Config, value time.Duration) *Duration

NewDurationC returns a new Duration instance with config.

Requirements for config are same as for WithConfig function.

Example:

d := NewDurationC(config, time.Second)
d.Le(time.Minute)

func (*Duration) Alias added in v2.10.0

func (d *Duration) Alias(name string) *Duration

Alias is similar to Value.Alias.

func (*Duration) Equal deprecated

func (d *Duration) Equal(value time.Duration) *Duration

Deprecated: use IsEqual instead.

func (*Duration) Ge

func (d *Duration) Ge(value time.Duration) *Duration

Ge succeeds if Duration is greater than or equal to given value.

Example:

d := NewDuration(t, time.Minute)
d.Ge(time.Second)

func (*Duration) Gt

func (d *Duration) Gt(value time.Duration) *Duration

Gt succeeds if Duration is greater than given value.

Example:

d := NewDuration(t, time.Minute)
d.Gt(time.Second)

func (*Duration) InList added in v2.11.0

func (d *Duration) InList(values ...time.Duration) *Duration

InList succeeds if Duration is equal to one of the values from given list of time.Duration.

Example:

d := NewDuration(t, time.Minute)
d.InList(time.Minute, time.Hour)

func (*Duration) InRange

func (d *Duration) InRange(min, max time.Duration) *Duration

InRange succeeds if Duration is within given range [min; max].

Example:

d := NewDuration(t, time.Minute)
d.InRange(time.Second, time.Hour)
d.InRange(time.Minute, time.Minute)

func (*Duration) IsEqual added in v2.11.0

func (d *Duration) IsEqual(value time.Duration) *Duration

IsEqual succeeds if Duration is equal to given value.

Example:

d := NewDuration(t, time.Second)
d.IsEqual(time.Second)

func (*Duration) IsSet deprecated

func (d *Duration) IsSet() *Duration

Deprecated: support for unset durations will be removed. The only method that can create unset duration is Cookie.MaxAge. Instead of Cookie.MaxAge().IsSet(), please use Cookie.HasMaxAge().

func (*Duration) Le

func (d *Duration) Le(value time.Duration) *Duration

Le succeeds if Duration is lesser than or equal to given value.

Example:

d := NewDuration(t, time.Second)
d.Le(time.Minute)

func (*Duration) Lt

func (d *Duration) Lt(value time.Duration) *Duration

Lt succeeds if Duration is lesser than given value.

Example:

d := NewDuration(t, time.Second)
d.Lt(time.Minute)

func (*Duration) NotEqual

func (d *Duration) NotEqual(value time.Duration) *Duration

NotEqual succeeds if Duration is not equal to given value.

Example:

d := NewDuration(t, time.Second)
d.NotEqual(time.Minute)

func (*Duration) NotInList added in v2.11.0

func (d *Duration) NotInList(values ...time.Duration) *Duration

NotInList succeeds if Duration is not equal to any of the values from given list of time.Duration.

Example:

d := NewDuration(t, time.Minute)
d.NotInList(time.Second, time.Hour)

func (*Duration) NotInRange added in v2.6.0

func (d *Duration) NotInRange(min, max time.Duration) *Duration

NotInRange succeeds if Duration is not within given range [min; max].

Example:

d := NewDuration(t, time.Minute*10)
d.NotInRange(time.Minute, time.Minute-time.Nanosecond)
d.NotInRange(time.Minute+time.Nanosecond, time.Minute*10)

func (*Duration) NotSet deprecated

func (d *Duration) NotSet() *Duration

Deprecated: support for unset durations will be removed. The only method that can create unset duration is Cookie.MaxAge. Instead of Cookie.MaxAge().NotSet(), please use Cookie.NotHasMaxAge().

func (*Duration) Raw

func (d *Duration) Raw() time.Duration

Raw returns underlying time.Duration value attached to Duration. This is the value originally passed to NewDuration.

Example:

d := NewDuration(t, duration)
assert.Equal(t, timestamp, d.Raw())

type Environment added in v2.6.0

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

Environment provides a container for arbitrary data shared between tests.

Example:

env := NewEnvironment(t)
env.Put("key", "value")
value := env.GetString("key")

func NewEnvironment added in v2.6.0

func NewEnvironment(reporter Reporter) *Environment

NewEnvironment returns a new Environment.

If reporter is nil, the function panics.

Example:

env := NewEnvironment(t)

func NewEnvironmentC added in v2.9.0

func NewEnvironmentC(config Config) *Environment

NewEnvironmentC returns a new Environment with config.

Requirements for config are same as for WithConfig function.

Example:

env := NewEnvironmentC(config)

func (*Environment) Clear added in v2.13.0

func (e *Environment) Clear()

Clear will delete all key value pairs from the environment

Example:

env := NewEnvironment(t)
env.Put("key1", 123)
env.Put("key2", 456)
env.Clear()

func (*Environment) Delete added in v2.11.0

func (e *Environment) Delete(key string)

Delete removes the value with key from the environment.

Example:

env := NewEnvironment(t)
env.Put("key1", "str")
env.Delete("key1")

func (*Environment) Get added in v2.6.0

func (e *Environment) Get(key string) interface{}

Get returns value stored in the environment.

If value does not exist, reports failure and returns nil.

Example:

value1 := env.Get("key1").(string)
value2 := env.Get("key1").(int)

func (*Environment) GetBool added in v2.6.0

func (e *Environment) GetBool(key string) bool

GetBool returns value stored in the environment, casted to bool.

If value does not exist, or is not bool, reports failure and returns false.

Example:

value := env.GetBool("key")

func (*Environment) GetBytes added in v2.6.0

func (e *Environment) GetBytes(key string) []byte

GetBytes returns value stored in the environment, casted to []byte.

If value does not exist, or is not []byte slice, reports failure and returns nil.

Example:

value := env.GetBytes("key")

func (*Environment) GetDuration added in v2.6.0

func (e *Environment) GetDuration(key string) time.Duration

GetDuration returns value stored in the environment, casted to time.Duration.

If value does not exist, is not time.Duration, reports failure and returns zero duration.

Example:

value := env.GetDuration("key")

func (*Environment) GetFloat added in v2.6.0

func (e *Environment) GetFloat(key string) float64

GetFloat returns value stored in the environment, casted to float64.

If value does not exist, or is not floating point value, reports failure and returns zero value.

Example:

value := env.GetFloat("key")

func (*Environment) GetInt added in v2.6.0

func (e *Environment) GetInt(key string) int

GetInt returns value stored in the environment, casted to int64.

If value does not exist, or is not signed or unsigned integer that can be represented as int without overflow, reports failure and returns zero.

Example:

value := env.GetInt("key")

func (*Environment) GetString added in v2.6.0

func (e *Environment) GetString(key string) string

GetString returns value stored in the environment, casted to string.

If value does not exist, or is not string, reports failure and returns empty string.

Example:

value := env.GetString("key")

func (*Environment) GetTime added in v2.6.0

func (e *Environment) GetTime(key string) time.Time

GetTime returns value stored in the environment, casted to time.Time.

If value does not exist, is not time.Time, reports failure and returns zero time.

Example:

value := env.GetTime("key")

func (*Environment) Glob added in v2.13.0

func (e *Environment) Glob(pattern string) []string

Glob accepts a glob pattern and returns a sorted slice of keys that match the pattern.

If the pattern is invalid, reports failure and returns an empty slice.

Example:

env := NewEnvironment(t)

for _, key := range env.Glob("foo.*") {
	...
}

func (*Environment) Has added in v2.6.0

func (e *Environment) Has(key string) bool

Has returns true if value exists in the environment.

Example:

if env.Has("key1") {
   ...
}

func (*Environment) List added in v2.13.0

func (e *Environment) List() []string

List returns a sorted slice of keys.

Example:

env := NewEnvironment(t)

for _, key := range env.List() {
	...
}

func (*Environment) Put added in v2.6.0

func (e *Environment) Put(key string, value interface{})

Put saves the value with key in the environment.

Example:

env := NewEnvironment(t)
env.Put("key1", "str")
env.Put("key2", 123)

type Expect

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

Expect is a toplevel object that contains user Config and allows to construct Request objects.

func Default added in v2.5.0

func Default(t TestingTB, baseURL string) *Expect

Default returns a new Expect instance with default config.

t is usually *testing.T, but can be any matching implementation.

baseURL specifies URL to be prepended to all requests. May be empty. If non-empty, trailing slash is allowed (but not required) and is appended automatically.

Default is a shorthand for WithConfig. It uses:

  • baseURL for Config.BaseURL
  • t.Name() for Config.TestName
  • NewAssertReporter(t) for Config.Reporter
  • NewCompactPrinter(t) for Config.Printers

Example:

func TestSomething(t *testing.T) {
	e := httpexpect.Default(t, "http://example.com/")

	e.GET("/path").
		Expect().
		Status(http.StatusOK)
}

func New deprecated

func New(t LoggerReporter, baseURL string) *Expect

Deprecated: use Default instead.

func WithConfig

func WithConfig(config Config) *Expect

WithConfig returns a new Expect instance with custom config.

Either Reporter or AssertionHandler should not be nil, otherwise the function panics.

Example:

func TestSomething(t *testing.T) {
	e := httpexpect.WithConfig(httpexpect.Config{
		TestName: t.Name(),
		BaseURL:  "http://example.com/",
		Client:   &http.Client{
			Transport: httpexpect.NewBinder(myHandler()),
			Jar:       httpexpect.NewCookieJar(),
		},
		Reporter: httpexpect.NewAssertReporter(t),
		Printers: []httpexpect.Printer{
			httpexpect.NewCurlPrinter(t),
			httpexpect.NewDebugPrinter(t, true)
		},
	})

	e.GET("/path").
		Expect().
		Status(http.StatusOK)
}

func (*Expect) Array deprecated

func (e *Expect) Array(value []interface{}) *Array

Deprecated: use NewArray or NewArrayC instead.

func (*Expect) Boolean deprecated

func (e *Expect) Boolean(value bool) *Boolean

Deprecated: use NewBoolean or NewBooleanC instead.

func (*Expect) Builder

func (e *Expect) Builder(builder func(*Request)) *Expect

Builder returns a copy of Expect instance with given builder attached to it. Returned copy contains all previously attached builders plus a new one. Builders are invoked from Request method, after constructing every new request.

Example:

e := httpexpect.Default(t, "http://example.com")

token := e.POST("/login").WithForm(Login{"ford", "betelgeuse7"}).
	Expect().
	Status(http.StatusOK).JSON().Object().Value("token").String().Raw()

auth := e.Builder(func (req *httpexpect.Request) {
	req.WithHeader("Authorization", "Bearer "+token)
})

auth.GET("/restricted").
   Expect().
   Status(http.StatusOK)

func (*Expect) DELETE

func (e *Expect) DELETE(path string, pathargs ...interface{}) *Request

DELETE is a shorthand for e.Request("DELETE", path, pathargs...).

func (*Expect) Env added in v2.6.0

func (e *Expect) Env() *Environment

Env returns Environment associated with Expect instance. Tests can use it to store arbitrary data.

Example:

e := httpexpect.Default(t, "http://example.com")

e.Env().Put("key", "value")
value := e.Env().GetString("key")

func (*Expect) GET

func (e *Expect) GET(path string, pathargs ...interface{}) *Request

GET is a shorthand for e.Request("GET", path, pathargs...).

func (*Expect) HEAD

func (e *Expect) HEAD(path string, pathargs ...interface{}) *Request

HEAD is a shorthand for e.Request("HEAD", path, pathargs...).

func (*Expect) Matcher

func (e *Expect) Matcher(matcher func(*Response)) *Expect

Matcher returns a copy of Expect instance with given matcher attached to it. Returned copy contains all previously attached matchers plus a new one. Matchers are invoked from Request.Expect method, after retrieving a new response.

Example:

 e := httpexpect.Default(t, "http://example.com")

 m := e.Matcher(func (resp *httpexpect.Response) {
	 resp.Header("API-Version").NotEmpty()
 })

 m.GET("/some-path").
		Expect().
		Status(http.StatusOK)

 m.GET("/bad-path").
		Expect().
		Status(http.StatusNotFound)

func (*Expect) Number deprecated

func (e *Expect) Number(value float64) *Number

Deprecated: use NewNumber or NewNumberC instead.

func (*Expect) OPTIONS

func (e *Expect) OPTIONS(path string, pathargs ...interface{}) *Request

OPTIONS is a shorthand for e.Request("OPTIONS", path, pathargs...).

func (*Expect) Object deprecated

func (e *Expect) Object(value map[string]interface{}) *Object

Deprecated: use NewObject or NewObjectC instead.

func (*Expect) PATCH

func (e *Expect) PATCH(path string, pathargs ...interface{}) *Request

PATCH is a shorthand for e.Request("PATCH", path, pathargs...).

func (*Expect) POST

func (e *Expect) POST(path string, pathargs ...interface{}) *Request

POST is a shorthand for e.Request("POST", path, pathargs...).

func (*Expect) PUT

func (e *Expect) PUT(path string, pathargs ...interface{}) *Request

PUT is a shorthand for e.Request("PUT", path, pathargs...).

func (*Expect) Request

func (e *Expect) Request(method, path string, pathargs ...interface{}) *Request

Request returns a new Request instance. Arguments are similar to NewRequest. After creating request, all builders attached to Expect instance are invoked. See Builder.

func (*Expect) String deprecated

func (e *Expect) String(value string) *String

Deprecated: use NewString or NewStringC instead.

func (*Expect) Value deprecated

func (e *Expect) Value(value interface{}) *Value

Deprecated: use NewValue or NewValueC instead.

type FastBinder

type FastBinder struct {
	// FastHTTP handler invoked for every request.
	Handler fasthttp.RequestHandler
	// TLS connection state used for https:// requests.
	TLS *tls.ConnectionState
	// If non-nil, fasthttp.RequestCtx.Logger() will print messages to it.
	Logger Logger
}

FastBinder implements networkless http.RoundTripper attached directly to fasthttp.RequestHandler.

FastBinder emulates network communication by invoking given fasthttp.RequestHandler directly. It converts http.Request to fasthttp.Request, invokes handler, and then converts fasthttp.Response to http.Response.

func NewFastBinder

func NewFastBinder(handler fasthttp.RequestHandler) FastBinder

NewFastBinder returns a new FastBinder given a fasthttp.RequestHandler.

Example:

client := &http.Client{
	Transport: NewFastBinder(fasthandler),
}

func (FastBinder) RoundTrip

func (binder FastBinder) RoundTrip(stdreq *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.RoundTrip.

type FatalReporter added in v2.11.0

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

FatalReporter is a struct that implements the Reporter interface and calls t.Fatalf() when a test fails.

func NewFatalReporter added in v2.11.0

func NewFatalReporter(t testing.TB) *FatalReporter

NewFatalReporter returns a new FatalReporter object.

func (*FatalReporter) Errorf added in v2.11.0

func (r *FatalReporter) Errorf(message string, args ...interface{})

Errorf implements Reporter.Errorf.

type FloatFormat added in v2.11.0

type FloatFormat int

FloatFormat defines the format in which all floats are printed.

const (
	// Print floats in scientific notation for large exponents,
	// otherwise print in decimal notation.
	// Precision is the smallest needed to identify the value uniquely.
	// Similar to %g format.
	FloatFormatAuto FloatFormat = iota

	// Always print floats in decimal notation.
	// Precision is the smallest needed to identify the value uniquely.
	// Similar to %f format.
	FloatFormatDecimal

	// Always print floats in scientific notation.
	// Precision is the smallest needed to identify the value uniquely.
	// Similar to %e format.
	FloatFormatScientific
)

type FormatData added in v2.5.0

type FormatData struct {
	TestName    string
	RequestName string

	AssertPath     []string
	AssertType     string
	AssertSeverity string

	Errors []string

	HaveActual bool
	Actual     string

	HaveExpected bool
	IsNegation   bool
	IsComparison bool
	ExpectedKind string
	Expected     []string

	HaveReference bool
	Reference     string

	HaveDelta bool
	Delta     string

	HaveDiff bool
	Diff     string

	HaveRequest bool
	Request     string

	HaveResponse bool
	Response     string

	HaveStacktrace bool
	Stacktrace     []string

	EnableColors bool
	LineWidth    int
}

FormatData defines data passed to template engine when DefaultFormatter formats assertion. You can use these fields in your custom templates.

type Formatter added in v2.5.0

type Formatter interface {
	FormatSuccess(*AssertionContext) string
	FormatFailure(*AssertionContext, *AssertionFailure) string
}

Formatter is used to format assertion messages into strings.

type Logger

type Logger interface {
	// Logf writes message to test log.
	Logf(fmt string, args ...interface{})
}

Logger is used as output backend for Printer. *testing.T implements this interface.

type LoggerFunc added in v2.15.0

type LoggerFunc func(fmt string, args ...interface{})

LoggerFunc is an adapter that allows a function to be used as the Logger

Example:

e := httpexpect.WithConfig(httpexpect.Config{
	Printers: []httpexpect.Printer{
		httpexpect.NewCompactPrinter(
			httpextect.LoggerFunc(
				func(fmt string, args ...interface{}) {
					// logger code here
				})),
	},
})

func (LoggerFunc) Logf added in v2.15.0

func (f LoggerFunc) Logf(fmt string, args ...interface{})

type LoggerReporter deprecated

type LoggerReporter interface {
	Logger
	Reporter
}

Deprecated: use TestingTB instead.

type Match

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

Match provides methods to inspect attached regexp match results.

func NewMatch

func NewMatch(reporter Reporter, submatches []string, names []string) *Match

NewMatch returns a new Match instance.

If reporter is nil, the function panics. Both submatches and names may be nil.

Example:

s := "http://example.com/users/john"
r := regexp.MustCompile(`http://(?P<host>.+)/users/(?P<user>.+)`)

m := NewMatch(t, r.FindStringSubmatch(s), r.SubexpNames())

m.NotEmpty()
m.Length().IsEqual(3)

m.Index(0).IsEqual("http://example.com/users/john")
m.Index(1).IsEqual("example.com")
m.Index(2).IsEqual("john")

m.Name("host").IsEqual("example.com")
m.Name("user").IsEqual("john")

func NewMatchC added in v2.9.0

func NewMatchC(config Config, submatches []string, names []string) *Match

NewMatchC returns a new Match instance with config.

Requirements for config are same as for WithConfig function. Both submatches and names may be nil.

See NewMatch for usage example.

func (*Match) Alias added in v2.10.0

func (m *Match) Alias(name string) *Match

Alias is similar to Value.Alias.

func (*Match) Empty deprecated

func (m *Match) Empty() *Match

Deprecated: use IsEmpty instead.

func (*Match) Index

func (m *Match) Index(index int) *String

Index returns a new String instance with submatch for given index.

Note that submatch with index 0 contains the whole match. If index is out of bounds, Index reports failure and returns empty (but non-nil) instance.

Example:

s := "http://example.com/users/john"

r := regexp.MustCompile(`http://(.+)/users/(.+)`)
m := NewMatch(t, r.FindStringSubmatch(s), nil)

m.Index(0).IsEqual("http://example.com/users/john")
m.Index(1).IsEqual("example.com")
m.Index(2).IsEqual("john")

func (*Match) IsEmpty added in v2.11.0

func (m *Match) IsEmpty() *Match

IsEmpty succeeds if submatches array is empty.

Example:

m := NewMatch(t, submatches, names)
m.IsEmpty()

func (*Match) Length

func (m *Match) Length() *Number

Length returns a new Number instance with number of submatches.

Example:

m := NewMatch(t, submatches, names)
m.Length().IsEqual(len(submatches))

func (*Match) Name

func (m *Match) Name(name string) *String

Name returns a new String instance with submatch for given name.

If there is no submatch with given name, Name reports failure and returns empty (but non-nil) instance.

Example:

s := "http://example.com/users/john"

r := regexp.MustCompile(`http://(?P<host>.+)/users/(?P<user>.+)`)
m := NewMatch(t, r.FindStringSubmatch(s), r.SubexpNames())

m.Name("host").IsEqual("example.com")
m.Name("user").IsEqual("john")

func (*Match) NotEmpty

func (m *Match) NotEmpty() *Match

NotEmpty succeeds if submatches array is non-empty.

Example:

m := NewMatch(t, submatches, names)
m.NotEmpty()

func (*Match) NotValues

func (m *Match) NotValues(values ...string) *Match

NotValues succeeds if submatches array, starting from index 1, is not equal to given array.

Note that submatch with index 0 contains the whole match and is not included into this check.

Example:

s := "http://example.com/users/john"
r := regexp.MustCompile(`http://(.+)/users/(.+)`)
m := NewMatch(t, r.FindStringSubmatch(s), nil)
m.NotValues("example.com", "bob")

func (*Match) Raw

func (m *Match) Raw() []string

Raw returns underlying submatches attached to Match. This is the value originally passed to NewMatch.

Example:

m := NewMatch(t, submatches, names)
assert.Equal(t, submatches, m.Raw())

func (*Match) Values

func (m *Match) Values(values ...string) *Match

Values succeeds if submatches array, starting from index 1, is equal to given array.

Note that submatch with index 0 contains the whole match and is not included into this check.

Example:

s := "http://example.com/users/john"
r := regexp.MustCompile(`http://(.+)/users/(.+)`)
m := NewMatch(t, r.FindStringSubmatch(s), nil)
m.Values("example.com", "john")

type Number

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

Number provides methods to inspect attached float64 value (Go representation of JSON number).

func NewNumber

func NewNumber(reporter Reporter, value float64) *Number

NewNumber returns a new Number instance.

If reporter is nil, the function panics.

Example:

number := NewNumber(t, 123.4)

func NewNumberC added in v2.9.0

func NewNumberC(config Config, value float64) *Number

NewNumberC returns a new Number instance with config.

Requirements for config are same as for WithConfig function.

Example:

number := NewNumberC(config, 123.4)

func (*Number) Alias added in v2.10.0

func (n *Number) Alias(name string) *Number

Alias is similar to Value.Alias.

func (*Number) Decode added in v2.10.0

func (n *Number) Decode(target interface{}) *Number

Decode unmarshals the underlying value attached to the Number to a target variable. target should be one of these:

  • pointer to an empty interface
  • pointer to any integer or floating type

Example:

value := NewNumber(t, 123)

var target interface{}
valude.decode(&target)

assert.Equal(t, 123, target)

func (*Number) Equal deprecated

func (n *Number) Equal(value interface{}) *Number

Deprecated: use IsEqual instead.

func (*Number) EqualDelta deprecated

func (n *Number) EqualDelta(value, delta float64) *Number

Deprecated: use InDelta instead.

func (*Number) Ge

func (n *Number) Ge(value interface{}) *Number

Ge succeeds if number is greater than or equal to given value.

value should have numeric type convertible to float64. Before comparison, it is converted to float64.

Example:

number := NewNumber(t, 123)
number.Ge(float64(122))
number.Ge(int32(122))

func (*Number) Gt

func (n *Number) Gt(value interface{}) *Number

Gt succeeds if number is greater than given value.

value should have numeric type convertible to float64. Before comparison, it is converted to float64.

Example:

number := NewNumber(t, 123)
number.Gt(float64(122))
number.Gt(int32(122))

func (*Number) InDelta added in v2.9.0

func (n *Number) InDelta(value, delta float64) *Number

InDelta succeeds if two numerals are within delta of each other.

Example:

number := NewNumber(t, 123.0)
number.InDelta(123.2, 0.3)

func (*Number) InList added in v2.11.0

func (n *Number) InList(values ...interface{}) *Number

InList succeeds if the number is equal to one of the values from given list of numbers. Before comparison, each value is converted to canonical form.

Each value should be numeric type convertible to float64. If at least one value has wrong type, failure is reported.

Example:

number := NewNumber(t, 123)
number.InList(float64(123), int32(123))

func (*Number) InRange

func (n *Number) InRange(min, max interface{}) *Number

InRange succeeds if number is within given range [min; max].

min and max should have numeric type convertible to float64. Before comparison, they are converted to float64.

Example:

number := NewNumber(t, 123)
number.InRange(float32(100), int32(200))  // success
number.InRange(100, 200)                  // success
number.InRange(123, 123)                  // success

func (*Number) IsEqual added in v2.11.0

func (n *Number) IsEqual(value interface{}) *Number

IsEqual succeeds if number is equal to given value.

value should have numeric type convertible to float64. Before comparison, it is converted to float64.

Example:

number := NewNumber(t, 123)
number.IsEqual(float64(123))
number.IsEqual(int32(123))

func (*Number) IsFinite added in v2.13.0

func (n *Number) IsFinite() *Number

IsFinite succeeds if number is neither ±Inf nor NaN.

Example:

number := NewNumber(t, 1234.5)
number.IsFinite() // success

number := NewNumber(t, math.NaN())
number.IsFinite() // failure

number := NewNumber(t, math.Inf(+1))
number.IsFinite() // failure

func (*Number) IsInt added in v2.13.0

func (n *Number) IsInt(bits ...int) *Number

IsInt succeeds if number is a signed integer of the specified bit width as an optional argument.

Bits argument defines maximum allowed bitness for the given number. If bits is omitted, boundary check is omitted too.

Example:

number := NewNumber(t, 1000000)
number.IsInt()   // success
number.IsInt(32) // success
number.IsInt(16) // failure

number := NewNumber(t, -1000000)
number.IsInt()   // success
number.IsInt(32) // success
number.IsInt(16) // failure

number := NewNumber(t, 0.5)
number.IsInt()   // failure

func (*Number) IsUint added in v2.13.0

func (n *Number) IsUint(bits ...int) *Number

IsUint succeeds if number is an unsigned integer of the specified bit width as an optional argument.

Bits argument defines maximum allowed bitness for the given number. If bits is omitted, boundary check is omitted too.

Example:

number := NewNumber(t, 1000000)
number.IsUint()   // success
number.IsUint(32) // success
number.IsUint(16) // failure

number := NewNumber(t, -1000000)
number.IsUint()   // failure
number.IsUint(32) // failure
number.IsUint(16) // failure

number := NewNumber(t, 0.5)
number.IsUint()   // failure

func (*Number) Le

func (n *Number) Le(value interface{}) *Number

Le succeeds if number is lesser than or equal to given value.

value should have numeric type convertible to float64. Before comparison, it is converted to float64.

Example:

number := NewNumber(t, 123)
number.Le(float64(124))
number.Le(int32(124))

func (*Number) Lt

func (n *Number) Lt(value interface{}) *Number

Lt succeeds if number is lesser than given value.

value should have numeric type convertible to float64. Before comparison, it is converted to float64.

Example:

number := NewNumber(t, 123)
number.Lt(float64(124))
number.Lt(int32(124))

func (*Number) NotEqual

func (n *Number) NotEqual(value interface{}) *Number

NotEqual succeeds if number is not equal to given value.

value should have numeric type convertible to float64. Before comparison, it is converted to float64.

Example:

number := NewNumber(t, 123)
number.NotEqual(float64(321))
number.NotEqual(int32(321))

func (*Number) NotEqualDelta deprecated

func (n *Number) NotEqualDelta(value, delta float64) *Number

Deprecated: use NotInDelta instead.

func (*Number) NotFinite added in v2.13.0

func (n *Number) NotFinite() *Number

NotFinite succeeds if number is either ±Inf or NaN.

Example:

number := NewNumber(t, 1234.5)
number.NotFinite() // failure

number := NewNumber(t, math.NaN())
number.NotFinite() // success

number := NewNumber(t, math.Inf(+1))
number.NotFinite() // success

func (*Number) NotInDelta added in v2.9.0

func (n *Number) NotInDelta(value, delta float64) *Number

NotInDelta succeeds if two numerals are not within delta of each other.

Example:

number := NewNumber(t, 123.0)
number.NotInDelta(123.2, 0.1)

func (*Number) NotInList added in v2.11.0

func (n *Number) NotInList(values ...interface{}) *Number

NotInList succeeds if the number is not equal to any of the values from given list of numbers. Before comparison, each value is converted to canonical form.

Each value should be numeric type convertible to float64. If at least one value has wrong type, failure is reported.

Example:

number := NewNumber(t, 123)
number.NotInList(float64(456), int32(456))

func (*Number) NotInRange added in v2.6.0

func (n *Number) NotInRange(min, max interface{}) *Number

NotInRange succeeds if number is not within given range [min; max].

min and max should have numeric type convertible to float64. Before comparison, they are converted to float64.

Example:

number := NewNumber(t, 100)
number.NotInRange(0, 99)
number.NotInRange(101, 200)

func (*Number) NotInt added in v2.13.0

func (n *Number) NotInt(bits ...int) *Number

NotInt succeeds if number is not a signed integer of the specified bit width as an optional argument.

Bits argument defines maximum allowed bitness for the given number. If bits is omitted, boundary check is omitted too.

Example:

number := NewNumber(t, 1000000)
number.NotInt()   // failure
number.NotInt(32) // failure
number.NotInt(16) // success

number := NewNumber(t, -1000000)
number.NotInt()   // failure
number.NotInt(32) // failure
number.NotInt(16) // success

number := NewNumber(t, 0.5)
number.NotInt()   // success

func (*Number) NotUint added in v2.13.0

func (n *Number) NotUint(bits ...int) *Number

NotUint succeeds if number is not an unsigned integer of the specified bit width as an optional argument.

Bits argument defines maximum allowed bitness for the given number. If bits is omitted, boundary check is omitted too.

Example:

number := NewNumber(t, 1000000)
number.NotUint()   // failure
number.NotUint(32) // failure
number.NotUint(16) // success

number := NewNumber(t, -1000000)
number.NotUint()   // success
number.NotUint(32) // success
number.NotUint(16) // success

number := NewNumber(t, 0.5)
number.NotUint()   // success

func (*Number) Path

func (n *Number) Path(path string) *Value

Path is similar to Value.Path.

func (*Number) Raw

func (n *Number) Raw() float64

Raw returns underlying value attached to Number. This is the value originally passed to NewNumber.

Example:

number := NewNumber(t, 123.4)
assert.Equal(t, 123.4, number.Raw())

func (*Number) Schema

func (n *Number) Schema(schema interface{}) *Number

Schema is similar to Value.Schema.

type Object

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

Object provides methods to inspect attached map[string]interface{} object (Go representation of JSON object).

func NewObject

func NewObject(reporter Reporter, value map[string]interface{}) *Object

NewObject returns a new Object instance.

If reporter is nil, the function panics. If value is nil, failure is reported.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})

func NewObjectC added in v2.9.0

func NewObjectC(config Config, value map[string]interface{}) *Object

NewObjectC returns a new Object instance with config.

Requirements for config are same as for WithConfig function. If value is nil, failure is reported.

Example:

object := NewObjectC(config, map[string]interface{}{"foo": 123})

func (*Object) Alias added in v2.10.0

func (o *Object) Alias(name string) *Object

Alias is similar to Value.Alias.

func (*Object) ContainsKey

func (o *Object) ContainsKey(key string) *Object

ContainsKey succeeds if object contains given key.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.ContainsKey("foo")

func (*Object) ContainsMap deprecated

func (o *Object) ContainsMap(value interface{}) *Object

Deprecated: use ContainsSubset instead.

func (*Object) ContainsSubset added in v2.6.0

func (o *Object) ContainsSubset(value interface{}) *Object

ContainsSubset succeeds if given value is a subset of object. Before comparison, both object and value are converted to canonical form.

value should be map[string]interface{} or struct.

Example:

object := NewObject(t, map[string]interface{}{
	"foo": 123,
	"bar": []interface{}{"x", "y"},
	"bar": map[string]interface{}{
		"a": true,
		"b": false,
	},
})

object.ContainsSubset(map[string]interface{}{  // success
	"foo": 123,
	"bar": map[string]interface{}{
		"a": true,
	},
})

object.ContainsSubset(map[string]interface{}{  // failure
	"foo": 123,
	"qux": 456,
})

object.ContainsSubset(map[string]interface{}{  // failure, slices should match exactly
	"bar": []interface{}{"x"},
})

func (*Object) ContainsValue added in v2.6.0

func (o *Object) ContainsValue(value interface{}) *Object

ContainsValue succeeds if object contains given value with any key. Before comparison, both object and value are converted to canonical form.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.ContainsValue(123)

func (*Object) Decode added in v2.10.0

func (o *Object) Decode(target interface{}) *Object

Decode unmarshals the underlying value attached to the Object to a target variable target should be one of this:

  • pointer to an empty interface
  • pointer to a map
  • pointer to a struct

Example:

type S struct{
	Foo int                    `json:"foo"`
	Bar []interface{}          `json:"bar"`
	Baz map[string]interface{} `json:"baz"`
	Bat struct{ A int }        `json:"bat"`
}

m := map[string]interface{}{
	"foo": 123,
	"bar": []interface{}{"123", 234.0},
	"baz": map[string]interface{}{
		"a": "b",
	},
	"bat": struct{ A int }{123},
}

value := NewObject(t, value)

var target S
value.Decode(&target)

assert.Equal(t, S{123,[]interface{}{"123", 234.0},
	map[string]interface{}{"a": "b"}, struct{ A int }{123},
}, target)

func (*Object) Empty deprecated

func (o *Object) Empty() *Object

Deprecated: use IsEmpty instead.

func (*Object) Equal deprecated

func (o *Object) Equal(value interface{}) *Object

Deprecated: use IsEqual instead.

func (*Object) Every added in v2.7.0

func (o *Object) Every(fn func(key string, value *Value)) *Object

Every runs the passed function for all the key value pairs in the object.

If assertion inside function fails, the original Object is marked failed.

Every will execute the function for all values in the object irrespective of assertion failures for some values in the object.

The function is invoked for key value pairs sorted by keys in ascending order.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123, "bar": 456})

object.Every(func(key string, value *httpexpect.Value) {
  value.String().NotEmpty()
})

func (*Object) Filter added in v2.7.0

func (o *Object) Filter(fn func(key string, value *Value) bool) *Object

Filter accepts a function that returns a boolean. The function is ran over the object elements. If the function returns true, the element passes the filter and is added to the new object of filtered elements. If false, the value is skipped (or in other words filtered out). After iterating through all the elements of the original object, the new filtered object is returned.

If there are any failed assertions in the filtering function, the element is omitted without causing test failure.

The function is invoked for key value pairs sorted by keys in ascending order.

Example:

object := NewObject(t, map[string]interface{}{
	"foo": "bar",
	"baz": 6,
	"qux": "quux",
})
filteredObject := object.Filter(func(key string, value *httpexpect.Value) bool {
	value.String().NotEmpty()		//fails on 6
	return value.Raw() != "bar"		//fails on "bar"
})
filteredObject.IsEqual(map[string]interface{}{"qux":"quux"})	//succeeds

func (*Object) Find added in v2.9.0

func (o *Object) Find(fn func(key string, value *Value) bool) *Value

Find accepts a function that returns a boolean, runs it over the object elements, and returns the first element on which it returned true.

If there are any failed assertions in the predicate function, the element is skipped without causing test failure.

If no elements were found, a failure is reported.

The function is invoked for key value pairs sorted by keys in ascending order.

Example:

object := NewObject(t, map[string]interface{}{
	"a": 1,
	"b": "foo",
	"c": 101,
	"d": "bar",
	"e": 201,
})
foundValue := object.Find(func(key string, value *httpexpect.Value)  bool {
	num := value.Number()      // skip if element is not a string
	return num.Raw() > 100     // check element value
})
foundValue.IsEqual(101) // succeeds

func (*Object) FindAll added in v2.9.0

func (o *Object) FindAll(fn func(key string, value *Value) bool) []*Value

FindAll accepts a function that returns a boolean, runs it over the object elements, and returns all the elements on which it returned true.

If there are any failed assertions in the predicate function, the element is skipped without causing test failure.

If no elements were found, empty slice is returned without reporting error.

The function is invoked for key value pairs sorted by keys in ascending order.

Example:

object := NewObject(t, map[string]interface{}{
	"a": 1,
	"b": "foo",
	"c": 101,
	"d": "bar",
	"e": 201,
})
foundValues := object.FindAll(func(key string, value *httpexpect.Value)  bool {
	num := value.Number()      // skip if element is not a string
	return num.Raw() > 100     // check element value
})

assert.Equal(t, len(foundValues), 2)
foundValues[0].IsEqual(101)
foundValues[1].IsEqual(201)

func (*Object) HasValue added in v2.13.0

func (o *Object) HasValue(key string, value interface{}) *Object

HasValue succeeds if object's value for given key is equal to given value. Before comparison, both values are converted to canonical form.

value should be map[string]interface{} or struct.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.HasValue("foo", 123)

func (*Object) InList added in v2.11.0

func (o *Object) InList(values ...interface{}) *Object

InList succeeds if whole object is equal to one of the values from given list of objects. Before comparison, each value is converted to canonical form.

Each value should be map[string]interface{} or struct. If at least one value has wrong type, failure is reported.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.InList(
	map[string]interface{}{"foo": 123},
	map[string]interface{}{"bar": 456},
)

func (*Object) IsEmpty added in v2.11.0

func (o *Object) IsEmpty() *Object

IsEmpty succeeds if object is empty.

Example:

object := NewObject(t, map[string]interface{}{})
object.IsEmpty()

func (*Object) IsEqual added in v2.11.0

func (o *Object) IsEqual(value interface{}) *Object

IsEqual succeeds if object is equal to given value. Before comparison, both object and value are converted to canonical form.

value should be map[string]interface{} or struct.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.IsEqual(map[string]interface{}{"foo": 123})

func (*Object) Iter added in v2.8.0

func (o *Object) Iter() map[string]Value

Iter returns a new map of Values attached to object elements.

Example:

numbers := map[string]interface{}{"foo": 123, "bar": 456}
object := NewObject(t, numbers)

for key, value := range object.Iter() {
	value.Number().IsEqual(numbers[key])
}

func (*Object) Keys

func (o *Object) Keys() *Array

Keys returns a new Array instance with object's keys. Keys are sorted in ascending order.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123, "bar": 456})
object.Keys().ContainsOnly("foo", "bar")

func (*Object) NotContainsKey

func (o *Object) NotContainsKey(key string) *Object

NotContainsKey succeeds if object doesn't contain given key.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.NotContainsKey("bar")

func (*Object) NotContainsMap deprecated

func (o *Object) NotContainsMap(value interface{}) *Object

Deprecated: use NotContainsSubset instead.

func (*Object) NotContainsSubset added in v2.6.0

func (o *Object) NotContainsSubset(value interface{}) *Object

NotContainsSubset succeeds if given value is not a subset of object. Before comparison, both object and value are converted to canonical form.

value should be map[string]interface{} or struct.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123, "bar": 456})
object.NotContainsSubset(map[string]interface{}{"foo": 123, "bar": "no-no-no"})

func (*Object) NotContainsValue added in v2.6.0

func (o *Object) NotContainsValue(value interface{}) *Object

NotContainsValue succeeds if object does not contain given value with any key. Before comparison, both object and value are converted to canonical form.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.NotContainsValue(456)

func (*Object) NotEmpty

func (o *Object) NotEmpty() *Object

NotEmpty succeeds if object is non-empty.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.NotEmpty()

func (*Object) NotEqual

func (o *Object) NotEqual(value interface{}) *Object

NotEqual succeeds if object is not equal to given value. Before comparison, both object and value are converted to canonical form.

value should be map[string]interface{} or struct.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.IsEqual(map[string]interface{}{"bar": 123})

func (*Object) NotFind added in v2.9.0

func (o *Object) NotFind(fn func(key string, value *Value) bool) *Object

NotFind accepts a function that returns a boolean, runs it over the object elelements, and checks that it does not return true for any of the elements.

If there are any failed assertions in the predicate function, the element is skipped without causing test failure.

If the predicate function did not fail and returned true for at least one element, a failure is reported.

The function is invoked for key value pairs sorted by keys in ascending order.

Example:

object := NewObject(t, map[string]interface{}{
	"a": 1,
	"b": "foo",
	"c": 2,
	"d": "bar",
})
object.NotFind(func(key string, value *httpexpect.Value) bool {
	num := value.Number()    // skip if element is not a number
	return num.Raw() > 100   // check element value
}) // succeeds

func (*Object) NotHasValue added in v2.13.0

func (o *Object) NotHasValue(key string, value interface{}) *Object

NotHasValue succeeds if object's value for given key is not equal to given value. Before comparison, both values are converted to canonical form.

value should be map[string]interface{} or struct.

If object doesn't contain any value for given key, failure is reported.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.NotHasValue("foo", "bad value")  // success
object.NotHasValue("bar", "bad value")  // failure! (key is missing)

func (*Object) NotInList added in v2.11.0

func (o *Object) NotInList(values ...interface{}) *Object

NotInList succeeds if the whole object is not equal to any of the values from given list of objects. Before comparison, each value is converted to canonical form.

Each value should be map[string]interface{} or struct. If at least one value has wrong type, failure is reported.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.NotInList(
	map[string]interface{}{"bar": 456},
	map[string]interface{}{"baz": 789},
)

func (*Object) Path

func (o *Object) Path(path string) *Value

Path is similar to Value.Path.

func (*Object) Raw

func (o *Object) Raw() map[string]interface{}

Raw returns underlying value attached to Object. This is the value originally passed to NewObject, converted to canonical form.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
assert.Equal(t, map[string]interface{}{"foo": 123.0}, object.Raw())

func (*Object) Schema

func (o *Object) Schema(schema interface{}) *Object

Schema is similar to Value.Schema.

func (*Object) Transform added in v2.7.0

func (o *Object) Transform(fn func(key string, value interface{}) interface{}) *Object

Transform runs the passed function on all the elements in the Object and returns a new object without effecting original object.

The function is invoked for key value pairs sorted by keys in ascending order.

Example:

object := NewObject(t, []interface{}{"x": "foo", "y": "bar"})
transformedObject := object.Transform(
	func(key string, value interface{}) interface{} {
		return strings.ToUpper(value.(string))
	})
transformedObject.IsEqual([]interface{}{"x": "FOO", "y": "BAR"})

func (*Object) Value

func (o *Object) Value(key string) *Value

Value returns a new Value instance with value for given key.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123})
object.Value("foo").Number().IsEqual(123)

func (*Object) ValueEqual deprecated

func (o *Object) ValueEqual(key string, value interface{}) *Object

Deprecated: use HasValue instead.

func (*Object) ValueNotEqual deprecated

func (o *Object) ValueNotEqual(key string, value interface{}) *Object

Deprecated: use NotHasValue instead.

func (*Object) Values

func (o *Object) Values() *Array

Values returns a new Array instance with object's values. Values are sorted by keys ascending order.

Example:

object := NewObject(t, map[string]interface{}{"foo": 123, "bar": 456})
object.Values().ContainsOnly(123, 456)

type PanicReporter added in v2.15.0

type PanicReporter struct{}

PanicReporter is a struct that implements the Reporter interface and panics when a test fails. Useful for multithreaded tests when you want to report fatal failures from goroutines other than the main goroutine, because the main goroutine is forbidden to call t.Fatal.

func NewPanicReporter added in v2.15.0

func NewPanicReporter() *PanicReporter

NewPanicReporter returns a new PanicReporter object.

func (*PanicReporter) Errorf added in v2.15.0

func (r *PanicReporter) Errorf(message string, args ...interface{})

Errorf implements Reporter.Errorf

type Printer

type Printer interface {
	// Request is called before request is sent.
	// It is allowed to read and close request body, or ignore it.
	Request(*http.Request)

	// Response is called after response is received.
	// It is allowed to read and close response body, or ignore it.
	Response(*http.Response, time.Duration)
}

Printer is used to print requests and responses. CompactPrinter, DebugPrinter, and CurlPrinter implement this interface.

type RedirectPolicy added in v2.3.0

type RedirectPolicy int

RedirectPolicy defines how redirection responses are handled.

Status codes 307, 308 require resending body. They are followed only if redirect policy is FollowAllRedirects.

Status codes 301, 302, 303 don't require resending body. On such redirect, http.Client automatically switches HTTP method to GET, if it's not GET or HEAD already. These redirects are followed if redirect policy is either FollowAllRedirects or FollowRedirectsWithoutBody.

Default redirect policy is FollowRedirectsWithoutBody.

const (

	// DontFollowRedirects forbids following any redirects.
	// Redirection response is returned to the user and can be inspected.
	DontFollowRedirects RedirectPolicy

	// FollowAllRedirects allows following any redirects, including those
	// which require resending body.
	FollowAllRedirects

	// FollowRedirectsWithoutBody allows following only redirects which
	// don't require resending body.
	// If redirect requires resending body, it's not followed, and redirection
	// response is returned instead.
	FollowRedirectsWithoutBody
)

type Reporter

type Reporter interface {
	// Errorf reports failure.
	// Allowed to return normally or terminate test using t.FailNow().
	Errorf(message string, args ...interface{})
}

Reporter is used to report failures. *testing.T, FatalReporter, AssertReporter, RequireReporter, PanicReporter implement it.

type ReporterFunc added in v2.15.0

type ReporterFunc func(message string, args ...interface{})

ReporterFunc is an adapter that allows a function to be used as the Reporter

Example:

e := httpexpect.WithConfig(httpexpect.Config{
	Reporter: httpextect.ReporterFunc(
		func(message string, args ...interface{}) {
			// reporter code here
		}),
})

func (ReporterFunc) Errorf added in v2.15.0

func (f ReporterFunc) Errorf(message string, args ...interface{})

type Request

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

Request provides methods to incrementally build http.Request object, send it, and receive response.

func NewRequest deprecated

func NewRequest(config Config, method, path string, pathargs ...interface{}) *Request

Deprecated: use NewRequestC instead.

func NewRequestC added in v2.9.0

func NewRequestC(config Config, method, path string, pathargs ...interface{}) *Request

NewRequestC returns a new Request instance.

Requirements for config are same as for WithConfig function.

method defines the HTTP method (GET, POST, PUT, etc.). path defines url path.

Simple interpolation is allowed for {named} parameters in path:

  • if pathargs is given, it's used to substitute first len(pathargs) parameters, regardless of their names
  • if WithPath() or WithPathObject() is called, it's used to substitute given parameters by name

For example:

req := NewRequestC(config, "POST", "/repos/{user}/{repo}", "gavv", "httpexpect")
// path will be "/repos/gavv/httpexpect"

Or:

req := NewRequestC(config, "POST", "/repos/{user}/{repo}")
req.WithPath("user", "gavv")
req.WithPath("repo", "httpexpect")
// path will be "/repos/gavv/httpexpect"

After interpolation, path is urlencoded and appended to Config.BaseURL, separated by slash. If BaseURL ends with a slash and path (after interpolation) starts with a slash, only single slash is inserted.

func (*Request) Alias added in v2.10.0

func (r *Request) Alias(name string) *Request

Alias is similar to Value.Alias.

func (*Request) Expect

func (r *Request) Expect() *Response

Expect constructs http.Request, sends it, receives http.Response, and returns a new Response instance.

Request is sent using Client interface, or WebsocketDialer in case of WebSocket request.

After calling Expect, there should not be any more calls of Expect or other WithXXX methods on the same Request instance.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithJSON(map[string]interface{}{"foo": 123})
resp := req.Expect()
resp.Status(http.StatusOK)

func (*Request) WithAssertionHandler added in v2.16.0

func (r *Request) WithAssertionHandler(handler AssertionHandler) *Request

WithAssertionHandler sets assertion handler to be used for this request.

The new handler overwrites assertion handler that will be used by Request and its children (Response, Body, etc.). It will be used to format and report test Failure or Success.

Example:

req := NewRequestC(config, "GET", "http://example.com/path")
req.WithAssertionHandler(&DefaultAssertionHandler{
	Reporter:  reporter,
	Formatter: formatter,
})

func (*Request) WithBasicAuth

func (r *Request) WithBasicAuth(username, password string) *Request

WithBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and password are not encrypted.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithBasicAuth("john", "secret")

func (*Request) WithBytes

func (r *Request) WithBytes(b []byte) *Request

WithBytes sets request body to given slice of bytes.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithHeader("Content-Type", "application/json")
req.WithBytes([]byte(`{"foo": 123}`))

func (*Request) WithChunked

func (r *Request) WithChunked(reader io.Reader) *Request

WithChunked enables chunked encoding and sets request body reader.

Expect() will read all available data from given reader. Content-Length is not set, and "chunked" Transfer-Encoding is used.

If protocol version is not at least HTTP/1.1 (required for chunked encoding), failure is reported.

Example:

req := NewRequestC(config, "PUT", "http://example.com/upload")
fh, _ := os.Open("data")
defer fh.Close()
req.WithHeader("Content-Type", "application/octet-stream")
req.WithChunked(fh)

func (*Request) WithClient

func (r *Request) WithClient(client Client) *Request

WithClient sets client.

The new client overwrites Config.Client. It will be used once to send the request and receive a response.

Example:

req := NewRequestC(config, "GET", "/path")
req.WithClient(&http.Client{
  Transport: &http.Transport{
	DisableCompression: true,
  },
})

func (*Request) WithContext added in v2.3.0

func (r *Request) WithContext(ctx context.Context) *Request

WithContext sets the context.

Config.Context will be overwritten.

Any retries will stop after one is cancelled. If the intended behavior is to continue any further retries, use WithTimeout.

Example:

ctx, _ = context.WithTimeout(context.Background(), time.Duration(3)*time.Second)
req := NewRequestC(config, "GET", "/path")
req.WithContext(ctx)
req.Expect().Status(http.StatusOK)

func (*Request) WithCookie

func (r *Request) WithCookie(k, v string) *Request

WithCookie adds given single cookie to request.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithCookie("name", "value")

func (*Request) WithCookies

func (r *Request) WithCookies(cookies map[string]string) *Request

WithCookies adds given cookies to request.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithCookies(map[string]string{
	"foo": "aa",
	"bar": "bb",
})

func (*Request) WithFile

func (r *Request) WithFile(key, path string, reader ...io.Reader) *Request

WithFile sets Content-Type header to "multipart/form-data", reads given file and adds its contents to request body.

If reader is given, it's used to read file contents. Otherwise, os.Open() is used to read a file with given path.

Multiple WithForm(), WithFormField(), and WithFile() calls may be combined. WithMultipart() should be called before WithFile(), otherwise WithFile() fails.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithFile("avatar", "./john.png")

req := NewRequestC(config, "PUT", "http://example.com/path")
fh, _ := os.Open("./john.png")
req.WithMultipart().
	WithFile("avatar", "john.png", fh)
fh.Close()

func (*Request) WithFileBytes

func (r *Request) WithFileBytes(key, path string, data []byte) *Request

WithFileBytes is like WithFile, but uses given slice of bytes as the file contents.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
fh, _ := os.Open("./john.png")
b, _ := io.ReadAll(fh)
req.WithMultipart().
	WithFileBytes("avatar", "john.png", b)
fh.Close()

func (*Request) WithForm

func (r *Request) WithForm(object interface{}) *Request

WithForm sets Content-Type header to "application/x-www-form-urlencoded" or (if WithMultipart() was called) "multipart/form-data", converts given object to url.Values using github.com/ajg/form, and adds it to request body.

Various object types are supported, including maps and structs. Structs may contain "form" struct tag, similar to "json" struct tag for json.Marshal(). See https://github.com/ajg/form for details.

Multiple WithForm(), WithFormField(), and WithFile() calls may be combined. If WithMultipart() is called, it should be called first.

Example:

type MyForm struct {
	Foo int `form:"foo"`
}

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithForm(MyForm{Foo: 123})

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithForm(map[string]interface{}{"foo": 123})

func (*Request) WithFormField

func (r *Request) WithFormField(key string, value interface{}) *Request

WithFormField sets Content-Type header to "application/x-www-form-urlencoded" or (if WithMultipart() was called) "multipart/form-data", converts given value to string using fmt.Sprint(), and adds it to request body.

Multiple WithForm(), WithFormField(), and WithFile() calls may be combined. If WithMultipart() is called, it should be called first.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithFormField("foo", 123).
	WithFormField("bar", 456)

func (*Request) WithHandler

func (r *Request) WithHandler(handler http.Handler) *Request

WithHandler configures client to invoke the given handler directly.

If Config.Client is http.Client, then only its Transport field is overwritten because the client may contain some state shared among requests like a cookie jar. Otherwise, the whole client is overwritten with a new client.

Example:

req := NewRequestC(config, "GET", "/path")
req.WithHandler(myServer.someHandler)

func (*Request) WithHeader

func (r *Request) WithHeader(k, v string) *Request

WithHeader adds given single header to request.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithHeader("Content-Type", "application/json")

func (*Request) WithHeaders

func (r *Request) WithHeaders(headers map[string]string) *Request

WithHeaders adds given headers to request.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithHeaders(map[string]string{
	"Content-Type": "application/json",
})

func (*Request) WithHost added in v2.2.0

func (r *Request) WithHost(host string) *Request

WithHost sets request host to given string.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithHost("example.com")

func (*Request) WithJSON

func (r *Request) WithJSON(object interface{}) *Request

WithJSON sets Content-Type header to "application/json; charset=utf-8" and sets body to object, marshaled using json.Marshal().

Example:

type MyJSON struct {
	Foo int `json:"foo"`
}

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithJSON(MyJSON{Foo: 123})

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithJSON(map[string]interface{}{"foo": 123})

func (*Request) WithMatcher

func (r *Request) WithMatcher(matcher func(*Response)) *Request

WithMatcher attaches a matcher to the request. All attached matchers are invoked in the Expect method for a newly created Response.

Example:

req := NewRequestC(config, "GET", "/path")
req.WithMatcher(func (resp *httpexpect.Response) {
	resp.Header("API-Version").NotEmpty()
})

func (*Request) WithMaxRedirects added in v2.3.0

func (r *Request) WithMaxRedirects(maxRedirects int) *Request

WithMaxRedirects sets maximum number of redirects to follow.

If the number of redirects exceedes this limit, request is failed.

Default limit is defined by Client implementation. Default behavior of http.Client corresponds to maximum of 10-1 redirects.

This method can be used only if Client interface points to *http.Client struct, since we rely on it in redirect handling.

Example:

req1 := NewRequestC(config, "POST", "/path")
req1.WithMaxRedirects(1)
req1.Expect().Status(http.StatusOK)

func (*Request) WithMaxRetries added in v2.3.0

func (r *Request) WithMaxRetries(maxRetries int) *Request

WithMaxRetries sets maximum number of retry attempts.

After first request failure, additional retry attempts may happen, depending on the retry policy.

Setting this to zero disables retries, i.e. only one request is sent. Setting this to N enables retries, and up to N+1 requests may be sent.

Default number of retries is zero, i.e. retries are disabled.

Example:

req := NewRequestC(config, "POST", "/path")
req.WithMaxRetries(1)
req.Expect().Status(http.StatusOK)

func (*Request) WithMultipart

func (r *Request) WithMultipart() *Request

WithMultipart sets Content-Type header to "multipart/form-data".

After this call, WithForm() and WithFormField() switch to multipart form instead of urlencoded form.

If WithMultipart() is called, it should be called before WithForm(), WithFormField(), and WithFile().

WithFile() always requires WithMultipart() to be called first.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithMultipart().
	WithForm(map[string]interface{}{"foo": 123})

func (*Request) WithName added in v2.5.0

func (r *Request) WithName(name string) *Request

WithName sets convenient request name. This name will be included in assertion reports for this request. It does not affect assertion chain path, inlike Alias.

Example:

req := NewRequestC(config, "POST", "/api/login")
req.WithName("Login Request")

func (*Request) WithPath

func (r *Request) WithPath(key string, value interface{}) *Request

WithPath substitutes named parameters in url path.

value is converted to string using fmt.Sprint(). If there is no named parameter '{key}' in url path, failure is reported.

Named parameters are case-insensitive.

Example:

req := NewRequestC(config, "POST", "/repos/{user}/{repo}")
req.WithPath("user", "gavv")
req.WithPath("repo", "httpexpect")
// path will be "/repos/gavv/httpexpect"

func (*Request) WithPathObject

func (r *Request) WithPathObject(object interface{}) *Request

WithPathObject substitutes multiple named parameters in url path.

object should be map or struct. If object is struct, it's converted to map using https://github.com/fatih/structs. Structs may contain "path" struct tag, similar to "json" struct tag for json.Marshal().

Each map value is converted to string using fmt.Sprint(). If there is no named parameter for some map '{key}' in url path, failure is reported.

Named parameters are case-insensitive.

Example:

type MyPath struct {
	Login string `path:"user"`
	Repo  string
}

req := NewRequestC(config, "POST", "/repos/{user}/{repo}")
req.WithPathObject(MyPath{"gavv", "httpexpect"})
// path will be "/repos/gavv/httpexpect"

req := NewRequestC(config, "POST", "/repos/{user}/{repo}")
req.WithPathObject(map[string]string{"user": "gavv", "repo": "httpexpect"})
// path will be "/repos/gavv/httpexpect"

func (*Request) WithProto

func (r *Request) WithProto(proto string) *Request

WithProto sets HTTP protocol version.

proto should have form of "HTTP/{major}.{minor}", e.g. "HTTP/1.1".

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithProto("HTTP/2.0")

func (*Request) WithQuery

func (r *Request) WithQuery(key string, value interface{}) *Request

WithQuery adds query parameter to request URL.

value is converted to string using fmt.Sprint() and urlencoded.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithQuery("a", 123)
req.WithQuery("b", "foo")
// URL is now http://example.com/path?a=123&b=foo

func (*Request) WithQueryObject

func (r *Request) WithQueryObject(object interface{}) *Request

WithQueryObject adds multiple query parameters to request URL.

object is converted to query string using github.com/google/go-querystring if it's a struct or pointer to struct, or github.com/ajg/form otherwise.

Various object types are supported. Structs may contain "url" struct tag, similar to "json" struct tag for json.Marshal().

Example:

type MyURL struct {
	A int    `url:"a"`
	B string `url:"b"`
}

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithQueryObject(MyURL{A: 123, B: "foo"})
// URL is now http://example.com/path?a=123&b=foo

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithQueryObject(map[string]interface{}{"a": 123, "b": "foo"})
// URL is now http://example.com/path?a=123&b=foo

func (*Request) WithQueryString

func (r *Request) WithQueryString(query string) *Request

WithQueryString parses given query string and adds it to request URL.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithQuery("a", 11)
req.WithQueryString("b=22&c=33")
// URL is now http://example.com/path?a=11&bb=22&c=33

func (*Request) WithRedirectPolicy added in v2.3.0

func (r *Request) WithRedirectPolicy(policy RedirectPolicy) *Request

WithRedirectPolicy sets policy for redirection response handling.

How redirect is handled depends on both response status code and redirect policy. See comments for RedirectPolicy for details.

Default redirect policy is defined by Client implementation. Default behavior of http.Client corresponds to FollowRedirectsWithoutBody.

This method can be used only if Client interface points to *http.Client struct, since we rely on it in redirect handling.

Example:

req1 := NewRequestC(config, "POST", "/path")
req1.WithRedirectPolicy(FollowAllRedirects)
req1.Expect().Status(http.StatusOK)

req2 := NewRequestC(config, "POST", "/path")
req2.WithRedirectPolicy(DontFollowRedirects)
req2.Expect().Status(http.StatusPermanentRedirect)

func (*Request) WithReporter added in v2.16.0

func (r *Request) WithReporter(reporter Reporter) *Request

WithReporter sets reporter to be used for this request.

The new reporter overwrites AssertionHandler. The new AssertionHandler is DefaultAssertionHandler with specified reporter, existing Config.Formatter and nil Logger. It will be used to report formatted fatal failure messages.

Example:

req := NewRequestC(config, "GET", "http://example.com/path")
req.WithReporter(t)

func (*Request) WithRetryDelay added in v2.3.0

func (r *Request) WithRetryDelay(minDelay, maxDelay time.Duration) *Request

WithRetryDelay sets minimum and maximum delay between retries.

If multiple retry attempts happen, delay between attempts starts from minDelay and then grows exponentionally until it reaches maxDelay.

Default delay range is [50ms; 5s].

Example:

req := NewRequestC(config, "POST", "/path")
req.WithRetryDelay(time.Second, time.Minute)
req.Expect().Status(http.StatusOK)

func (*Request) WithRetryPolicy added in v2.3.0

func (r *Request) WithRetryPolicy(policy RetryPolicy) *Request

WithRetryPolicy sets policy for retries.

Whether a request is retried depends on error type (if any), response status code (if any), and retry policy.

How much retry attempts happens is defined by WithMaxRetries(). How much to wait between attempts is defined by WithRetryDelay().

Default retry policy is RetryTimeoutAndServerErrors, but default maximum number of retries is zero, so no retries happen unless WithMaxRetries() is called.

Example:

req := NewRequestC(config, "POST", "/path")
req.WithRetryPolicy(RetryAllErrors)
req.Expect().Status(http.StatusOK)

func (*Request) WithText

func (r *Request) WithText(s string) *Request

WithText sets Content-Type header to "text/plain; charset=utf-8" and sets body to given string.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithText("hello, world!")

func (*Request) WithTimeout added in v2.3.0

func (r *Request) WithTimeout(timeout time.Duration) *Request

WithTimeout sets a timeout duration for the request.

Will attach to the request a context.WithTimeout around the Config.Context or any context set WithContext. If these are nil, the new context will be created on top of a context.Background().

Any retries will continue after one is cancelled. If the intended behavior is to stop any further retries, use WithContext or Config.Context.

Example:

req := NewRequestC(config, "GET", "/path")
req.WithTimeout(time.Duration(3)*time.Second)
req.Expect().Status(http.StatusOK)

func (*Request) WithTransformer added in v2.2.0

func (r *Request) WithTransformer(transformer func(*http.Request)) *Request

WithTransformer attaches a transform to the Request. All attachhed transforms are invoked in the Expect methods for http.Request struct, after it's encoded and before it's sent.

Example:

req := NewRequestC(config, "PUT", "http://example.com/path")
req.WithTransformer(func(r *http.Request) { r.Header.Add("foo", "bar") })

func (*Request) WithURL

func (r *Request) WithURL(urlStr string) *Request

WithURL sets request URL.

This URL overwrites Config.BaseURL. Request path passed to request constructor is appended to this URL, separated by slash if necessary.

Example:

req := NewRequestC(config, "PUT", "/path")
req.WithURL("http://example.com")
// URL is now http://example.com/path

func (*Request) WithWebsocketDialer

func (r *Request) WithWebsocketDialer(dialer WebsocketDialer) *Request

WithWebsocketDialer sets the custom websocket dialer.

The new dialer overwrites Config.WebsocketDialer. It will be used once to establish the WebSocket connection and receive a response of handshake result.

Example:

req := NewRequestC(config, "GET", "/path")
req.WithWebsocketUpgrade()
req.WithWebsocketDialer(&websocket.Dialer{
  EnableCompression: false,
})
ws := req.Expect().Status(http.StatusSwitchingProtocols).Websocket()
defer ws.Disconnect()

func (*Request) WithWebsocketUpgrade

func (r *Request) WithWebsocketUpgrade() *Request

WithWebsocketUpgrade enables upgrades the connection to websocket.

At least the following fields are added to the request header:

Upgrade: websocket
Connection: Upgrade

The actual set of header fields is define by the protocol implementation in the gorilla/websocket package.

The user should then call the Response.Websocket() method which returns the Websocket instance. This instance can be used to send messages to the server, to inspect the received messages, and to close the websocket.

Example:

req := NewRequestC(config, "GET", "/path")
req.WithWebsocketUpgrade()
ws := req.Expect().Status(http.StatusSwitchingProtocols).Websocket()
defer ws.Disconnect()

type RequestFactory

type RequestFactory interface {
	NewRequest(method, url string, body io.Reader) (*http.Request, error)
}

RequestFactory is used to create all http.Request objects. aetest.Instance from the Google App Engine implements this interface.

type RequestFactoryFunc added in v2.15.0

type RequestFactoryFunc func(
	method string, url string, body io.Reader,
) (*http.Request, error)

RequestFactoryFunc is an adapter that allows a function to be used as the RequestFactory

Example:

e := httpexpect.WithConfig(httpexpect.Config{
	RequestFactory: httpextect.RequestFactoryFunc(
		func(method string, url string, body io.Reader) (*http.Request, error) {
			// factory code here
		}),
})

func (RequestFactoryFunc) NewRequest added in v2.15.0

func (f RequestFactoryFunc) NewRequest(
	method string, url string, body io.Reader,
) (*http.Request, error)

type RequireReporter

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

RequireReporter implements Reporter interface using `testify/require' package. Failures are fatal with this reporter.

func NewRequireReporter

func NewRequireReporter(t require.TestingT) *RequireReporter

NewRequireReporter returns a new RequireReporter object.

func (*RequireReporter) Errorf

func (r *RequireReporter) Errorf(message string, args ...interface{})

Errorf implements Reporter.Errorf.

type Response

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

Response provides methods to inspect attached http.Response object.

func NewResponse

func NewResponse(
	reporter Reporter, response *http.Response, rtt ...time.Duration,
) *Response

NewResponse returns a new Response instance.

If reporter is nil, the function panics. If response is nil, failure is reported.

If rtt is given, it defines response round-trip time to be reported by response.RoundTripTime().

func NewResponseC added in v2.9.0

func NewResponseC(
	config Config, response *http.Response, rtt ...time.Duration,
) *Response

NewResponse returns a new Response instance with config.

Requirements for config are same as for WithConfig function. If response is nil, failure is reported.

If rtt is given, it defines response round-trip time to be reported by response.RoundTripTime().

func (*Response) Alias added in v2.10.0

func (r *Response) Alias(name string) *Response

Alias is similar to Value.Alias.

func (*Response) Body

func (r *Response) Body() *String

Body returns a new String instance with response body.

Example:

resp := NewResponse(t, response)
resp.Body().NotEmpty()
resp.Body().Length().IsEqual(100)

func (*Response) ContentEncoding deprecated

func (r *Response) ContentEncoding(encoding ...string) *Response

Deprecated: use HasContentEncoding instead.

func (*Response) ContentType deprecated

func (r *Response) ContentType(mediaType string, charset ...string) *Response

Deprecated: use HasContentType instead.

func (*Response) Cookie

func (r *Response) Cookie(name string) *Cookie

Cookie returns a new Cookie instance with specified cookie from response.

Note that this returns only cookies set by Set-Cookie headers of this response. It doesn't return session cookies from previous responses, which may be stored in a cookie jar.

Example:

resp := NewResponse(t, response)
resp.Cookie("session").Domain().IsEqual("example.com")

func (*Response) Cookies

func (r *Response) Cookies() *Array

Cookies returns a new Array instance with all cookie names set by this response. Returned Array contains a String value for every cookie name.

Note that this returns only cookies set by Set-Cookie headers of this response. It doesn't return session cookies from previous responses, which may be stored in a cookie jar.

Example:

resp := NewResponse(t, response)
resp.Cookies().Contains("session")

func (*Response) Duration deprecated

func (r *Response) Duration() *Number

Deprecated: use RoundTripTime instead.

func (*Response) Form

func (r *Response) Form(options ...ContentOpts) *Object

Form returns a new Object instance with form decoded from response body.

Form succeeds if response contains "application/x-www-form-urlencoded" Content-Type header and if form may be decoded from response body. Decoding is performed using https://github.com/ajg/form.

Example:

resp := NewResponse(t, response)
resp.Form().Value("foo").IsEqual("bar")
resp.Form(ContentOpts{
  MediaType: "application/x-www-form-urlencoded",
}).Value("foo").IsEqual("bar")

func (*Response) HasContentEncoding added in v2.16.0

func (r *Response) HasContentEncoding(encoding ...string) *Response

HasContentEncoding succeeds if response has exactly given Content-Encoding list. Common values are empty, "gzip", "compress", "deflate", "identity" and "br".

func (*Response) HasContentType added in v2.16.0

func (r *Response) HasContentType(mediaType string, charset ...string) *Response

HasContentType succeeds if response contains Content-Type header with given media type and charset.

If charset is omitted, and mediaType is non-empty, Content-Type header should contain empty or utf-8 charset.

If charset is omitted, and mediaType is also empty, Content-Type header should contain no charset.

func (*Response) HasTransferEncoding added in v2.16.0

func (r *Response) HasTransferEncoding(encoding ...string) *Response

HasTransferEncoding succeeds if response contains given Transfer-Encoding list. Common values are empty, "chunked" and "identity".

func (*Response) Header

func (r *Response) Header(header string) *String

Header returns a new String instance with given header field.

Example:

resp := NewResponse(t, response)
resp.Header("Content-Type").IsEqual("application-json")
resp.Header("Date").AsDateTime().Le(time.Now())

func (*Response) Headers

func (r *Response) Headers() *Object

Headers returns a new Object instance with response header map.

Example:

resp := NewResponse(t, response)
resp.Headers().Value("Content-Type").String().IsEqual("application-json")

func (*Response) JSON

func (r *Response) JSON(options ...ContentOpts) *Value

JSON returns a new Value instance with JSON decoded from response body.

JSON succeeds if response contains "application/json" Content-Type header with empty or "utf-8" charset and if JSON may be decoded from response body.

Example:

resp := NewResponse(t, response)
resp.JSON().Array().ConsistsOf("foo", "bar")
resp.JSON(ContentOpts{
  MediaType: "application/json",
}).Array.ConsistsOf("foo", "bar")

func (*Response) JSONP

func (r *Response) JSONP(callback string, options ...ContentOpts) *Value

JSONP returns a new Value instance with JSONP decoded from response body.

JSONP succeeds if response contains "application/javascript" Content-Type header with empty or "utf-8" charset and response body of the following form:

callback(<valid json>);

or:

callback(<valid json>)

Whitespaces are allowed.

Example:

resp := NewResponse(t, response)
resp.JSONP("myCallback").Array().ConsistsOf("foo", "bar")
resp.JSONP("myCallback", ContentOpts{
  MediaType: "application/javascript",
}).Array.ConsistsOf("foo", "bar")

func (*Response) NoContent

func (r *Response) NoContent() *Response

NoContent succeeds if response contains empty Content-Type header and empty body.

func (*Response) Raw

func (r *Response) Raw() *http.Response

Raw returns underlying http.Response object. This is the value originally passed to NewResponse.

func (*Response) RoundTripTime

func (r *Response) RoundTripTime() *Duration

RoundTripTime returns a new Duration instance with response round-trip time.

The returned duration is the time interval starting just before request is sent and ending right after response is received (handshake finished for WebSocket request), retrieved from a monotonic clock source.

Example:

resp := NewResponse(t, response, time.Duration(10000000))
resp.RoundTripTime().Lt(10 * time.Millisecond)

func (*Response) Status

func (r *Response) Status(status int) *Response

Status succeeds if response contains given status code.

Example:

resp := NewResponse(t, response)
resp.Status(http.StatusOK)

func (*Response) StatusList added in v2.9.0

func (r *Response) StatusList(values ...int) *Response

StatusList succeeds if response matches with any given status code list

Example:

resp := NewResponse(t, response)
resp.StatusList(http.StatusForbidden, http.StatusUnauthorized)

func (*Response) StatusRange

func (r *Response) StatusRange(rn StatusRange) *Response

StatusRange succeeds if response status belongs to given range.

Supported ranges:

  • Status1xx - Informational
  • Status2xx - Success
  • Status3xx - Redirection
  • Status4xx - Client Error
  • Status5xx - Server Error

See https://en.wikipedia.org/wiki/List_of_HTTP_status_codes.

Example:

resp := NewResponse(t, response)
resp.StatusRange(Status2xx)

func (*Response) Text

func (r *Response) Text(options ...ContentOpts) *String

Text returns a new String instance with response body.

Text succeeds if response contains "text/plain" Content-Type header with empty or "utf-8" charset.

Example:

resp := NewResponse(t, response)
resp.Text().IsEqual("hello, world!")
resp.Text(ContentOpts{
  MediaType: "text/plain",
}).IsEqual("hello, world!")

func (*Response) TransferEncoding deprecated

func (r *Response) TransferEncoding(encoding ...string) *Response

Deprecated: use HasTransferEncoding instead.

func (*Response) Websocket

func (r *Response) Websocket() *Websocket

Websocket returns Websocket instance for interaction with WebSocket server.

May be called only if the WithWebsocketUpgrade was called on the request. That is responsibility of the caller to explicitly disconnect websocket after use.

Example:

req := NewRequestC(config, "GET", "/path")
req.WithWebsocketUpgrade()
ws := req.Expect().Websocket()
defer ws.Disconnect()

type RetryPolicy added in v2.3.0

type RetryPolicy int

RetryPolicy defines how failed requests are retried.

Whether a request is retried depends on error type (if any), response status code (if any), and retry policy.

const (
	// DontRetry disables retrying at all.
	DontRetry RetryPolicy = iota

	// Deprecated: use RetryTimeoutErrors instead.
	RetryTemporaryNetworkErrors

	// Deprecated: use RetryTimeoutAndServerErrors instead.
	RetryTemporaryNetworkAndServerErrors

	// RetryTimeoutErrors enables retrying of timeout errors.
	// Retry happens if Client returns net.Error and its Timeout() method
	// returns true.
	RetryTimeoutErrors

	// RetryTimeoutAndServerErrors enables retrying of network timeout errors,
	// as well as 5xx status codes.
	RetryTimeoutAndServerErrors

	// RetryAllErrors enables retrying of any error or 4xx/5xx status code.
	RetryAllErrors
)

type StacktraceEntry added in v2.16.0

type StacktraceEntry struct {
	Pc uintptr // Program counter

	File string // File path
	Line int    // Line number

	Func *runtime.Func // Function information

	FuncName    string  // Function name (without package and parenthesis)
	FuncPackage string  // Function package
	FuncOffset  uintptr // Program counter offset relative to function start

	// True if this is program entry point
	// (like main.main or testing.tRunner)
	IsEntrypoint bool
}

Stacktrace entry.

type StacktraceMode added in v2.16.0

type StacktraceMode int

StacktraceMode defines the format of stacktrace.

const (
	// Don't print stacktrace.
	StacktraceModeDisabled StacktraceMode = iota

	// Standard, verbose format.
	StacktraceModeStandard

	// Compact format.
	StacktraceModeCompact
)

type StatusRange

type StatusRange int

StatusRange is enum for response status ranges.

const (
	// Status1xx defines "Informational" status codes.
	Status1xx StatusRange = 100

	// Status2xx defines "Success" status codes.
	Status2xx StatusRange = 200

	// Status3xx defines "Redirection" status codes.
	Status3xx StatusRange = 300

	// Status4xx defines "Client Error" status codes.
	Status4xx StatusRange = 400

	// Status5xx defines "Server Error" status codes.
	Status5xx StatusRange = 500
)

type String

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

String provides methods to inspect attached string value (Go representation of JSON string).

func NewString

func NewString(reporter Reporter, value string) *String

NewString returns a new String instance.

If reporter is nil, the function panics.

Example:

str := NewString(t, "Hello")

func NewStringC added in v2.9.0

func NewStringC(config Config, value string) *String

NewStringC returns a new String instance with config.

Requirements for config are same as for WithConfig function.

Example:

str := NewStringC(config, "Hello")

func (*String) Alias added in v2.10.0

func (s *String) Alias(name string) *String

Alias is similar to Value.Alias.

func (*String) AsBoolean added in v2.6.0

func (s *String) AsBoolean() *Boolean

AsBoolean parses true/false value string and returns a new Boolean instance with result.

Accepts string values "true", "True", "false", "False".

Example:

str := NewString(t, "true")
str.AsBoolean().IsTrue()

func (*String) AsDateTime added in v2.6.0

func (s *String) AsDateTime(format ...string) *DateTime

AsDateTime parses date/time from string and returns a new DateTime instance with result.

If format is given, AsDateTime() uses time.Parse() with every given format. Otherwise, it uses the list of predefined common formats.

If the string can't be parsed with any format, AsDateTime reports failure and returns empty (but non-nil) instance.

Example:

str := NewString(t, "Tue, 15 Nov 1994 08:12:31 GMT")
str.AsDateTime().Lt(time.Now())

str := NewString(t, "15 Nov 94 08:12 GMT")
str.AsDateTime(time.RFC822).Lt(time.Now())

func (*String) AsNumber added in v2.6.0

func (s *String) AsNumber(base ...int) *Number

AsNumber parses float from string and returns a new Number instance with result.

If base is 10 or omitted, uses strconv.ParseFloat. Otherwise, uses strconv.ParseInt or strconv.ParseUint with given base.

Example:

str := NewString(t, "100")
str.AsNumber().IsEqual(100)

Specifying base:

str.AsNumber(10).IsEqual(100)
str.AsNumber(16).IsEqual(256)

func (*String) Contains

func (s *String) Contains(value string) *String

Contains succeeds if string contains given Go string as a substring.

Example:

str := NewString(t, "Hello")
str.Contains("ell")

func (*String) ContainsFold

func (s *String) ContainsFold(value string) *String

ContainsFold succeeds if string contains given Go string as a substring after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello")
str.ContainsFold("ELL")

func (*String) DateTime deprecated

func (s *String) DateTime(layout ...string) *DateTime

Deprecated: use AsDateTime instead.

func (*String) Decode added in v2.10.0

func (s *String) Decode(target interface{}) *String

Decode unmarshals the underlying value attached to the String to a target variable. target should be one of these:

  • pointer to an empty interface
  • pointer to a string

Example:

value := NewString(t, "foo")

var target string
value.Decode(&target)

assert.Equal(t, "foo", target)

func (*String) Empty deprecated

func (s *String) Empty() *String

Deprecated: use IsEmpty instead.

func (*String) Equal deprecated

func (s *String) Equal(value string) *String

Deprecated: use IsEqual instead.

func (*String) EqualFold deprecated

func (s *String) EqualFold(value string) *String

Deprecated: use IsEqualFold instead.

func (*String) HasPrefix added in v2.7.0

func (s *String) HasPrefix(value string) *String

HasPrefix succeeds if string has given Go string as prefix

Example:

str := NewString(t, "Hello World")
str.HasPrefix("Hello")

func (*String) HasPrefixFold added in v2.7.0

func (s *String) HasPrefixFold(value string) *String

HasPrefixFold succeeds if string has given Go string as prefix after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello World")
str.HasPrefixFold("hello")

func (*String) HasSuffix added in v2.7.0

func (s *String) HasSuffix(value string) *String

HasSuffix succeeds if string has given Go string as suffix

Example:

str := NewString(t, "Hello World")
str.HasSuffix("World")

func (*String) HasSuffixFold added in v2.7.0

func (s *String) HasSuffixFold(value string) *String

HasSuffixFold succeeds if string has given Go string as suffix after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello World")
str.HasSuffixFold("world")

func (*String) InList added in v2.11.0

func (s *String) InList(values ...string) *String

InList succeeds if the string is equal to one of the values from given list of strings.

Example:

str := NewString(t, "Hello")
str.InList("Hello", "Goodbye")

func (*String) InListFold added in v2.12.0

func (s *String) InListFold(values ...string) *String

InListFold succeeds if the string is equal to one of the values from given list of strings after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello")
str.InListFold("hEllo", "Goodbye")

func (*String) IsASCII added in v2.8.0

func (s *String) IsASCII() *String

IsASCII succeeds if all string characters belongs to ASCII.

Example:

str := NewString(t, "Hello")
str.IsASCII()

func (*String) IsEmpty added in v2.11.0

func (s *String) IsEmpty() *String

IsEmpty succeeds if string is empty.

Example:

str := NewString(t, "")
str.IsEmpty()

func (*String) IsEqual added in v2.11.0

func (s *String) IsEqual(value string) *String

IsEqual succeeds if string is equal to given Go string.

Example:

str := NewString(t, "Hello")
str.IsEqual("Hello")

func (*String) IsEqualFold added in v2.11.0

func (s *String) IsEqualFold(value string) *String

IsEqualFold succeeds if string is equal to given Go string after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello")
str.IsEqualFold("hELLo")

func (*String) Length

func (s *String) Length() *Number

Length returns a new Number instance with string length.

Example:

str := NewString(t, "Hello")
str.Length().IsEqual(5)

func (*String) Match

func (s *String) Match(re string) *Match

Match matches the string with given regexp and returns a new Match instance with found submatches.

If regexp is invalid or string doesn't match regexp, Match fails and returns empty (but non-nil) instance. regexp.Compile is used to construct regexp, and Regexp.FindStringSubmatch is used to construct matches.

Example:

s := NewString(t, "http://example.com/users/john")
m := s.Match(`http://(?P<host>.+)/users/(?P<user>.+)`)

m.NotEmpty()
m.Length().IsEqual(3)

m.Index(0).IsEqual("http://example.com/users/john")
m.Index(1).IsEqual("example.com")
m.Index(2).IsEqual("john")

m.Name("host").IsEqual("example.com")
m.Name("user").IsEqual("john")

func (*String) MatchAll

func (s *String) MatchAll(re string) []Match

MatchAll find all matches in string for given regexp and returns a list of found matches.

If regexp is invalid or string doesn't match regexp, MatchAll fails and returns empty (but non-nil) slice. regexp.Compile is used to construct regexp, and Regexp.FindAllStringSubmatch is used to find matches.

Example:

s := NewString(t,
   "http://example.com/users/john http://example.com/users/bob")

m := s.MatchAll(`http://(?P<host>\S+)/users/(?P<user>\S+)`)

m[0].Name("user").IsEqual("john")
m[1].Name("user").IsEqual("bob")

func (*String) NotASCII added in v2.9.0

func (s *String) NotASCII() *String

NotASCII succeeds if at least one string character does not belong to ASCII.

Example:

str := NewString(t, "こんにちは")
str.NotASCII()

func (*String) NotContains

func (s *String) NotContains(value string) *String

NotContains succeeds if string doesn't contain Go string as a substring.

Example:

str := NewString(t, "Hello")
str.NotContains("bye")

func (*String) NotContainsFold

func (s *String) NotContainsFold(value string) *String

NotContainsFold succeeds if string doesn't contain given Go string as a substring after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello")
str.NotContainsFold("BYE")

func (*String) NotEmpty

func (s *String) NotEmpty() *String

NotEmpty succeeds if string is non-empty.

Example:

str := NewString(t, "Hello")
str.NotEmpty()

func (*String) NotEqual

func (s *String) NotEqual(value string) *String

NotEqual succeeds if string is not equal to given Go string.

Example:

str := NewString(t, "Hello")
str.NotEqual("Goodbye")

func (*String) NotEqualFold

func (s *String) NotEqualFold(value string) *String

NotEqualFold succeeds if string is not equal to given Go string after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello")
str.NotEqualFold("gOODBYe")

func (*String) NotHasPrefix added in v2.7.0

func (s *String) NotHasPrefix(value string) *String

NotHasPrefix succeeds if string doesn't have given Go string as prefix

Example:

str := NewString(t, "Hello World")
str.NotHasPrefix("Bye")

func (*String) NotHasPrefixFold added in v2.7.0

func (s *String) NotHasPrefixFold(value string) *String

NotHasPrefixFold succeeds if string doesn't have given Go string as prefix after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello World")
str.NotHasPrefixFold("Bye")

func (*String) NotHasSuffix added in v2.7.0

func (s *String) NotHasSuffix(value string) *String

NotHasSuffix succeeds if string doesn't have given Go string as suffix

Example:

str := NewString(t, "Hello World")
str.NotHasSuffix("Hello")

func (*String) NotHasSuffixFold added in v2.7.0

func (s *String) NotHasSuffixFold(value string) *String

NotHasSuffixFold succeeds if string doesn't have given Go string as suffix after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello World")
str.NotHasSuffixFold("Bye")

func (*String) NotInList added in v2.11.0

func (s *String) NotInList(values ...string) *String

NotInList succeeds if the string is not equal to any of the values from given list of strings.

Example:

str := NewString(t, "Hello")
str.NotInList("Sayonara", "Goodbye")

func (*String) NotInListFold added in v2.12.0

func (s *String) NotInListFold(values ...string) *String

NotInListFold succeeds if the string is not equal to any of the values from given list of strings after applying Unicode case-folding (so it's a case-insensitive match).

Example:

str := NewString(t, "Hello")
str.NotInListFold("Bye", "Goodbye")

func (*String) NotIsASCII deprecated added in v2.8.0

func (s *String) NotIsASCII() *String

Deprecated: use NotASCII instead.

func (*String) NotMatch

func (s *String) NotMatch(re string) *String

NotMatch succeeds if the string doesn't match to given regexp.

regexp.Compile is used to construct regexp, and Regexp.MatchString is used to perform match.

Example:

s := NewString(t, "a")
s.NotMatch(`[^a]`)

func (*String) Number deprecated added in v2.4.0

func (s *String) Number() *Number

Deprecated: use AsNumber instead.

func (*String) Path

func (s *String) Path(path string) *Value

Path is similar to Value.Path.

func (*String) Raw

func (s *String) Raw() string

Raw returns underlying value attached to String. This is the value originally passed to NewString.

Example:

str := NewString(t, "Hello")
assert.Equal(t, "Hello", str.Raw())

func (*String) Schema

func (s *String) Schema(schema interface{}) *String

Schema is similar to Value.Schema.

type TestingTB added in v2.5.0

type TestingTB interface {
	Reporter
	Logger
	Name() string // Returns current test name.
}

TestingTB is a subset of testing.TB interface used by httpexpect. You can use *testing.T or pass custom implementation.

type Value

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

Value provides methods to inspect attached interface{} object (Go representation of arbitrary JSON value) and cast it to concrete type.

func NewValue

func NewValue(reporter Reporter, value interface{}) *Value

NewValue returns a new Value instance.

If reporter is nil, the function panics. Value may be nil.

Example:

value := NewValue(t, map[string]interface{}{"foo": 123})
value.IsObject()

value := NewValue(t, []interface{}{"foo", 123})
value.IsArray()

value := NewValue(t, "foo")
value.IsString()

value := NewValue(t, 123)
value.IsNumber()

value := NewValue(t, true)
value.IsBoolean()

value := NewValue(t, nil)
value.IsNull()

func NewValueC added in v2.9.0

func NewValueC(config Config, value interface{}) *Value

NewValueC returns a new Value instance with config.

Requirements for config are same as for WithConfig function. Value may be nil.

See NewValue for usage example.

func (*Value) Alias added in v2.10.0

func (v *Value) Alias(name string) *Value

Alias returns a new Value object with alias. When a test of Value object with alias is failed, an assertion is displayed as a chain starting from the alias.

Example:

// In this example, GET /example responds "foo"
foo := e.GET("/example").Expect().Status(http.StatusOK).JSON().Object()

// When a test is failed, an assertion without alias is
// Request("GET").Expect().JSON().Object().IsEqual()
foo.IsEqual("bar")

// Set Alias
fooWithAlias := e.GET("/example").
	Expect().
	Status(http.StatusOK).JSON().Object().Alias("foo")

// When a test is failed, an assertion with alias is
// foo.IsEqual()
fooWithAlias.IsEqual("bar")

func (*Value) Array

func (v *Value) Array() *Array

Array returns a new Array attached to underlying value.

If underlying value is not an array ([]interface{}), failure is reported and empty (but non-nil) value is returned.

Example:

value := NewValue(t, []interface{}{"foo", 123})
value.Array().ConsistsOf("foo", 123)

func (*Value) Boolean

func (v *Value) Boolean() *Boolean

Boolean returns a new Boolean attached to underlying value.

If underlying value is not a bool, failure is reported and empty (but non-nil) value is returned.

Example:

value := NewValue(t, true)
value.Boolean().IsTrue()

func (*Value) Decode added in v2.11.0

func (v *Value) Decode(target interface{}) *Value

Decode unmarshals the underlying value attached to the Object to a target variable target should be pointer to any type.

Example:

type S struct {
	Foo int             `json:"foo"`
	Bar []interface{}   `json:"bar"`
	Baz struct{ A int } `json:"baz"`
}

m := map[string]interface{}{
	"foo": 123,
	"bar": []interface{}{"123", 456.0},
	"baz": struct{ A int }{123},
}

value = NewValue(reporter,m)

var target S
value.Decode(&target)

assert.Equal(t, S{123, []interface{}{"123", 456.0}, struct{ A int }{123}, target})

func (*Value) Equal deprecated

func (v *Value) Equal(value interface{}) *Value

Deprecated: use IsEqual instead.

func (*Value) InList added in v2.11.0

func (v *Value) InList(values ...interface{}) *Value

InList succeeds if whole value is equal to one of the values from given list of values (e.g. map, slice, string, etc). Before comparison, all values are converted to canonical form.

If at least one value has wrong type, failure is reported.

Example:

value := NewValue(t, "foo")
value.InList("foo", 123)

func (*Value) IsArray added in v2.11.0

func (v *Value) IsArray() *Value

IsArray succeeds if the underlying value is an array.

If underlying value is not an array ([]interface{}), failure is reported.

Example:

value := NewValue(t, []interface{}{"foo", "123"})
value.IsArray()

func (*Value) IsBoolean added in v2.11.0

func (v *Value) IsBoolean() *Value

IsBoolean succeeds if the underlying value is a boolean.

If underlying value is not a boolean, failure is reported.

Example:

value := NewValue(t, true)
value.IsBoolean()

func (*Value) IsEqual added in v2.11.0

func (v *Value) IsEqual(value interface{}) *Value

IsEqual succeeds if value is equal to another value (e.g. map, slice, string, etc). Before comparison, both values are converted to canonical form.

Example:

value := NewValue(t, "foo")
value.IsEqual("foo")

func (*Value) IsNull added in v2.12.0

func (v *Value) IsNull() *Value

IsNull succeeds if value is nil.

Note that non-nil interface{} that points to nil value (e.g. nil slice or map) is also treated as null value. Empty (non-nil) slice or map, empty string, and zero number are not treated as null value.

Example:

value := NewValue(t, nil)
value.IsNull()

value := NewValue(t, []interface{}(nil))
value.IsNull()

func (*Value) IsNumber added in v2.11.0

func (v *Value) IsNumber() *Value

IsNumber succeeds if the underlying value is a number.

If underlying value is not a number (numeric type convertible to float64), failure is reported

Example:

value := NewValue(t, 123)
value.IsNumber()

func (*Value) IsObject added in v2.11.0

func (v *Value) IsObject() *Value

IsObject succeeds if the underlying value is an object.

If underlying value is not an object (map[string]interface{}), failure is reported.

Example:

value := NewValue(t, map[string]interface{}{"foo": 123})
value.IsObject()

func (*Value) IsString added in v2.11.0

func (v *Value) IsString() *Value

IsString succeeds if the underlying value is a string.

If underlying value is not a string, failure is reported.

Example:

value := NewValue(t, "foo")
value.IsString()

func (*Value) NotArray added in v2.11.0

func (v *Value) NotArray() *Value

NotArray succeeds if the underlying value is not an array.

If underlying value is an array ([]interface{}), failure is reported.

Example:

value := NewValue(t, nil)
value.NotArray()

func (*Value) NotBoolean added in v2.11.0

func (v *Value) NotBoolean() *Value

NotBoolean succeeds if the underlying value is not a boolean.

If underlying value is a boolean, failure is reported.

Example:

value := NewValue(t, nil)
value.NotBoolean()

func (*Value) NotEqual

func (v *Value) NotEqual(value interface{}) *Value

NotEqual succeeds if value is not equal to another value (e.g. map, slice, string, etc). Before comparison, both values are converted to canonical form.

Example:

value := NewValue(t, "foo")
value.NorEqual("bar")

func (*Value) NotInList added in v2.11.0

func (v *Value) NotInList(values ...interface{}) *Value

NotInList succeeds if the whole value is not equal to any of the values from given list of values (e.g. map, slice, string, etc). Before comparison, all values are converted to canonical form.

If at least one value has wrong type, failure is reported.

Example:

value := NewValue(t, "foo")
value.NotInList("bar", 123)

func (*Value) NotNull

func (v *Value) NotNull() *Value

NotNull succeeds if value is not nil.

Note that non-nil interface{} that points to nil value (e.g. nil slice or map) is also treated as null value. Empty (non-nil) slice or map, empty string, and zero number are not treated as null value.

Example:

value := NewValue(t, "")
value.NotNull()

value := NewValue(t, make([]interface{}, 0))
value.NotNull()

func (*Value) NotNumber added in v2.11.0

func (v *Value) NotNumber() *Value

NotNumber succeeds if the underlying value is a not a number.

If underlying value is a number (numeric type convertible to float64), failure is reported

Example:

value := NewValue(t, nil)
value.NotNumber()

func (*Value) NotObject added in v2.11.0

func (v *Value) NotObject() *Value

NotObject succeeds if the underlying value is not an object.

If underlying value is an object (map[string]interface{}), failure is reported.

Example:

value := NewValue(t, nil)
value.NotObject()

func (*Value) NotString added in v2.11.0

func (v *Value) NotString() *Value

NotString succeeds if the underlying value is not a string.

If underlying value is a string, failure is reported.

Example:

value := NewValue(t, nil)
value.NotString()

func (*Value) Null deprecated

func (v *Value) Null() *Value

Deprecated: use IsNull instead.

func (*Value) Number

func (v *Value) Number() *Number

Number returns a new Number attached to underlying value.

If underlying value is not a number (numeric type convertible to float64), failure is reported and empty (but non-nil) value is returned.

Example:

value := NewValue(t, 123)
value.Number().InRange(100, 200)

func (*Value) Object

func (v *Value) Object() *Object

Object returns a new Object attached to underlying value.

If underlying value is not an object (map[string]interface{}), failure is reported and empty (but non-nil) value is returned.

Example:

value := NewValue(t, map[string]interface{}{"foo": 123})
value.Object().ContainsKey("foo")

func (*Value) Path

func (v *Value) Path(path string) *Value

Path returns a new Value object for child object(s) matching given JSONPath expression.

JSONPath is a simple XPath-like query language. See http://goessner.net/articles/JsonPath/.

We currently use https://github.com/yalp/jsonpath, which implements only a subset of JSONPath, yet useful for simple queries. It doesn't support filters and requires double quotes for strings.

Example 1:

json := `{"users": [{"name": "john"}, {"name": "bob"}]}`
value := NewValue(t, json)

value.Path("$.users[0].name").String().IsEqual("john")
value.Path("$.users[1].name").String().IsEqual("bob")

Example 2:

json := `{"yfGH2a": {"user": "john"}, "f7GsDd": {"user": "john"}}`
value := NewValue(t, json)

for _, user := range value.Path("$..user").Array().Iter() {
	user.String().IsEqual("john")
}

func (*Value) Raw

func (v *Value) Raw() interface{}

Raw returns underlying value attached to Value. This is the value originally passed to NewValue, converted to canonical form.

Example:

value := NewValue(t, "foo")
assert.Equal(t, "foo", number.Raw().(string))

func (*Value) Schema

func (v *Value) Schema(schema interface{}) *Value

Schema succeeds if value matches given JSON Schema.

JSON Schema specifies a JSON-based format to define the structure of JSON data. See http://json-schema.org/. We use https://github.com/xeipuuv/gojsonschema implementation.

schema should be one of the following:

  • go value that can be json.Marshal-ed to a valid schema
  • type convertible to string containing valid schema
  • type convertible to string containing valid http:// or file:// URI, pointing to reachable and valid schema

Example 1:

 schema := `{
   "type": "object",
   "properties": {
	  "foo": {
		  "type": "string"
	  },
	  "bar": {
		  "type": "integer"
	  }
  },
  "require": ["foo", "bar"]
}`

value := NewValue(t, map[string]interface{}{
	"foo": "a",
	"bar": 1,
})

value.Schema(schema)

Example 2:

value := NewValue(t, data)
value.Schema("http://example.com/schema.json")

func (*Value) String

func (v *Value) String() *String

String returns a new String attached to underlying value.

If underlying value is not a string, failure is reported and empty (but non-nil) value is returned.

Example:

value := NewValue(t, "foo")
value.String().IsEqualFold("FOO")

type Websocket

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

Websocket provides methods to read from, write into and close WebSocket connection.

func NewWebsocket deprecated

func NewWebsocket(config Config, conn WebsocketConn) *Websocket

Deprecated: use NewWebsocketC instead.

func NewWebsocketC added in v2.9.0

func NewWebsocketC(config Config, conn WebsocketConn) *Websocket

NewWebsocketC returns a new Websocket instance.

Requirements for config are same as for WithConfig function.

func (*Websocket) Alias added in v2.10.0

func (ws *Websocket) Alias(name string) *Websocket

Alias is similar to Value.Alias.

func (*Websocket) Close

func (ws *Websocket) Close(code ...int) *Websocket

Close cleanly closes the underlying WebSocket connection by sending an empty close message and then waiting (with timeout) for the server to close the connection.

WebSocket close code may be optionally specified. If not, then "1000 - Normal Closure" will be used.

WebSocket close codes are defined in RFC 6455, section 11.7. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

It's okay to call this function multiple times.

Example:

conn := resp.Connection()
conn.Close(websocket.CloseUnsupportedData)

func (*Websocket) CloseWithBytes

func (ws *Websocket) CloseWithBytes(b []byte, code ...int) *Websocket

CloseWithBytes cleanly closes the underlying WebSocket connection by sending given slice of bytes as a close message and then waiting (with timeout) for the server to close the connection.

WebSocket close code may be optionally specified. If not, then "1000 - Normal Closure" will be used.

WebSocket close codes are defined in RFC 6455, section 11.7. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

It's okay to call this function multiple times.

Example:

conn := resp.Connection()
conn.CloseWithBytes([]byte("bye!"), websocket.CloseGoingAway)

func (*Websocket) CloseWithJSON

func (ws *Websocket) CloseWithJSON(
	object interface{}, code ...int,
) *Websocket

CloseWithJSON cleanly closes the underlying WebSocket connection by sending given object (marshaled using json.Marshal()) as a close message and then waiting (with timeout) for the server to close the connection.

WebSocket close code may be optionally specified. If not, then "1000 - Normal Closure" will be used.

WebSocket close codes are defined in RFC 6455, section 11.7. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

It's okay to call this function multiple times.

Example:

type MyJSON struct {
  Foo int `json:"foo"`
}

conn := resp.Connection()
conn.CloseWithJSON(MyJSON{Foo: 123}, websocket.CloseUnsupportedData)

func (*Websocket) CloseWithText

func (ws *Websocket) CloseWithText(s string, code ...int) *Websocket

CloseWithText cleanly closes the underlying WebSocket connection by sending given text as a close message and then waiting (with timeout) for the server to close the connection.

WebSocket close code may be optionally specified. If not, then "1000 - Normal Closure" will be used.

WebSocket close codes are defined in RFC 6455, section 11.7. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

It's okay to call this function multiple times.

Example:

conn := resp.Connection()
conn.CloseWithText("bye!")

func (*Websocket) Conn added in v2.2.0

func (ws *Websocket) Conn() WebsocketConn

Conn returns underlying WebsocketConn object. This is the value originally passed to NewConnection.

func (*Websocket) Disconnect

func (ws *Websocket) Disconnect() *Websocket

Disconnect closes the underlying WebSocket connection without sending or waiting for a close message.

It's okay to call this function multiple times.

It's recommended to always call this function after connection usage is over to ensure that no resource leaks will happen.

Example:

conn := resp.Connection()
defer conn.Disconnect()

func (*Websocket) Expect

func (ws *Websocket) Expect() *WebsocketMessage

Expect reads next message from WebSocket connection and returns a new WebsocketMessage instance.

Example:

msg := conn.Expect()
msg.JSON().Object().HasValue("message", "hi")

func (*Websocket) Raw deprecated

func (ws *Websocket) Raw() *websocket.Conn

Deprecated: use Conn instead.

func (*Websocket) Subprotocol

func (ws *Websocket) Subprotocol() *String

Subprotocol returns a new String instance with negotiated protocol for the connection.

func (*Websocket) WithReadTimeout

func (ws *Websocket) WithReadTimeout(timeout time.Duration) *Websocket

WithReadTimeout sets timeout duration for WebSocket connection reads.

By default no timeout is used.

func (*Websocket) WithWriteTimeout

func (ws *Websocket) WithWriteTimeout(timeout time.Duration) *Websocket

WithWriteTimeout sets timeout duration for WebSocket connection writes.

By default no timeout is used.

func (*Websocket) WithoutReadTimeout

func (ws *Websocket) WithoutReadTimeout() *Websocket

WithoutReadTimeout removes timeout for WebSocket connection reads.

func (*Websocket) WithoutWriteTimeout

func (ws *Websocket) WithoutWriteTimeout() *Websocket

WithoutWriteTimeout removes timeout for WebSocket connection writes.

If not used then DefaultWebsocketTimeout will be used.

func (*Websocket) WriteBytesBinary

func (ws *Websocket) WriteBytesBinary(b []byte) *Websocket

WriteBytesBinary is a shorthand for c.WriteMessage(websocket.BinaryMessage, b).

func (*Websocket) WriteBytesText

func (ws *Websocket) WriteBytesText(b []byte) *Websocket

WriteBytesText is a shorthand for c.WriteMessage(websocket.TextMessage, b).

func (*Websocket) WriteJSON

func (ws *Websocket) WriteJSON(object interface{}) *Websocket

WriteJSON writes to the underlying WebSocket connection given object, marshaled using json.Marshal().

func (*Websocket) WriteMessage

func (ws *Websocket) WriteMessage(typ int, content []byte, closeCode ...int) *Websocket

WriteMessage writes to the underlying WebSocket connection a message of given type with given content. Additionally, WebSocket close code may be specified for close messages.

WebSocket message types are defined in RFC 6455, section 11.8. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

WebSocket close codes are defined in RFC 6455, section 11.7. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

Example:

conn := resp.Connection()
conn.WriteMessage(websocket.CloseMessage, []byte("Namárië..."))

func (*Websocket) WriteText

func (ws *Websocket) WriteText(s string) *Websocket

WriteText is a shorthand for c.WriteMessage(websocket.TextMessage, []byte(s)).

type WebsocketConn added in v2.2.0

type WebsocketConn interface {
	ReadMessage() (messageType int, p []byte, err error)
	WriteMessage(messageType int, data []byte) error
	Close() error
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
	Subprotocol() string
}

WebsocketConn is used by Websocket to communicate with actual WebSocket connection.

type WebsocketDialer

type WebsocketDialer interface {
	// Dial establishes new Websocket connection and returns response
	// of handshake result.
	Dial(url string, reqH http.Header) (*websocket.Conn, *http.Response, error)
}

WebsocketDialer is used to establish websocket.Conn and receive http.Response of handshake result. websocket.Dialer implements this interface.

NewWebsocketDialer and NewFastWebsocketDialer may be used to obtain this interface implementation.

Example:

e := httpexpect.WithConfig(httpexpect.Config{
	WebsocketDialer: httpexpect.NewWebsocketDialer(myHandler),
})

type WebsocketDialerFunc added in v2.15.0

type WebsocketDialerFunc func(
	url string, reqH http.Header,
) (*websocket.Conn, *http.Response, error)

WebsocketDialerFunc is an adapter that allows a function to be used as the WebsocketDialer

Example:

e := httpexpect.WithConfig(httpexpect.Config{
	WebsocketDialer: httpextect.WebsocketDialerFunc(
		func(url string, reqH http.Header) (*websocket.Conn, *http.Response, error) {
			// dialer code here
		}),
})

func (WebsocketDialerFunc) Dial added in v2.15.0

func (f WebsocketDialerFunc) Dial(
	url string, reqH http.Header,
) (*websocket.Conn, *http.Response, error)

type WebsocketMessage

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

WebsocketMessage provides methods to inspect message read from WebSocket connection.

func NewWebsocketMessage

func NewWebsocketMessage(
	reporter Reporter, typ int, content []byte, closeCode ...int,
) *WebsocketMessage

NewWebsocketMessage returns a new WebsocketMessage instance.

If reporter is nil, the function panics. Content may be nil.

Example:

m := NewWebsocketMessage(t, websocket.TextMessage, []byte("content"), 0)
m.TextMessage()

func NewWebsocketMessageC added in v2.9.0

func NewWebsocketMessageC(
	config Config, typ int, content []byte, closeCode ...int,
) *WebsocketMessage

NewWebsocketMessageC returns a new WebsocketMessage instance with config.

Requirements for config are same as for WithConfig function. Content may be nil.

Example:

m := NewWebsocketMessageC(config, websocket.TextMessage, []byte("content"), 0)
m.TextMessage()

func (*WebsocketMessage) Alias added in v2.10.0

func (wm *WebsocketMessage) Alias(name string) *WebsocketMessage

Alias is similar to Value.Alias.

func (*WebsocketMessage) BinaryMessage

func (wm *WebsocketMessage) BinaryMessage() *WebsocketMessage

BinaryMessage is a shorthand for m.Type(websocket.BinaryMessage).

func (*WebsocketMessage) Body

func (wm *WebsocketMessage) Body() *String

Body returns a new String instance with WebSocket message content.

Example:

msg := conn.Expect()
msg.Body().NotEmpty()
msg.Body().Length().IsEqual(100)

func (*WebsocketMessage) CloseMessage

func (wm *WebsocketMessage) CloseMessage() *WebsocketMessage

CloseMessage is a shorthand for m.Type(websocket.CloseMessage).

func (*WebsocketMessage) Code

func (wm *WebsocketMessage) Code(codes ...int) *WebsocketMessage

Code succeeds if WebSocket close code is one of the given.

Code fails if WebSocket message type is not "8 - Connection Close Frame".

WebSocket close codes are defined in RFC 6455, section 11.7. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

Example:

msg := conn.Expect().Closed()
msg.Code(websocket.CloseNormalClosure, websocket.CloseGoingAway)

func (*WebsocketMessage) JSON

func (wm *WebsocketMessage) JSON() *Value

JSON returns a new Value instance with JSON contents of WebSocket message.

JSON succeeds if JSON may be decoded from message content.

Example:

msg := conn.Expect()
msg.JSON().Array().ConsistsOf("foo", "bar")

func (*WebsocketMessage) NoContent

func (wm *WebsocketMessage) NoContent() *WebsocketMessage

NoContent succeeds if WebSocket message has no content (is empty).

func (*WebsocketMessage) NotBinaryMessage

func (wm *WebsocketMessage) NotBinaryMessage() *WebsocketMessage

NotBinaryMessage is a shorthand for m.NotType(websocket.BinaryMessage).

func (*WebsocketMessage) NotCloseMessage

func (wm *WebsocketMessage) NotCloseMessage() *WebsocketMessage

NotCloseMessage is a shorthand for m.NotType(websocket.CloseMessage).

func (*WebsocketMessage) NotCode

func (wm *WebsocketMessage) NotCode(codes ...int) *WebsocketMessage

NotCode succeeds if WebSocket close code is none of the given.

NotCode fails if WebSocket message type is not "8 - Connection Close Frame".

WebSocket close codes are defined in RFC 6455, section 11.7. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

Example:

msg := conn.Expect().Closed()
msg.NotCode(websocket.CloseAbnormalClosure, websocket.CloseNoStatusReceived)

func (*WebsocketMessage) NotTextMessage

func (wm *WebsocketMessage) NotTextMessage() *WebsocketMessage

NotTextMessage is a shorthand for m.NotType(websocket.TextMessage).

func (*WebsocketMessage) NotType

func (wm *WebsocketMessage) NotType(types ...int) *WebsocketMessage

NotType succeeds if WebSocket message type is none of the given.

WebSocket message types are defined in RFC 6455, section 11.8. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

Example:

msg := conn.Expect()
msg.NotType(websocket.CloseMessage, websocket.BinaryMessage)

func (*WebsocketMessage) Raw

func (wm *WebsocketMessage) Raw() (typ int, content []byte, closeCode int)

Raw returns underlying type, content and close code of WebSocket message. Theses values are originally read from WebSocket connection.

func (*WebsocketMessage) TextMessage

func (wm *WebsocketMessage) TextMessage() *WebsocketMessage

TextMessage is a shorthand for m.Type(websocket.TextMessage).

func (*WebsocketMessage) Type

func (wm *WebsocketMessage) Type(types ...int) *WebsocketMessage

Type succeeds if WebSocket message type is one of the given.

WebSocket message types are defined in RFC 6455, section 11.8. See also https://godoc.org/github.com/gorilla/websocket#pkg-constants

Example:

msg := conn.Expect()
msg.Type(websocket.TextMessage, websocket.BinaryMessage)

type WebsocketPrinter

type WebsocketPrinter interface {
	Printer

	// WebsocketWrite is called before writes to WebSocket connection.
	WebsocketWrite(typ int, content []byte, closeCode int)

	// WebsocketRead is called after reads from WebSocket connection.
	WebsocketRead(typ int, content []byte, closeCode int)
}

WebsocketPrinter is used to print writes and reads of WebSocket connection.

If WebSocket connection is used, all Printers that also implement WebsocketPrinter are invoked on every WebSocket message read or written.

DebugPrinter implements this interface.

Jump to

Keyboard shortcuts

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