mtest

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2023 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package mtest is unstable and there is no backward compatibility guarantee. It is experimental and subject to change.

Index

Constants

View Source
const (
	// TestDb specifies the name of default test database.
	TestDb = "test"
)

Variables

View Source
var (
	// MajorityWc is the majority write concern.
	MajorityWc = writeconcern.New(writeconcern.WMajority())
	// PrimaryRp is the primary read preference.
	PrimaryRp = readpref.Primary()
	// SecondaryRp is the secondary read preference.
	SecondaryRp = readpref.Secondary()
	// LocalRc is the local read concern
	LocalRc = readconcern.Local()
	// MajorityRc is the majority read concern
	MajorityRc = readconcern.Majority()
)
View Source
var (
	// MockDescription is the server description used for the mock deployment. Each mocked connection returns this
	// value from its Description method.
	MockDescription = description.Server{
		CanonicalAddr:         serverAddress,
		MaxDocumentSize:       maxDocumentSize,
		MaxMessageSize:        maxMessageSize,
		MaxBatchCount:         maxBatchCount,
		SessionTimeoutMinutes: sessionTimeoutMinutes,
		Kind:                  description.RSPrimary,
		WireVersion: &description.VersionRange{
			Max: topology.SupportedWireVersions.Max,
		},
	}
)

Functions

func AuthEnabled

func AuthEnabled() bool

AuthEnabled returns whether or not the cluster requires auth.

func ClusterConnString

func ClusterConnString() connstring.ConnString

ClusterConnString returns the parsed ConnString for the cluster.

func ClusterURI

func ClusterURI() string

ClusterURI returns the connection string for the cluster.

func CompareServerVersions

func CompareServerVersions(v1 string, v2 string) int

CompareServerVersions compares two version number strings (i.e. positive integers separated by periods). Comparisons are done to the lesser precision of the two versions. For example, 3.2 is considered equal to 3.2.11, whereas 3.2.0 is considered less than 3.2.11.

Returns a positive int if version1 is greater than version2, a negative int if version1 is less than version2, and 0 if version1 is equal to version2.

func CreateCommandErrorResponse

func CreateCommandErrorResponse(ce CommandError) bson.D

CreateCommandErrorResponse creates a response with a command error.

func CreateCursorResponse

func CreateCursorResponse(cursorID int64, ns string, identifier BatchIdentifier, batch ...bson.D) bson.D

CreateCursorResponse creates a response for a cursor command.

func CreateSuccessResponse

func CreateSuccessResponse(elems ...bson.E) bson.D

CreateSuccessResponse creates a response for a successful operation with the given elements.

func CreateWriteConcernErrorResponse

func CreateWriteConcernErrorResponse(wce WriteConcernError) bson.D

CreateWriteConcernErrorResponse creates a response with a write concern error.

func CreateWriteErrorsResponse

func CreateWriteErrorsResponse(writeErrorrs ...WriteError) bson.D

CreateWriteErrorsResponse creates a response with one or more write errors.

func DropEncryptedCollection

func DropEncryptedCollection(t *T, coll *mongo.Collection, encryptedFields interface{})

DropEncryptedCollection drops a collection with EncryptedFields. The EncryptedFields option is not supported in Collection.Drop(). See GODRIVER-2413.

func GlobalClient

func GlobalClient() *mongo.Client

GlobalClient returns a Client connected to the cluster configured with read concern majority, write concern majority, and read preference primary.

func GlobalTopology

func GlobalTopology() *topology.Topology

GlobalTopology returns a Topology that's connected to the cluster.

func IsCSFLEEnabled

func IsCSFLEEnabled() bool

IsCSFLEEnabled returns true if driver is built with Client Side Field Level Encryption support. Client Side Field Level Encryption support is enabled with the cse build tag.

func MultiMongosLoadBalancerURI

func MultiMongosLoadBalancerURI() string

MultiMongosLoadBalancerURI returns the URI for a load balancer fronting multiple mongoses. This will only be set if the cluster is load balanced.

func SSLEnabled

func SSLEnabled() bool

SSLEnabled returns whether or not the cluster requires SSL.

func ServerVersion

func ServerVersion() string

ServerVersion returns the server version of the cluster. This assumes that all nodes in the cluster have the same version.

func Serverless

func Serverless() bool

Serverless returns whether the test is running against a serverless instance.

func SetFailPoint

func SetFailPoint(fp FailPoint, client *mongo.Client) error

SetFailPoint configures the provided fail point on the cluster under test using the provided Client.

func SetRawFailPoint

func SetRawFailPoint(fp bson.Raw, client *mongo.Client) error

