Documentation
¶
Overview ¶
Package tester provides structures to help with testing custom assertions and test helpers.
Index ¶
- Constants
- type Spy
- func (spy *Spy) AssertExpectations() bool
- func (spy *Spy) Cleanup(f func())
- func (spy *Spy) Close() *Spy
- func (spy *Spy) Context() context.Context
- func (spy *Spy) Error(args ...any)
- func (spy *Spy) Errorf(format string, args ...any)
- func (spy *Spy) ExamineLog() string
- func (spy *Spy) ExpectCleanups(cnt int) *Spy
- func (spy *Spy) ExpectError() *Spy
- func (spy *Spy) ExpectFail() *Spy
- func (spy *Spy) ExpectFatal() *Spy
- func (spy *Spy) ExpectHelpers(cnt int) *Spy
- func (spy *Spy) ExpectLog(matcher Strategy, msg string, args ...any) *Spy
- func (spy *Spy) ExpectLogContain(format string, args ...any) *Spy
- func (spy *Spy) ExpectLogEqual(format string, args ...any) *Spy
- func (spy *Spy) ExpectLogNotContain(format string, args ...any) *Spy
- func (spy *Spy) ExpectSetenv(key, value string) *Spy
- func (spy *Spy) ExpectSkipped() *Spy
- func (spy *Spy) ExpectTempDir(cnt int) *Spy
- func (spy *Spy) ExpectedNames(cnt int) *Spy
- func (spy *Spy) FailNow()
- func (spy *Spy) Failed() bool
- func (spy *Spy) Fatal(args ...any)
- func (spy *Spy) Fatalf(format string, args ...any)
- func (spy *Spy) Finish() *Spy
- func (spy *Spy) GetTempDir(idx int) string
- func (spy *Spy) Helper()
- func (spy *Spy) IgnoreLogs() *Spy
- func (spy *Spy) Log(args ...any)
- func (spy *Spy) Logf(format string, args ...any)
- func (spy *Spy) Name() string
- func (spy *Spy) Setenv(key, value string)
- func (spy *Spy) Skip(args ...any)
- func (spy *Spy) TempDir() string
- type Strategy
- type T
Constants ¶
const FailNowMsg = "FailNow was called directly"
FailNowMsg represents a message the Spy.FailNow method uses in panic.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Spy ¶
type Spy struct {
// contains filtered or unexported fields
}
Spy is a spy for tester.T interface.
Creating test helpers is an integral part of comprehensive testing, but those helpers in turn also need to be tested to make sure assertions made by them are implemented correctly. The Spy is a tool that makes testing such helpers very easy.
Pass an instance of Spy to the Helper Under Test (HUT) and assert the expected behavior using Spy.Expect* methods.
func New ¶
New returns new instance of Spy which implements T interface. The tt argument is used to proxy calls to testing.T.TempDir, testing.T.Setenv and testing.T.Context as well as to report errors when the Spy expectations are not met by Helper Under Test (HUT). The constructor function adds a cleanup function to tt which calls Spy.Finish and Spy.AssertExpectations methods to determine if the tt should be failed.
The call to New should be followed by zero or more calls to Spy.Expect* methods and finished with call to Spy.Close method:
tspy := New(t) tspy.ExpectError() // tspy.ExpectXXX() tspy.Close()
To assert expectations manually call the Spy.AssertExpectations, or it will be called automatically when test (tt) finishes.
Full example:
t.Run("closes file at the end of test", func(t *testing.T) {
// --- Given ---
tspy := tester.New(t).ExpectCleanups(1).Close()
// --- When ---
fil := OpenFile(tspy, "testdata/file.txt")
// --- Then ---
tspy.AssertExpectations()
assert.ErrorIs(t, os.ErrClosed, fil.Close())
})
If the optional argument expectHelpers is provided the Spy.ExpectHelpers will be called with it. See Spy.ExpectHelpers method documentation for details.
func (*Spy) AssertExpectations ¶
AssertExpectations asserts all expectations and returns true on success, false otherwise. Each failed expectation is logged using tt instance.
func (*Spy) Cleanup ¶
func (spy *Spy) Cleanup(f func())
Cleanup registers a function to be called when the test and all its subtests complete. The registered function is always called at the end of the test.
func (*Spy) Close ¶
Close closes the instance. You cannot add any expectations to a closed instance.
func (*Spy) ExamineLog ¶ added in v0.10.0
ExamineLog returns so far logged messages.
func (*Spy) ExpectCleanups ¶
ExpectCleanups sets the number of expected calls to the Spy.Cleanup method.
func (*Spy) ExpectError ¶
ExpectError sets the expectation that HUT should call one of the Spy.Error or Spy.Errorf methods at least once.
func (*Spy) ExpectFail ¶
ExpectFail sets expectation the HUT should call one of the Fatal* or Error* methods.
func (*Spy) ExpectFatal ¶
ExpectFatal sets expectation that HUT should call one of the Spy.Fatal or Spy.Fatalf methods at least once.
func (*Spy) ExpectHelpers ¶
ExpectHelpers sets expectation how many times HUT should call Spy.Helper method. The value -1 means the Spy.Helper method must be run at least once.
Method will panic if the cnt value is less than -1 or the method is called more than once.
func (*Spy) ExpectLog ¶
ExpectLog sets expectation the HUT should call one of the Spy.Log or Spy.Logf methods with a given message. The expected message is constructed using format and args arguments, which are the same as in fmt.Sprintf. The matcher strategy is used to match the message.
Method call will panic if Spy.IgnoreLogs was called before.
func (*Spy) ExpectLogContain ¶
ExpectLogContain sets expectation the HUT should call one of the Log* methods. The expected message is constructed using format and args arguments which are the same as in fmt.Sprintf. The Contains strategy is used to match a log message.
Method call will panic if Spy.IgnoreLogs was called before.
func (*Spy) ExpectLogEqual ¶
ExpectLogEqual sets expectation the HUT should call one of the Log* methods. The expected message is constructed using format and args arguments which are the same as in fmt.Sprintf. The Equal strategy is used to match messages.
Method call will panic if Spy.IgnoreLogs was called before.
func (*Spy) ExpectLogNotContain ¶
ExpectLogNotContain sets expectation the HUT should call one of the Log* methods. The expected message is constructed using format and args arguments which are the same as in fmt.Sprintf. The NotContains strategy is used to match log messages.
Method call will panic if Spy.IgnoreLogs was called before.
func (*Spy) ExpectSetenv ¶
ExpectSetenv sets expectation that given environment variable is set by the HUT.
func (*Spy) ExpectSkipped ¶
ExpectSkipped sets expectation that HUT will skip the test.
func (*Spy) ExpectTempDir ¶
ExpectTempDir sets expectation the HUT should call Spy.TempDir cnt number of times. If cnt is -1 the Spy.TempDir method can be called any number of times.
func (*Spy) ExpectedNames ¶
ExpectedNames sets expectation the HUT should call Spy.Name cnt number of times.
func (*Spy) Failed ¶
Failed reports whether the HUT called any of the Spy.Error, Spy.Errorf, Spy.Fatal, Spy.Fatalf or Spy.FailNow methods. It's worth noting this method returning false DOES NOT mean the Spy expectations were met. The HUT may have never called the methods listed previously, but the spy itself didn't meet expectations.
func (*Spy) Finish ¶
Finish marks the end of the test. It can be called by hand, or it's called automatically by a cleanup function as described in New. After Spy.Finish is called, most of the Spy methods will panic when called - check specific method documentation for details.
func (*Spy) GetTempDir ¶
GetTempDir returns the Nth (zero-indexed) temporary directory path returned by Spy.TempDir method. It will fail the test if the Spy.TempDir method was never called or the index of the directory is invalid.
func (*Spy) IgnoreLogs ¶
IgnoreLogs instruct Spy to ignore checking logged messages. Method will panic if any of the Spy.ExpectLog* methods were already called.
type Strategy ¶
type Strategy string
Strategy is the strategy of matching logs produced by Helper Under Test (HUT).
const ( // Equal is a strategy where messages logged by HUT are matched exactly. Equal Strategy = "equal" // Contains is a strategy where messages logged by HUT contain a string. Contains Strategy = "contains" // NotContains is a strategy where messages logged by HUT don't contain a // string. NotContains Strategy = "not-contains" // Regexp is a strategy where messages logged by the HUT match regular // expression. Regexp Strategy = "regexp" )
Log matching strategies.
type T ¶
type T interface {
// Cleanup registers a function to be called when the test and all its
// subtests complete. Cleanup functions will be called in last added,
// first called order.
Cleanup(func())
// Error is equivalent to Log followed by Fail.
Error(args ...any)
// Errorf is equivalent to Logf followed by Fail.
Errorf(format string, args ...any)
// Fatal is equivalent to Log followed by FailNow.
Fatal(args ...any)
// Fatalf is equivalent to Logf followed by FailNow.
Fatalf(format string, args ...any)
// FailNow marks the function as having failed and stops its execution
// by calling [runtime.Goexit] (which then runs all deferred calls in the
// current goroutine). Execution will continue at the next test or
// benchmark. FailNow must be called from the goroutine running the test or
// benchmark function, not from other goroutines created during the test.
// Calling FailNow does not stop.
FailNow()
// Failed reports whether the function has failed.
Failed() bool
// Helper marks the calling function as a test helper function. When
// printing file and line information, that function will be skipped.
// Helper may be called simultaneously from multiple goroutines.
Helper()
// Log formats its arguments using default formatting, analogous to Println,
// and records the text in the error log. For tests, the text will be
// printed only if the test fails or the -test.v flag is set. For
// benchmarks, the text is always printed to avoid having performance
// depend on the value of the -test.v flag.
Log(args ...any)
// Logf formats its arguments according to the format, analogous to Printf,
// and records the text in the error log. A final newline is added if not
// provided. For tests, the text will be printed only if the test fails or
// the -test.v flag is set. For benchmarks, the text is always printed to
// avoid having performance depend on the value of the -test.v flag.
Logf(format string, args ...any)
// Name returns the name of the running (sub-) test.
//
// The name will include the name of the test along with the names of any
// nested subtests. If two sibling subtests have the same name, Name will
// append a suffix to guarantee the returned name is unique.
Name() string
// Setenv calls os.Setenv(key, value) and uses Cleanup to restore the
// environment variable to its original value after the test.
//
// This cannot be used in parallel tests.
Setenv(key, value string)
// Skip is equivalent to Log followed by SkipNow.
Skip(args ...any)
// TempDir returns a temporary directory for the test to use. The directory
// is automatically removed by Cleanup when the test and all its subtests
// complete. Each subsequent call to TempDir returns a unique directory;
// if the directory creation fails, TempDir terminates the test by calling
// Fatal.
TempDir() string
// Context returns a context that is canceled just before Cleanup
// registered functions are called. Cleanup functions can wait for any
// resources that shut down on Context.Done before the test or benchmark
// completes.
Context() context.Context
}
T is a subset of testing.TB interface it has been defined to allow mocking.