Documentation ¶
Overview ¶
Package testutil contains helper functions for writing tests.
Index ¶
- Constants
- Variables
- func CanReplay(replayFilename string) bool
- func Credentials(ctx context.Context, scopes ...string) *google.Credentials
- func CredentialsEnv(ctx context.Context, envVar string, scopes ...string) *google.Credentials
- func DecodeResumeToken(t []byte) (uint64, error)
- func Diff(x, y interface{}, opts ...cmp.Option) string
- func EncodeResumeToken(t uint64) []byte
- func Equal(x, y interface{}, opts ...cmp.Option) bool
- func JWTConfig() (*jwt.Config, error)
- func NewRand(t time.Time) *rand.Rand
- func PageBounds(pageSize int, pageToken string, length int) (from, to int, nextPageToken string, err error)
- func ProjID() string
- func Retry(t *testing.T, maxAttempts int, sleep time.Duration, f func(r *R)) bool
- func RetryWithoutTest(maxAttempts int, sleep time.Duration, f func(r *R)) bool
- func TokenSource(ctx context.Context, scopes ...string) oauth2.TokenSource
- func TokenSourceEnv(ctx context.Context, envVar string, scopes ...string) oauth2.TokenSource
- type ErroringTokenSource
- type HeaderChecker
- type HeadersEnforcer
- type InMemInstanceAdminServer
- type InMemSpannerServer
- type MockedSpannerInMemTestServer
- func NewMockedSpannerInMemTestServer(t *testing.T, sopt ...grpc.ServerOption) (mockedServer *MockedSpannerInMemTestServer, opts []option.ClientOption, ...)
- func NewMockedSpannerInMemTestServerWithAddr(t *testing.T, addr string, sopt ...grpc.ServerOption) (mockedServer *MockedSpannerInMemTestServer, opts []option.ClientOption, ...)
- type OpenTelemetryTestExporter
- type PartialResultSetExecutionTime
- type R
- type Server
- type SimulatedExecutionTime
- type StatementResult
- type StatementResultType
- type TestExporter
Constants ¶
const ( MethodBeginTransaction string = "BEGIN_TRANSACTION" MethodCommitTransaction string = "COMMIT_TRANSACTION" MethodBatchCreateSession string = "BATCH_CREATE_SESSION" MethodCreateSession string = "CREATE_SESSION" MethodDeleteSession string = "DELETE_SESSION" MethodGetSession string = "GET_SESSION" MethodExecuteSql string = "EXECUTE_SQL" MethodExecuteStreamingSql string = "EXECUTE_STREAMING_SQL" MethodExecuteBatchDml string = "EXECUTE_BATCH_DML" MethodStreamingRead string = "EXECUTE_STREAMING_READ" MethodBatchWrite string = "BATCH_WRITE" )
The method names that can be used to register execution times and errors.
const SelectFooFromBar = "SELECT FOO FROM BAR"
SelectFooFromBar is a SELECT statement that is added to the mocked test server and will return a one-col-two-rows result set containing the INT64 values 1 and 2.
const SelectSingerIDAlbumIDAlbumTitleFromAlbums = "SELECT SingerId, AlbumId, AlbumTitle FROM Albums"
SelectSingerIDAlbumIDAlbumTitleFromAlbums i a SELECT statement that is added to the mocked test server and will return a 3-cols-3-rows result set.
const SelectSingerIDAlbumIDAlbumTitleFromAlbumsColCount int = 3
SelectSingerIDAlbumIDAlbumTitleFromAlbumsColCount is the number of cols returned by the SelectSingerIDAlbumIDAlbumTitleFromAlbums statement.
const SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount int64 = 3
SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount is the number of rows returned by the SelectSingerIDAlbumIDAlbumTitleFromAlbums statement.
const UpdateBarSetFoo = "UPDATE FOO SET BAR=1 WHERE BAZ=2"
UpdateBarSetFoo is an UPDATE statement that is added to the mocked test server that will return an update count of 5.
const UpdateBarSetFooRowCount = 5
UpdateBarSetFooRowCount is the constant update count value returned by the statement defined in UpdateBarSetFoo.
Variables ¶
var ( // KvMeta is the Metadata for mocked KV table. KvMeta = spannerpb.ResultSetMetadata{ RowType: &spannerpb.StructType{ Fields: []*spannerpb.StructType_Field{ { Name: "Key", Type: &spannerpb.Type{Code: spannerpb.TypeCode_STRING}, }, { Name: "Value", Type: &spannerpb.Type{Code: spannerpb.TypeCode_STRING}, }, }, }, } )
var XGoogClientHeaderChecker = &HeaderChecker{ Key: "x-goog-api-client", ValuesValidator: func(values ...string) error { if len(values) == 0 { return errors.New("expecting values") } for _, value := range values { switch { case strings.Contains(value, "gl-go/"): return nil default: } } return errors.New("unmatched values") }, }
XGoogClientHeaderChecker is a HeaderChecker that ensures that the "x-goog-api-client" header is present on outgoing metadata.
Functions ¶
func CanReplay ¶
CanReplay reports whether an integration test can be run in replay mode. The replay file must exist, and the GCLOUD_TESTS_GOLANG_ENABLE_REPLAY environment variable must be non-empty.
func Credentials ¶
func Credentials(ctx context.Context, scopes ...string) *google.Credentials
Credentials returns the credentials to use in integration tests, or nil if none is configured. It uses the standard environment variable for tests in this repo.
func CredentialsEnv ¶
CredentialsEnv returns the credentials to use in integration tests, or nil if none is configured. If the environment variable is unset, CredentialsEnv will try to find 'Application Default Credentials'. Else, CredentialsEnv will return nil. CredentialsEnv will log.Fatal if the token source is specified but missing or invalid.
func DecodeResumeToken ¶
DecodeResumeToken decodes a mock resume token into an uint64 integer.
func EncodeResumeToken ¶
EncodeResumeToken return mock resume token encoding for an uint64 integer.
func JWTConfig ¶
JWTConfig reads the JSON private key file whose name is in the default environment variable, and returns the jwt.Config it contains. It ignores scopes. If the environment variable is empty, it returns (nil, nil).
func NewRand ¶
NewRand creates a new *rand.Rand seeded with t. The return value is safe for use with multiple goroutines.
func PageBounds ¶
func PageBounds(pageSize int, pageToken string, length int) (from, to int, nextPageToken string, err error)
PageBounds converts an incoming page size and token from an RPC request into slice bounds and the outgoing next-page token.
PageBounds assumes that the complete, unpaginated list of items exists as a single slice. In addition to the page size and token, PageBounds needs the length of that slice.
PageBounds's first two return values should be used to construct a sub-slice of the complete, unpaginated slice. E.g. if the complete slice is s, then s[from:to] is the desired page. Its third return value should be set as the NextPageToken field of the RPC response.
func ProjID ¶
func ProjID() string
ProjID returns the project ID to use in integration tests, or the empty string if none is configured.
func Retry ¶
Retry runs function f for up to maxAttempts times until f returns successfully, and reports whether f was run successfully. It will sleep for the given period between invocations of f. Use the provided *testutil.R instead of a *testing.T from the function.
func RetryWithoutTest ¶
RetryWithoutTest is a variant of Retry that does not use a testing parameter. It is meant for testing utilities that do not pass around the testing context, such as cloudrunci.
func TokenSource ¶
func TokenSource(ctx context.Context, scopes ...string) oauth2.TokenSource
TokenSource returns the OAuth2 token source to use in integration tests, or nil if none is configured. It uses the standard environment variable for tests in this repo.
func TokenSourceEnv ¶
TokenSourceEnv returns the OAuth2 token source to use in integration tests. or nil if none is configured. It tries to get credentials from the filename in the environment variable envVar. If the environment variable is unset, TokenSourceEnv will try to find 'Application Default Credentials'. Else, TokenSourceEnv will return nil. TokenSourceEnv will log.Fatal if the token source is specified but missing or invalid.
Types ¶
type ErroringTokenSource ¶
type ErroringTokenSource struct{}
ErroringTokenSource is a token source for testing purposes, to always return a non-nil error to its caller. It is useful when testing error responses with bad oauth2 credentials.
type HeaderChecker ¶
type HeaderChecker struct { // Key is the header name to be checked against e.g. "x-goog-api-client". Key string // ValuesValidator validates the header values retrieved from mapping against // Key in the Headers. ValuesValidator func(values ...string) error }
HeaderChecker defines header checking and validation rules for any outgoing metadata.
type HeadersEnforcer ¶
type HeadersEnforcer struct { // Checkers maps header keys that are expected to be sent in the metadata // of outgoing gRPC requests, against the values passed into the custom // validation functions. // // If Checkers is nil or empty, only the default header "x-goog-api-client" // will be checked for. // Otherwise, if you supply Matchers, those keys and their respective // validation functions will be checked. Checkers []*HeaderChecker // OnFailure is the function that will be invoked after all validation // failures have been composed. If OnFailure is nil, log.Fatal will be // invoked instead. OnFailure func(fmt_ string, args ...interface{}) }
HeadersEnforcer asserts that outgoing RPC headers are present and match expectations. If the expected headers are not present or don't match expectations, it'll invoke OnFailure with the validation error, or instead log.Fatal if OnFailure is nil.
It expects that every declared key will be present in the outgoing RPC header and each value will be validated by the validation function.
func DefaultHeadersEnforcer ¶
func DefaultHeadersEnforcer() *HeadersEnforcer
DefaultHeadersEnforcer returns a HeadersEnforcer that at bare minimum checks that the "x-goog-api-client" key is present in the outgoing metadata headers. On any validation failure, it will invoke log.Fatalf with the error message.
func (*HeadersEnforcer) CallOptions ¶
func (h *HeadersEnforcer) CallOptions() (copts []option.ClientOption)
CallOptions returns ClientOptions consisting of unary and stream interceptors to enforce the presence and validity of expected headers.
func (*HeadersEnforcer) DialOptions ¶
func (h *HeadersEnforcer) DialOptions() []grpc.DialOption
DialOptions returns gRPC DialOptions consisting of unary and stream interceptors to enforce the presence and validity of expected headers.
func (*HeadersEnforcer) StreamInterceptors ¶
func (h *HeadersEnforcer) StreamInterceptors() []grpc.StreamClientInterceptor
StreamInterceptors returns a list of StreamClientInterceptor functions which enforce the presence and validity of expected headers during streaming RPCs.
For client implementations which provide their own StreamClientInterceptor(s) these interceptors should be specified as the final elements to WithChainStreamInterceptor.
Alternatively, users may apply gPRC options produced from DialOptions to apply all applicable gRPC interceptors.
func (*HeadersEnforcer) UnaryInterceptors ¶
func (h *HeadersEnforcer) UnaryInterceptors() []grpc.UnaryClientInterceptor
UnaryInterceptors returns a list of UnaryClientInterceptor functions which enforce the presence and validity of expected headers during unary RPCs.
For client implementations which provide their own UnaryClientInterceptor(s) these interceptors should be specified as the final elements to WithChainUnaryInterceptor.
Alternatively, users may apply gPRC options produced from DialOptions to apply all applicable gRPC interceptors.
type InMemInstanceAdminServer ¶
type InMemInstanceAdminServer interface { instancepb.InstanceAdminServer Stop() Resps() []proto.Message SetResps([]proto.Message) Reqs() []proto.Message SetReqs([]proto.Message) SetErr(error) }
InMemInstanceAdminServer contains the InstanceAdminServer interface plus a couple of specific methods for setting mocked results.
func NewInMemInstanceAdminServer ¶
func NewInMemInstanceAdminServer() InMemInstanceAdminServer
NewInMemInstanceAdminServer creates a new in-mem test server.
type InMemSpannerServer ¶
type InMemSpannerServer interface { spannerpb.SpannerServer // Stops this server. Stop() // Resets the in-mem server to its default state, deleting all sessions and // transactions that have been created on the server. Mocked results are // not deleted. Reset() // Sets an error that will be returned by the next server call. The server // call will also automatically clear the error. SetError(err error) // Puts a mocked result on the server for a specific sql statement. The // server does not parse the SQL string in any way, it is merely used as // a key to the mocked result. The result will be used for all methods that // expect a SQL statement, including (batch) DML methods. PutStatementResult(sql string, result *StatementResult) error // Puts a mocked result on the server for a specific partition token. The // result will only be used for query requests that specify a partition // token. PutPartitionResult(partitionToken []byte, result *StatementResult) error // Adds a PartialResultSetExecutionTime to the server that should be returned // for the specified SQL string. AddPartialResultSetError(sql string, err PartialResultSetExecutionTime) // Removes a mocked result on the server for a specific sql statement. RemoveStatementResult(sql string) // Aborts the specified transaction . This method can be used to test // transaction retry logic. AbortTransaction(id []byte) // Puts a simulated execution time for one of the Spanner methods. PutExecutionTime(method string, executionTime SimulatedExecutionTime) // Freeze stalls all requests. Freeze() // Unfreeze restores processing requests. Unfreeze() TotalSessionsCreated() uint TotalSessionsDeleted() uint SetMaxSessionsReturnedByServerPerBatchRequest(sessionCount int32) SetMaxSessionsReturnedByServerInTotal(sessionCount int32) ReceivedRequests() chan interface{} DumpSessions() map[string]bool ClearPings() DumpPings() []string }
InMemSpannerServer contains the SpannerServer interface plus a couple of specific methods for adding mocked results and resetting the server.
func NewInMemSpannerServer ¶
func NewInMemSpannerServer() InMemSpannerServer
NewInMemSpannerServer creates a new in-mem test server.
type MockedSpannerInMemTestServer ¶
type MockedSpannerInMemTestServer struct { TestSpanner InMemSpannerServer TestInstanceAdmin InMemInstanceAdminServer ServerAddress string // contains filtered or unexported fields }
MockedSpannerInMemTestServer is an InMemSpannerServer with results for a number of SQL statements readily mocked.
func NewMockedSpannerInMemTestServer ¶
func NewMockedSpannerInMemTestServer(t *testing.T, sopt ...grpc.ServerOption) (mockedServer *MockedSpannerInMemTestServer, opts []option.ClientOption, teardown func())
NewMockedSpannerInMemTestServer creates a MockedSpannerInMemTestServer at localhost with a random port and returns client options that can be used to connect to it.
func NewMockedSpannerInMemTestServerWithAddr ¶
func NewMockedSpannerInMemTestServerWithAddr(t *testing.T, addr string, sopt ...grpc.ServerOption) (mockedServer *MockedSpannerInMemTestServer, opts []option.ClientOption, teardown func())
NewMockedSpannerInMemTestServerWithAddr creates a MockedSpannerInMemTestServer at a given listening address and returns client options that can be used to connect to it.
func (*MockedSpannerInMemTestServer) CreateSingleRowSingersResult ¶
func (s *MockedSpannerInMemTestServer) CreateSingleRowSingersResult(rowNum int64) *StatementResult
CreateSingleRowSingersResult creates a result set containing a single row of the SelectSingerIDAlbumIDAlbumTitleFromAlbums result set, or zero rows if the given rowNum is greater than the number of rows in the result set. This method can be used to mock results for different partitions of a BatchReadOnlyTransaction.
type OpenTelemetryTestExporter ¶
type OpenTelemetryTestExporter struct {
// contains filtered or unexported fields
}
OpenTelemetryTestExporter is a test utility exporter. It should be created with NewOpenTelemetryTestExporter.
func NewOpenTelemetryTestExporter ¶
func NewOpenTelemetryTestExporter() *OpenTelemetryTestExporter
NewOpenTelemetryTestExporter creates a OpenTelemetryTestExporter with underlying InMemoryExporter and TracerProvider from OpenTelemetry.
func (*OpenTelemetryTestExporter) Spans ¶
func (te *OpenTelemetryTestExporter) Spans() tracetest.SpanStubs
Spans returns the current in-memory stored spans.
func (*OpenTelemetryTestExporter) Unregister ¶
func (te *OpenTelemetryTestExporter) Unregister(ctx context.Context)
Unregister shuts down the underlying OpenTelemetry TracerProvider.
type PartialResultSetExecutionTime ¶
type PartialResultSetExecutionTime struct { ResumeToken []byte ExecutionTime time.Duration Err error }
PartialResultSetExecutionTime represents execution times and errors that should be used when a PartialResult at the specified resume token is to be returned.
type R ¶
type R struct { // The number of current attempt. Attempt int // contains filtered or unexported fields }
R is passed to each run of a flaky test run, manages state and accumulates log statements.
type Server ¶
type Server struct { Addr string Port int Gsrv *grpc.Server // contains filtered or unexported fields }
A Server is an in-process gRPC server, listening on a system-chosen port on the local loopback interface. Servers are for testing only and are not intended to be used in production code.
To create a server, make a new Server, register your handlers, then call Start:
srv, err := NewServer() ... mypb.RegisterMyServiceServer(srv.Gsrv, &myHandler) .... srv.Start()
Clients should connect to the server with no security:
conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure()) ...
func NewServer ¶
func NewServer(opts ...grpc.ServerOption) (*Server, error)
NewServer creates a new Server. The Server will be listening for gRPC connections at the address named by the Addr field, without TLS.
func NewServerWithPort ¶
func NewServerWithPort(port int, opts ...grpc.ServerOption) (*Server, error)
NewServerWithPort creates a new Server at a specific port. The Server will be listening for gRPC connections at the address named by the Addr field, without TLS.
type SimulatedExecutionTime ¶
type SimulatedExecutionTime struct { MinimumExecutionTime time.Duration RandomExecutionTime time.Duration Errors []error // Keep error after execution. The error will continue to be returned until // it is cleared. KeepError bool }
SimulatedExecutionTime represents the time the execution of a method should take, and any errors that should be returned by the method.
type StatementResult ¶
type StatementResult struct { Type StatementResultType Err error ResultSet *spannerpb.ResultSet UpdateCount int64 ResumeTokens [][]byte }
StatementResult represents a mocked result on the test server. The result is either of: a ResultSet, an update count or an error.
func (*StatementResult) ToPartialResultSets ¶
func (s *StatementResult) ToPartialResultSets(resumeToken []byte) (result []*spannerpb.PartialResultSet, err error)
ToPartialResultSets converts a ResultSet to a PartialResultSet. This method is used to convert a mocked result to a PartialResultSet when one of the streaming methods are called.
type StatementResultType ¶
type StatementResultType int
StatementResultType indicates the type of result returned by a SQL statement.
const ( // StatementResultError indicates that the sql statement returns an error. StatementResultError StatementResultType = 0 // StatementResultResultSet indicates that the sql statement returns a // result set. StatementResultResultSet StatementResultType = 1 // StatementResultUpdateCount indicates that the sql statement returns an // update count. StatementResultUpdateCount StatementResultType = 2 // MaxRowsPerPartialResultSet is the maximum number of rows returned in // each PartialResultSet. This number is deliberately set to a low value to // ensure that most queries return more than one PartialResultSet. MaxRowsPerPartialResultSet = 1 )
type TestExporter ¶
type TestExporter struct { Spans []*trace.SpanData Stats chan *view.Data Views []*view.View // contains filtered or unexported fields }
TestExporter is a test utility exporter. It should be created with NewtestExporter.
func NewTestExporter ¶
func NewTestExporter(views ...*view.View) *TestExporter
NewTestExporter creates a TestExporter and registers it with OpenCensus.
func (*TestExporter) ExportSpan ¶
func (te *TestExporter) ExportSpan(s *trace.SpanData)
ExportSpan exports a span.
func (*TestExporter) ExportView ¶
func (te *TestExporter) ExportView(vd *view.Data)
ExportView exports a view.
func (*TestExporter) Unregister ¶
func (te *TestExporter) Unregister()
Unregister unregisters the exporter from OpenCensus.