# README
go-hit
hit is an http integration test framework written in golang.
It is designed to be flexible as possible, but to keep a simple to use interface for developers.
So lets get started!
go get -u github.com/Eun/go-hit
package main
import (
"net/http"
. "github.com/Eun/go-hit"
)
func main() {
MustDo(
Description("Post to httpbin.org"),
Get("https://httpbin.org/post"),
Expect().Status().Equal(http.StatusMethodNotAllowed),
Expect().Body().String().Contains("Method Not Allowed"),
)
}
Or use the Test()
function:
package main_test
import (
"testing"
"net/http"
. "github.com/Eun/go-hit"
)
func TestHttpBin(t *testing.T) {
Test(t,
Description("Post to httpbin.org"),
Get("https://httpbin.org/post"),
Expect().Status().Equal(http.StatusMethodNotAllowed),
Expect().Body().String().Contains("Method Not Allowed"),
)
}
Expect, Expect, Expect, ....
MustDo(
Get("https://httpbin.org/post"),
Expect().Status().Equal(http.StatusMethodNotAllowed),
Expect().Headers("Content-Type").NotEmpty(),
Expect().Body().String().Contains("Method Not Allowed"),
)
Sending Data
MustDo(
Post("https://httpbin.org/post"),
Send().Body().String("Hello HttpBin"),
Expect().Status().Equal(http.StatusOK),
Expect().Body().String().Contains("Hello HttpBin"),
)
Sending And Expecting JSON
MustDo(
Post("https://httpbin.org/post"),
Send().Headers("Content-Type").Add("application/json"),
Send().Body().JSON(map[string][]string{"Foo": []string{"Bar", "Baz"}}),
Expect().Status().Equal(http.StatusOK),
Expect().Body().JSON().JQ(".json.Foo[1]").Equal("Baz"),
)
Storing Data From The Response
var name string
var roles []string
MustDo(
Post("https://httpbin.org/post"),
Send().Headers("Content-Type").Add("application/json"),
Send().Body().JSON(map[string]interface{}{"Name": "Joe", "Roles": []string{"Admin", "Developer"}}),
Expect().Status().Equal(http.StatusOK),
Store().Response().Body().JSON().JQ(".json.Name").In(&name),
Store().Response().Body().JSON().JQ(".json.Roles").In(&roles),
)
fmt.Printf("%s has %d roles\n", name, len(roles))
Problems? Debug
!
MustDo(
Post("https://httpbin.org/post"),
Debug(),
Debug().Response().Body(),
)
Handling Errors
It is possible to handle errors in a custom way.
func login(username, password string) error {
err := Do(
Get("https://httpbin.org/basic-auth/joe/secret"),
Send().Headers("Authorization").Add("Basic " + base64.StdEncoding.EncodeToString([]byte(username + ":" + password))),
Expect().Status().Equal(http.StatusOK),
)
var hitError *Error
if errors.As(err, &hitError) {
if hitError.FailingStepIs(Expect().Status().Equal(http.StatusOK)) {
return errors.New("login failed")
}
}
return err
}
Build the request url manually
MustDo(
Request().Method(http.MethodPost),
Request().URL().Scheme("https"),
Request().URL().Host("httpbin.org"),
Request().URL().Path("/post"),
Request().URL().Query("page").Add(1),
Expect().Status().Equal(200),
Send().Body().String("Hello World"),
Expect().Body().String().Contains("Hello"),
)
Twisted!
Although the following is hard to read it is possible to do!
MustDo(
Post("https://httpbin.org/post"),
Expect().Status().Equal(200),
Send().Body().String("Hello World"),
Expect().Body().String().Contains("Hello"),
)
Custom Send And Expects
MustDo(
Get("https://httpbin.org/get"),
Send().Custom(func(hit Hit) error {
hit.Request().Body().SetStringf("Hello %s", "World")
return nil
}),
Expect().Custom(func(hit Hit) error {
if len(hit.Response().Body().MustString()) <= 0 {
return errors.New("expected the body to be not empty")
}
return nil
}),
Custom(AfterExpectStep, func(Hit) error {
fmt.Println("everything done")
return nil
}),
)
Templates / Multiuse
template := CombineSteps(
Post("https://httpbin.org/post"),
Send().Headers("Content-Type").Add("application/json"),
Expect().Headers("Content-Type").Equal("application/json"),
)
MustDo(
template,
Send().Body().JSON("Hello World"),
)
MustDo(
template,
Send().Body().JSON("Hello Universe"),
)
Clean Previous Steps
Sometimes it is necessary to remove some steps that were added before.
template := CombineSteps(
Get("https://httpbin.org/basic-auth/joe/secret"),
Expect().Status().Equal(http.StatusOK),
)
MustDo(
Description("login with correct credentials"),
template,
Send().Headers("Authorization").Add("Basic " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))),
)
Test(t,
Description("login with incorrect credentials"),
template,
Clear().Expect().Status(),
Expect().Status().Equal(http.StatusUnauthorized),
Send().Headers("Authorization").Add("Basic " + base64.StdEncoding.EncodeToString([]byte("joe:joe"))),
)
More examples can be found in the examples directory
Changelog
0.5.0
- Rehaul the api, make things more explicit
- Fix some issues
Store()
functionality- Generate
Clear()
paths - Infinite
JQ()
functionality - Test
README.md
and documentation parts
0.4.0
- Fixed a double run bug in
CombineSteps
(#3) - Better
Clear
functionality, you can now clear any previous step by prependingClear()
, eg.Do( Get("https://example.com"), Expect().Body("Hello World"), Clear().Expect(), // remove all previous Expect() steps // Clear().Expect().Body("Hello World"), // remove only the Expect().Body("Hello World") step ) // also works for CombineSteps Do( Post("https://example.com"), CombineSteps( Send().Body().String("Hello World"), Expect().Body("Hello World"), ), Clear().Expect(), )
- Simplified
Expect().Header()
use, no moreExpect().Headers()
, everything can now be done in theExpect().Header()
function. - More documentation and examples
hit.Do
andhit.MustDo
for inline steps.- Removal of inline steps (use
hit.Do
andhit.MustDo
)Do( Get("https://example.com"), Expect().Custon(func (hit Hit) { // Expect("Hello World") is invalid now // you must use MustDo() or Do() hit.MustDo( Expect("Hello World"), ) }), )
hit.InsertSteps
to insert steps during runtime
# Packages
Package doctest is a package to help test the hit framework.
Package errortrace provides a method to track function stacktrace and populate it in case of error.
No description provided by the author
No description provided by the author
Package httpbody contains a http body representation with a reusable body that can be consumed multiple times.
# Functions
BaseURL sets the base url for each Connect, Delete, Get, Head, Post, Options, Put, Trace or Method.
Clear can be used to remove previous steps.
CombineSteps combines multiple steps to one.
Connect sets the the method to CONNECT and the specified url.
Context sets the context for the request.
Custom can be used to run custom logic during various steps.
Debug prints the current Request and Response.
Delete sets the the method to DELETE and the specified url.
Description sets a custom description for this test.
Do runs the specified steps and returns error if something was wrong.
Expect provides assertions for the response data, e.g.
Fdebug prints the current Request and Response to the specified writer.
Get sets the the method to GET and the specified url.
Head sets the the method to HEAD and the specified url.
HTTPClient sets the client for the request.
JoinURL joins the specified parts to one url.
Method sets the specified method and url.
MustDo runs the specified steps and panics with the error if something was wrong.
Options sets the the method to OPTIONS and the specified url.
Post sets the the method to POST and the specified url.
Put sets the the method to PUT and the specified url.
Request provides methods to set request parameters.
Return stops the current execution of hit, resulting in ignoring all future steps.
Send sends the specified data as the body payload.
StepCallPath returns the representation of the step that is passed in.
Store stores the current Request or Response.
Test runs the specified steps and calls t.FailNow() if any error occurs during execution.
Trace sets the the method to TRACE and the specified url.
# Constants
AfterExpectStep runs after the Expect() steps.
AfterSendStep runs after the Send() steps, note that this is still before the actual sending process.
BeforeExpectStep runs before the Expect() steps (this is after we got the data from the server).
BeforeSendStep runs before the Send() steps.
ExpectStep runs during the Expect() steps.
SendStep runs during the Send() steps.
# Structs
Error represents the error that will be returned during an execution.
HTTPRequest contains the http.Request and methods to extract/set data for the body.
HTTPResponse contains the http.Response and methods to extract/set data for the body.
# Interfaces
Hit is the interface that will be passed in for Custom() steps.
IClear provides a clear functionality to remove previous steps from running.
IClearExpect provides methods to clear steps.
IClearExpectBody provides methods to clear steps.
IClearExpectBodyJSON provides methods to clear steps.
IClearExpectBodyJSONJQ provides methods to clear steps.
IClearExpectBytes provides methods to clear steps.
IClearExpectFloat32 provides methods to clear steps.
IClearExpectFloat64 provides methods to clear steps.
IClearExpectFormValues provides methods to clear steps.
IClearExpectHeaders provides methods to clear steps.
IClearExpectHeaderValue provides methods to clear steps.
IClearExpectInt provides methods to clear steps.
IClearExpectInt16 provides methods to clear steps.
IClearExpectInt32 provides methods to clear steps.
IClearExpectInt64 provides methods to clear steps.
IClearExpectInt8 provides methods to clear steps.
IClearExpectString provides methods to clear steps.
IClearExpectUint provides methods to clear steps.
IClearExpectUint16 provides methods to clear steps.
IClearExpectUint32 provides methods to clear steps.
IClearExpectUint64 provides methods to clear steps.
IClearExpectUint8 provides methods to clear steps.
IClearSend provides methods to clear steps.
IClearSendBody provides methods to clear steps.
IClearSendFormValues provides methods to clear steps.
IClearSendHeaders provides methods to clear steps.
IDebug provides a debug functionality for the Request and Response.
IDebugBody defines the debug functions that are available for the http request/response body.
IDebugBodyJSON defines the debug functions that are available for the http request/response body in JSON format.
IDebugRequest defines the debug functions that are available for the http request.
IDebugResponse defines the debug functions that are available for the http response.
IExpect provides assertions on the http response.
IExpectBody provides assertions on the http response body.
IExpectBodyJSON provides assertions on the http response json body.
IExpectBodyJSONJQ provides assertions on the http response json body.
IExpectBytes provides assertions for the byte slice type.
IExpectFloat32 provides assertions for the float32 type.
IExpectFloat64 provides assertions for the float64 type.
nolint:dupl // the methods of IExpectFormValues and IExpectHeaders are the same however the comments are different.
nolint:dupl // the methods of IExpectFormValues and IExpectHeaders are the same however the comments are different.
IExpectHeaderValue provides assertions on the http response header value.
IExpectInt provides assertions for the int type.
IExpectInt16 provides assertions for the int16 type.
IExpectInt32 provides assertions for the int32 type.
IExpectInt64 provides assertions for the int64 type.
IExpectInt8 provides assertions for the int8 type.
IExpectString provides assertions for the string type.
IExpectUint provides assertions for the uint type.
IExpectUint16 provides assertions for the uint16 type.
IExpectUint32 provides assertions for the uint32 type.
IExpectUint64 provides assertions for the uint64 type.
IExpectUint8 provides assertions for the uint8 type.
IRequest provides methods to set request url parameters.
IRequestURL provides methods to set request url parameters.
IRequestURLQuery provides methods to send header/trailer.
IRequestURLUser provides methods to set the username and/or password for the request.
ISend provides methods to set request data, such as body or headers.
ISendBody provides methods to set request body.
ISendFormValues provides methods to send form values.
ISendHeaders provides methods to send header/trailer.
IStep defines a hit step.
IStore provides a store functionality for the Request and Response.
IStoreBody defines the functions that can be used to store data from the http request/response body.
IStoreBodyJSON defines the functions that can be used to store data from the http request/response body (in JSON format).
IStoreRequest defines the functions that can be used to store data from the http request.
IStoreResponse defines the functions that can be used to store data from the http response.
IStoreStep defines the In function for the Store() functionality.
IStoreURL defines the functions that can be used to store a URL part.
IStoreUserInfo defines the functions that can be used to store a user part.
TestingT is the minimum interface that is required for Test().