testhelper

package
v16.5.0-rc43 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2023 License: MIT Imports: 58 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// RepositoryAuthToken is the default token used to authenticate
	// against other Gitaly servers. It is inject as part of the
	// GitalyServers metadata.
	RepositoryAuthToken = "the-secret-token"
	// DefaultStorageName is the default name of the Gitaly storage.
	DefaultStorageName = "default"
)

Variables

This section is empty.

Functions

func AssertGrpcCode

func AssertGrpcCode(tb testing.TB, err error, expectedCode codes.Code)

AssertGrpcCode asserts that the error has the expected gRPC status code.

func Context

func Context(tb testing.TB, opts ...ContextOpt) context.Context

Context returns that gets canceled at the end of the test.

func ContextWithSimulatedTimeout added in v16.4.0

func ContextWithSimulatedTimeout(ctx context.Context) (context.Context, context.CancelFunc, context.CancelFunc)

ContextWithSimulatedTimeout creates a new context and allows the caller to simulate a timeout event. It returns a new context, a cancelation function, and a function that triggers the timeout event. After timeout, ctx.Done() channel is closed and ctx.Err() returns context.DeadlineExceeded. The context can be cancelled earlier by calling the returned cancelation function. This behavior is similar to any context returned from context.WithTimeout() or context.WithDeadline().

func ContextWithoutCancel

func ContextWithoutCancel(opts ...ContextOpt) context.Context

ContextWithoutCancel returns a non-cancellable context.

func CopyFile

func CopyFile(tb testing.TB, src, dst string)

CopyFile copies a file at the path src to a file at the path dst

func CreateGlobalDirectory

func CreateGlobalDirectory(tb testing.TB, name string) string

CreateGlobalDirectory creates a directory in the test directory that is shared across all between all tests.

func CreateTestLogDir

func CreateTestLogDir(tb testing.TB) string

CreateTestLogDir creates a new log directory for testing purposes if the environment variable `TEST_LOG_DIR` is set. The log directory will then be created as a subdirectory of the value that `TEST_LOG_DIR` points to. The name of the subdirectory will match the executing test's name.

Returns the name of the created log directory. If the environment variable is not set then this functions returns an empty string.

func EnabledOrDisabledFlag

func EnabledOrDisabledFlag[T any](ctx context.Context, flag featureflag.FeatureFlag, enabled, disabled T) T

EnabledOrDisabledFlag returns either the enabled value or the disabled value depending on the feature flag's state.

func GetLocalhostListener

func GetLocalhostListener(tb testing.TB) (net.Listener, string)

GetLocalhostListener listens on the next available TCP port and returns the listener and the localhost address (host:port) string.

func GetTemporaryGitalySocketFileName

func GetTemporaryGitalySocketFileName(tb testing.TB) string

GetTemporaryGitalySocketFileName will return a unique, useable socket file name

func GitLabTestCommit

func GitLabTestCommit(id string) *gitalypb.GitCommit

GitLabTestCommit provides a key value lookup for commits in the GitLab-Test repository

func GitalyOrPraefect

func GitalyOrPraefect[Type any](gitaly, praefect Type) Type

GitalyOrPraefect returns either the Gitaly- or Praefect-specific object depending on whether tests are running with Praefect as a proxy or not.

func GitlabTestStoragePath

func GitlabTestStoragePath() string

GitlabTestStoragePath returns the storage path to the gitlab-test repo.

func IsPraefectEnabled

func IsPraefectEnabled() bool

IsPraefectEnabled returns whether this testing run is done with Praefect in front of the Gitaly.

func IsWALEnabled added in v16.3.0

func IsWALEnabled() bool

IsWALEnabled returns whether write-ahead logging is enabled in this testing run.

func MergeIncomingMetadata

func MergeIncomingMetadata(ctx context.Context, md ...metadata.MD) context.Context

MergeIncomingMetadata merges provided metadata-s and returns context with resulting value.

