testutil
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package testutil contains helper functions for writing tests.
Index¶
- 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 Diff(x, y interface{}, opts ...cmp.Option) string
- 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 OpenTelemetryTestExporter
- type R
- type Server
Constants¶
This section is empty.
Variables¶
var XGoogClientHeaderChecker = &HeaderChecker{Key: "x-goog-api-client",ValuesValidator: func(values ...string)error {iflen(values) == 0 {returnerrors.New("expecting values")}for _, value := range values {switch {casestrings.Contains(value, "gl-go/"):returnnildefault:}}returnerrors.New("unmatched values")},}
XGoogClientHeaderChecker is a HeaderChecker that ensures that the "x-goog-api-client"header is present on outgoing metadata.
Functions¶
funcCanReplay¶added inv0.25.0
CanReplay reports whether an integration test can be run in replay mode.The replay file must exist, and the GCLOUD_TESTS_GOLANG_ENABLE_REPLAYenvironment variable must be non-empty.
funcCredentials¶added inv0.37.0
func Credentials(ctxcontext.Context, scopes ...string) *google.Credentials
Credentials returns the credentials to use in integration tests, or nil ifnone is configured. It uses the standard environment variable for tests inthis repo.
funcCredentialsEnv¶added inv0.37.0
CredentialsEnv returns the credentials to use in integration tests, or nilif none is configured. If the environment variable is unset, CredentialsEnvwill try to find 'Application Default Credentials'. Else, CredentialsEnvwill return nil. CredentialsEnv will log.Fatal if the token source isspecified but missing or invalid.
funcDiff¶added inv0.11.0
Diff reports the differences between two values.Diff(x, y) == "" iff Equal(x, y).
funcJWTConfig¶added inv0.17.0
JWTConfig reads the JSON private key file whose name is in the defaultenvironment variable, and returns the jwt.Config it contains. It ignoresscopes.If the environment variable is empty, it returns (nil, nil).
funcNewRand¶added inv0.25.0
NewRand creates a new *rand.Rand seeded with t. The return value is safe for usewith multiple goroutines.
funcPageBounds¶added inv0.18.0
func PageBounds(pageSizeint, pageTokenstring, lengthint) (from, toint, nextPageTokenstring, errerror)
PageBounds converts an incoming page size and token from an RPC request intoslice bounds and the outgoing next-page token.
PageBounds assumes that the complete, unpaginated list of items exists as asingle slice. In addition to the page size and token, PageBounds needs thelength of that slice.
PageBounds's first two return values should be used to construct a sub-slice ofthe complete, unpaginated slice. E.g. if the complete slice is s, thens[from:to] is the desired page. Its third return value should be set as theNextPageToken field of the RPC response.
funcProjID¶
func ProjID()string
ProjID returns the project ID to use in integration tests, or the emptystring if none is configured.
funcRetry¶added inv0.97.0
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.
funcRetryWithoutTest¶added inv0.97.0
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.
funcTokenSource¶
func TokenSource(ctxcontext.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 variablefor tests in this repo.
funcTokenSourceEnv¶added inv0.15.0
TokenSourceEnv returns the OAuth2 token source to use in integration tests. or nilif none is configured. It tries to get credentials from the filename in theenvironment variable envVar. If the environment variable is unset, TokenSourceEnvwill try to find 'Application Default Credentials'. Else, TokenSourceEnv willreturn nil. TokenSourceEnv will log.Fatal if the token source is specified butmissing or invalid.
Types¶
typeErroringTokenSource¶added inv0.37.3
type ErroringTokenSource struct{}ErroringTokenSource is a token source for testing purposes,to always return a non-nil error to its caller. It is usefulwhen testing error responses with bad oauth2 credentials.
typeHeaderChecker¶added inv0.46.0
type HeaderChecker struct {// Key is the header name to be checked against e.g. "x-goog-api-client".Keystring// 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.
typeHeadersEnforcer¶added inv0.46.0
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 headersare present and match expectations. If the expected headersare not present or don't match expectations, it'll invoke OnFailurewith the validation error, or instead log.Fatal if OnFailure is nil.
It expects that every declared key will be present in the outgoingRPC header and each value will be validated by the validation function.
funcDefaultHeadersEnforcer¶added inv0.46.0
func DefaultHeadersEnforcer() *HeadersEnforcer
DefaultHeadersEnforcer returns a HeadersEnforcer that at bare minimum checks thatthe "x-goog-api-client" key is present in the outgoing metadata headers. On anyvalidation failure, it will invoke log.Fatalf with the error message.
func (*HeadersEnforcer)CallOptions¶added inv0.46.0
func (h *HeadersEnforcer) CallOptions() (copts []option.ClientOption)
CallOptions returns ClientOptions consisting of unary and stream interceptorsto enforce the presence and validity of expected headers.
func (*HeadersEnforcer)DialOptions¶added inv0.46.0
func (h *HeadersEnforcer) DialOptions() []grpc.DialOption
DialOptions returns gRPC DialOptions consisting of unary and stream interceptorsto enforce the presence and validity of expected headers.
func (*HeadersEnforcer)StreamInterceptors¶added inv0.48.0
func (h *HeadersEnforcer) StreamInterceptors() []grpc.StreamClientInterceptor
StreamInterceptors returns a list of StreamClientInterceptor functions whichenforce 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 toWithChainStreamInterceptor.
Alternatively, users may apply gPRC options produced from DialOptions toapply all applicable gRPC interceptors.
func (*HeadersEnforcer)UnaryInterceptors¶added inv0.48.0
func (h *HeadersEnforcer) UnaryInterceptors() []grpc.UnaryClientInterceptor
UnaryInterceptors returns a list of UnaryClientInterceptor functions whichenforce 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 toWithChainUnaryInterceptor.
Alternatively, users may apply gPRC options produced from DialOptions toapply all applicable gRPC interceptors.
typeOpenTelemetryTestExporter¶added inv0.111.0
type OpenTelemetryTestExporter struct {// contains filtered or unexported fields}OpenTelemetryTestExporter is a test utility exporter. It should be createdwith NewOpenTelemetryTestExporter.
funcNewOpenTelemetryTestExporter¶added inv0.111.0
func NewOpenTelemetryTestExporter() *OpenTelemetryTestExporter
NewOpenTelemetryTestExporter creates a OpenTelemetryTestExporter withunderlying InMemoryExporter and TracerProvider from OpenTelemetry.
func (*OpenTelemetryTestExporter)Spans¶added inv0.111.0
func (te *OpenTelemetryTestExporter) Spans()tracetest.SpanStubs
Spans returns the current in-memory stored spans.
func (*OpenTelemetryTestExporter)Unregister¶added inv0.111.0
func (te *OpenTelemetryTestExporter) Unregister(ctxcontext.Context)
Unregister shuts down the underlying OpenTelemetry TracerProvider.
typeR¶added inv0.97.0
type R struct {// The number of current attempt.Attemptint// contains filtered or unexported fields}R is passed to each run of a flaky test run, manages state and accumulates log statements.
func (*R)Fail¶added inv0.97.0
func (r *R) Fail()
Fail marks the run as failed, and will retry once the function returns.
typeServer¶
A Server is an in-process gRPC server, listening on a system-chosen port onthe local loopback interface. Servers are for testing only and are notintended to be used in production code.
To create a server, make a new Server, register your handlers, then callStart:
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())...
funcNewServer¶
func NewServer(opts ...grpc.ServerOption) (*Server,error)
NewServer creates a new Server on localhost. The Server will be listening forgRPC connections at the address named by the Addr field, without TLS.
funcNewServerWithAddress¶added inv0.119.0
func NewServerWithAddress(addrstring, opts ...grpc.ServerOption) (*Server,error)
NewServerWithAddress creates a new Server with a specific address (host andport). The Server will be listening for gRPC connections at the address namedby the Addr field, without TLS.
funcNewServerWithPort¶added inv0.29.0
func NewServerWithPort(portint, opts ...grpc.ServerOption) (*Server,error)
NewServerWithPort creates a new Server on localhost at a specific port. TheServer will be listening for gRPC connections at the address named by theAddr field, without TLS.