SetRawFailPoint configures the fail point represented by the fp parameter on the cluster under test using the provided Client

func Setup

func Setup(setupOpts ...*SetupOptions) error

Setup initializes the current testing context. This function must only be called one time and must be called before any tests run.

func SingleMongosLoadBalancerURI

func SingleMongosLoadBalancerURI() string

SingleMongosLoadBalancerURI returns the URI for a load balancer fronting a single mongos. This will only be set if the cluster is load balanced.

func Teardown

func Teardown() error

Teardown cleans up resources initialized by Setup. This function must be called once after all tests have finished running.

Types

type BatchIdentifier

type BatchIdentifier string

BatchIdentifier specifies the keyword to identify the batch in a cursor response.

const (
	FirstBatch BatchIdentifier = "firstBatch"
	NextBatch  BatchIdentifier = "nextBatch"
)

These constants specify valid values for BatchIdentifier.

type ClientType

type ClientType int

ClientType specifies the type of Client that should be created for a test.

const (
	// Default specifies a client to the connection string in the MONGODB_URI env variable with command monitoring
	// enabled.
	Default ClientType = iota
	// Pinned specifies a client that is pinned to a single mongos in a sharded cluster.
	Pinned
	// Mock specifies a client that communicates with a mock deployment.
	Mock
	// Proxy specifies a client that proxies messages to the server and also stores parsed copies. The proxied
	// messages can be retrieved via T.GetProxiedMessages or T.GetRawProxiedMessages.
	Proxy
)

These constants specify valid values for ClientType

type Collection

type Collection struct {
	Name         string
	DB           string        // defaults to mt.DB.Name() if not specified
	Client       *mongo.Client // defaults to mt.Client if not specified
	Opts         *options.CollectionOptions
	CreateOpts   *options.CreateCollectionOptions
	ViewOn       string
	ViewPipeline interface{}
	// contains filtered or unexported fields
}

Collection is used to configure a new collection created during a test.

type CommandError

type CommandError struct {
	Code    int32
	Message string
	Name    string
	Labels  []string
}

CommandError is a representation of a command error from the server.

type FailPoint

type FailPoint struct {
	ConfigureFailPoint string `bson:"configureFailPoint"`
	// Mode should be a string, FailPointMode, or map[string]interface{}
	Mode interface{}   `bson:"mode"`
	Data FailPointData `bson:"data"`
}

FailPoint is a representation of a server fail point. See https://github.com/mongodb/specifications/tree/HEAD/source/transactions/tests#server-fail-point for more information regarding fail points.

type FailPointData

type FailPointData struct {
	FailCommands                  []string               `bson:"failCommands,omitempty"`
	CloseConnection               bool                   `bson:"closeConnection,omitempty"`
	ErrorCode                     int32                  `bson:"errorCode,omitempty"`
	FailBeforeCommitExceptionCode int32                  `bson:"failBeforeCommitExceptionCode,omitempty"`
	ErrorLabels                   *[]string              `bson:"errorLabels,omitempty"`
	WriteConcernError             *WriteConcernErrorData `bson:"writeConcernError,omitempty"`
	BlockConnection               bool                   `bson:"blockConnection,omitempty"`
	BlockTimeMS                   int32                  `bson:"blockTimeMS,omitempty"`
	AppName                       string                 `bson:"appName,omitempty"`
}

FailPointData is a representation of the FailPoint.Data field.

type FailPointMode

type FailPointMode struct {
	Times int32 `bson:"times"`
	Skip  int32 `bson:"skip"`
}

FailPointMode is a representation of the Failpoint.Mode field.

type Options

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

Options is the type used to configure a new T instance.

func NewOptions

func NewOptions() *Options

NewOptions creates an empty Options instance.

func (*Options) AtlasDataLake

func (op *Options) AtlasDataLake(adl bool) *Options

AtlasDataLake specifies whether this test should only be run against Atlas Data Lake servers. Defaults to false.

func (*Options) Auth

func (op *Options) Auth(auth bool) *Options

Auth specifies whether or not auth should be enabled for this test to run. By default, a test will run regardless of whether or not auth is enabled.

func (*Options) ClientOptions

func (op *Options) ClientOptions(opts *options.ClientOptions) *Options

ClientOptions sets the options to use when creating a client for a test.

func (*Options) ClientType

func (op *Options) ClientType(ct ClientType) *Options

ClientType specifies the type of client that should be created for a test. This option will be propagated to all sub-tests. If the provided ClientType is Proxy, the SSL(false) option will be also be added because the internal proxy dialer and connection types do not support SSL.

func (*Options) CollectionCreateOptions