func MergeOutgoingMetadata

func MergeOutgoingMetadata(ctx context.Context, md ...metadata.MD) context.Context

MergeOutgoingMetadata merges provided metadata-s and returns context with resulting value.

func MustClose

func MustClose(tb testing.TB, closer io.Closer)

MustClose calls Close() on the Closer and fails the test in case it returns an error. This function is useful when closing via `defer`, as a simple `defer require.NoError(t, closer.Close())` would cause `closer.Close()` to be executed early already.

func MustCreateCustomHooksTar

func MustCreateCustomHooksTar(tb testing.TB) io.Reader

MustCreateCustomHooksTar creates a temporary custom hooks tar archive on disk for testing and returns its file path.

func MustReadFile

func MustReadFile(tb testing.TB, filename string) []byte

MustReadFile returns the content of a file or fails at once.

func MustRunCommand

func MustRunCommand(tb testing.TB, stdin io.Reader, name string, args ...string) []byte

MustRunCommand runs a command with an optional standard input and returns the standard output, or fails.

func MustServe

func MustServe(tb testing.TB, server Server, listener net.Listener)

MustServe starts to serve the given server with the listener. This function asserts that the server was able to successfully serve and is useful in contexts where one wants to simply spawn a server in a Goroutine.

func NewHealthServerWithListener

func NewHealthServerWithListener(tb testing.TB, listener net.Listener) *health.Server

NewHealthServerWithListener creates a new gRPC server with the health server set up. It will listen on the given listener.

func NewLogger added in v16.4.0

func NewLogger(tb testing.TB, options ...LoggerOption) log.LogrusLogger

NewLogger returns a logger that records the log output and prints it out only if the test fails.

func NewServerWithHealth

func NewServerWithHealth(tb testing.TB, socketName string) *health.Server

NewServerWithHealth creates a new gRPC server with the health server set up. It will listen on the socket identified by `socketName`.

func PkgPath

func PkgPath(paths ...string) string

PkgPath returns the gitaly module package path, including major version number. paths will be path joined to the returned package path.

func ProtoEqual

func ProtoEqual(tb testing.TB, expected, actual interface{}, opts ...cmp.Option)

ProtoEqual asserts that expected and actual protobuf messages are equal. It can accept not only proto.Message, but slices, maps, and structs too. This is required as comparing messages directly with `require.Equal` doesn't work.

func Receive added in v16.3.0

func Receive[Response any](receiver func() (Response, error)) ([]Response, error)

Receive receives all responses from the receiver until an error is encountered or `io.EOF` is received.

func ReceiveAndFold added in v16.3.0

func ReceiveAndFold[Response, Result any](receiver func() (Response, error), folder func(initial Result, response Response) Result) (Result, error)

ReceiveAndFold receives all responses from the receiver and then folds the results with the given folder. The folder will be called even in the case where the receiver returns an error.

func RequireDirectoryState

func RequireDirectoryState(tb testing.TB, rootDirectory, relativeDirectory string, expected DirectoryState)

RequireDirectoryState asserts that given directory matches the expected state. The rootDirectory and relativeDirectory are joined together to decide the directory to walk. rootDirectory is trimmed out of the paths in the DirectoryState to make assertions easier by using the relative paths only. For example, given `/root-path` and `relative/path`, the directory walked is `/root-path/relative/path`. The paths in DirectoryState trim the root prefix, thus they should be like `/relative/path/...`. The beginning point of the walk has path "/".

func RequireGrpcCode

func RequireGrpcCode(tb testing.TB, err error, expectedCode codes.Code)

RequireGrpcCode asserts that the error has the expected gRPC status code.

func RequireGrpcError

func RequireGrpcError(tb testing.TB, expected, actual error, opts ...cmp.Option)

RequireGrpcError asserts that expected and actual gRPC errors are equal. Comparing gRPC errors directly with `require.Equal()` will not typically work correct.

