httpx

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2020 License: MIT Imports: 5 Imported by: 0

README

httpx

Go v1.13 Godoc No added preservatives

Simple :bowtie:, elegant ❄ and concise 🎯 tests for those HTTP endpoints in Go!

Overview

httpx provides a minimal, yet powerful, function-driven framework to write simple and concise tests for HTTP, that reads like poem 🎶

The primary motivation is to enable developers to write self-describing and concise test cases, that also serves as documentation.

Using httpx, you can write your test cases like,

import (
  . "go.riyazali.net/httpx"
  "testing"
)

func TestHttpbinGet(t *testing.T) {
  WithDefaultClient().
    MakeRequest(
      Get(Url("https://httpbin.org/get", WithQueryParam("a", "1"))),
      WithHeader("Accept", "application/json"),
    ).
    ExpectIt(t,
      ToHaveStatus(http.StatusOK),
    )
}

httpx is quite versatile and allows you to use the same set of methods whether you are testing a remote endpoint (using WithClient(...)) or a local handler (using WithHandler(...)) 🎉

Usage

To use it, first install it using

go get -u go.riyazali.net/httpx

httpx defines a set of core types all of which plugs into one another to provide a simple and cohesive framework.

The primary entry point into the framework is the ExecFn which defines any function capable of executing an http transaction (take an http.Request and return an http.Response). The core library provides two Execfn functions, WithClient(..) and WithHandler(..) (and some variations of those two).

After creating the ExecFn, you would normally want to call it's MakeRequest method, which would allow you to craft an http.Request and invoke the corresponding ExecFn on it. See RequestFactory and RequestBuilder for details on how to craft a custom request, the set of built-in factories and builders the library provides and how you can write your own!

Once you've crafted a request, MakeRequest would return an Assertable which you could then use to perform assertions on the received http.Response. See Assertion for more details.

And that's pretty much it! that's the core of the library! roughly ~120 lines of code (give or take 😉)

Example

This example demonstrates how you would use httpx to make a GET request to httpbin.org and carry out assertions on the received http.Response.

import (
  . "go.riyazali.net/httpx"
  . "go.riyazali.net/httpx/helpers"
  "net/http"
  "testing"
)

func TestRemote(t *testing.T) {
  type X struct {
    Args map[string]string `json:"args"`
  }

  WithDefaultClient().
    MakeRequest(
      Get(Url("https://httpbin.org/get", WithQueryParam("a", "1"))),
      WithHeader("Accept", "application/json"),
    ).
    ExpectIt(t,
      ToHaveStatus(http.StatusOK),
      BodyJson(func(x X) error {
        return Multiple(
          AssertThat(x.Args["a"] != "", "'a' is empty"),
          AssertThat(x.Args["b"] == "", "'b' is present"),
        )
      }),
    )
}

For more examples and samples, make sure to checkout the godoc here

Documentation

Overview

Package httpx provides an expressive framework to test http endpoints and handlers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Assertable

type Assertable func(TestingT, ...Assertion)

Assertable defines a function that can take a slice of assertions and apply it on http.Response.

Although exported, user's won't be able to do much with this type. Instead they should use the ExpectIt(...) method to allow fluent chaining with MakeRequest(...).

func (Assertable) ExpectIt

func (a Assertable) ExpectIt(t TestingT, assertions ...Assertion)

ExpectIt allows us to implement fluent chaining with MakeRequest(...). Use this method instead of directly invoking the Assertable to improve readability of your code.

type Assertion

type Assertion func(*http.Response) error

Assertion defines a function that performs some sort of assertion on the response to make sure that request was executed as expected.

type ExecFn

type ExecFn func(*http.Request) (*http.Response, error)

ExecFn defines a function that can take an http.Request and return an http.Response (and optionally, an error).

This is the core type defined by this package and instances of this type does the actual heavy lifting work of making the request, receiving responses and more. How the actual execution is done is left to the implementation. Some may make actual http calls to remote endpoint whereas others would call in-memory http.Handler.

The core package provides two implementations that works with net/http package.

func (ExecFn) MakeRequest

func (fn ExecFn) MakeRequest(factory RequestFactory, builders ...RequestBuilder) Assertable

MakeRequest is the primary entry point into the framework.

This method builds a request object, apply the given customisations / builders to it and then pass it to the ExecFn for execution returning an Assertable which you can then use to perform assertions on the response etc.

The core library provides certain general purpose builders. See RequestBuilder and it's implementations for more details on builders and how you can create a custom builder.

type RequestBuilder

type RequestBuilder func(*http.Request) error

RequestBuilder defines a function that customises the request before it's sent out.

type RequestFactory

type RequestFactory func() (*http.Request, error)

RequestFactory defines a function capable of creating http.Request instances. Use of this type allows us to decouple MakeRequest(...) from the actual underlying mechanism of building an http.Request. Implementations of this type could (say) create instances configured for a PaaS (like Google App Engine) and more.

The core library provides a default implementation which should be sufficient for most use cases.

func Delete

func Delete(url string) RequestFactory

Delete is a shorthand method to create a RequestFactory with http.MethodDelete

func Get

func Get(url string) RequestFactory

Get is a shorthand method to create a RequestFactory with http.MethodGet

func Post

func Post(url string, body io.Reader) RequestFactory

Post is a shorthand method to create a RequestFactory with http.MethodPost

func Put

func Put(url string, body io.Reader) RequestFactory

Put is a shorthand method to create a RequestFactory with http.MethodPut

func Using

func Using(method, url string, body io.Reader) RequestFactory

Using returns a RequestFactory which is a wrapper over the default http.NewRequest method

type TestingT

type TestingT interface {
	Errorf(format string, args ...interface{})
	FailNow()
	Helper()
}

TestingT allows us to decouple our code from the actual testing.T type. Most end user shouldn't care about it.

Directories

Path Synopsis
Package assertions provides set of handy assertions for httpx.
Package assertions provides set of handy assertions for httpx.
Package builders provides set of handy request builders for httpx.
Package builders provides set of handy request builders for httpx.
Package executors provides default httpx.ExecFn based on Go standard library.
Package executors provides default httpx.ExecFn based on Go standard library.

Jump to

Keyboard shortcuts

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