README ¶
GDUTILS
Simple library with methods useful for e2e testing of HTTP(s) API.
Library is suitable for steps in godog framework.
Downloading
go get github.com/pawelWritesCode/gdutils
Related project:
Skeleton that allows to write e2e tests using godog & gdutils almost instantly with minimal configuration. https://github.com/pawelWritesCode/godog-example-setup
Roadmap (not yet implemented ideas):
- New method for adding cookies to HTTP(s) request
- New method for saving fixed values from scenario under provided cache key (not only from HTTP(s) response)
- New method for asserting on HTTP(s) response using cucumber datatable (field | matcher | type | value )
- New method for asserting on HTTP(s) request-response time
- Upgrade assertion for validating last HTTP(s) response with user provided (as []bytes) JSON schema
- Upgrade assertion for validating last HTTP(s) response against JSON Schema to accept URL
- Upgrade assertion using qjson-jsonpath to accept another jsonpath library syntax: (https://github.com/oliveagle/jsonpath)
Available methods:
NAME | DESCRIPTION |
---|---|
Sending HTTP(s) requests: | |
ISendRequestToWithBodyAndHeaders | Sends HTTP(s) request with provided body and headers. |
IPrepareNewRequestToAndSaveItAs | Prepare HTTP(s) request |
ISetFollowingHeadersForPreparedRequest | Sets provided headers for previously prepared request |
ISetFollowingBodyForPreparedRequest | Sets body for previously prepared request |
ISendRequest | Sends previously prepared HTTP(s) request |
Random data generation: | |
IGenerateARandomIntInTheRangeToAndSaveItAs | Generates random integer from provided range and save it under provided cache key |
IGenerateARandomFloatInTheRangeToAndSaveItAs | Generates random float from provided range and save it under provided cache key |
IGenerateARandomStringInTheRangeToAndSaveItAs | Creates generator for random strings from provided charset in provided range |
IGenerateARandomSentenceInTheRangeFromToWordsAndSaveItAs | Creates generator for random sentence from provided charset in provided range |
Preserving data: | |
ISaveFromTheLastResponseJSONNodeAs | Saves from last response body JSON node under given cacheKey key |
ISaveAs | Saves into cache arbitrary passed value |
Debugging: | |
IPrintLastResponseBody | Prints last response from request |
IStartDebugMode | Starts debugging mode |
IStopDebugMode | Stops debugging mode |
Flow control: | |
IWait | Stops test execution for provided amount of time |
Assertions: | |
TheResponseShouldHaveHeader | Checks whether last HTTP(s) response has given header |
TheResponseShouldHaveHeaderOfValue | Checks whether last HTTP(s) response has given header with provided value |
TheResponseStatusCodeShouldBe | Checks last HTTP(s) response status code |
TheResponseBodyShouldHaveType | Checks whether last HTTP(s) response body has given data format |
TheJSONResponseShouldHaveNode | Checks whether last response body contains given key |
TheJSONNodeShouldBeOfValue | Compares json node value from expression to expected by user |
TheJSONNodeShouldBe | Checks whether JSON node from last HTTP(s) response body is of provided type |
TheJSONNodeShouldNotBe | Checks whether JSON node from last response body is not of provided type |
TheJSONResponseShouldHaveNodes | Checks whether last HTTP(s) response body JSON has given nodes |
TheJSONNodeShouldBeSliceOfLength | checks whether given key is slice and has given length |
IValidateLastResponseBodyWithSchemaReference | Validates last HTTP(s) response body against provided in reference JSON schema |
IValidateLastResponseBodyWithSchemaString | Validates last HTTP(s) response body against provided JSON schema |
TimeBetweenLastHTTPRequestResponseShouldBeLessThanOrEqualTo | Asserts that last HTTP(s) request-response time is <= than expected |
Documentation ¶
Overview ¶
Package gdutils provides State struct with methods that may be used for behavioral testing of HTTP API.
State may be initialized by two ways:
First, returns *State with default services:
func NewDefaultState(isDebug bool, jsonSchemaDir string) *State
Second, more customisable returns *State with provided services:
func NewState(cli *http.Client, c cache.Cache, jv JSONSchemaValidators, r jsonpath.Resolver, d formatter.Deserializer, isDebug bool) *State
No matter which way you choose, you can inject your custom services afterwards with one of available setters:
func (s *State) SetDebugger(d debugger.Debugger) func (s *State) SetCache(c cache.Cache) func (s *State) SetHttpContext(c httpctx.HttpContext) func (s *State) SetTemplateEngine(t template.Engine) func (s *State) SetJSONSchemaValidators(j JSONSchemaValidators) func (s *State) SetJSONPathResolver(j jsonpath.Resolver) func (s *State) SetDeserializer(d formatter.Deserializer)
Those services will be used in utility methods. For example, if you want to use your own debugger, create your own struct, implement debugger.Debugger interface on it, and then inject it with "func (s *State) SetDebugger(d debugger.Debugger)" method.
Testing HTTP API usually consist the following aspects:
* Data generation:
func (s *State) IGenerateARandomIntInTheRangeToAndSaveItAs(from, to int, cacheKey string) error func (s *State) IGenerateARandomFloatInTheRangeToAndSaveItAs(from, to int, cacheKey string) error func (s *State) IGenerateARandomStringInTheRangeToAndSaveItAs(charset string) func(from, to int, cacheKey string) error func (s *State) IGenerateARandomSentenceInTheRangeFromToWordsAndSaveItAs(charset string, wordMinLength, wordMaxLength int) func(from, to int, cacheKey string) error
* Sending HTTP(s) requests:
func (s *State) ISendRequestToWithBodyAndHeaders(method, urlTemplate string, bodyTemplate *godog.DocString) error
or
func (s *State) IPrepareNewRequestToAndSaveItAs(method, urlTemplate, cacheKey string) error func (s *State) ISetFollowingHeadersForPreparedRequest(cacheKey string, headersTemplate *godog.DocString) error func (s *State) ISetFollowingBodyForPreparedRequest(cacheKey string, bodyTemplate *godog.DocString) error func (s *State) ISendRequest(cacheKey string) error
* Assertions:
func (s *State) TheResponseStatusCodeShouldBe(code int) error func (s *State) TheResponseBodyShouldHaveType(dataType string) error func (s *State) TheJSONResponseShouldHaveNode(expr string) error func (s *State) TheJSONNodeShouldNotBe(expr string, goType string) error func (s *State) TheJSONNodeShouldBe(expr string, goType string) error func (s *State) TheJSONResponseShouldHaveNodes(nodeExprs string) error func (s *State) TheJSONNodeShouldBeSliceOfLength(expr string, length int) error func (s *State) TheJSONNodeShouldBeOfValue(expr, dataType, dataValue string) error func (s *State) TheResponseShouldHaveHeader(name string) error func (s *State) TheResponseShouldHaveHeaderOfValue(name, value string) error func (s *State) IValidateLastResponseBodyWithSchemaReference(source string) error func (s *State) IValidateLastResponseBodyWithSchemaString(jsonSchema *godog.DocString) error func (s *State) TimeBetweenLastHTTPRequestResponseShouldBeLessThanOrEqualTo(timeInterval string)
* Preserving JSON nodes:
func (s *State) ISaveFromTheLastResponseJSONNodeAs(expr, cacheKey string) error func (s *State) ISaveAs(value, cacheKey string) error
* Temporary stopping scenario execution:
func (s *State) IWait(timeInterval string) error
* Debugging:
func (s *State) IPrintLastResponseBody() error func (s *State) IStartDebugMode() error func (s *State) IStopDebugMode() error
Index ¶
- Variables
- type BodyHeaders
- type JSONSchemaValidators
- type State
- func (s *State) IGenerateARandomFloatInTheRangeToAndSaveItAs(from, to int, cacheKey string) error
- func (s *State) IGenerateARandomIntInTheRangeToAndSaveItAs(from, to int, cacheKey string) error
- func (s *State) IGenerateARandomRunesInTheRangeToAndSaveItAs(charset string) func(from, to int, cacheKey string) error
- func (s *State) IGenerateARandomSentenceInTheRangeFromToWordsAndSaveItAs(charset string, wordMinLength, wordMaxLength int) func(from, to int, cacheKey string) error
- func (s *State) IPrepareNewRequestToAndSaveItAs(method, urlTemplate, cacheKey string) error
- func (s *State) IPrintLastResponseBody() error
- func (s *State) ISaveAs(value, cacheKey string) error
- func (s *State) ISaveFromTheLastResponseJSONNodeAs(expr, cacheKey string) error
- func (s *State) ISendRequest(cacheKey string) error
- func (s *State) ISendRequestToWithBodyAndHeaders(method, urlTemplate string, bodyTemplate *godog.DocString) error
- func (s *State) ISetFollowingBodyForPreparedRequest(cacheKey string, bodyTemplate *godog.DocString) error
- func (s *State) ISetFollowingHeadersForPreparedRequest(cacheKey string, headersTemplate *godog.DocString) error
- func (s *State) IStartDebugMode() error
- func (s *State) IStopDebugMode() error
- func (s *State) IValidateLastResponseBodyWithSchemaReference(reference string) error
- func (s *State) IValidateLastResponseBodyWithSchemaString(jsonSchema *godog.DocString) error
- func (s *State) IWait(timeInterval string) error
- func (s *State) ResetState(isDebug bool)
- func (s *State) SetCache(c cache.Cache)
- func (s *State) SetDebugger(d debugger.Debugger)
- func (s *State) SetDeserializer(d formatter.Deserializer)
- func (s *State) SetHttpContext(c httpctx.HttpContext)
- func (s *State) SetJSONPathResolver(j jsonpath.Resolver)
- func (s *State) SetJSONSchemaValidators(j JSONSchemaValidators)
- func (s *State) SetTemplateEngine(t template.Engine)
- func (s *State) TheJSONNodeShouldBe(expr string, goType string) error
- func (s *State) TheJSONNodeShouldBeOfValue(expr, dataType, dataValue string) error
- func (s *State) TheJSONNodeShouldBeSliceOfLength(expr string, length int) error
- func (s *State) TheJSONNodeShouldNotBe(expr string, goType string) error
- func (s *State) TheJSONResponseShouldHaveNode(expr string) error
- func (s *State) TheJSONResponseShouldHaveNodes(expressions string) error
- func (s *State) TheResponseBodyShouldHaveType(dataType string) error
- func (s *State) TheResponseShouldHaveHeader(name string) error
- func (s *State) TheResponseShouldHaveHeaderOfValue(name, valueTemplate string) error
- func (s *State) TheResponseStatusCodeShouldBe(code int) error
- func (s *State) TimeBetweenLastHTTPRequestResponseShouldBeLessThanOrEqualTo(timeInterval string) error
Constants ¶
This section is empty.
Variables ¶
var ErrGdutils = errors.New("gdutils")
ErrGdutils is general package error and can be tested against
var ErrHTTPReqRes = fmt.Errorf("%w: something wrong with HTTP(s) request/response", ErrGdutils)
ErrHTTPReqRes tells that there is problem with last HTTP(s) request/response
var ErrJson = fmt.Errorf("%w: something wrong with JSON", ErrGdutils)
ErrJson tells that there is problem with JSON
var ErrPreservedData = errors.New("preserved data error")
ErrPreservedData tells indices that there is some kind of error with scenario preserved data.
var ErrQJSON = fmt.Errorf("%w: could not obtain value from JSON", ErrJson)
ErrQJSON occurs when value could not be obtained from JSON
Functions ¶
This section is empty.
Types ¶
type BodyHeaders ¶ added in v0.7.4
type BodyHeaders struct { // Body should contain HTTP(s) request body Body interface{} // Headers should contain HTTP(s) request headers Headers map[string]string }
BodyHeaders is entity that holds information about request body and request headers.
type JSONSchemaValidators ¶ added in v0.9.1
type JSONSchemaValidators struct { // StringValidator represents entity that has ability to validate document against string of JSON schema StringValidator validator.SchemaValidator // ReferenceValidator represents entity that has ability to validate document against JSON schema // provided by reference like URL or relative/full OS path ReferenceValidator validator.SchemaValidator }
JSONSchemaValidators is container for JSON schema validators
type State ¶
type State struct { // Debugger represents scenario debugger. Debugger debugger.Debugger // Cache is storage for scenario data. Cache cache.Cache // HttpContext is service that works with HTTP(s) req/res. HttpContext httpctx.HttpContext // TemplateEngine is entity that has ability to work with template values. TemplateEngine template.Engine // JSONSchemaValidators holds validators available to validate JSON Schemas JSONSchemaValidators JSONSchemaValidators // JSONPathResolver is entity that has ability to obtain data from JSON JSONPathResolver jsonpath.Resolver // Deserializer is entity that has ability to deserialize data in expected format Deserializer formatter.Deserializer }
State struct represents data shared across one scenario.
func NewDefaultState ¶
NewDefaultState returns *State with default services. jsonSchemaDir may be empty string or valid full path to directory with JSON schemas
func NewState ¶
func NewState(cli *http.Client, c cache.Cache, jv JSONSchemaValidators, r jsonpath.Resolver, d formatter.Deserializer, isDebug bool) *State
NewState returns *State
func (*State) IGenerateARandomFloatInTheRangeToAndSaveItAs ¶
IGenerateARandomFloatInTheRangeToAndSaveItAs generates random float from provided range and preserve it under given cacheKey key
func (*State) IGenerateARandomIntInTheRangeToAndSaveItAs ¶
IGenerateARandomIntInTheRangeToAndSaveItAs generates random integer from provided range and preserve it under given cacheKey key
func (*State) IGenerateARandomRunesInTheRangeToAndSaveItAs ¶ added in v0.9.0
func (s *State) IGenerateARandomRunesInTheRangeToAndSaveItAs(charset string) func(from, to int, cacheKey string) error
IGenerateARandomRunesInTheRangeToAndSaveItAs creates random runes generator func using provided charset return func creates runes from provided range and preserve it under given cacheKey
func (*State) IGenerateARandomSentenceInTheRangeFromToWordsAndSaveItAs ¶ added in v0.9.1
func (s *State) IGenerateARandomSentenceInTheRangeFromToWordsAndSaveItAs(charset string, wordMinLength, wordMaxLength int) func(from, to int, cacheKey string) error
IGenerateARandomSentenceInTheRangeFromToWordsAndSaveItAs creates generator func for creating random sentences each sentence has length from - to as provided in params and is saved in provided cacheKey Given I generate a random sentence in the range from "5" to "10" words and save it as "ABC"
func (*State) IPrepareNewRequestToAndSaveItAs ¶ added in v0.7.0
IPrepareNewRequestToAndSaveItAs prepares new request and saves it in cache under cacheKey
func (*State) IPrintLastResponseBody ¶
IPrintLastResponseBody prints last response from request
func (*State) ISaveFromTheLastResponseJSONNodeAs ¶
ISaveFromTheLastResponseJSONNodeAs saves from last response body JSON node under given cacheKey key. expr should be valid according to injected JSONPathResolver
func (*State) ISendRequest ¶ added in v0.7.0
ISendRequest sends previously prepared HTTP(s) request
func (*State) ISendRequestToWithBodyAndHeaders ¶
func (s *State) ISendRequestToWithBodyAndHeaders(method, urlTemplate string, bodyTemplate *godog.DocString) error
ISendRequestToWithBodyAndHeaders sends HTTP(s) requests with provided body and headers. Argument "method" indices HTTP request method for example: "POST", "GET" etc. Argument "urlTemplate" should be full valid URL. May include template values. Argument "bodyTemplate" should contain data (may include template values) in format acceptable by Deserializer with keys "body" and "headers". Internally method will marshal request body to JSON format and add it to request. If you want to send request body in arbitrary data format, use step-by-step flow containing following methods: IPrepareNewRequestToAndSaveItAs - creates request object and save it to cache ISetFollowingHeadersForPreparedRequest - sets header for saved request ISetFollowingBodyForPreparedRequest - sets body for saved request ISendRequest - sends previously saved request Because method ISetFollowingBodyForPreparedRequest pass any bytes to HTTP(s) request body without any mutation.
func (*State) ISetFollowingBodyForPreparedRequest ¶ added in v0.7.0
func (s *State) ISetFollowingBodyForPreparedRequest(cacheKey string, bodyTemplate *godog.DocString) error
ISetFollowingBodyForPreparedRequest sets body for previously prepared request bodyTemplate may be in any format and accepts template values
func (*State) ISetFollowingHeadersForPreparedRequest ¶ added in v0.7.0
func (s *State) ISetFollowingHeadersForPreparedRequest(cacheKey string, headersTemplate *godog.DocString) error
ISetFollowingHeadersForPreparedRequest sets provided headers for previously prepared request. incoming data should be in format acceptable by injected Deserializer
func (*State) IStartDebugMode ¶
IStartDebugMode starts debugging mode
func (*State) IStopDebugMode ¶
IStopDebugMode stops debugging mode
func (*State) IValidateLastResponseBodyWithSchemaReference ¶ added in v0.9.1
IValidateLastResponseBodyWithSchemaReference validates last response body against JSON schema as provided in reference. reference may be: URL or full/relative path
func (*State) IValidateLastResponseBodyWithSchemaString ¶ added in v0.9.1
IValidateLastResponseBodyWithSchemaString validates last response body against jsonSchema.
func (*State) IWait ¶
IWait waits for given timeInterval amount of time timeInterval should be string valid for time.ParseDuration func
func (*State) ResetState ¶
ResetState resets State struct instance to default values.
func (*State) SetDebugger ¶ added in v0.9.3
SetDebugger sets new debugger for State
func (*State) SetDeserializer ¶ added in v0.9.5
func (s *State) SetDeserializer(d formatter.Deserializer)
SetDeserializer sets new deserializer for State
func (*State) SetHttpContext ¶ added in v0.9.3
func (s *State) SetHttpContext(c httpctx.HttpContext)
SetHttpContext sets new HttpContext for State
func (*State) SetJSONPathResolver ¶ added in v0.9.3
SetJSONPathResolver sets new JSON path resolver for State
func (*State) SetJSONSchemaValidators ¶ added in v0.9.3
func (s *State) SetJSONSchemaValidators(j JSONSchemaValidators)
SetJSONSchemaValidators sets new JSONSchemaValidators for State
func (*State) SetTemplateEngine ¶ added in v0.9.3
SetTemplateEngine sets new template Engine for State
func (*State) TheJSONNodeShouldBe ¶
TheJSONNodeShouldBe checks whether JSON node from last response body is of provided type goType may be one of: nil, string, int, float, bool, map, slice expr should be valid according to qjson library
func (*State) TheJSONNodeShouldBeOfValue ¶
TheJSONNodeShouldBeOfValue compares json node value from expression to expected by user dataValue of given by user dataType available data types are listed in switch section in each case directive expr should be valid according to injected JSONPathResolver
func (*State) TheJSONNodeShouldBeSliceOfLength ¶
TheJSONNodeShouldBeSliceOfLength checks whether given key is slice and has given length expr should be valid according to injected JSONPathResolver
func (*State) TheJSONNodeShouldNotBe ¶
TheJSONNodeShouldNotBe checks whether JSON node from last response body is not of provided type. goType may be one of: nil, string, int, float, bool, map, slice, expr should be valid according to injected JSONPathResolver
func (*State) TheJSONResponseShouldHaveNode ¶
TheJSONResponseShouldHaveNode checks whether last response body contains given node. expr should be valid according to injected JSONPathResolver
func (*State) TheJSONResponseShouldHaveNodes ¶
TheJSONResponseShouldHaveNodes checks whether last request body has keys defined in string separated by comma nodeExprs should be valid according to injected JSONPathResolver expressions separated by comma (,)
func (*State) TheResponseBodyShouldHaveType ¶
TheResponseBodyShouldHaveType checks whether last response body has given data type available data types are listed as package constants
func (*State) TheResponseShouldHaveHeader ¶
TheResponseShouldHaveHeader checks whether last HTTP response has given header
func (*State) TheResponseShouldHaveHeaderOfValue ¶
TheResponseShouldHaveHeaderOfValue checks whether last HTTP response has given header with provided valueTemplate
func (*State) TheResponseStatusCodeShouldBe ¶
TheResponseStatusCodeShouldBe compare last response status code with given in argument.
func (*State) TimeBetweenLastHTTPRequestResponseShouldBeLessThanOrEqualTo ¶ added in v0.9.4
func (s *State) TimeBetweenLastHTTPRequestResponseShouldBeLessThanOrEqualTo(timeInterval string) error
TimeBetweenLastHTTPRequestResponseShouldBeLessThanOrEqualTo asserts that last HTTP request-response time is <= than expected timeInterval. timeInterval should be string acceptable by time.ParseDuration func
Directories ¶
Path | Synopsis |
---|---|
Package pkg holds packages used for steps.
|
Package pkg holds packages used for steps. |
cache
Package cache holds definition of Cache used for storing and retrieving data.
|
Package cache holds definition of Cache used for storing and retrieving data. |
datatype
Package datatype holds utilities for working with different data formats.
|
Package datatype holds utilities for working with different data formats. |
debugger
Package debugger holds definition of Debugger.
|
Package debugger holds definition of Debugger. |
formatter
Package formatter holds utilities for working with different data formats.
|
Package formatter holds utilities for working with different data formats. |
httpcache
Package httpcache connects package httpctx and cache
|
Package httpcache connects package httpctx and cache |
httpctx
Package httpctx holds utilities for working with HTTP protocol.
|
Package httpctx holds utilities for working with HTTP protocol. |
jsonpath
Package jsonpath holds utilities for working with JSON path.
|
Package jsonpath holds utilities for working with JSON path. |
mathutils
Package mathutils holds utilities related with mathematics.
|
Package mathutils holds utilities related with mathematics. |
reflectutils
Package reflectutils holds utility methods related with reflect package.
|
Package reflectutils holds utility methods related with reflect package. |
stringutils
Package stringutils holds utility methods for working with strings.
|
Package stringutils holds utility methods for working with strings. |
template
Package template holds utilities for working with templates.
|
Package template holds utilities for working with templates. |
validator
Package validator holds utilities for validating data.
|
Package validator holds utilities for validating data. |