func RequireStatusWithErrorMetadataRegexp added in v16.2.0

func RequireStatusWithErrorMetadataRegexp(tb testing.TB, expected, actual error, expectedMetadata map[string]string)

RequireStatusWithErrorMetadataRegexp asserts that expected and actual error match each other. Both are expected to be status errors. The error metadata in the status is matched against regular expressions defined in expectedMetadata. expectedMetadata is keyed by error metadata key, and the value is a regex string that the value is expected to match.

This method is useful when the error metadata contains values that should not be asserted for equality like changing paths. If the metadata is expected to be equal, use an equality assertion instead.

func RequireTarState

func RequireTarState(tb testing.TB, tarball io.Reader, expected DirectoryState)

RequireTarState asserts that the provided tarball contents matches the expected state.

func Run

func Run(m *testing.M, opts ...RunOption)

Run sets up required testing state and executes the given test suite. It can optionally receive a variable number of RunOptions.

func SetCtxGrpcMethod

func SetCtxGrpcMethod(ctx context.Context, method string) context.Context

SetCtxGrpcMethod will set the gRPC context value for the proper key responsible for an RPC full method name. This directly corresponds to the gRPC function responsible for extracting the method: https://godoc.org/google.golang.org/grpc#Method

func SharedLogger added in v16.4.0

func SharedLogger(tb testing.TB) log.LogrusLogger

SharedLogger returns a logger that is global to the running test case. When called first time during a test, a new logger is created and returned. All follow up calls to SharedLogger return the same logger instance.

This is more of a workaround. It would be preferable to inject the same logger returned from the first call everywhere in the test. We have however a large number of tests which are creating new loggers all over the place instead of passing the logger around. This sharing mechanism serves as a workaround to use the same logger everywhere in the same test case. Using the same logger ensures the log messages are properly ordered.

func SkipQuarantinedTest

func SkipQuarantinedTest(t *testing.T, issue string, tests ...string)

SkipQuarantinedTest skips the test if the test name has been specified as quarantined. If no test names are provided the test is always skipped.

func SkipWithPraefect

func SkipWithPraefect(tb testing.TB, reason string)

SkipWithPraefect skips the test if it is being executed with Praefect in front of the Gitaly.

func SkipWithWAL added in v16.3.0

func SkipWithWAL(tb testing.TB, reason string)

SkipWithWAL skips the test if write-ahead logging is enabled in this testing run. A reason should be provided either as a description or a link to an issue to explain why the test is skipped.

func StubTracingReporter

func StubTracingReporter(t *testing.T, opts ...StubTracingReporterOption) (*jaeger.InMemoryReporter, func())

StubTracingReporter stubs the distributed tracing's global tracer. It returns a reporter that records all generated spans along the way. The data is cleaned up afterward after the test is done. As there is only one global tracer, this stub is not safe to run in parallel.

func TempDir

func TempDir(tb testing.TB) string

TempDir is a wrapper around os.MkdirTemp that provides a cleanup function.

func ToInterceptedMetadata added in v16.1.0

func ToInterceptedMetadata(err structerr.Error) structerr.Error

ToInterceptedMetadata converts error metadata to intercepted error details.

func Umask added in v16.4.0

func Umask() perm.Umask

Umask return the umask of the current procses. Note that this value is computed once at initialization time because it is shared global state that is unsafe to access when there are multiple threads running at the same time. It follows that tests should never update the umask.

func Unsetenv

func Unsetenv(tb testing.TB, key string)

Unsetenv unsets an environment variable. The variable will be restored after the test has finished.

func WithInterceptedMetadata added in v16.1.0

func WithInterceptedMetadata(err structerr.Error, key string, value any) structerr.Error

WithInterceptedMetadata adds an additional metadata item to the Error in the form of an error detail. Note that this is only intended to be used in the context of tests where we convert error metadata into structured errors via the StructErrUnaryInterceptor and StructErrStreamInterceptor so that we can test that metadata has been set as expected on the client-side of a gRPC call.

