cstesting

package
v0.0.0-...-6f8fa1e Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2016 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package cstesting provides testing helpers

Index

Constants

View Source
const (
	HeaderUserID = "X-Test-User-ID"
	HeaderLoopID = "X-Test-Loop-ID"
	HeaderSleep  = "X-Test-Sleep"
)

Header* got set within an user iteration to allow you to identify a request.

View Source
const EnvDSN string = "CS_DSN"

EnvDSN is the name of the environment variable

Variables

This section is empty.

Functions

func ChangeDir

func ChangeDir(t fataler, dir string) func()

ChangeDir temporarily changes the working directory for non parallel tests.

defer cstesting.ChangeDir(t, os.TempDir())()

func ChangeEnv

func ChangeEnv(t fataler, key, value string) func()

ChangeEnv temporarily changes the environment for non parallel tests.

defer cstesting.ChangeEnv(t, "PATH", ".")()

func ContainsCount

func ContainsCount(t errorFormater, str, contains string, maxOccurrences int)

ContainsCount checks if str contains the substring contains maxOccurrences times.

func EqualPointers

func EqualPointers(t errorFormater, expected, actual interface{}) bool

EqualPointers compares pointers for equality. errorFormater is *testing.T.

func GCPause

func GCPause() time.Duration

GCPause runs the garbage collector and measures the time taken.

func LoadCSV

func LoadCSV(opts ...csvOptions) (columns []string, rows [][]driver.Value, err error)

LoadCSV loads a csv file for mocked database testing. Like github.com/DATA-DOG/go-sqlmock does. CSV file should be comma separated.

func MockDB

func MockDB(t fataler) (*dbr.Connection, sqlmock.Sqlmock)

MockDB creates a mocked database connection. Fatals on error.

func MockRows

func MockRows(opts ...csvOptions) (sqlmock.Rows, error)

MockRows same as LoadCSV() but creates a fully functional driver.Rows interface from a CSV file.

func MustConnectDB

func MustConnectDB(opts ...dbr.ConnectionOption) (*dbr.Connection, magento.Version)

MustConnectDB is a helper function that creates a new database connection using a DSN from an environment variable found in the constant csdb.EnvDSN. It queries the database to figure out the current version of Magento. If the DSN environment variable has not been set it returns nil,0.

func MustGetDSN

func MustGetDSN() string

MustGetDSN returns the data source name from an environment variable or panics on error.

func MustMockRows

func MustMockRows(opts ...csvOptions) sqlmock.Rows

MustMockRows same as MockRows but panics on error

func SQLMockQuoteMeta

func SQLMockQuoteMeta(s string) string

SQLMockQuoteMeta hacky work around to remove multiple \s via regexp and replace them with a single whitespace. Because the SQL Mock driver creates from a multi line string a single line string.

func WithFile

func WithFile(elem ...string) csvOptions

WithFile sets the file name. File path prefix is always RootPath variable.

func WithReaderConfig

func WithReaderConfig(cr CSVConfig) csvOptions

WithReaderConfig sets CSV reader options

func WithTestMode

func WithTestMode() csvOptions

WithTestMode allows better testing. Converts []bytes in driver.Value to text.Chars

Types

type CSVConfig

type CSVConfig struct {
	// Comma is the field delimiter.
	// It is set to comma (',') by NewReader.
	Comma rune
	// Comment, if not 0, is the comment character. Lines beginning with the
	// Comment character without preceding whitespace are ignored. With leading
	// whitespace the Comment character becomes part of the field, even if
	// TrimLeadingSpace is true.
	Comment rune
	// FieldsPerRecord is the number of expected fields per record. If
	// FieldsPerRecord is positive, Read requires each record to have the given
	// number of fields. If FieldsPerRecord is 0, Read sets it to the number of
	// fields in the first record, so that future records must have the same
	// field count. If FieldsPerRecord is negative, no check is made and records
	// may have a variable number of fields.
	FieldsPerRecord int
	// If LazyQuotes is true, a quote may appear in an unquoted field and a
	// non-doubled quote may appear in a quoted field.
	LazyQuotes *bool
	// If TrimLeadingSpace is true, leading white space in a field is ignored.
	// This is done even if the field delimiter, Comma, is white space.
	TrimLeadingSpace *bool
}

