testutil

package
v0.114.0 Latest Latest
Warning

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

Go to latest
Published: May 23, 2024 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package testutil contains helper functions for writing tests.

Index

Constants

This section is empty.

Variables

View Source
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 added in v0.25.0

func CanReplay(replayFilename string) bool

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 added in v0.37.0

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 added in v0.37.0

func CredentialsEnv(ctx context.Context, envVar string, scopes ...string) *google.Credentials

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 Diff added in v0.11.0

func Diff(x, y interface{}, opts ...cmp.Option) string

Diff reports the differences between two values. Diff(x, y) == "" iff Equal(x, y).

func Equal added in v0.11.0

func Equal(x, y interface{}, opts ...cmp.Option) bool

Equal tests two values for equality.

func JWTConfig added in v0.17.0

func JWTConfig() (*jwt.Config, error)

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 added in v0.25.0

func NewRand(t time.Time) *rand.Rand

NewRand creates a new *rand.Rand seeded with t. The return value is safe for use with multiple goroutines.

func PageBounds added in v0.18.0

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 added in v0.97.0

func Retry(t *testing.T, maxAttempts int, sleep time.Duration, f func(r *R)) bool

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 added in v0.97.0

func RetryWithoutTest(maxAttempts int, sleep time.Duration, f func(r *R)) bool

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 added in v0.15.0

func TokenSourceEnv(ctx context.Context, envVar string, scopes ...string) oauth2.TokenSource

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 added in v0.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 useful when testing error responses with bad oauth2 credentials.

func (ErroringTokenSource) Token added in v0.37.3

func (fts ErroringTokenSource) Token() (*oauth2.Token, error)

Token implements oauth2.TokenSource, returning a nil oauth2.Token and a non-nil error.

type HeaderChecker added in v0.46.0

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 added in v0.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 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 added in v0.46.0

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 added in v0.46.0

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 added in v0.46.0

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 added in v0.48.0

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 added in v0.48.0

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 OpenTelemetryTestExporter added in v0.111.0

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

OpenTelemetryTestExporter is a test utility exporter. It should be created with NewOpenTelemetryTestExporter.

func NewOpenTelemetryTestExporter added in v0.111.0

func NewOpenTelemetryTestExporter() *OpenTelemetryTestExporter

NewOpenTelemetryTestExporter creates a OpenTelemetryTestExporter with underlying InMemoryExporter and TracerProvider from OpenTelemetry.

func (*OpenTelemetryTestExporter) Spans added in v0.111.0

Spans returns the current in-memory stored spans.

func (*OpenTelemetryTestExporter) Unregister added in v0.111.0

func (te *OpenTelemetryTestExporter) Unregister(ctx context.Context)

Unregister shuts down the underlying OpenTelemetry TracerProvider.

type R added in v0.97.0

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.

func (*R) Errorf added in v0.97.0

func (r *R) Errorf(s string, v ...interface{})

Errorf is equivalent to Logf followed by Fail.

func (*R) Fail added in v0.97.0

func (r *R) Fail()

Fail marks the run as failed, and will retry once the function returns.

func (*R) Logf added in v0.97.0

func (r *R) Logf(s string, v ...interface{})

Logf formats its arguments and records it in the error log. The text is only printed for the final unsuccessful run or the first successful run.

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 added in v0.29.0

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.

func (*Server) Close

func (s *Server) Close()

Close shuts down the server.

func (*Server) Start

func (s *Server) Start()

Start causes the server to start accepting incoming connections. Call Start after registering handlers.

type TestExporter added in v0.21.0

type TestExporter struct {
	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 added in v0.21.0

func NewTestExporter(views ...*view.View) *TestExporter

NewTestExporter creates a TestExporter and registers it with OpenCensus.

func (*TestExporter) ExportSpan added in v0.21.0

func (te *TestExporter) ExportSpan(s *trace.SpanData)

ExportSpan exports a span.

func (*TestExporter) ExportView added in v0.21.0

func (te *TestExporter) ExportView(vd *view.Data)

ExportView exports a view.

func (*TestExporter) Spans added in v0.21.0

func (te *TestExporter) Spans() []*trace.SpanData

Spans returns the exported spans.

func (*TestExporter) Unregister added in v0.21.0

func (te *TestExporter) Unregister()

Unregister unregisters the exporter from OpenCensus.

Jump to

Keyboard shortcuts

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