func WithInterceptedMetadataItems added in v16.1.0

func WithInterceptedMetadataItems(err structerr.Error, items ...structerr.MetadataItem) structerr.Error

WithInterceptedMetadataItems adds multiple metadata items to the Error. It behaves as if WithInterceptedMetadata was called with each of the key-value items separately.

func WriteExecutable

func WriteExecutable(tb testing.TB, path string, content []byte) string

WriteExecutable ensures that the parent directory exists, and writes an executable with provided content. The executable must not exist previous to writing it. Returns the path of the written executable.

func WriteFiles added in v16.3.0

func WriteFiles(tb testing.TB, root string, files map[string]any)

WriteFiles writes a map of files to the filesystem where the map key is the filename relative to root and the value is one of string, []byte or io.Reader.

Types

type Certificate added in v16.1.0

type Certificate struct {
	CertPath string
	KeyPath  string
}

Certificate is a generated certificate.

func GenerateCertificate added in v16.1.0

func GenerateCertificate(tb testing.TB) Certificate

GenerateCertificate creates a certificate that can be used to establish TLS protected TCP connections.

func (Certificate) Cert added in v16.1.0

func (c Certificate) Cert(tb testing.TB) tls.Certificate

Cert returns the parsed certificate.

func (Certificate) CertPool added in v16.1.0

func (c Certificate) CertPool(tb testing.TB) *x509.CertPool

CertPool creates a new certificate pool containing the certificate.

func (Certificate) TransportCredentials added in v16.1.0

func (c Certificate) TransportCredentials(tb testing.TB) credentials.TransportCredentials

TransportCredentials creates new transport credentials that contain the generated certificates.

type Cleanup

type Cleanup func()

Cleanup functions should be called in a defer statement immediately after they are returned from a test helper

type ContextOpt

type ContextOpt func(context.Context) context.Context

ContextOpt returns a new context instance with the new additions to it.

type DirectoryEntry

type DirectoryEntry struct {
	// Mode is the file mode of the entry.
	Mode fs.FileMode
	// Content contains the file content if this is a regular file.
	Content any
	// ParseContent is a function that receives the file's absolute path, actual content
	// and returns it parsed into the expected form. The returned value is ultimately
	// asserted for equality with the Content.
	ParseContent func(tb testing.TB, path string, content []byte) any
}

DirectoryEntry models an entry in a directory.

type DirectoryState

type DirectoryState map[string]DirectoryEntry

DirectoryState models the contents of a directory. The key is relative of the entry in the rootDirectory as described on RequireDirectoryState.

type FakeDNSServer

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

FakeDNSServer starts a fake DNS server serving real DNS queries via UDP. The answers are returned from an input handler method.

func NewFakeDNSServer

func NewFakeDNSServer(t *testing.T) *FakeDNSServer

NewFakeDNSServer returns a new real fake DNS server object

func (*FakeDNSServer) Addr

func (s *FakeDNSServer) Addr() string

Addr returns the UDP address used to access the DNS nameserver

func (*FakeDNSServer) Start

func (s *FakeDNSServer) Start() *FakeDNSServer

Start starts the DNS name server. The server stops in the test clean-up phase

func (*FakeDNSServer) WithHandler

func (s *FakeDNSServer) WithHandler(t uint16, handler fakeDNSHandler) *FakeDNSServer

WithHandler adds a handler for an input DNS record type

type FeatureSet

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

FeatureSet is a representation of a set of features that should be disabled. This is useful in situations where a test needs to test any combination of features toggled on and off. It is designed to disable features as all features are enabled by default, please see: testhelper.Context()

func (FeatureSet) Apply

func (f FeatureSet) Apply(ctx context.Context) context.Context

Apply applies all feature flags in the given FeatureSet to the given context.

func (FeatureSet) Desc

func (f FeatureSet) Desc() string