func (op *Options) CollectionCreateOptions(opts *options.CreateCollectionOptions) *Options

CollectionCreateOptions sets the options to pass to Database.CreateCollection() when creating a collection for a test.

func (*Options) CollectionName

func (op *Options) CollectionName(collName string) *Options

CollectionName specifies the name for the collection for the test.

func (*Options) CollectionOptions

func (op *Options) CollectionOptions(opts *options.CollectionOptions) *Options

CollectionOptions sets the options to use when creating a collection for a test.

func (*Options) CreateClient

func (op *Options) CreateClient(create bool) *Options

CreateClient specifies whether or not a client should be created for a test. This should be set to false when running a test that only runs other tests.

func (*Options) CreateCollection

func (op *Options) CreateCollection(create bool) *Options

CreateCollection specifies whether or not a collection should be created for a test. The default value is true.

func (*Options) DatabaseName

func (op *Options) DatabaseName(dbName string) *Options

DatabaseName specifies the name of the database for the test.

func (*Options) Enterprise

func (op *Options) Enterprise(ent bool) *Options

Enterprise specifies whether or not this test should only be run on enterprise server variants. Defaults to false.

func (*Options) MaxServerVersion

func (op *Options) MaxServerVersion(version string) *Options

MaxServerVersion specifies the maximum server version for the test.

func (*Options) MinServerVersion

func (op *Options) MinServerVersion(version string) *Options

MinServerVersion specifies the minimum server version for the test.

func (*Options) MockResponses

func (op *Options) MockResponses(responses ...bson.D) *Options

MockResponses specifies the responses returned by a mock deployment. This should only be used if the current test is being run with MockDeployment(true). Responses can also be added after a sub-test has already been created.

func (*Options) RequireAPIVersion

func (op *Options) RequireAPIVersion(rav bool) *Options

RequireAPIVersion specifies whether this test should only be run when REQUIRE_API_VERSION is true. Defaults to false.

func (*Options) RunOn

func (op *Options) RunOn(blocks ...RunOnBlock) *Options

RunOn specifies run-on blocks used to determine if a test should run. If a test's environment meets at least one of the given constraints, it will be run. Otherwise, it will be skipped.

func (*Options) SSL

func (op *Options) SSL(ssl bool) *Options

SSL specifies whether or not SSL should be enabled for this test to run. By default, a test will run regardless of whether or not SSL is enabled.

func (*Options) ShareClient

func (op *Options) ShareClient(share bool) *Options

ShareClient specifies whether or not a test should pass its client down to sub-tests. This should be set when calling New() if the inheriting behavior is desired. This option must not be used if the test accesses command monitoring events.

func (*Options) Topologies

func (op *Options) Topologies(topos ...TopologyKind) *Options

Topologies specifies a list of topologies that the test can run on.

type ProxyMessage

type ProxyMessage struct {
	ServerAddress string
	CommandName   string
	Sent          *SentMessage
	Received      *ReceivedMessage
}

ProxyMessage represents a sent/received pair of parsed wire messages.

type ReceivedMessage

type ReceivedMessage struct {
	ResponseTo int32
	RawMessage wiremessage.WireMessage
	Response   bsoncore.Document
}

ReceivedMessage represents a message received from the server.

type RunOnBlock

type RunOnBlock struct {
	MinServerVersion string                   `bson:"minServerVersion"`
	MaxServerVersion string                   `bson:"maxServerVersion"`
	Topology         []TopologyKind           `bson:"topology"`
	Serverless       string                   `bson:"serverless"`
	ServerParameters map[string]bson.RawValue `bson:"serverParameters"`
	Auth             *bool                    `bson:"auth"`
	AuthEnabled      *bool                    `bson:"authEnabled"`
	CSFLE            *bool                    `bson:"csfle"`
}

RunOnBlock describes a constraint for a test.

func (*RunOnBlock) UnmarshalBSON

func (r *RunOnBlock) UnmarshalBSON(data []byte) error

UnmarshalBSON implements custom BSON unmarshalling behavior for RunOnBlock because some test formats use the "topology" key while the unified test format uses "topologies".

type SentMessage

type SentMessage struct {
	RequestID  int32
	RawMessage wiremessage.WireMessage
	Command    bsoncore.Document
	OpCode     wiremessage.OpCode

	// The $readPreference document. This is separated into its own field even though it's included in the larger
	// command document in both OP_QUERY and OP_MSG because OP_QUERY separates the command into a $query sub-document
	// if there is a read preference. To unify OP_QUERY and OP_MSG, we pull this out into a separate field and set
	// the Command field to the $query sub-document.
	ReadPreference bsoncore.Document

	// The documents sent for an insert, update, or delete command. This is separated into its own field because it's
	// sent as part of the command document in OP_QUERY and as a document sequence outside the command document in
	// OP_MSG.
	DocumentSequence *bsoncore.DocumentSequence
}

SentMessage represents a message sent by the driver to the server.

type SetupOptions

type SetupOptions struct {
	// Specifies the URI to connect to. Defaults to URI based on the environment variables MONGODB_URI,
	// MONGO_GO_DRIVER_CA_FILE, and MONGO_GO_DRIVER_COMPRESSOR
	URI *string
}

SetupOptions is the type used to configure mtest setup

func MergeSetupOptions deprecated

func MergeSetupOptions(opts ...*SetupOptions) *SetupOptions

MergeSetupOptions combines the given *SetupOptions into a single *Options in a last one wins fashion.

Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a single options struct instead.

func NewSetupOptions

func NewSetupOptions() *SetupOptions

NewSetupOptions creates an empty SetupOptions struct

func (*SetupOptions) SetURI

func (so *SetupOptions) SetURI(uri string) *SetupOptions

SetURI sets the uri to connect to

type T

type T struct {
	*testing.T

	Client *mongo.Client
	DB     *mongo.Database
	Coll   *mongo.Collection
	// contains filtered or unexported fields
}

T is a wrapper around testing.T.

func New

func New(wrapped *testing.T, opts ...*Options) *T

New creates a new T instance with the given options. If the current environment does not satisfy constraints specified in the options, the test will be skipped automatically.

func (*T) AddMockResponses

func (t *T) AddMockResponses(responses ...bson.D)

AddMockResponses adds responses to be returned by the mock deployment. This should only be used if T is being run against a mock deployment.

func (*T) ClearCollections

func (t *T) ClearCollections()

ClearCollections drops all collections previously created by this test.

func (*T) ClearEvents

func (t *T) ClearEvents()

ClearEvents clears the existing command monitoring events.

func (*T) ClearFailPoints

func (t *T) ClearFailPoints()

ClearFailPoints disables all previously set failpoints for this test.

func (*T) ClearMockResponses

func (t *T) ClearMockResponses()

ClearMockResponses clears all responses in the mock deployment.

func (*T) CloneCollection

func (t *T) CloneCollection(opts *options.CollectionOptions)

CloneCollection modifies the default collection for this test to match the given options.

func (*T) CloneDatabase

func (t *T) CloneDatabase(opts *options.DatabaseOptions)

CloneDatabase modifies the default database for this test to match the given options.

func (*T) Close

func (t *T) Close()

Close cleans up any resources associated with a T. There should be one Close corresponding to every New.

func (*T) CreateCollection

func (t *T) CreateCollection(coll Collection, createOnServer bool) *mongo.Collection

CreateCollection creates a new collection with the given configuration. The collection will be dropped after the test finishes running. If createOnServer is true, the function ensures that the collection has been created server-side by running the create command. The create command will appear in command monitoring channels.

func (*T) FilterFailedEvents

func (t *T) FilterFailedEvents(filter func(*event.CommandFailedEvent) bool)

FilterFailedEvents filters the existing CommandFailedEVent instances for this test using the provided filter callback. An event will be retained if the filter returns true. The list of filtered events will be used to overwrite the list of events for this test and will therefore change the output of t.GetAllFailedEvents().

func (*T) FilterStartedEvents

func (t *T) FilterStartedEvents(filter func(*event.CommandStartedEvent) bool)

FilterStartedEvents filters the existing CommandStartedEvent instances for this test using the provided filter callback. An event will be retained if the filter returns true. The list of filtered events will be used to overwrite the list of events for this test and will therefore change the output of t.GetAllStartedEvents().

func (*T) FilterSucceededEvents

func (t *T) FilterSucceededEvents(filter func(*event.CommandSucceededEvent) bool)

FilterSucceededEvents filters the existing CommandSucceededEvent instances for this test using the provided filter callback. An event will be retained if the filter returns true. The list of filtered events will be used to overwrite the list of events for this test and will therefore change the output of t.GetAllSucceededEvents().

func (*T) GetAllFailedEvents

func (t *T) GetAllFailedEvents() []*event.CommandFailedEvent

GetAllFailedEvents returns a slice of all CommandFailedEvent instances for this test. This can be called multiple times.

func (*T) GetAllStartedEvents

func (t *T) GetAllStartedEvents() []*event.CommandStartedEvent

GetAllStartedEvents returns a slice of all CommandStartedEvent instances for this test. This can be called multiple times.

func (*T) GetAllSucceededEvents

func (t *T) GetAllSucceededEvents() []*event.CommandSucceededEvent

