Movatterモバイル変換


[0]ホーム

URL:


tstest

package
v1.92.2Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License:BSD-3-ClauseImports:27Imported by:0

Details

Repository

github.com/tailscale/tailscale

Links

Documentation

Overview

Package tstest provides utilities for use in unit tests.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

funcCheckIsZeroadded inv1.74.0

func CheckIsZero[TIsZeroable](ttesting.TB, nonzeroValues map[reflect.Type]any)

CheckIsZero checks that the IsZero method of a given type functionscorrectly, by instantiating a new value of that type, changing a field, andthen checking that the IsZero method returns false.

The nonzeroValues map should contain non-zero values for each type thatexists in the type T or any contained types. Basic types like string, bool,and numeric types are handled automatically.

funcFixLogs

func FixLogs(t *testing.T)

funcKernelVersionadded inv1.92.0

func KernelVersion() (major, minor, patchint)

KernelVersion returns the major, minor, and patch version of the Linux kernel.It returns (0, 0, 0) if the version cannot be determined.

funcMinAllocsPerRunadded inv1.18.0

func MinAllocsPerRun(t *testing.T, targetuint64, f func())error

MinAllocsPerRun asserts that f can run with no more than target allocations.It runs f up to 1000 times or 5s, whichever happens first.If f has executed more than target allocations on every run, it returns a non-nil error.

MinAllocsPerRun sets GOMAXPROCS to 1 during its measurement and restoresit before returning.

funcPanicOnLog

func PanicOnLog()

PanicOnLog modifies the standard library log package's default output toan io.Writer that panics, to root out code that's not plumbing their loggingthrough explicit tailscale.com/logger.Logf paths.

funcParalleladded inv1.52.0

func Parallel(t *testing.T)

Parallel calls t.Parallel, unless TS_SERIAL_TESTS is set true.

funcReplaceadded inv1.38.0

func Replace[Tany](ttesting.TB, target *T, val T)

Replace replaces the value of target with val.The old value is restored when the test ends.

funcResourceCheck

func ResourceCheck(tbtesting.TB)

ResourceCheck takes a snapshot of the current goroutines and registers acleanup on tb to verify that after the rest, all goroutines created by thetest go away. (well, at least that the count matches. Maybe in the future itcan look at specific routines).

It panics if called from a parallel test.

funcShardadded inv1.52.0

func Shard(ttesting.TB)

Shard skips t if it's not running if the TS_TEST_SHARD test shard is set to"n/m" and this test execution number in the process mod m is not equal to n-1.That is, to run with 4 shards, set TS_TEST_SHARD=1/4, ..., TS_TEST_SHARD=4/4for the four jobs.

funcSkipOnKernelVersionsadded inv1.92.0

func SkipOnKernelVersions(ttesting.TB, issuestring, versions ...string)

SkipOnKernelVersions skips the test if the currentkernel version is in the specified list.

funcSkipOnUnshardedCIadded inv1.52.0

func SkipOnUnshardedCI(ttesting.TB)

SkipOnUnshardedCI skips t if we're in CI and the TS_TEST_SHARDenvironment variable isn't set.

funcUnfixLogs

func UnfixLogs(t *testing.T)

funcWaitForadded inv1.8.0

func WaitFor(maxWaittime.Duration, try func()error)error

WaitFor retries try for up to maxWait.It returns nil once try returns nil the first time.If maxWait passes without success, it returns try's last error.

funcWhileTestRunningLoggeradded inv1.34.0

func WhileTestRunningLogger(ttestenv.TB)logger.Logf

WhileTestRunningLogger returns a logger.Logf that logs to t.Logf until thetest finishes, at which point it no longer logs anything.

Types

typeClock

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

Clock is a testing clock that advances every time its Now method iscalled, beginning at its start time. If no start time is specified usingClockBuilder, an arbitrary start time will be selected when the Clock iscreated and can be retrieved by calling Clock.Start().

