test_helpers

package
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: BSD-2-Clause Imports: 23 Imported by: 0

Documentation

Overview

Package test_helpers provides helpers for managing Tarantool process for testing purposes.

Package introduces go helpers for starting a tarantool process and validating Tarantool version. Helpers are based on os/exec calls. Retries to connect test tarantool instance handled explicitly, see tarantool/go-tarantool/#136.

Tarantool's instance Lua scripts use environment variables to configure box.cfg. Listen port is set in the end of script so it is possible to connect only if every other thing was set up already.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckEqualBoxErrors

func CheckEqualBoxErrors(t T, expected tarantool.BoxError, actual tarantool.BoxError)

CheckEqualBoxErrors checks equivalence of tarantool.BoxError objects.

Tarantool errors are not comparable by nature:

tarantool> msgpack.decode(mp_error_repr) == msgpack.decode(mp_error_repr) --- - false ...

Tarantool error file and line could differ even between different patches.

So we check equivalence of all attributes except for Line and File. For Line and File, we check that they are filled with some non-default values (lines are counted starting with 1 and empty file path is not expected too).

func CheckPoolStatuses

func CheckPoolStatuses(args CheckStatusesArgs) error

func ConnectWithValidation

func ConnectWithValidation(t T,
	dialer tarantool.Dialer,
	opts tarantool.Opts) *tarantool.Connection

ConnectWithValidation tries to connect to a Tarantool instance. It returns a valid connection if it is successful, otherwise finishes a test with an error.

func ConvertUint64

func ConvertUint64(v any) (result uint64, err error)

ConvertUint64 converts an interface value to uint64. The msgpack.v5 decodes different uint types depending on value, this function helps to unify a result.

func DeleteRecordByKey

func DeleteRecordByKey(t T, conn tarantool.Connector,
	space any, index any, key []any)

func DumpLogsIfFailed

func DumpLogsIfFailed(t failedLogger, inst *TarantoolInstance)

DumpLogsIfFailed prints the tail of the tarantool instance's captured stdout/stderr via t.Logf when the test has already failed. Intended for use as `defer test_helpers.DumpLogsIfFailed(t, inst)` right after a successful StartTarantool, so an assertion failure later in the test surfaces the corresponding tarantool log alongside the failure.

No-op when the test passed, the instance is nil, or no log was captured.

func ExecuteOnAll

func ExecuteOnAll(ctx context.Context, dialers []tarantool.Dialer,
	fn func(context.Context, tarantool.Dialer, int) error) error

func GetConnectContext

func GetConnectContext() (context.Context, context.CancelFunc)

func GetPoolConnectContext

func GetPoolConnectContext() (context.Context, context.CancelFunc)

func InsertOnInstance

func InsertOnInstance(ctx context.Context, dialer tarantool.Dialer, connOpts tarantool.Opts,
	space any, tuple any) error

func InsertOnInstances

func InsertOnInstances(
	ctx context.Context,
	dialers []tarantool.Dialer,
	connOpts tarantool.Opts,
	space any,
	tuple any) error

func IsTarantoolEE

func IsTarantoolEE() (bool, error)

IsTarantoolEE checks if Tarantool is Enterprise edition.

func IsTarantoolVersionLess

func IsTarantoolVersionLess(majorMin uint64, minorMin uint64, patchMin uint64) (bool, error)

IsTarantoolVersionLess checks if tarantool version is less than passed <major.minor.patch>. Returns error if failed to extract version.

func IsTcsSupported

func IsTcsSupported() (bool, error)

IsTcsSupported checks if Tarantool supports centralized storage. Tarantool supports centralized storage with Enterprise since 3.3.0 version.

func ProcessListenOnInstance

func ProcessListenOnInstance(args ListenOnInstanceArgs) error

ProcessListenOnInstance helper calls "return box.cfg.listen" as many times as there are servers in the connection pool with specified mode. For ModeRO mode expected received ports equals to replica ports. For ModeRW mode expected received ports equals to master ports. For ModePreferRO mode expected received ports equals to replica ports or to all ports. For ModePreferRW mode expected received ports equals to master ports or to all ports.

func Ptr

func Ptr[T any](val T) *T

Ptr returns a pointer to an existing value.

Example:

func NewInt() int { return 1 }
var b *int = Ptr(NewInt())

func RestartTarantool

func RestartTarantool(inst *TarantoolInstance) error

RestartTarantool restarts a tarantool instance for tests with specifies parameters (refer to StartOpts) which were specified in inst parameter. inst is a tarantool instance that was started by StartTarantool. Rewrites inst.Cmd.Process to stop instance with StopTarantool. Process must be stopped with StopTarantool.

func SetClusterRO

func SetClusterRO(ctx context.Context, dialers []tarantool.Dialer, connOpts tarantool.Opts,
	roles []bool) error

func SetInstanceRO

func SetInstanceRO(ctx context.Context, dialer tarantool.Dialer, connOpts tarantool.Opts,
	isReplica bool) error

func SkipIfCrudSpliceBroken

func SkipIfCrudSpliceBroken(t T)

SkipIfCrudSpliceBroken skips test run if splice operation is broken on the crud side. https://github.com/tarantool/crud/issues/397

func SkipIfErrorExtendedInfoUnsupported

func SkipIfErrorExtendedInfoUnsupported(t T)

SkipIfErrorExtendedInfoUnsupported skips test run if Tarantool without IPROTO_ERROR (0x52) support is used.

func SkipIfErrorMessagePackTypeUnsupported

func SkipIfErrorMessagePackTypeUnsupported(t T)

SkipIfErrorMessagePackTypeUnsupported skips test run if Tarantool without MP_ERROR type over iproto support is used.

func SkipIfFeatureDropped

func SkipIfFeatureDropped(t T, feature string, major, minor, patch uint64)

SkipIfFeatureDropped skips test run if Tarantool had dropped support of a feature.

func SkipIfFeatureSupported

func SkipIfFeatureSupported(t T, feature string, major, minor, patch uint64)

SkipIfFeatureSupported skips test run if Tarantool supports a feature. Helper if useful when we want to test if everything is alright on older versions.

func SkipIfFeatureUnsupported

func SkipIfFeatureUnsupported(t T, feature string, major, minor, patch uint64)

SkipIfFeatureUnsupported skips test run if Tarantool does not yet support a feature.

func SkipIfGreaterOrEqual

func SkipIfGreaterOrEqual(t T, reason string, major, minor, patch uint64)

SkipIfGreaterOrEqual skips test run if Tarantool version is greater or equal than expected.

func SkipIfIdSupported

func SkipIfIdSupported(t T)

SkipIfIdSupported skips test run if Tarantool with IPROTO_ID support is used. Skip is useful for tests validating that protocol info is processed as expected even for pre-IPROTO_ID instances.

func SkipIfIdUnsupported

func SkipIfIdUnsupported(t T)

SkipIfIdUnsupported skips test run if Tarantool without IPROTO_ID support is used.

func SkipIfIsSyncUnsupported

func SkipIfIsSyncUnsupported(t T)

SkipIfIsSyncUnsupported skips test run if Tarantool without IS_SYNC support is used.

func SkipIfLess

func SkipIfLess(t T, reason string, major, minor, patch uint64)

SkipIfLess skips test run if Tarantool version is less than expected.

func SkipIfPaginationUnsupported

func SkipIfPaginationUnsupported(t T)

SkipIfPaginationUnsupported skips test run if Tarantool without pagination is used.

func SkipIfSQLUnsupported

func SkipIfSQLUnsupported(t T)

func SkipIfStreamsUnsupported

func SkipIfStreamsUnsupported(t T)

SkipIfStreamsUnsupported skips test run if Tarantool without streams support is used.

func SkipIfTcsUnsupported

func SkipIfTcsUnsupported(t T)

SkipIfTcsUnsupported skips test if no centralized storage support.

func SkipIfWatchOnceSupported

func SkipIfWatchOnceSupported(t T)

SkipIfWatchOnceSupported skips test run if Tarantool with WatchOnce request type is used.

func SkipIfWatchOnceUnsupported

func SkipIfWatchOnceUnsupported(t T)

SkipIfWatchOnceUnsupported skips test run if Tarantool without WatchOnce request type is used.

func SkipIfWatchersSupported

func SkipIfWatchersSupported(t T)

SkipIfWatchersSupported skips test run if Tarantool with watchers support is used.

func SkipIfWatchersUnsupported

func SkipIfWatchersUnsupported(t T)

SkipIfWatchersUnsupported skips test run if Tarantool without watchers support is used.

func StopTarantool

func StopTarantool(inst *TarantoolInstance)

StopTarantool stops a tarantool instance started with StartTarantool. Waits until any resources associated with the process is released. If something went wrong, fails.

func StopTarantoolInstances

func StopTarantoolInstances(instances []*TarantoolInstance)

func StopTarantoolWithCleanup

func StopTarantoolWithCleanup(inst *TarantoolInstance)

StopTarantoolWithCleanup stops a tarantool instance started with StartTarantool. Waits until any resources associated with the process is released. Cleans work directory after stop. If something went wrong, fails.

func WaitUntilReconnected

func WaitUntilReconnected(conn *tarantool.Connection, retries uint, timeout time.Duration) bool

WaitUntilReconnected waits until connection is reestablished. Returns false in case of connection is not in the connected state after specified retries count, true otherwise.

Types

type CheckStatusesArgs

type CheckStatusesArgs struct {
	Pool               *pool.Pool
	Servers            []string
	Mode               pool.Mode
	ExpectedPoolStatus bool
	ExpectedStatuses   map[string]bool
}

type ListenOnInstanceArgs

type ListenOnInstanceArgs struct {
	Pool          *pool.Pool
	Mode          pool.Mode
	ServersNumber int
	ExpectedPorts map[string]bool
}

type MockDoer

type MockDoer interface {
	// AddResponse adds a response with a custom header and a body
	// packed inside an io.Reader and returns the MockDoer for chaining.
	AddResponse(header tarantool.Header, body io.Reader) MockDoer
	// AddResponseRaw adds a response with an empty header and the given
	// data, which is encoded with msgpack, and returns the MockDoer for
	// chaining.
	AddResponseRaw(data any) MockDoer
	// AddResponseError adds an error response and returns the MockDoer for
	// chaining.
	AddResponseError(err error) MockDoer
	// Requests returns a slice of requests received via Do calls.
	Requests() []tarantool.Request
	// Do processes the request and returns a Future with the next
	// configured response or error. It calls Fatalf on the test if
	// no responses are configured.
	Do(req tarantool.Request) tarantool.Future
}

MockDoer is an interface for a mock doer used for custom testing. It allows building a sequence of responses and inspecting requests that were sent via Do calls.

Example (NoResponses)
package main

import (
	"fmt"
	"os"

	"github.com/tarantool/go-tarantool/v3"
	"github.com/tarantool/go-tarantool/v3/test_helpers"
)

func main() {
	// This example demonstrates that MockDoer calls Fatalf on the test
	// when Do() is called more times than responses were configured.
	mockDoer := test_helpers.NewMockDoer(testingAdapter{}).
		AddResponseRaw([]any{"first"})

	data, err := mockDoer.Do(tarantool.NewPingRequest()).Get()
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("first response:", data)

	mockDoer.Do(tarantool.NewPingRequest())

}

type testingAdapter struct {
	test_helpers.T
}

func (testingAdapter) Helper() {}
func (testingAdapter) Fatalf(format string, args ...any) {
	_, _ = fmt.Fprintf(os.Stdout, format, args...)
}
Output:
first response: [first]
MockDoer.Do: no responses configured, 1 Do() calls were made

func NewMockDoer

func NewMockDoer(t T) MockDoer

NewMockDoer creates a MockDoer for testing. Use AddResponse, AddResponseRaw, and AddResponseError methods to configure the sequence of responses.

type MockRequest

type MockRequest struct {
}

MockRequest is an empty mock request used for testing purposes.

func NewMockRequest

func NewMockRequest() *MockRequest

NewMockRequest creates an empty MockRequest.

func (*MockRequest) Async

func (req *MockRequest) Async() bool

Async returns if MockRequest expects a response.

func (*MockRequest) Body