Desc describes the feature such that it is suitable as a testcase description.

type FeatureSets

type FeatureSets []FeatureSet

FeatureSets is a slice containing many FeatureSets

func NewFeatureSets

func NewFeatureSets(features ...featureflag.FeatureFlag) FeatureSets

NewFeatureSets takes Go feature flags and returns the combination of FeatureSets.

func (FeatureSets) Bench

func (s FeatureSets) Bench(b *testing.B, test func(b *testing.B, ctx context.Context))

Bench executes the given benchmarking function for each of the FeatureSets. The passed in context has the feature flags set accordingly.

func (FeatureSets) Run

func (s FeatureSets) Run(t *testing.T, test func(t *testing.T, ctx context.Context))

Run executes the given test function for each of the FeatureSets. The passed in context has the feature flags set accordingly.

type LoggerHook added in v16.4.0

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

LoggerHook is a hook that can be installed on the test logger in order to intercept log entries.

func AddLoggerHook added in v16.4.0

func AddLoggerHook(logger log.LogrusLogger) LoggerHook

AddLoggerHook installs a hook on the logger.

func (LoggerHook) AllEntries added in v16.4.0

func (h LoggerHook) AllEntries() []*logrus.Entry

AllEntries returns all log entries that have been intercepted by the hook.

func (LoggerHook) LastEntry added in v16.4.0

func (h LoggerHook) LastEntry() *logrus.Entry

LastEntry returns the last log entry or `nil` if there are no logged entries.

func (LoggerHook) Reset added in v16.4.0

func (h LoggerHook) Reset()

Reset empties the list of intercepted log entries.

type LoggerOption added in v16.4.0

type LoggerOption func(*loggerOptions)

LoggerOption configures a logger.

func WithLoggerName added in v16.4.0

func WithLoggerName(name string) LoggerOption

WithLoggerName sets the name of the logger. The name is included along the logs to help identifying the logs if multiple loggers are used.

type RunOption

type RunOption func(*runConfig)

RunOption is an option that can be passed to Run.

func WithDisabledGoroutineChecker deprecated

func WithDisabledGoroutineChecker() RunOption

WithDisabledGoroutineChecker disables checking for leaked Goroutines after tests have run. This should ideally only be used as a temporary measure until all Goroutine leaks have been fixed.

Deprecated: This should not be used, but instead you should try to fix all Goroutine leakages.

func WithSetup

func WithSetup(setup func() error) RunOption

WithSetup allows the caller of Run to pass a setup function that will be called after global test state has been configured.

type Server

type Server interface {
	Serve(net.Listener) error
}

Server is an interface for a server that can serve requests on a specific listener. This interface is used by the MustServe helper function.

type Span

type Span struct {
	// Operation is the name of the operation being traced.
	Operation string
	// StartTime is the point in time when the span started.
	StartTime time.Time
	// Duration captures the elapsed time of the operation traced by the span.
	Duration time.Duration
	// Tags is a map that contains key-value pairs of stringified tags associated with the span.
	Tags map[string]string
}

Span is a struct that provides a more test-friendly way to assert distributed tracing spans.

func ReportedSpans

func ReportedSpans(t *testing.T, reporter *jaeger.InMemoryReporter) []*Span

ReportedSpans function converts the spans that were captured by the stubbed reporter into an assertable data structure. Initially, the collected traces are represented using opentracing's Span interface. However, this interface is not suitable for testing purposes. Therefore, we must cast them to a Jaeger Span, which contains a lot of information that is not relevant to testing. The new span struct that is created contains only essential and safe-for-testing fields

type StubTracingReporterOption

type StubTracingReporterOption func(*stubTracingReporterConfig)

StubTracingReporterOption is a function that modifies the config of stubbed tracing reporter

func NeverSampled

func NeverSampled() StubTracingReporterOption

NeverSampled is an option that makes the stubbed tracer never sample spans

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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