funcNewClockadded inv1.46.0

func NewClock(coClockOpts) *Clock

NewClock creates a Clock with the specified settings. To create aClock with only the default settings, new(Clock) is equivalent, except thatthe start time will not be computed until one of the receivers is called.

func (*Clock)Advanceadded inv1.0.0

func (c *Clock) Advance(dtime.Duration)time.Time

Advance moves simulated time forward or backwards by a relative amount. AnyTimer or Ticker that is waiting will fire at the requested point in simulatedtime. Advance returns the new simulated time. If this Clock follows real timethen the next call to Now will equal the return value of Advance + theelapsed time since calling Advance. Otherwise, the next call to Now willequal the return value of Advance, regardless of the current step.

func (*Clock)AdvanceToadded inv1.46.0

func (c *Clock) AdvanceTo(ttime.Time)

AdvanceTo moves simulated time to a new absolute value. Any Timer or Tickerthat is waiting will fire at the requested point in simulated time. If thisClock follows real time then the next call to Now will equal t + the elapsedtime since calling Advance. Otherwise, the next call to Now will equal t,regardless of the configured step.

func (*Clock)AfterFuncadded inv1.46.0

func (c *Clock) AfterFunc(dtime.Duration, f func())tstime.TimerController

AfterFunc returns a Timer that calls f when it fires, using this Clock foraccessing the current time.

func (*Clock)GetStartadded inv1.46.0

func (c *Clock) GetStart()time.Time

GetStart returns the initial simulated time when this Clock was created.

func (*Clock)GetStepadded inv1.46.0

func (c *Clock) GetStep()time.Duration

GetStep returns the amount that simulated time advances on every call to Now.

func (*Clock)NewTickeradded inv1.46.0

func (c *Clock) NewTicker(dtime.Duration) (tstime.TickerController, <-chantime.Time)

NewTicker returns a Ticker that uses this Clock for accessing the currenttime.

func (*Clock)NewTimeradded inv1.46.0

func (c *Clock) NewTimer(dtime.Duration) (tstime.TimerController, <-chantime.Time)

NewTimer returns a Timer that uses this Clock for accessing the currenttime.

func (*Clock)Now

func (c *Clock) Now()time.Time

Now returns the virtual clock's current time, and advances itaccording to its step configuration.

func (*Clock)PeekNowadded inv1.46.0

func (c *Clock) PeekNow()time.Time

PeekNow returns the last time reported by Now. If Now has never been called,PeekNow returns the same value as GetStart.

func (*Clock)SetStepadded inv1.46.0

func (c *Clock) SetStep(dtime.Duration)

SetStep updates the amount that simulated time advances on every call to Now.

func (*Clock)SetTimerChannelSizeadded inv1.46.0

func (c *Clock) SetTimerChannelSize(nint)

SetTimerChannelSize changes the channel size for any Timer or Ticker createdin the future. It does not affect those that were already created.

func (*Clock)Sinceadded inv1.46.0

func (c *Clock) Since(ttime.Time)time.Duration

Since subtracts specified duration from Now().

typeClockOptsadded inv1.46.0

