Movatterモバイル変換


[0]ホーム

URL:


testutil

package
v2.23.0Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2025 License:AGPL-3.0Imports:42Imported by:0

Details

Repository

github.com/coder/coder

Links

Documentation

Index

Constants

View Source
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.

View Source
const (IntervalFast   = 25 *time.MillisecondIntervalMedium = 250 *time.MillisecondIntervalSlow   =time.Second)

Constants for delaying repeated operations, e.g. inrequire.Eventually.

Variables

View Source
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

funcAssertReceiveadded inv2.23.0

func AssertReceive[Aany](ctxcontext.Context, ttesting.TB, c <-chan A) (A,bool)

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.

funcAssertSendadded inv2.23.0

func AssertSend[Aany](ctxcontext.Context, ttesting.TB, c chan<- A, a A)bool

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.

funcContext

func Context(t *testing.T, durtime.Duration)context.Context

funcCreateTaradded inv2.18.0

func CreateTar(ttesting.TB, files map[string]string) []byte

Creates an in-memory tar of the files provided.Files in the archive are written with nobodyowner/group, and -rw-rw-rw- permissions.

funcCreateTemp

func CreateTemp(t *testing.T, dir, patternstring) *os.File

CreateTemp is a convenience function for creating a temporary file, likeos.CreateTemp, but it also registers a cleanup function to close and removethe file.

funcCreateZipadded inv2.18.0

func CreateZip(ttesting.TB, files map[string]string) []byte

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

funcGetRandomNameadded inv2.14.0

func GetRandomName(ttesting.TB)string

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.

funcGetRandomNameHyphenatedadded inv2.22.0

func GetRandomNameHyphenated(ttesting.TB)string

GetRandomNameHyphenated is as GetRandomName but uses a hyphen "-" instead ofan underscore.

funcGoadded inv2.4.0

func Go(t *testing.T, fn func()) (done <-chan struct{})

Go runs fn in a goroutine and waits until fn has completed beforetest completion. Done is returned for optionally waiting for fn toexit.

funcIgnoreLoggedErroradded inv2.18.0

func IgnoreLoggedError(entryslog.SinkEntry)bool

funcInCI

func InCI()bool

funcLoggeradded inv2.18.0

func Logger(ttesting.TB)slog.Logger

Logger returns a "standard" testing logger, with debug level and common flakyerrors ignored.

funcMustRandStringadded inv2.7.0

func MustRandString(t *testing.T, nint)string

MustRandString returns a random string of length n.

funcPersistentCacheDiradded inv2.22.0

func PersistentCacheDir(t *testing.T)string

PersistentCacheDir returns a path to a directorythat will be cached between test runs in Github Actions.

funcPopulateStructadded inv2.17.0

func PopulateStruct(s interface{}, r *Random)error

PopulateStruct does a best effort to populate a struct with random values.

funcPromCounterAssertionadded inv2.12.0

func PromCounterAssertion(ttesting.TB, metrics []*dto.MetricFamily, assert func(infloat64)bool, namestring, labels ...string)bool

funcPromCounterGatheredadded inv2.12.0

func PromCounterGathered(ttesting.TB, metrics []*dto.MetricFamily, namestring, labels ...string)bool

funcPromCounterHasValueadded inv2.8.0

func PromCounterHasValue(ttesting.TB, metrics []*dto.MetricFamily, valuefloat64, namestring, labels ...string)bool

funcPromGaugeAssertionadded inv2.12.0

func PromGaugeAssertion(ttesting.TB, metrics []*dto.MetricFamily, assert func(infloat64)bool, namestring, labels ...string)bool

funcPromGaugeGatheredadded inv2.12.0

func PromGaugeGathered(ttesting.TB, metrics []*dto.MetricFamily, namestring, labels ...string)bool

funcPromGaugeHasValueadded inv2.8.0

func PromGaugeHasValue(ttesting.TB, metrics []*dto.MetricFamily, valuefloat64, namestring, labels ...string)bool

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.

funcRandomIPv6added inv2.21.0

func RandomIPv6(ttesting.TB)string

RandomIPv6 returns a random IPv6 address in the 2001:db8::/32 range.2001:db8::/32 is reserved for documentation and example code.

funcRandomPortadded inv2.9.0

func RandomPort(t *testing.T)int

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_.

funcRandomPortNoListenadded inv2.9.0

func RandomPortNoListen(*testing.T)uint16

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.

funcRequireJSONEqadded inv2.21.0

func RequireJSONEq(t *testing.T, expected, actualstring)

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.

funcRequireReceiveadded inv2.22.0

func RequireReceive[Aany](ctxcontext.Context, ttesting.TB, c <-chan A) A

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`.

funcRequireSendadded inv2.22.0

func RequireSend[Aany](ctxcontext.Context, ttesting.TB, c chan<- A, a A)

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

func SkipIfNotTiming(t *testing.T)

funcSoftTryReceiveadded inv2.23.0

func SoftTryReceive[Aany](ctxcontext.Context, ttesting.TB, c <-chan A) (A,bool)

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.

funcTempFile

func TempFile(t *testing.T, dir, patternstring)string

TempFile returns the name of a temporary file that does not exist.

funcTryReceiveadded inv2.22.0

func TryReceive[Aany](ctxcontext.Context, ttesting.TB, c <-chan A) A

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)Doadded inv2.7.0

func (*OAuth2Config)Exchange

func (*OAuth2Config)TokenSource

typeOAuth2TokenSource

type OAuth2TokenSource func() (*oauth2.Token,error)

func (OAuth2TokenSource)Token

func (oOAuth2TokenSource) Token() (*oauth2.Token,error)

typeRandomadded inv2.17.0

type Random struct {String  func()stringBool    func()boolInt     func()int64Uint    func()uint64Float   func()float64Complex func()complex128Time    func()time.Time}

funcNewRandomadded inv2.17.0

func NewRandom() *Random

typeReaderWriterConnadded inv2.22.0

type ReaderWriterConn struct {io.Readerio.Writer}

func (*ReaderWriterConn)Closeadded inv2.22.0

func (*ReaderWriterConn) Close() (errerror)

func (*ReaderWriterConn)LocalAddradded inv2.22.0

func (*ReaderWriterConn) LocalAddr()net.Addr

func (*ReaderWriterConn)RemoteAddradded inv2.22.0

func (*ReaderWriterConn) RemoteAddr()net.Addr

func (*ReaderWriterConn)SetDeadlineadded inv2.22.0

func (*ReaderWriterConn) SetDeadline(_time.Time)error

func (*ReaderWriterConn)SetReadDeadlineadded inv2.22.0

func (*ReaderWriterConn) SetReadDeadline(_time.Time)error

func (*ReaderWriterConn)SetWriteDeadlineadded inv2.22.0

func (*ReaderWriterConn) SetWriteDeadline(_time.Time)error

typeTerminalReaderadded 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.

funcNewTerminalReaderadded inv2.2.0

func NewTerminalReader(t *testing.T, rio.Reader) *TerminalReader

func (*TerminalReader)ReadUntiladded inv2.2.0

func (tr *TerminalReader) ReadUntil(ctxcontext.Context, matcher func(linestring)bool) (retErrerror)

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)ReadUntilStringadded 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.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp