Documentation
¶
Overview ¶
Package test contains the main collection of functions and types for setting up the basic isolated test environment. It is part of the public interface and starting to get stable, however, we are still experimenting to optimize the interface and the user experience.
Index ¶
- Variables
- func ConsumedCall[T any](creator func(*gomock.Controller) *T, method, caller, ecaller string, ...) func(Test, *mock.Mocks) mock.SetupFunc
- func EqCall(x any) gomock.Matcher
- func EqError(x any) gomock.Matcher
- func Error(args ...any) mock.SetupFunc
- func Errorf(format string, args ...any) mock.SetupFunc
- func Fail() mock.SetupFunc
- func FailNow() mock.SetupFunc
- func Fatal(args ...any) mock.SetupFunc
- func Fatalf(format string, args ...any) mock.SetupFunc
- func Find[P, T any](param P, deflt T, names ...string) T
- func InRun(expect Expect, test func(Test)) func(Test)
- func MissingCalls(setups ...mock.SetupFunc) func(Test, *mock.Mocks) mock.SetupFunc
- func NewErrInvalidType(value any) error
- func Panic(arg any) mock.SetupFunc
- func Run(expect Expect, test func(Test)) func(*testing.T)
- func RunSeq(expect Expect, test func(Test)) func(*testing.T)
- func TestMain(main func()) func(t Test, param MainParams)
- func TestName[P any](name string, param P) string
- func UnexpectedCall[T any](creator func(*gomock.Controller) *T, method, caller string, args ...any) func(Test, *mock.Mocks) mock.SetupFunc
- type Builder
- type Cleanuper
- type Context
- func (t *Context) Cleanup(cleanup func())
- func (t *Context) Deadline() (time.Time, bool)
- func (t *Context) Error(args ...any)
- func (t *Context) Errorf(format string, args ...any)
- func (t *Context) Fail()
- func (t *Context) FailNow()
- func (t *Context) Failed() bool
- func (t *Context) Fatal(args ...any)
- func (t *Context) Fatalf(format string, args ...any)
- func (t *Context) Helper()
- func (t *Context) Log(args ...any)
- func (t *Context) Logf(format string, args ...any)
- func (t *Context) Name() string
- func (t *Context) Panic(arg any)
- func (t *Context) Parallel()
- func (t *Context) Reporter(reporter Reporter)
- func (t *Context) Run(test func(Test), parallel bool) Test
- func (t *Context) Setenv(key, value string)
- func (t *Context) Skip(args ...any)
- func (t *Context) SkipNow()
- func (t *Context) Skipf(format string, args ...any)
- func (t *Context) Skipped() bool
- func (t *Context) StopEarly(time time.Duration) *Context
- func (t *Context) TempDir() string
- func (t *Context) Timeout(timeout time.Duration) *Context
- func (t *Context) WaitGroup(wg sync.WaitGroup)
- type Expect
- type Finder
- type Getter
- type MainParams
- type Name
- type Recorder
- func (r *Recorder) Error(args ...any) *gomock.Call
- func (r *Recorder) Errorf(format string, args ...any) *gomock.Call
- func (r *Recorder) Fail() *gomock.Call
- func (r *Recorder) FailNow() *gomock.Call
- func (r *Recorder) Fatal(args ...any) *gomock.Call
- func (r *Recorder) Fatalf(format string, args ...any) *gomock.Call
- func (r *Recorder) Panic(arg any) *gomock.Call
- type Reporter
- type Runner
- type Setter
- type Test
- type Validator
- func (v *Validator) EXPECT() *Recorder
- func (v *Validator) Error(args ...any)
- func (v *Validator) Errorf(format string, args ...any)
- func (v *Validator) Fail()
- func (v *Validator) FailNow()
- func (v *Validator) Fatal(args ...any)
- func (v *Validator) Fatalf(format string, args ...any)
- func (v *Validator) Panic(arg any)
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidType = errors.New("invalid type")
ErrInvalidType is an error for invalid types.
Functions ¶
func ConsumedCall ¶
func EqCall ¶
EqCall creates a new call matcher that allows to match calls by translating them to the string containing the core information instead of using the standard matcher using reflect.DeepEquals that fails for the contained actions.
func EqError ¶
EqError creates a new error matcher that allows to match either the error or alternatively the string describing the error.
func Find ¶ added in v0.0.21
Find returns the first value of a parameter field from the given list of field names with a type matching the default value type. If the name list is empty or contains a star (`*`), the first matching field in order of the struct declaration is returned as fallback. If no matching field is found, the default value is returned.
The `param“ object can be a struct, a pointer to a struct, or an arbitrary value matching the default value type. In the last case, the arbitrary value is returned as is.
func InRun ¶
InRun creates an isolated, (by default) sequential test context for the given test function with given expectation. If the expectation is not met, a test failure is created in the parent test context.
func MissingCalls ¶
MissingCalls creates an expectation for all missing calls.
func NewErrInvalidType ¶ added in v0.0.22
NewErrInvalidType creates a new invalid type error.
func Panic ¶
Panic creates a validation method call setup for a panic. It allows to match the panic object, which usually is an error and alternatively the error string representing the error, since runtime errors may be irreproducible.
func Run ¶
Run creates an isolated (by default) parallel test context running the given test function with given expectation. If the expectation is not met, a test failure is created in the parent test context.
func RunSeq ¶
RunSeq creates an isolated, test context for the given test function with given expectation. If the expectation is not met, a test failure is created in the parent test context.
func TestMain ¶ added in v0.0.8
func TestMain(main func()) func(t Test, param MainParams)
TestMain creates a test function that runs the given `main`-method in a separate test process to allow capturing the exit code and checking it against the expectation. This can be applied as follows:
testMainParams := map[string]test.MainParams{ "no mocks": { Args: []string{"mock"}, Env: []string{}, ExitCode: 0, }, } func TestMain(t *testing.T) { test.Map(t, testMainParams).Run(test.TestMain(main)) }
The test method is spawning a new test using the `TEST` environment variable to select the expected parameter set containing the command line arguments (`Args`) to execute in the spawned process. The test instance is also called setting the given additional environment variables (`Env`) to allow modification of the test environment.
func TestName ¶ added in v0.0.21
TestName returns the normalized test case name for the given name and given parameter set. If the name is empty, the name is resolved from the parameter set using the `name` parameter. The resolved name is normalized before being returned.
func UnexpectedCall ¶
func UnexpectedCall[T any]( creator func(*gomock.Controller) *T, method, caller string, args ...any, ) func(Test, *mock.Mocks) mock.SetupFunc
UnexpectedCall creates expectation for unexpected calls. We only support one unexpected call since the test execution stops in this case.
Types ¶
type Builder ¶ added in v0.0.20
type Builder[T any] interface { // Getter is a generic interface that allows you to access unexported fields // of a (pointer) struct by field name. Getter[T] // Finder is a generic interface that allows you to access unexported fields // of a (pointer) struct by field name. Finder[T] // Setter is a generic fluent interface that allows you to modify unexported // fields of a (pointer) struct by field name. Setter[T] }
Builder is a generic, partially fluent interface that allows you to access and modify unexported fields of a (pointer) struct by field name.
func NewAccessor ¶ added in v0.0.15
NewAccessor creates a generic builder/accessor for a given target struct. The builder allows you to access and modify unexported fields of the struct by field name.
If the target is a pointer to a struct (template), the pointer is stored and the instance is modified directly. If the pointer is nil a new instance is created and stored for modification.
If the target is a struct, it cannot be modified directly and a new pointer struct is created to circumvent the access restrictions on private fields. The pointer struct is stored for modification.
func NewBuilder ¶ added in v0.0.20
NewBuilder creates a generic builder for a target struct type. The builder allows you to access and modify unexported fields of the struct by field name.
type Cleanuper ¶
type Cleanuper interface {
Cleanup(cleanup func())
}
Cleanuper defines an interface to add a custom mehtod that is called after the test execution to cleanup the test environment.
type Context ¶ added in v0.0.22
type Context struct { sync.Synchronizer // contains filtered or unexported fields }
Context is a test isolation environment based on the `Test` abstraction. It can be used as a drop in replacement for `testing.T` in various libraries to check for expected test failures.
func New ¶
New creates a new minimal isolated test context based on the given test context with the given expectation. The parent test context is used to delegate methods calls to the parent context to propagate test results.
func (*Context) Cleanup ¶ added in v0.0.22
func (t *Context) Cleanup(cleanup func())
Cleanup is a function called to setup test cleanup after execution. This method is allowing `gomock` to register its `finish` method that reports the missing mock calls.
func (*Context) Deadline ¶ added in v0.0.22
Deadline delegates request to the parent context. It returns the deadline of the test and a flag indicating whether the deadline is set.
func (*Context) Error ¶ added in v0.0.22
Error handles failure messages where the test is supposed to continue. On an expected success, the failure is also delegated to the parent test context. Else it delegates the request to the test reporter if available.
func (*Context) Errorf ¶ added in v0.0.22
Errorf handles failure messages where the test is supposed to continue. On an expected success, the failure is also delegated to the parent test context. Else it delegates the request to the test reporter if available.
func (*Context) Fail ¶ added in v0.0.22
func (t *Context) Fail()
Fail handles a failure message that immediate aborts of the test execution. On an expected success, the failure handling is also delegated to the parent test context. Else it delegates the request to the test reporter if available.
func (*Context) FailNow ¶ added in v0.0.22
func (t *Context) FailNow()
FailNow handles fatal failure notifications without log output that aborts test execution immediately. On an expected success, it the failure handling is also delegated to the parent test context. Else it delegates the request to the test reporter if available.
func (*Context) Fatal ¶ added in v0.0.22
Fatal handles a fatal failure message that immediate aborts of the test execution. On an expected success, the failure handling is also delegated to the parent test context. Else it delegates the request to the test reporter if available.
func (*Context) Fatalf ¶ added in v0.0.22
Fatalf handles a fatal failure message that immediate aborts of the test execution. On an expected success, the failure handling is also delegated to the parent test context. Else it delegates the request to the test reporter if available.
func (*Context) Helper ¶ added in v0.0.22
func (t *Context) Helper()
Helper delegates request to the parent test context.
func (*Context) Log ¶ added in v0.0.22
Log delegates request to the parent context. It provides a logging function for the test.
func (*Context) Logf ¶ added in v0.0.22
Logf delegates request to the parent context. It provides a logging function for the test.
func (*Context) Panic ¶ added in v0.0.22
Panic handles failure notifications of panics that also abort the test execution immediately.
func (*Context) Parallel ¶ added in v0.0.22
func (t *Context) Parallel()
Parallel robustly delegates request to the parent context. It can be called multiple times, since it is swallowing the panic that is raised when calling `t.Parallel()` multiple times.
func (*Context) Reporter ¶ added in v0.0.22
Reporter sets up a test failure reporter. This can be used to validate the reported failures in a test environment.
func (*Context) Run ¶ added in v0.0.22
Run executes the test function in a safe detached environment and check the failure state after the test function has finished. If the test result is not according to expectation, a failure is created in the parent test context.
func (*Context) Setenv ¶ added in v0.0.22
Setenv delegates request to the parent context, if it is of type `*testing.T`. Else it is swallowing the request silently.
func (*Context) Skip ¶ added in v0.0.22
Skip delegates request to the parent context. It is a helper method to skip the test.
func (*Context) SkipNow ¶ added in v0.0.22
func (t *Context) SkipNow()
SkipNow delegates request to the parent context. It is a helper method to skip the test immediately.
func (*Context) Skipf ¶ added in v0.0.22
Skipf delegates request to the parent context. It is a helper method to skip the test with a formatted message.
func (*Context) Skipped ¶ added in v0.0.22
Skipped delegates request to the parent context. It reports whether the test has been skipped.
func (*Context) StopEarly ¶ added in v0.0.22
StopEarly stops the test by the given duration ahead of the individual or global test deadline, to ensure that a cleanup function has sufficient time to finish before a global deadline exceeds. The method is not able to extend the test deadline. A negative or zero duration is ignored.
Warning: calling this method multiple times will also reduce the deadline step by step.
func (*Context) TempDir ¶ added in v0.0.22
TempDir delegates the request to the parent test context.
func (*Context) Timeout ¶ added in v0.0.22
Timeout sets up an individual timeout for the test. This does not affect the global test timeout or a pending parent timeout that may abort the test, if the given duration is exceeding the timeout. A negative or zero duration is ignored and will not change the timeout.
type Finder ¶ added in v0.0.22
type Finder[T any] interface { // Find returns the first value of a field from the given list of field // names with a type matching the default value type. If the name list is // empty or contains a star (`*`), the first matching field in order of the // struct declaration is returned as fallback. If no matching field is // found, the default value is returned. Find(dflt any, names ...string) any }
Finder is a generic interface that allows you to access unexported fields of a (pointer) struct by field name.
type Getter ¶ added in v0.0.22
type Getter[T any] interface { // Get returns the value of the field with the given name. If the name is // empty, the stored target instance is returned. Get(name string) any }
Getter is a generic interface that allows you to access unexported fields of a (pointer) struct by field name.
type MainParams ¶ added in v0.0.8
MainParams provides the test parameters for testing a `main`-method.
type Recorder ¶
type Recorder struct {
// contains filtered or unexported fields
}
Recorder a test failure validator recorder.
type Reporter ¶
type Reporter interface { // Error reports a failure messages when a test is supposed to continue. Error(args ...any) // Errorf reports a failure messages when a test is supposed to continue. Errorf(format string, args ...any) // Fatal reports a fatal failure message that immediate aborts of the test // execution. Fatal(args ...any) // Fatalf reports a fatal failure message that immediate aborts of the test // execution. Fatalf(format string, args ...any) // Fail reports a failure message that immediate aborts of the test // execution. Fail() // FailNow reports fatal failure notifications without log output that // aborts test execution immediately. FailNow() // Panic reports a panic. Panic(arg any) }
Reporter is a minimal interface for abstracting test report methods that are needed to setup an isolated test environment for GoMock and Testify.
type Runner ¶
type Runner[P any] interface { // Filter sets up a filter for the test cases using the given pattern and // match flag. The pattern is a regular expression that is matched against // the test case name. The match flag is used to include or exclude the // test cases that match the pattern. Filter(pattern string, match bool) Runner[P] // Timeout sets up a timeout for the test cases executed by the test runner. // Setting a timeout is useful to prevent the test execution from waiting // too long in case of deadlocks. The timeout is not affecting the global // test timeout that may only abort a test earlier. If the given duration is // zero or negative, the timeout is ignored. Timeout(timeout time.Duration) Runner[P] // StopEarly stops the test by the given duration ahead of an individual or // global test deadline. This is useful to ensure that resources can be // cleaned up before the global deadline is exceeded. StopEarly(time time.Duration) Runner[P] // Run runs all test parameter sets in parallel. If the test parameter sets // are provided as a map, the test case name is used as the test name. If // the test parameter sets are provided as a slice, the test case name is // created by appending the index to the test name. If the test parameter // sets are provided as a single parameter set, the test case name is used // as the test name. The test case name is normalized before being used. Run(call func(t Test, param P)) Runner[P] // RunSeq runs the test parameter sets in a sequence. If the test parameter // sets are provided as a map, the test case name is used as the test name. // If the test parameter sets are provided as a slice, the test case name is // created by appending the index to the test name. If the test parameter // sets are provided as a single parameter set, the test case name is used // as the test name. The test case name is normalized before being used. RunSeq(call func(t Test, param P)) Runner[P] // Cleanup register a function to be called to cleanup after all tests have // finished to remove the shared resources. Cleanup(call func()) }
Runner is a generic test runner interface.
func Any ¶ added in v0.0.22
Any creates a new parallel test runner with given parameter set(s). The set can be a single test parameter set, a slice of test parameter sets, or a map of named test parameter sets. The test runner is looking into the parameter set to determine a suitable test case name, e.g. by using a `name` parameter.
type Setter ¶ added in v0.0.22
type Setter[T any] interface { // Set sets the value of the field with the given name. If the name is empty, // and of the same type the stored target instance is replaced by the given // value. Set(name string, value any) Setter[T] // Build returns the created or modified target instance of the builder. Build() T }
Setter is a generic fluent interface that allows you to modify unexported fields of a (pointer) struct by field name.
type Test ¶
type Test interface { // Name provides the test name. Name() string // Helper declares a test helper function. Helper() // Parallel declares that the test is to be run in parallel with (and only // with) other parallel tests. Parallel() // TempDir creates a new temporary directory for the test. TempDir() string // Setenv sets an environment variable for the test. Setenv(key, value string) // Deadline returns the deadline of the test and a flag indicating whether // the deadline is set. Deadline() (deadline time.Time, ok bool) // Skip is a helper method to skip the test. Skip(args ...any) // Skipf is a helper method to skip the test with a formatted message. Skipf(format string, args ...any) // SkipNow is a helper method to skip the test immediately. SkipNow() // Skipped reports whether the test has been skipped. Skipped() bool // Log provides a logging function for the test. Log(args ...any) // Logf provides a logging function for the test. Logf(format string, args ...any) // Error handles a failure messages when a test is supposed to continue. Error(args ...any) // Errorf handles a failure messages when a test is supposed to continue. Errorf(format string, args ...any) // Fatal handles a fatal failure message that immediate aborts of the test // execution. Fatal(args ...any) // Fatalf handles a fatal failure message that immediate aborts of the test // execution. Fatalf(format string, args ...any) // Fail handles a failure message that immediate aborts of the test // execution. Fail() // FailNow handles fatal failure notifications without log output that // aborts test execution immediately. FailNow() // Failed reports whether the test has failed. Failed() bool // Cleanup is a function called to setup test cleanup after execution. Cleanup(cleanup func()) }
Test is a minimal interface for abstracting test methods that are needed to setup an isolated test environment for GoMock and Testify.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator a test failure validator based on the test reporter interface.
func NewValidator ¶
func NewValidator(ctrl *gomock.Controller) *Validator
NewValidator creates a new test validator for validating error messages and panics created during test execution.
func (*Validator) EXPECT ¶
EXPECT implements the usual `gomock.EXPECT` call to request the recorder.
func (*Validator) Fail ¶ added in v0.0.22
func (v *Validator) Fail()
Fail receive expected method call to `Fail`.
func (*Validator) FailNow ¶
func (v *Validator) FailNow()
FailNow receive expected method call to `FailNow`.