GetAllSucceededEvents returns a slice of all CommandSucceededEvent instances for this test. This can be called multiple times.

func (*T) GetFailedEvent

func (t *T) GetFailedEvent() *event.CommandFailedEvent

GetFailedEvent returns the most recent CommandFailedEvent, or nil if one is not present. This can only be called once per event.

func (*T) GetProxiedMessages

func (t *T) GetProxiedMessages() []*ProxyMessage

GetProxiedMessages returns the messages proxied to the server by the test. If the client type is not Proxy, this returns nil.

func (*T) GetStartedEvent

func (t *T) GetStartedEvent() *event.CommandStartedEvent

GetStartedEvent returns the most recent CommandStartedEvent, or nil if one is not present. This can only be called once per event.

func (*T) GetSucceededEvent

func (t *T) GetSucceededEvent() *event.CommandSucceededEvent

GetSucceededEvent returns the most recent CommandSucceededEvent, or nil if one is not present. This can only be called once per event.

func (*T) NumberConnectionsCheckedOut

func (t *T) NumberConnectionsCheckedOut() int

NumberConnectionsCheckedOut returns the number of connections checked out from the test Client.

func (*T) ResetClient

func (t *T) ResetClient(opts *options.ClientOptions)

ResetClient resets the existing client with the given options. If opts is nil, the existing options will be used. If t.Coll is not-nil, it will be reset to use the new client. Should only be called if the existing client is not nil. This will Disconnect the existing client but will not drop existing collections. To do so, ClearCollections must be called before calling ResetClient.

func (*T) Run

func (t *T) Run(name string, callback func(*T))

Run creates a new T instance for a sub-test and runs the given callback. It also creates a new collection using the given name which is available to the callback through the T.Coll variable and is dropped after the callback returns.

func (*T) RunOpts

func (t *T) RunOpts(name string, opts *Options, callback func(*T))

RunOpts creates a new T instance for a sub-test with the given options. If the current environment does not satisfy constraints specified in the options, the new sub-test will be skipped automatically. If the test is not skipped, the callback will be run with the new T instance. RunOpts creates a new collection with the given name which is available to the callback through the T.Coll variable and is dropped after the callback returns.

func (*T) SetFailPoint

func (t *T) SetFailPoint(fp FailPoint)

SetFailPoint sets a fail point for the client associated with T. Commands to create the failpoint will appear in command monitoring channels. The fail point will automatically be disabled after this test has run.

func (*T) SetFailPointFromDocument

func (t *T) SetFailPointFromDocument(fp bson.Raw)

SetFailPointFromDocument sets the fail point represented by the given document for the client associated with T. This method assumes that the given document is in the form {configureFailPoint: <failPointName>, ...}. Commands to create the failpoint will appear in command monitoring channels. The fail point will be automatically disabled after this test has run.

func (*T) TrackFailPoint

func (t *T) TrackFailPoint(fpName string)

TrackFailPoint adds the given fail point to the list of fail points to be disabled when the current test finishes. This function does not create a fail point on the server.

type TopologyKind

type TopologyKind string

TopologyKind describes the topology that a test is run on.

const (
	ReplicaSet   TopologyKind = "replicaset"
	Sharded      TopologyKind = "sharded"
	Single       TopologyKind = "single"
	LoadBalanced TopologyKind = "load-balanced"
	// ShardedReplicaSet is a special case of sharded that requires each shard to be a replica set rather than a
	// standalone server.
	ShardedReplicaSet TopologyKind = "sharded-replicaset"
)

These constants specify valid values for TopologyKind

func ClusterTopologyKind

func ClusterTopologyKind() TopologyKind

ClusterTopologyKind returns the topology kind of the cluster under test.

type WriteConcernError

type WriteConcernError struct {
	Name    string   `bson:"codeName"`
	Code    int      `bson:"code"`
	Message string   `bson:"errmsg"`
	Details bson.Raw `bson:"errInfo"`
}

WriteConcernError is a representation of a write concern error from the server.

type WriteConcernErrorData

type WriteConcernErrorData struct {
	Code        int32     `bson:"code"`
	Name        string    `bson:"codeName"`
	Errmsg      string    `bson:"errmsg"`
	ErrorLabels *[]string `bson:"errorLabels,omitempty"`
	ErrInfo     bson.Raw  `bson:"errInfo,omitempty"`
}

WriteConcernErrorData is a representation of the FailPoint.Data.WriteConcern field.

type WriteError

type WriteError struct {
	Index   int
	Code    int
	Message string
}

WriteError is a representation of a write error from the server.

Jump to

Keyboard shortcuts

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