type ClockOpts struct {// Start is the starting time for the Clock. When FollowRealTime is false,// Start is also the value that will be returned by the first call// to Clock.Now.Starttime.Time// Step is the amount of time the Clock will advance whenever Clock.Now is// called. If set to zero, the Clock will only advance when Clock.Advance is// called and/or if FollowRealTime is true.//// FollowRealTime and Step cannot be enabled at the same time.Steptime.Duration// TimerChannelSize configures the maximum buffered ticks that are// permitted in the channel of any Timer and Ticker created by this Clock.// The special value 0 means to use the default of 1. The buffer may need to// be increased if time is advanced by more than a single tick and proper// functioning of the test requires that the ticks are not lost.TimerChannelSizeint// FollowRealTime makes the simulated time increment along with real time.// It is a compromise between determinism and the difficulty of explicitly// managing the simulated time via Step or Clock.Advance. When// FollowRealTime is set, calls to Now() and PeekNow() will add the// elapsed real-world time to the simulated time.//// FollowRealTime and Step cannot be enabled at the same time.FollowRealTimebool}

ClockOpts is used to configure the initial settings for a Clock. Once thesettings are configured as desired, call NewClock to get the resulting Clock.

typeIsZeroableadded inv1.74.0

type IsZeroable interface {IsZero()bool}

IsZeroable is the interface for things with an IsZero method.

typeLogLineTrackeradded inv1.2.0

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

LogLineTracker is a logger that tracks which log format patterns it'sseen and can report which expected ones were not seen later.

funcNewLogLineTrackeradded inv1.2.0

func NewLogLineTracker(logflogger.Logf, expectedFormatStrings []string) *LogLineTracker

NewLogLineTracker produces a LogLineTracker wrapping a given logf that tracks whether expectedFormatStrings were seen.

func (*LogLineTracker)Checkadded inv1.2.0

func (lt *LogLineTracker) Check() []string

Check returns which format strings haven't been logged yet.

func (*LogLineTracker)Closeadded inv1.4.0

func (lt *LogLineTracker) Close()

Close closes lt. After calling Close, calls to Logf become no-ops.

func (*LogLineTracker)Logfadded inv1.2.0

func (lt *LogLineTracker) Logf(formatstring, args ...any)

Logf logs to its underlying logger and also tracks that the given format pattern has been seen.

func (*LogLineTracker)Resetadded inv1.8.0

func (lt *LogLineTracker) Reset()

Reset forgets everything that it's seen.

typeMemLoggeradded inv1.14.6

type MemLogger struct {sync.Mutexbytes.Buffer}

MemLogger is a bytes.Buffer with a Logf method for tests that wantto log to a buffer.

func (*MemLogger)Logfadded inv1.14.6

func (ml *MemLogger) Logf(formatstring, args ...any)

func (*MemLogger)Stringadded inv1.14.6

func (ml *MemLogger) String()string

typeTickeradded inv1.46.0

type Ticker struct {C <-chantime.Time// The channel on which ticks are delivered.// contains filtered or unexported fields}

Ticker is a time.Ticker lookalike for use in tests that need to control whenevents fire. Ticker could be made standalone in future but for now isexpected to be paired with a Clock and created by Clock.NewTicker.

func (*Ticker)Fireadded inv1.46.0

func (t *Ticker) Fire(curTimetime.Time)time.Time

Fire triggers the ticker. curTime is the timestamp to write to the channel.The next trigger time for the ticker is updated to the last computed triggertime + the ticker period (set at creation or using Reset). The next triggertime is computed this way to match standard time.Ticker behavior, whichprevents accumulation of long term drift caused by delays in event execution.

func (*Ticker)Resetadded inv1.46.0

func (t *Ticker) Reset(dtime.Duration)

Reset adjusts the Ticker's period to d and reschedules the next fire time tothe current simulated time + d.

func (*Ticker)ResetAbsoluteadded inv1.46.0

func (t *Ticker) ResetAbsolute(nextTriggertime.Time, dtime.Duration)

ResetAbsolute adjusts the Ticker's period to d and reschedules the next firetime to nextTrigger.

func (*Ticker)Stopadded inv1.46.0

func (t *Ticker) Stop()

Stop deactivates the Ticker.

typeTimeradded inv1.46.0

type Timer struct {C <-chantime.Time// The channel on which ticks are delivered.// contains filtered or unexported fields}

Timer is a time.Timer lookalike for use in tests that need to control whenevents fire. Timer could be made standalone in future but for now must bepaired with a Clock and created by Clock.NewTimer.

func (*Timer)Fireadded inv1.46.0

func (t *Timer) Fire(curTimetime.Time)time.Time

Fire triggers the ticker. curTime is the timestamp to write to the channel.The next trigger time for the ticker is updated to the last computed triggertime + the ticker period (set at creation or using Reset). The next triggertime is computed this way to match standard time.Ticker behavior, whichprevents accumulation of long term drift caused by delays in event execution.

func (*Timer)Resetadded inv1.46.0

func (t *Timer) Reset(dtime.Duration)bool

Reset reschedules the next fire time to the current simulated time + d.Reset reports whether the timer was still active before the reset.

func (*Timer)ResetAbsoluteadded inv1.46.0

func (t *Timer) ResetAbsolute(nextTriggertime.Time)bool

ResetAbsolute reschedules the next fire time to nextTrigger.ResetAbsolute reports whether the timer was still active before the reset.

func (*Timer)Stopadded inv1.46.0

func (t *Timer) Stop()bool

Stop deactivates the Timer. Stop reports whether the timer was active beforestopping.

Source Files

View all Source files

Directories

PathSynopsis
Package chonktest contains a shared set of tests for the Chonk interface used to store AUM messages in Tailnet Lock, which we can share between different implementations.
Package chonktest contains a shared set of tests for the Chonk interface used to store AUM messages in Tailnet Lock, which we can share between different implementations.
The deptest package contains a shared implementation of negative dependency tests for other packages, making sure we don't start depending on certain packages.
The deptest package contains a shared implementation of negative dependency tests for other packages, making sure we don't start depending on certain packages.
Package integration contains Tailscale integration tests.
Package integration contains Tailscale integration tests.
testcontrol
Package testcontrol contains a minimal control plane server for testing purposes.
Package testcontrol contains a minimal control plane server for testing purposes.
vms
Package vms does VM-based integration/functional tests by using qemu and a bank of pre-made VM images.
Package vms does VM-based integration/functional tests by using qemu and a bank of pre-made VM images.
Package iosdeps is a just a list of the packages we import on iOS, to let us test that our transitive closure of dependencies on iOS doesn't accidentally grow too large, as we've historically been memory constrained there.
Package iosdeps is a just a list of the packages we import on iOS, to let us test that our transitive closure of dependencies on iOS doesn't accidentally grow too large, as we've historically been memory constrained there.
Package jsdeps is a just a list of the packages we import in the JavaScript/WASM build, to let us test that our transitive closure of dependencies doesn't accidentally grow too large, since binary size is more of a concern.
Package jsdeps is a just a list of the packages we import in the JavaScript/WASM build, to let us test that our transitive closure of dependencies doesn't accidentally grow too large, since binary size is more of a concern.
The mts ("Multiple Tailscale") command runs multiple tailscaled instances for development, managing their directories and sockets, and lets you easily direct tailscale CLI commands to them.
The mts ("Multiple Tailscale") command runs multiple tailscaled instances for development, managing their directories and sockets, and lets you easily direct tailscale CLI commands to them.
Package natlab lets us simulate different types of networks all in-memory without running VMs or requiring root, etc.
Package natlab lets us simulate different types of networks all in-memory without running VMs or requiring root, etc.
vnet
Package vnet simulates a virtual Internet containing a set of networks with various NAT behaviors.
Package vnet simulates a virtual Internet containing a set of networks with various NAT behaviors.
Package nettest contains additional test helpers related to network state that can't go into tstest for circular dependency reasons.
Package nettest contains additional test helpers related to network state that can't go into tstest for circular dependency reasons.
tkatest has functions for creating a mock control server that responds to TKA endpoints.
tkatest has functions for creating a mock control server that responds to TKA endpoints.
Package tlstest contains code to help test Tailscale's TLS support without depending on real WebPKI roots or certificates during tests.
Package tlstest contains code to help test Tailscale's TLS support without depending on real WebPKI roots or certificates during tests.
Package typewalk provides utilities to walk Go types using reflection.
Package typewalk provides utilities to walk Go types using reflection.

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