testutils

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2018 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultServerName = "testService"
	DefaultClientName = "testService-client"
)

Default service names for the test channels.

Variables

This section is empty.

Functions

func AssertEcho added in v1.0.8

func AssertEcho(tb testing.TB, src *tchannel.Channel, targetHostPort, targetService string)

AssertEcho calls the "echo" endpoint with random data, and asserts that the returned data matches the arguments "echo" was called with.

func Batch added in v1.0.8

func Batch(n, batchSize int) []int

Batch returns a slice with n broken into batches of size batchSize.

func Buckets added in v1.0.8

func Buckets(n int, numBuckets int) []int

Buckets splits n over the specified number of buckets.

func CallEcho

func CallEcho(src *tchannel.Channel, targetHostPort, targetService string, args *raw.Args) error

CallEcho calls the "echo" endpoint from the given src to target.

func DurationArray

func DurationArray(dd ...time.Duration) []time.Duration

DurationArray returns an array with the given durations.

func FrameRelay

func FrameRelay(t *testing.T, destination string, relayFunc func(outgoing bool, f *tchannel.Frame) *tchannel.Frame) (listenHostPort string, cancel func())

FrameRelay sets up a relay that can modify frames using relayFunc.

func GetAcceptCloseHostPort added in v1.0.5

func GetAcceptCloseHostPort(t testing.TB) (string, func())

GetAcceptCloseHostPort returns a host:port that will accept a connection then immediately close it. The returned function can be used to stop the listener.

func GetClosedHostPort

func GetClosedHostPort(t testing.TB) string

GetClosedHostPort will return a host:port that will refuse connections.

func NewClient

func NewClient(t testing.TB, opts *ChannelOpts) *tchannel.Channel

NewClient returns a new TChannel that is not listening.

func NewClientChannel

func NewClientChannel(opts *ChannelOpts) (*tchannel.Channel, error)

NewClientChannel creates a TChannel that is not listening. Passed in options may be mutated (for post-verification of state).

func NewIncomingCall

func NewIncomingCall(callerName string) tchannel.IncomingCall

NewIncomingCall creates an incoming call for tests.

func NewServer

func NewServer(t testing.TB, opts *ChannelOpts) *tchannel.Channel

NewServer returns a new TChannel server that listens on :0.

func NewServerChannel

func NewServerChannel(opts *ChannelOpts) (*tchannel.Channel, error)

NewServerChannel creates a TChannel that is listening and returns the channel. Passed in options may be mutated (for post-verification of state).

func Ping

func Ping(src, target *tchannel.Channel) error

Ping sends a ping from src to target.

func RandBytes

func RandBytes(n int) []byte

RandBytes returns n random byte slice that points to a shared random byte array. Since the underlying random array is shared, the returned byte slice must NOT be modified.

func RandString

func RandString(n int) string

RandString returns a random alphanumeric string for testing.

func RegisterEcho

func RegisterEcho(src tchannel.Registrar, f func())

RegisterEcho registers an echo endpoint on the given channel. The optional provided function is run before the handler returns.

func RegisterFunc

func RegisterFunc(ch tchannel.Registrar, name string,
	f func(ctx context.Context, args *raw.Args) (*raw.Res, error))

RegisterFunc registers a function as a handler for the given method name.

func ResetSleepStub

func ResetSleepStub(funcVar *func(time.Duration))

ResetSleepStub resets a Sleep stub.

func RunN

func RunN(n int, f func(i int))

