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¶
Index¶
- Constants
- Variables
- func AssertReceive[A any](ctx context.Context, t testing.TB, c <-chan A) (A, bool)
- func AssertSend[A any](ctx context.Context, t testing.TB, c chan<- A, a A) bool
- func Context(t *testing.T, dur time.Duration) context.Context
- func CreateTar(t testing.TB, files map[string]string) []byte
- func CreateTemp(t *testing.T, dir, pattern string) *os.File
- func CreateZip(t testing.TB, files map[string]string) []byte
- func Eventually(ctx context.Context, t testing.TB, ...) (done bool)
- func GenerateTLSCertificate(t testing.TB, commonName string) tls.Certificate
- func GetRandomName(t testing.TB) string
- func GetRandomNameHyphenated(t testing.TB) string
- func Go(t *testing.T, fn func()) (done <-chan struct{})
- func IgnoreLoggedError(entry slog.SinkEntry) bool
- func InCI() bool
- func Logger(t testing.TB) slog.Logger
- func MustRandString(t *testing.T, n int) string
- func PersistentCacheDir(t *testing.T) string
- func PopulateStruct(s interface{}, r *Random) error
- func PromCounterAssertion(t testing.TB, metrics []*dto.MetricFamily, assert func(in float64) bool, ...) bool
- func PromCounterGathered(t testing.TB, metrics []*dto.MetricFamily, name string, labels ...string) bool
- func PromCounterHasValue(t testing.TB, metrics []*dto.MetricFamily, value float64, name string, ...) bool
- func PromGaugeAssertion(t testing.TB, metrics []*dto.MetricFamily, assert func(in float64) bool, ...) bool
- func PromGaugeGathered(t testing.TB, metrics []*dto.MetricFamily, name string, labels ...string) bool
- func PromGaugeHasValue(t testing.TB, metrics []*dto.MetricFamily, value float64, name string, ...) bool
- func RaceEnabled() bool
- func RandomIPv6(t testing.TB) string
- func RandomPort(t *testing.T) int
- func RandomPortNoListen(*testing.T) uint16
- func RequireJSONEq(t *testing.T, expected, actual string)
- func RequireReceive[A any](ctx context.Context, t testing.TB, c <-chan A) A
- func RequireSend[A any](ctx context.Context, t testing.TB, c chan<- A, a A)
- func SkipIfNotTiming(t *testing.T)
- func SoftTryReceive[A any](ctx context.Context, t testing.TB, c <-chan A) (A, bool)
- func TempFile(t *testing.T, dir, pattern string) string
- func TryReceive[A any](ctx context.Context, t testing.TB, c <-chan A) A
- type OAuth2Config
- func (*OAuth2Config) AuthCodeURL(state string, _ ...oauth2.AuthCodeOption) string
- func (*OAuth2Config) Do(_ context.Context, _ promoauth.Oauth2Source, req *http.Request) (*http.Response, error)
- func (c *OAuth2Config) Exchange(_ context.Context, _ string, _ ...oauth2.AuthCodeOption) (*oauth2.Token, error)
- func (c *OAuth2Config) TokenSource(_ context.Context, _ *oauth2.Token) oauth2.TokenSource
- type OAuth2TokenSource
- type Random
- type ReaderWriterConn
- func (*ReaderWriterConn) Close() (err error)
- func (*ReaderWriterConn) LocalAddr() net.Addr
- func (*ReaderWriterConn) RemoteAddr() net.Addr
- func (*ReaderWriterConn) SetDeadline(_ time.Time) error
- func (*ReaderWriterConn) SetReadDeadline(_ time.Time) error
- func (*ReaderWriterConn) SetWriteDeadline(_ time.Time) error
- type TerminalReader
Constants¶
const (WaitShort = 10 *time.SecondWaitMedium = 15 *time.SecondWaitLong = 25 *time.SecondWaitSuperLong = 60 *time.Second)
Constants for timing out operations, usable for creating contextsthat timeout or in require.Eventually.
const (IntervalFast = 25 *time.MillisecondIntervalMedium = 250 *time.MillisecondIntervalSlow =time.Second)
Constants for delaying repeated operations, e.g. inrequire.Eventually.
Variables¶
var GoleakOptions []goleak.Option = []goleak.Option{goleak.IgnoreAnyFunction("github.com/cihub/seelog.(*asyncLoopLogger).processQueue"),goleak.IgnoreTopFunction("gopkg.in/natefinch/lumberjack%2ev2.(*Logger).millRun"),goleak.IgnoreTopFunction("gopkg.in/natefinch/lumberjack%2ev2.(*Logger).mill.func1"),goleak.IgnoreTopFunction("github.com/lib/pq.NewDialListener"),}
GoleakOptions is a common list of options to pass to goleak. This is useful if there is a knownleaky function we want to exclude from goleak.
Functions¶
funcAssertReceive¶added inv2.23.0
AssertReceive will receive a value from the chan and return it. If thecontext expires or the channel is closed before a value can be received,it will mark the test as failed but continue execution.The second return value indicates whether the receive was successful.
Safety: can be called from any goroutine.
funcAssertSend¶added inv2.23.0
AssertSend will send the given value over the chan and then return. Ifthe context expires before the send succeeds, it will mark the test as failedbut continue execution.The second return value indicates whether the send was successful.
Safety: can be called from any goroutine.
funcCreateTar¶added inv2.18.0
Creates an in-memory tar of the files provided.Files in the archive are written with nobodyowner/group, and -rw-rw-rw- permissions.
funcCreateTemp¶
CreateTemp is a convenience function for creating a temporary file, likeos.CreateTemp, but it also registers a cleanup function to close and removethe file.
funcCreateZip¶added inv2.18.0
Creates an in-memory zip of the files provided.Uses archive.CreateZipFromTar under the hood.
funcEventually¶
func Eventually(ctxcontext.Context, ttesting.TB, condition func(ctxcontext.Context) (donebool), ticktime.Duration, msgAndArgs ...interface{}) (donebool)
Eventually is like require.Eventually except it allows passinga context into the condition. It is safe to use with `require.*`.
If ctx times out, the test will fail, but not immediately.It is the caller's responsibility to exit early if required.
It is the caller's responsibility to ensure that ctx has adeadline or timeout set. Eventually will panic if this is notthe case in order to avoid potentially waiting forever.
condition is not run in a goroutine; use the providedcontext argument for cancellation if required.
funcGenerateTLSCertificate¶
func GenerateTLSCertificate(ttesting.TB, commonNamestring)tls.Certificate
funcGetRandomName¶added inv2.14.0
GetRandomName returns a random name using moby/pkg/namesgenerator.namesgenerator.GetRandomName exposes a retry parameter that appendsa pseudo-random number between 1 and 10 to its return value.While this reduces the probability of collisions, it does not negate them.This function calls namesgenerator.GetRandomName without the retryparameter and instead increments a monotonically increasing integerto the return value.
funcGetRandomNameHyphenated¶added inv2.22.0
GetRandomNameHyphenated is as GetRandomName but uses a hyphen "-" instead ofan underscore.
funcGo¶added inv2.4.0
Go runs fn in a goroutine and waits until fn has completed beforetest completion. Done is returned for optionally waiting for fn toexit.
funcIgnoreLoggedError¶added inv2.18.0
funcLogger¶added inv2.18.0
Logger returns a "standard" testing logger, with debug level and common flakyerrors ignored.
funcMustRandString¶added inv2.7.0
MustRandString returns a random string of length n.
funcPersistentCacheDir¶added inv2.22.0
PersistentCacheDir returns a path to a directorythat will be cached between test runs in Github Actions.
funcPopulateStruct¶added inv2.17.0
PopulateStruct does a best effort to populate a struct with random values.
funcPromCounterAssertion¶added inv2.12.0
funcPromCounterGathered¶added inv2.12.0
funcPromCounterHasValue¶added inv2.8.0
funcPromGaugeAssertion¶added inv2.12.0
funcPromGaugeGathered¶added inv2.12.0
funcPromGaugeHasValue¶added inv2.8.0
funcRaceEnabled¶
func RaceEnabled()bool
RaceEnabled returns whether the race detector is enabled.This is a constant at compile time. It should be used toconditionally skip tests that are known to be sensitive tobeing run with the race detector enabled.Please use sparingly and as a last resort.
funcRandomIPv6¶added inv2.21.0
RandomIPv6 returns a random IPv6 address in the 2001:db8::/32 range.2001:db8::/32 is reserved for documentation and example code.
funcRandomPort¶added inv2.9.0
RandomPort is a helper function to find a free random port.Note that the OS may reallocate the port very quickly, sothis is not _guaranteed_.
funcRandomPortNoListen¶added inv2.9.0
RandomPortNoListen returns a random port in the ephemeral port range.Does not attempt to listen and close to find a port as the OS mayreallocate the port very quickly.
funcRequireJSONEq¶added inv2.21.0
RequireJSONEq is like assert.RequireJSONEq, but it's actually readable.Note that this calls t.Fatalf under the hood, so it should neverbe called in a goroutine.
funcRequireReceive¶added inv2.22.0
RequireReceive will receive a value from the chan and return it. If thecontext expires or the channel is closed before a value can be received,it will fail the test.
Safety: Must only be called from the Go routine that created `t`.
funcRequireSend¶added inv2.22.0
RequireSend will send the given value over the chan and then return. Ifthe context expires before the send succeeds, it will fail the test.
Safety: Must only be called from the Go routine that created `t`.
funcSkipIfNotTiming¶
funcSoftTryReceive¶added inv2.23.0
SoftTryReceive will attempt to receive a value from the chan and return it. Ifthe context expires before a value can be received, it will mark the test asfailed but continue execution. If the channel is closed, the zero value of thechannel type will be returned.The second return value indicates whether the receive was successful. Inparticular, if the channel is closed, the second return value will be true.
Safety: can be called from any goroutine.
funcTryReceive¶added inv2.22.0
TryReceive will attempt to receive a value from the chan and return it. Ifthe context expires before a value can be received, it will fail the test. Ifthe channel is closed, the zero value of the channel type will be returned.
Safety: Must only be called from the Go routine that created `t`.
Types¶
typeOAuth2Config¶
type OAuth2Config struct {Token *oauth2.TokenTokenSourceFuncOAuth2TokenSource}
func (*OAuth2Config)AuthCodeURL¶
func (*OAuth2Config) AuthCodeURL(statestring, _ ...oauth2.AuthCodeOption)string
func (*OAuth2Config)Do¶added inv2.7.0
func (*OAuth2Config) Do(_context.Context, _promoauth.Oauth2Source, req *http.Request) (*http.Response,error)
func (*OAuth2Config)Exchange¶
func (c *OAuth2Config) Exchange(_context.Context, _string, _ ...oauth2.AuthCodeOption) (*oauth2.Token,error)
func (*OAuth2Config)TokenSource¶
func (c *OAuth2Config) TokenSource(_context.Context, _ *oauth2.Token)oauth2.TokenSource
typeRandom¶added inv2.17.0
typeReaderWriterConn¶added inv2.22.0
func (*ReaderWriterConn)Close¶added inv2.22.0
func (*ReaderWriterConn) Close() (errerror)
func (*ReaderWriterConn)LocalAddr¶added inv2.22.0
func (*ReaderWriterConn) LocalAddr()net.Addr
func (*ReaderWriterConn)RemoteAddr¶added inv2.22.0
func (*ReaderWriterConn) RemoteAddr()net.Addr
func (*ReaderWriterConn)SetDeadline¶added inv2.22.0
func (*ReaderWriterConn) SetDeadline(_time.Time)error
func (*ReaderWriterConn)SetReadDeadline¶added inv2.22.0
func (*ReaderWriterConn) SetReadDeadline(_time.Time)error
func (*ReaderWriterConn)SetWriteDeadline¶added inv2.22.0
func (*ReaderWriterConn) SetWriteDeadline(_time.Time)error
typeTerminalReader¶added inv2.2.0
type TerminalReader struct {// contains filtered or unexported fields}
TerminalReader emulates a terminal and allows matching output. It's important in cases where wecan get control sequences to parse them correctly, and keep the state of the terminal across thelifespan of the PTY, since some control sequences are relative to the current cursor position.
funcNewTerminalReader¶added inv2.2.0
func NewTerminalReader(t *testing.T, rio.Reader) *TerminalReader
func (*TerminalReader)ReadUntil¶added inv2.2.0
ReadUntil emulates a terminal and reads one byte at a time until the matcherreturns true or the context expires. If the matcher is nil, read until EOF.The PTY must be sized to 80x80 or there could be unexpected results.
func (*TerminalReader)ReadUntilString¶added inv2.2.0
func (tr *TerminalReader) ReadUntilString(ctxcontext.Context, wantstring)error
ReadUntilString emulates a terminal and reads one byte at a time until weeither see the string we want, or the context expires. The PTY must be sizedto 80x80 or there could be unexpected results.