CSVConfig allows to set special options when parsing the csv file.

type HTTPParallelUsers

type HTTPParallelUsers struct {
	// Users or also known as number of threads
	Users int
	// Loops each user runs these loops
	Loops int
	// RampUpPeriod time to take to generate to the full request force. The
	// duration calculates: RampUpPeriod * Interval
	RampUpPeriod int
	// Interval an enum set of time.Nanosecond, time.Microsecond, time.Millisecond,
	// time.Second, time.Minute, time.Hour.
	Interval time.Duration
	// AssertResponse provides the possibility to check the written data after each
	// request.
	AssertResponse func(*httptest.ResponseRecorder)
}

HTTPParallelUsers allows to run parallel and concurrent calls to a given http.Handler.

func NewHTTPParallelUsers

func NewHTTPParallelUsers(users, loopsPerUser, rampUpPeriod int, interval time.Duration) HTTPParallelUsers

NewHTTPParallelUsers initializes a new request producer. Users means the total amount of parallel users. Each user can execute a specific loopsPerUser count. The rampUpPeriod defines the total runtime of the test and the period it takes to produce the finally total amount of parallel requests. The interval applies to the exported constants of the time package: time.Nanosecond, time.Microsecond, time.Millisecond, time.Second, time.Minute, time.Hour. The total runtime calculates rampUpPeriod * interval. Every (rampUpPeriod / users) a new user starts with its requests. Each user request sleeps a specific equal time until the test ends. With the last started user the maximum amount of parallel requests will be reached.

func (HTTPParallelUsers) ServeHTTP

func (hpu HTTPParallelUsers) ServeHTTP(r *http.Request, h http.Handler)

ServeHTTP starts the testing and the request gets called with http.Handler. You might run into a race condition when trying to add a request body (an io.ReadCloser), because multiple reads and writes into the buffer. Use the function ServeHTTPNewRequest() if you need for each call to http.Handler a new request object.

func (HTTPParallelUsers) ServeHTTPNewRequest

func (hpu HTTPParallelUsers) ServeHTTPNewRequest(rf func() *http.Request, h http.Handler)

ServeHTTPNewRequest same as ServeHTTP() but creates for each iteration a new fresh request which will be passed to http.Handler. Does not trigger a race condition.

type HTTPTrip

type HTTPTrip struct {
	GenerateResponse func(*http.Request) *http.Response
	Err              error
	sync.Mutex
	RequestCache map[*http.Request]struct{}
}

HTTPTrip used for mocking the Transport field in http.Client.

func NewHTTPTrip

func NewHTTPTrip(code int, body string, err error) *HTTPTrip

NewHTTPTrip creates a new http.RoundTripper

func NewHTTPTripFromFile

func NewHTTPTripFromFile(code int, filename string) *HTTPTrip

NewHTTPTripFromFile creates a new trip with content found in the provided file. You must close the body and hence close the file.

func (*HTTPTrip) RequestsCount

func (tp *HTTPTrip) RequestsCount(t interface {
	Errorf(format string, args ...interface{})
}, expected int)

RequestsCount counts the requests in the cache and compares it with your expected value.

func (*HTTPTrip) RequestsMatchAll

func (tp *HTTPTrip) RequestsMatchAll(t interface {
	Errorf(format string, args ...interface{})
}, f func(*http.Request) bool)

RequestsMatchAll checks if all requests in the cache matches the predicate function f.

func (*HTTPTrip) RoundTrip

func (tp *HTTPTrip) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper and adds the Request to the field Req for later inspection.

Jump to

Keyboard shortcuts

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