RunN runs the given f n times (and passes the run's index) and waits till they complete. It starts n-1 goroutines, and runs one instance in the current goroutine.

func SetTimeout

func SetTimeout(t *testing.T, timeout time.Duration) func()

SetTimeout is used to fail tests after a timeout. It returns a function that should be run once the test is complete. The standard way is to use defer, e.g. defer SetTimeout(t, time.Second)()

func SleepStub

func SleepStub(funcVar *func(time.Duration)) (
	argCh <-chan time.Duration, unblockCh chan<- struct{}, closeFn func())

SleepStub stubs a function variable that points to time.Sleep. It returns two channels to control the sleep stub, and a function to close the channels. Once the stub is closed, any further sleeps will cause panics. The two channels returned are: <-chan time.Duration which will contain arguments that the stub was called with. chan<- struct{} that should be written to when you want the Sleep to return.

func StrArray

func StrArray(ss ...string) []string

StrArray will return an array with the given strings.

func StrMap

func StrMap(ss ...string) map[string]struct{}

StrMap returns a map where the keys are the given strings.

func Timeout

func Timeout(timeout time.Duration) time.Duration

Timeout returns the timeout multiplied by any set multiplier.

func WaitFor

func WaitFor(timeout time.Duration, f func() bool) bool

WaitFor will retry f till it returns true for a maximum of timeout. It returns true if f returned true, false if timeout was hit.

func WaitWG

func WaitWG(wg *sync.WaitGroup, timeout time.Duration) bool

WaitWG waits for the given WaitGroup to be complete with a timeout and returns whether the WaitGroup completed within the timeout.

func WithServer

func WithServer(t testing.TB, opts *ChannelOpts, f func(ch *tchannel.Channel, hostPort string))

WithServer sets up a TChannel that is listening and runs the given function with the channel.

func WithTestServer added in v1.0.5

func WithTestServer(t testing.TB, chanOpts *ChannelOpts, f func(*TestServer))

WithTestServer creates a new TestServer, runs the passed function, and then verifies that no resources were leaked.

Types

type ChannelOpts

type ChannelOpts struct {
	tchannel.ChannelOptions

	// ServiceName defaults to DefaultServerName or DefaultClientName.
	ServiceName string

	// LogVerification contains options for controlling the log verification.
	LogVerification LogVerification

	// DisableRelay disables the relay interposed between clients/servers.
	// By default, all tests are run with a relay interposed.
	DisableRelay bool

	// OnlyRelay instructs TestServer the test must only be run with a relay.
	OnlyRelay bool

	// RunCount is the number of times the test should be run. Zero or
	// negative values are treated as a single run.
	RunCount int
	// contains filtered or unexported fields
}

ChannelOpts contains options to create a test channel using WithServer

func DefaultOpts

func DefaultOpts(opts *ChannelOpts) *ChannelOpts

DefaultOpts will return opts if opts is non-nil, NewOpts otherwise.

func NewOpts

func NewOpts() *ChannelOpts

NewOpts returns a new ChannelOpts that can be used in a chained fashion.

func (*ChannelOpts) AddLogFilter

func (o *ChannelOpts) AddLogFilter(filter string, maxCount uint, fields ...string) *ChannelOpts

AddLogFilter sets an allowed filter for warning/error logs and sets the maximum number of times that log can occur.

func (*ChannelOpts) Copy added in v1.0.8

func (o *ChannelOpts) Copy() *ChannelOpts

Copy copies the channel options (so that they can be safely modified).

func (*ChannelOpts) DisableLogVerification

func (o *ChannelOpts) DisableLogVerification() *ChannelOpts

DisableLogVerification disables log verification for this channel.

func (*ChannelOpts) NoRelay added in v1.0.8

func (o *ChannelOpts) NoRelay() *ChannelOpts

NoRelay disables running the test with a relay interposed.

func (*ChannelOpts) SetFramePool

func (o *ChannelOpts) SetFramePool(framePool tchannel.FramePool) *ChannelOpts

SetFramePool sets FramePool in DefaultConnectionOptions.

func (*ChannelOpts) SetHealthChecks added in v1.8.0

func (o *ChannelOpts) SetHealthChecks(healthChecks tchannel.HealthCheckOptions) *ChannelOpts

SetHealthChecks sets HealthChecks in DefaultConnectionOptions.

func (*ChannelOpts) SetIdleCheckInterval added in v1.9.0

func (o *ChannelOpts) SetIdleCheckInterval(d time.Duration) *ChannelOpts

SetIdleCheckInterval sets the frequency of the periodic poller that removes stale connections from the channel.

func (*ChannelOpts) SetMaxIdleTime added in v1.9.0

func (o *ChannelOpts) SetMaxIdleTime(d time.Duration) *ChannelOpts

SetMaxIdleTime sets a threshold after which idle connections will automatically get dropped. See idle_sweep.go for more details.

func (*ChannelOpts) SetOnPeerStatusChanged added in v1.6.0

func (o *ChannelOpts) SetOnPeerStatusChanged(f func(*tchannel.Peer)) *ChannelOpts

SetOnPeerStatusChanged sets the callback for channel status change noficiations.

func (*ChannelOpts) SetProcessName

func (o *ChannelOpts) SetProcessName(processName string) *ChannelOpts

SetProcessName sets the ProcessName in ChannelOptions.

func (*ChannelOpts) SetRelayHost added in v1.2.2

func (o *ChannelOpts) SetRelayHost(rh tchannel.RelayHost) *ChannelOpts

SetRelayHost sets the channel's RelayHost, which enables relaying.

func (*ChannelOpts) SetRelayLocal added in v1.1.0

func (o *ChannelOpts) SetRelayLocal(relayLocal ...string) *ChannelOpts

SetRelayLocal sets the channel's relay local handlers for service names that should be handled by the relay channel itself.

func (*ChannelOpts) SetRelayMaxTimeout added in v1.2.2

func (o *ChannelOpts) SetRelayMaxTimeout(d time.Duration) *ChannelOpts

SetRelayMaxTimeout sets the maximum allowable timeout for relayed calls.

func (*ChannelOpts) SetRelayOnly added in v1.0.8

func (o *ChannelOpts) SetRelayOnly() *ChannelOpts

SetRelayOnly instructs TestServer to only run with a relay in front of this channel.

func (*ChannelOpts) SetRunCount added in v1.0.8

func (o *ChannelOpts) SetRunCount(n int) *ChannelOpts

SetRunCount sets the number of times run the test.

func (*ChannelOpts) SetSendBufferSize added in v1.2.2

func (o *ChannelOpts) SetSendBufferSize(bufSize int) *ChannelOpts

SetSendBufferSize sets the SendBufferSize in DefaultConnectionOptions.

func (*ChannelOpts) SetServiceName

func (o *ChannelOpts) SetServiceName(svcName string) *ChannelOpts

SetServiceName sets ServiceName.

func (*ChannelOpts) SetStatsReporter

func (o *ChannelOpts) SetStatsReporter(statsReporter tchannel.StatsReporter) *ChannelOpts

SetStatsReporter sets StatsReporter in ChannelOptions.

func (*ChannelOpts) SetTimeNow

func (o *ChannelOpts) SetTimeNow(timeNow func() time.Time) *ChannelOpts

SetTimeNow sets TimeNow in ChannelOptions.

func (*ChannelOpts) SetTimeTicker added in v1.8.0

func (o *ChannelOpts) SetTimeTicker(timeTicker func(d time.Duration) *time.Ticker) *ChannelOpts

SetTimeTicker sets TimeTicker in ChannelOptions.

func (*ChannelOpts) SetTosPriority added in v1.6.0

func (o *ChannelOpts) SetTosPriority(tosPriority tos.ToS) *ChannelOpts

SetTosPriority set TosPriority in DefaultConnectionOptions.

type Decrement added in v1.0.8

type Decrement interface {
	// Single returns whether any more tokens are remaining.
	Single() bool

	// Multiple tries to get n tokens. It returns the actual amount of tokens
	// available to use. If this is 0, it means there are no tokens left.
	Multiple(n int) int
}

Decrement is the interface returned by Decrementor.

func Decrementor

func Decrementor(n int) Decrement

Decrementor returns a function that can be called from multiple goroutines and ensures it will only return true n times.

type FakeCallFrame added in v1.0.8

type FakeCallFrame struct {
	ServiceF, MethodF, CallerF, RoutingKeyF, RoutingDelegateF string
}

FakeCallFrame is a stub implementation of the CallFrame interface.

func (FakeCallFrame) Caller added in v1.0.8

func (f FakeCallFrame) Caller() []byte

Caller returns the caller field.

func (FakeCallFrame) Method added in v1.0.8

func (f FakeCallFrame) Method() []byte

Method returns the method field.

func (FakeCallFrame) RoutingDelegate added in v1.1.0

func (f FakeCallFrame) RoutingDelegate() []byte

RoutingDelegate returns the routing delegate field.

func (FakeCallFrame) RoutingKey added in v1.2.0

func (f FakeCallFrame) RoutingKey() []byte

RoutingKey returns the routing delegate field.

func (FakeCallFrame) Service added in v1.0.8

func (f FakeCallFrame) Service() []byte

Service returns the service name field.

type FakeIncomingCall

type FakeIncomingCall struct {
	// CallerNameF is the calling service's name.
	CallerNameF string

	// ShardKeyF is the intended destination for this call.
	ShardKeyF string

	// RemotePeerF is the calling service's peer info.
	RemotePeerF tchannel.PeerInfo

	// LocalPeerF is the local service's peer info.
	LocalPeerF tchannel.LocalPeerInfo

	// RoutingKeyF is the routing key.
	RoutingKeyF string

	// RoutingDelegateF is the routing delegate.
	RoutingDelegateF string
}

FakeIncomingCall implements IncomingCall interface. Note: the F suffix for the fields is to clash with the method name.

func (*FakeIncomingCall) CallOptions added in v1.0.8

func (f *FakeIncomingCall) CallOptions() *tchannel.CallOptions

CallOptions returns the incoming call options suitable for proxying a request.

func (*FakeIncomingCall) CallerName

func (f *FakeIncomingCall) CallerName() string

CallerName returns the caller name as specified in the fake call.

func (*FakeIncomingCall) LocalPeer added in v1.2.2

func (f *FakeIncomingCall) LocalPeer() tchannel.LocalPeerInfo

LocalPeer returns the local peer information for this call.

func (*FakeIncomingCall) RemotePeer

func (f *FakeIncomingCall) RemotePeer() tchannel.PeerInfo

RemotePeer returns the remote peer information for this call.

func (*FakeIncomingCall) RoutingDelegate added in v1.0.2

func (f *FakeIncomingCall) RoutingDelegate() string

RoutingDelegate returns the routing delegate as specified in the fake call.

func (*FakeIncomingCall) RoutingKey added in v1.2.0

func (f *FakeIncomingCall) RoutingKey() string

RoutingKey returns the routing delegate as specified in the fake call.

func (*FakeIncomingCall) ShardKey

func (f *FakeIncomingCall) ShardKey() string

ShardKey returns the shard key as specified in the fake call.

type FakeTicker added in v1.9.0

type FakeTicker struct {
	// contains filtered or unexported fields
}

FakeTicker is a ticker for unit tests that can be controlled deterministically.

func NewFakeTicker added in v1.9.0

func NewFakeTicker() *FakeTicker

NewFakeTicker returns a new instance of FakeTicker

func (*FakeTicker) New added in v1.9.0

func (ft *FakeTicker) New(d time.Duration) *time.Ticker

New can be used in tests as a factory method for tickers, by passing it to ChannelOptions.TimeTicker

func (*FakeTicker) Tick added in v1.9.0

func (ft *FakeTicker) Tick()

Tick sends an immediate tick call to the receiver

func (*FakeTicker) TryTick added in v1.9.0

func (ft *FakeTicker) TryTick() bool

TryTick attempts to send a tick, if the channel isn't blocked.

type LogFilter

type LogFilter struct {
	// Filter specifies the substring match to search
	// for in the log message to skip raising an error.
	Filter string

	// Count is the maximum number of allowed warn+ logs matching
	// Filter before errors are raised.
	Count uint

	// FieldFilters specifies expected substring matches for fields.
	FieldFilters map[string]string
}

LogFilter is a single substring match that can be ignored.

func (LogFilter) Matches added in v1.0.3

func (f LogFilter) Matches(msg string, fields tchannel.LogFields) bool

Matches returns true if the message and fields match the filter.

type LogVerification

type LogVerification struct {
	Disabled bool

	Filters []LogFilter
}

LogVerification contains options to control the log verification.

func (*LogVerification) WrapLogger

func (v *LogVerification) WrapLogger(t testing.TB, l tchannel.Logger) tchannel.Logger

WrapLogger wraps the given logger with extra verification.

type StubClock added in v1.8.1

type StubClock struct {
	// contains filtered or unexported fields
}

StubClock is a fake wall-clock, exposing a Now() method that returns a test-controlled time.

func NewStubClock added in v1.8.1

func NewStubClock(initial time.Time) *StubClock

NewStubClock returns a fake wall-clock object

func (*StubClock) Elapse added in v1.8.1

func (c *StubClock) Elapse(addAmt time.Duration)

Elapse increments the time returned by Now()

func (*StubClock) Now added in v1.8.1

func (c *StubClock) Now() time.Time

Now returns the current time stored in StubClock

type TestServer added in v1.0.5

type TestServer struct {
	testing.TB
	// contains filtered or unexported fields
}

A TestServer encapsulates a TChannel server, a client factory, and functions to ensure that we're not leaking resources.

func NewTestServer added in v1.0.5

func NewTestServer(t testing.TB, opts *ChannelOpts) *TestServer

NewTestServer constructs a TestServer.

func (*TestServer) AssertRelayStats added in v1.0.8

func (ts *TestServer) AssertRelayStats(expected *relaytest.MockStats)

AssertRelayStats checks that the relayed call graph matches expectations. If there's no relay, AssertRelayStats is a no-op.

func (*TestServer) CloseAndVerify added in v1.0.5

func (ts *TestServer) CloseAndVerify()

CloseAndVerify closes all channels verifying each channel as it is closed. It then verifies that no goroutines were leaked.

func (*TestServer) HasRelay added in v1.0.8

func (ts *TestServer) HasRelay() bool

HasRelay indicates whether this TestServer has a relay interposed between the server and clients.

func (*TestServer) HostPort added in v1.0.5

func (ts *TestServer) HostPort() string

HostPort returns the host:port for clients to connect to. Note that this may not be the same as the host:port of the server channel.

func (*TestServer) NewClient added in v1.0.5

func (ts *TestServer) NewClient(opts *ChannelOpts) *tchannel.Channel

NewClient returns a client that with log verification. TODO: Verify message exchanges and leaks for client channels as well.

func (*TestServer) NewServer added in v1.0.5

func (ts *TestServer) NewServer(opts *ChannelOpts) *tchannel.Channel

NewServer returns a server with log and channel state verification.

func (*TestServer) Register added in v1.0.5

func (ts *TestServer) Register(h tchannel.Handler, methodName string)

Register registers a handler on the server channel.

func (*TestServer) RegisterFunc added in v1.0.8

func (ts *TestServer) RegisterFunc(name string, f func(context.Context, *raw.Args) (*raw.Res, error))

RegisterFunc registers a function as a handler for the given method name.

TODO: Delete testutils.RegisterFunc in favor of this test server.

func (*TestServer) Relay added in v1.0.8

func (ts *TestServer) Relay() *tchannel.Channel

Relay returns the relay channel, if one is present.

func (*TestServer) RelayHost added in v1.2.2

func (ts *TestServer) RelayHost() *relaytest.StubRelayHost

RelayHost returns the stub RelayHost for mapping service names to peers.

func (*TestServer) Server added in v1.0.5

func (ts *TestServer) Server() *tchannel.Channel

Server returns the underlying TChannel for the server (i.e., the channel on which we're registering handlers).

To support test cases with relays interposed between clients and servers, callers should use the Client(), HostPort(), ServiceName(), and Register() methods instead of accessing the server channel explicitly.

func (*TestServer) ServiceName added in v1.0.5

func (ts *TestServer) ServiceName() string

ServiceName returns the service name of the server channel.

func (*TestServer) SetVerifyOpts added in v1.0.5

func (ts *TestServer) SetVerifyOpts(opts *goroutines.VerifyOpts)

SetVerifyOpts specifies the options we'll use during teardown to verify that no goroutines were leaked.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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