func (req *MockRequest) Body(resolver tarantool.SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the watch request body.

func (*MockRequest) Conn

func (req *MockRequest) Conn() *tarantool.Connection

Conn returns the Connection object the request belongs to.

func (*MockRequest) Ctx

func (req *MockRequest) Ctx() context.Context

Ctx returns a context of the MockRequest.

func (*MockRequest) Response

func (req *MockRequest) Response(header tarantool.Header,
	body io.Reader) (tarantool.Response, error)

Response creates a response for the MockRequest.

func (*MockRequest) Type

func (req *MockRequest) Type() iproto.Type

Type returns an iproto type for MockRequest.

type MockRequestNamed

type MockRequestNamed struct {
	MockRequest

	Name string
}

MockRequestNamed is a mock request with a name used for testing purposes. It is useful for verifying that a specific request was sent via the MockDoer by checking the Name field of recorded requests.

func NewMockRequestNamed

func NewMockRequestNamed(name string) *MockRequestNamed

NewMockRequestNamed creates a MockRequestNamed with the given name.

type MockResponse

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

MockResponse is a mock response used for testing purposes.

func CreateMockResponse

func CreateMockResponse(header tarantool.Header, body io.Reader) (*MockResponse, error)

CreateMockResponse creates a MockResponse from the header and a data, packed inside an io.Reader.

func NewMockResponse

func NewMockResponse(t T, body any) *MockResponse

NewMockResponse creates a new MockResponse with an empty header and the given data. body should be passed as a structure to be encoded. The encoded body is served as response data and will be decoded once the response is decoded.

func (*MockResponse) Decode

func (resp *MockResponse) Decode() ([]any, error)

Decode returns the result of decoding the response data as slice.

func (*MockResponse) DecodeTyped

func (resp *MockResponse) DecodeTyped(res any) error

DecodeTyped returns the result of decoding the response data.

func (*MockResponse) Header

func (resp *MockResponse) Header() tarantool.Header

Header returns a header for the MockResponse.

func (*MockResponse) Release

func (resp *MockResponse) Release()

Release free used data.

type StartOpts

type StartOpts struct {
	// Auth is an authentication method for a Tarantool instance.
	Auth tarantool.Auth

	// InitScript is a Lua script for tarantool to run on start.
	InitScript string

	// ConfigFile is a path to a configuration file for a Tarantool instance.
	// Required in pair with InstanceName.
	ConfigFile string

	// InstanceName is a name of an instance to run.
	// Required in pair with ConfigFile.
	InstanceName string

	// Listen is box.cfg listen parameter for tarantool.
	// Use this address to connect to tarantool after configuration.
	// https://www.tarantool.io/en/doc/latest/reference/configuration/#cfg-basic-listen
	Listen string

	// WorkDir is box.cfg work_dir parameter for a Tarantool instance:
	// a folder to store data files. If not specified, helpers create a
	// new temporary directory.
	// Folder must be unique for each Tarantool process used simultaneously.
	// https://www.tarantool.io/en/doc/latest/reference/configuration/#confval-work_dir
	WorkDir string

	// SslCertsDir is a path to a directory with SSL certificates. It will be
	// copied to the working directory.
	SslCertsDir string

	// WaitStart is a time to wait before starting to ping tarantool.
	WaitStart time.Duration

	// ConnectRetry is a count of retry attempts to ping tarantool. If the
	// value < 0 then there will be no ping tarantool at all.
	ConnectRetry int

	// RetryTimeout is a time between tarantool ping retries.
	RetryTimeout time.Duration

	// MemtxUseMvccEngine is flag to enable transactional
	// manager if set to true.
	MemtxUseMvccEngine bool

	// Dialer to check that connection established.
	Dialer tarantool.Dialer
}

type T

type T interface {
	// Helper marks the calling function as a test helper function.
	Helper()
	// Errorf marks the test as a test failure.
	Errorf(format string, args ...any)
	// Fatalf marks the test as a test failure and stops its execution.
	Fatalf(format string, args ...any)
	// Skipf marks the test as skipped.
	Skipf(format string, args ...any)
	// FailNow marks the function as having failed and stops its execution.
	// It is required for github.com/stretchr/testify/require functions.
	FailNow()
}

T is a subset of testing.T interface used by test helpers. It allows test helpers to be used in example functions, benchmarks, and custom test frameworks. The standard *testing.T satisfies this interface, so existing code continues to work without changes.

type TarantoolInstance

type TarantoolInstance struct {
	// Cmd is a Tarantool command. Used to kill Tarantool process.
	//
	// Deprecated: Cmd field will be removed in the next major version.
	// Use `Wait()` and `Stop()` methods, instead of calling `Cmd.Process.Wait()` or
	// `Cmd.Process.Kill()` directly.
	Cmd *exec.Cmd

	// Options for restarting a tarantool instance.
	Opts StartOpts

	// Dialer to check that connection established.
	Dialer tarantool.Dialer
	// contains filtered or unexported fields
}

TarantoolInstance is a data for instance graceful shutdown and cleanup.

func StartTarantool

func StartTarantool(startOpts StartOpts) (*TarantoolInstance, error)

StartTarantool starts a tarantool instance for tests with specifies parameters (refer to StartOpts). Process must be stopped with StopTarantool.

func StartTarantoolInstances

func StartTarantoolInstances(instsOpts []StartOpts) ([]*TarantoolInstance, error)

func (*TarantoolInstance) IsExit

func (t *TarantoolInstance) IsExit() bool

IsExit checks if Tarantool process was terminated.

func (*TarantoolInstance) LogTail

func (t *TarantoolInstance) LogTail() string

LogTail returns the tail of the spawned tarantool's combined stdout/stderr captured since the process was started — up to the last 50 lines. Includes a partial trailing line if the process did not flush a newline. Empty if no output was captured.

func (*TarantoolInstance) Signal

func (t *TarantoolInstance) Signal(sig os.Signal) error

Signal sends a signal to the Tarantool instance.

func (*TarantoolInstance) Stop

func (t *TarantoolInstance) Stop() error

Stop terminates Tarantool process and waits until it exit.

func (*TarantoolInstance) Wait

func (t *TarantoolInstance) Wait() error

Wait waits until Tarantool process is terminated. Returns error as process result status.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL