helpers

package
v1.25.4 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2024 License: Apache-2.0 Imports: 26 Imported by: 3

Documentation

Overview

Package helpers contains function and data types used in tests.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertAPIRequest

func AssertAPIRequest(
	t testing.TB,
	testServer ServerInitializer,
	APIPrefix string,
	request *APIRequest,
	expectedResponse *APIResponse,

)

AssertAPIRequest sends sends api request and checks api response (see docs for APIRequest and APIResponse) to the provided testServer using the provided APIPrefix

func AssertReportResponsesEqual

func AssertReportResponsesEqual(t testing.TB, expected, got []byte)

AssertReportResponsesEqual checks if reports in answer are the same

func AssertReportResponsesEqualCustomElementsChecker added in v1.6.1

func AssertReportResponsesEqualCustomElementsChecker(
	t testing.TB, expected, got []byte, elementsChecker func(testing.TB, []types.RuleOnReport, []types.RuleOnReport),
)

AssertReportResponsesEqualCustomElementsChecker checks if reports in answer are the same using custom checker for elements

func AssertRuleResponsesEqual added in v1.4.1

func AssertRuleResponsesEqual(t testing.TB, expected, got []byte)

AssertRuleResponsesEqual checks if rules in answer are the same

func AssertStringsAreEqualJSON

func AssertStringsAreEqualJSON(t testing.TB, expected, got string)

AssertStringsAreEqualJSON checks whether strings represent the same JSON (whitespaces and order of elements doesn't matter) and asserts error otherwise

func CatchingOutputs added in v1.7.2

func CatchingOutputs(t *testing.T, f func()) (string, string)

CatchingOutputs execute a function capturing and returning Stdout and Stderr for later checks

func CheckResponseBodyJSON

func CheckResponseBodyJSON(t testing.TB, expectedJSON string, body io.ReadCloser)

CheckResponseBodyJSON checks if body is the same json as in expected (ignores whitespaces, newlines, etc) also validates both expected and body to be a valid json

func CleanAfterGock added in v1.2.1

func CleanAfterGock(t testing.TB)

CleanAfterGock cleans after gock library and prints all unmatched requests

func CompareReportResponses added in v1.23.7

func CompareReportResponses(t testing.TB, expected, actual types.RuleOnReport, createdAt time.Time)

CompareReportResponses compares two RuleOnReport struct field by field, except for the CreatedAt field that is compared with createdAt timestamp. If createdAt.isZero() the filed will be ignored

func ExecuteRequest

func ExecuteRequest(testServer ServerInitializer, req *http.Request) *httptest.ResponseRecorder

ExecuteRequest executes http request on a testServer

func FailOnError

func FailOnError(t testing.TB, err error, msgAndArgs ...interface{})

FailOnError logs error and stops next test's execution if non nil value is passed to err optionally, you can add a message

func FrisbyExpectItemInArray

func FrisbyExpectItemInArray(fieldName string, expectedItem interface{}) frisby.ExpectFunc

FrisbyExpectItemInArray returns checker function for frisby to check if item is in the array Example:

frisby.Create("test creating organization"). Get(apiURL + "/organization"). Send(). ExpectStatus(200). Expect(helpers.FrisbyExpectItemInArray("organizations", 55))

will check if 55 is in organizations, like here `{"organizations": [1, 2, 3, 55], "status": "ok"}`

func GockExpectAPIRequest added in v1.2.1

func GockExpectAPIRequest(t testing.TB, baseURL string, request *APIRequest, response *APIResponse)

GockExpectAPIRequest makes gock expect the request with the baseURL and sends back the response

func IsStringJSON added in v1.4.2

func IsStringJSON(str string) bool

IsStringJSON check if the string is a JSON

func JSONUnmarshalStrict

func JSONUnmarshalStrict(data []byte, outObj interface{}) error

JSONUnmarshalStrict unmarshales json and returns error if some field exist in data, but not in outObj

func MakeXRHTokenString added in v1.4.3

func MakeXRHTokenString(t testing.TB, token *types.Token) string

MakeXRHTokenString converts types.Token to a token string(base64 encoded)

func MustGobSerialize added in v1.2.1

func MustGobSerialize(t testing.TB, obj interface{}) []byte

MustGobSerialize serializes an object using gob or panics

func NewGockAPIEndpointMatcher

func NewGockAPIEndpointMatcher(endpoint string) func(req *http.Request, _ *gock.Request) (bool, error)

NewGockAPIEndpointMatcher returns new matcher for github.com/h2non/gock to match endpoint with any args

func NewGockRequestMatcher added in v1.2.1

func NewGockRequestMatcher(
	t testing.TB, method string, url string, body interface{},
) func(*http.Request, *gock.Request) (bool, error)

NewGockRequestMatcher returns a new matcher for github.com/h2non/gock to match requests with provided method, url and body(the same types as body in APIRequest(see the docs))

func RunTestWithTimeout

func RunTestWithTimeout(t testing.TB, test TestFunctionPtr, timeToRun time.Duration)

RunTestWithTimeout runs test with timeToRun timeout and fails if it wasn't in time

func SortReports added in v1.23.7

func SortReports(reports []types.RuleOnReport) []types.RuleOnReport

SortReports sorts a list of RuleOnReport by ErrorKey field

func ToJSONPrettyString added in v1.2.1

func ToJSONPrettyString(obj interface{}) string

ToJSONPrettyString converts anything to indented JSON or panics if it's not possible

func ToJSONString

func ToJSONString(obj interface{}) string

ToJSONString converts anything to JSON or panics if it's not possible

Types

type APIRequest

type APIRequest struct {
	Method             string
	Endpoint           string
	EndpointArgs       []interface{}
	Body               interface{}
	UserID             types.UserID
	OrgID              types.OrgID
	XRHIdentity        string
	AuthorizationToken string
	ExtraHeaders       http.Header
}

APIRequest is a request to api to use in AssertAPIRequest

(required) Method is an http method (required) Endpoint is an endpoint without api prefix EndpointArgs are the arguments to pass to endpoint template (leave empty if endpoint is not a template) Body is a request body which can be a string or []byte (leave empty to not send) UserID is a user id for methods requiring user id (leave empty to not use it) OrgID is an org id for methods requiring it to be in token (leave empty to not use it) XRHIdentity is an authentication token (leave empty to not use it) AuthorizationToken is an authentication token (leave empty to not use it)

type APIResponse

type APIResponse struct {
	StatusCode  int
	Body        interface{}
	BodyChecker BodyChecker
	Headers     map[string]string
}

APIResponse is an expected api response to use in AssertAPIRequest

StatusCode is an expected http status code (leave empty to not check for status code) Body is an expected body which can be a string or []byte(leave empty to not check for body) BodyChecker is a custom body checker function (leave empty to use default one - CheckResponseBodyJSON)

type BodyChecker added in v1.2.1

type BodyChecker func(t testing.TB, expected, got []byte)

BodyChecker represents body checker type for api response

type MicroHTTPServer added in v1.3.0

type MicroHTTPServer struct {
	Serv      *http.Server
	Router    *mux.Router
	APIPrefix string
}

MicroHTTPServer in an implementation of ServerInitializer interface This small implementation could help implementing tests without using a real HTTP server implementation

func NewMicroHTTPServer added in v1.3.0

func NewMicroHTTPServer(address, apiPrefix string) *MicroHTTPServer

NewMicroHTTPServer creates a MicroHTTPServer for the given address and prefix

func (*MicroHTTPServer) AddEndpoint added in v1.3.0

func (server *MicroHTTPServer) AddEndpoint(endpoint string, f func(http.ResponseWriter, *http.Request))

AddEndpoint adds a handler function to the router in order to response to the given endpoint

func (*MicroHTTPServer) Initialize added in v1.3.0

func (server *MicroHTTPServer) Initialize() http.Handler

Initialize returns the Handler instance in order to be modified

type MockT added in v1.5.0

type MockT struct {
	*testing.T
	Expects *mock_testing.MockTB
	// contains filtered or unexported fields
}

MockT wraps testing.T to be able to test functions accepting testing.TB. Don't forget to call Finish at the end of the test `defer mockT.Finish()`

func NewMockT added in v1.5.0

func NewMockT(t *testing.T) *MockT

NewMockT constructs a new instance of MockT

func (*MockT) Cleanup added in v1.5.0

func (t *MockT) Cleanup(f func())

Cleanup mocks Cleanup method of testing.T

func (*MockT) Error added in v1.5.0

func (t *MockT) Error(args ...interface{})

Error mocks Error method of testing.T

func (*MockT) Errorf added in v1.5.0

func (t *MockT) Errorf(format string, args ...interface{})

Errorf mocks Errorf method of testing.T

func (*MockT) ExpectFailOnError added in v1.5.0

func (t *MockT) ExpectFailOnError(err error)

ExpectFailOnError adds expects corresponding to those called by helpers.FailOnError function

func (*MockT) ExpectFailOnErrorAnyArgument added in v1.5.0

func (t *MockT) ExpectFailOnErrorAnyArgument()

ExpectFailOnErrorAnyArgument adds expects corresponding to those called by helpers.FailOnError function with any argument

func (*MockT) Fail added in v1.5.0

func (t *MockT) Fail()

Fail mocks Fail method of testing.T

func (*MockT) FailNow added in v1.5.0

func (t *MockT) FailNow()

FailNow mocks Fail method of testing.T

func (*MockT) Failed added in v1.5.0

func (t *MockT) Failed() bool

Failed mocks Failed method of testing.T

func (*MockT) Fatal added in v1.5.0

func (t *MockT) Fatal(args ...interface{})

Fatal mocks Fatal method of testing.T

func (*MockT) Fatalf added in v1.5.0

func (t *MockT) Fatalf(format string, args ...interface{})

Fatalf mocks Fatalf method of testing.T

func (*MockT) Finish added in v1.5.0

func (t *MockT) Finish()

Finish cleans up after the MockT

func (*MockT) Log added in v1.5.0

func (t *MockT) Log(args ...interface{})

Log mocks Log method of testing.T

func (*MockT) Logf added in v1.5.0

func (t *MockT) Logf(format string, args ...interface{})

Logf mocks Logf method of testing.T

func (*MockT) Skip added in v1.5.0

func (t *MockT) Skip(args ...interface{})

Skip mocks Skip method of testing.T

func (*MockT) SkipNow added in v1.5.0

func (t *MockT) SkipNow()

SkipNow mocks SkipNow method of testing.T

func (*MockT) Skipf added in v1.5.0

func (t *MockT) Skipf(format string, args ...interface{})

Skipf mocks Skipf method of testing.T

func (*MockT) Skipped added in v1.5.0

func (t *MockT) Skipped() bool

Skipped mocks Skipped method of testing.T

type ServerInitializer

type ServerInitializer interface {
	Initialize() http.Handler
}

ServerInitializer is interface which is implemented for any server having Initialize method

type TestFunctionPtr

type TestFunctionPtr = func(testing.TB)

TestFunctionPtr pointer to test function

Jump to

Keyboard shortcuts

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