Skip to main content

MongoDB DSL

Architecture

With the MongoDB DSL the user can inject a proxy client into the main test code with just a few annotations,

and use a set of predefined actions on this proxy client that are optimised for testing.

Those actions make the client capable of running queries and updates on a non-relational Mongo database, and

asserting expected results from the returned responses.

To have the Mongo proxy client injected in the test the only required step is to include an argument of

type MongoApplication in the list of arguments of the test and to annotate it with the minimum required annotations.

The respective object initialization happens automatically and allows it to be readily used during the test.

Example:


class TestClass {


@Test

void sampleTest(

@Capability(key = BROWSER_NAME, value = "pn5-mongo")

@Capability(key = CAPABILITY_MONGO_HOSTNAME, value = "localhost", type = ValueType.STRING)

@Capability(key = CAPABILITY_MONGO_PORT, value = "27017", type = ValueType.INTEGER)

@Capability(key = CAPABILITY_MONGO_DATABASE, value = "myDatabase", type = ValueType.STRING)

@Capability(key = CAPABILITY_MONGO_USERNAME, value = "test.user", type = ValueType.STRING)

@Capability(key = CAPABILITY_MONGO_PASSWORD, value = "password123", type = ValueType.STRING)

MongoApplication mongoApplication) {


mongoApplication

.prepareCommand()

.createCollection("myNewCollection")

.execute()

.assertIsSuccessful()

.andThen()

.prepareCommand()

.listCollections()

.execute()

.assertCollectionIsPresent("myNewCollection");

}

}

On the background, Pumpo#5 starts a session on the testing farm and transfers specified capabilities to the proxy client. Those are mainly related to the credentials required to connect to the Mongo database.

The capabilities that can be passed to the Mongo proxy client are documented in the section related to configuring connection to systems under test

Wrapping in custom objects

Instead of using the predefined methods in the MongoApplication interface, it is possible to define a custom interface that extends MongoApplication and to wrap the predefined actions into more business oriented methods.

Example:


class TestClass {

@Test

public void sampleTest(MyCustomMongoApplication mongo) {

mongo

.createCollection("myNewCollection");

}

}


@Capability(key = BROWSER_NAME, value = "pn5-mongo")

@Capability(key = CAPABILITY_MONGO_HOSTNAME, value = "mongo.host", type = ValueType.STRING_PROPERTY)

@Capability(key = CAPABILITY_MONGO_PORT, value = "mongo.port", type = ValueType.INTEGER_PROPERTY)

@Capability(key = CAPABILITY_MONGO_DATABASE, value = "mongo.database", type = ValueType.STRING_PROPERTY)

@Capability(key = CAPABILITY_MONGO_USERNAME, value = "mongo.user", type = ValueType.STRING_PROPERTY)

@Capability(key = CAPABILITY_MONGO_PASSWORD, value = "mongo.password", type = ValueType.STRING_PROPERTY)

public interface MyCustomMongoApplication extends MongoApplication {

default CommandResponse createNewCollection(String collectionName) {

return mongo

.prepareCommand()

.createCollection(collectionName)

.execute();

}

}

This pattern is common for all domains handled by Pumpo#5 and is the recommended coding style to keep tests readable also for people not having deeper knowledge of implementation details.

MongoApplication methods

This reference is only about the methods available in our Mongo DSL.

For further details please refer to the official MongoDB documentation.

MongoApplication::prepareQuery

Parameter | Type | Description

---|---|---

collection | String | Name of the collection where the query should occur

Used to start preparing a query to find documents on the database you are connected to, via capabilities,

and returns a QueryBuilder object.

You can pass more parameters using the build methods on this

object, and then run the query by calling the .execute() method.

MongoApplication::prepareUpdate

Parameter | Type | Description

---|---|---

collection | String | Name of the collection where the update should occur

Used to start preparing a query to update one or more documents on the database you are connected to, via capabilities,

and returns an UpdateBuilder object.

You can pass more parameters using the build methods on this

object, and then run the update by calling the .execute() method.

MongoApplication::prepareInsert

Parameter | Type | Description

---|---|---

collection | String | Name of the collection where the insertion should occur

Used to start preparing a query to insert one or more documents on the database you are connected to, via capabilities,

and returns an InsertBuilder object.

You can pass more parameters using the build methods on this

object, and then run the insertion by calling the .execute() method.

MongoApplication::prepareDelete

Parameter | Type | Description

---|---|---

collection | String | Name of the collection where the deletion should occur

Used to start preparing a query to delete one or more documents on the database you are connected to, via capabilities,

and returns a DeleteBuilder object.

You can pass more parameters using the build methods on this

object, and then run the deletion by calling the .execute() method.

MongoApplication::prepareAggregate

Parameter | Type | Description

---|---|---

collection | String | Name of the collection where the aggregation should occur

Used to start preparing an aggregation to be executed on the database you are connected to, via capabilities,

and returns an AggregationBuilder object.

You can pass more parameters using the build methods on this

object, and then run the insertion by calling the .execute() method.

MongoApplication::prepareCommand

Used to run some administrative commands on the database you are connected to, via capabilities,

and returns a CommandBuilder object.

You can pass more parameters using the build methods on this

object, and then run the command by calling the .execute() method.

QueryBuilder methods

QueryBuilder::filter

Parameter | Type | Description

---|-----------|---

filter | org.bson.Document | A document whose fields will be added to current filters

Adds all the key-value pairs contained in the Document passed as parameter to the current filters.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current filters

value | Object | The value associated with the key being passed

Adds a key-value pair to the current filters.

Those filters will be used to match documents on the server.

The matched documents are returned in the query response object.

QueryBuilder::project

Parameter | Type | Description

---|-----------|---

projection | org.bson.Document | A document whose fields will be added to current projection

Adds all the key-value pairs contained in the Document passed as parameter to the current projection.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current projection

value | Object | The value associated with the key being passed

Adds a key-value pair to the current projection.

A projection in a query refers to specifying which fields you want to retrieve from documents that match the query criteria.

It allows you to control which parts of the documents are returned in the query results.

QueryBuilder::sort

Parameter | Type | Description

---|-----------|---

sort | org.bson.Document | A document whose fields will be added to current sorting criteria

Adds all the key-value pairs contained in the Document passed as parameter to the current sorting criteria.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current sorting criteria

value | Object | The value associated with the key being passed

Adds a key-value pair to the current sorting criteria.

Sorting in a query refers to arranging the documents returned by a query, in a specified order, based on the values of one or more fields.

QueryBuilder::limit

Parameter | Type | Description

---|---------|---

limit | Integer | The maximum number of documents to be returned by the query

Specifies a limit on how many documents should be returned by the query.

Could be helpful for pagination purposes when used in conjuction with skip.

QueryBuilder::skip

Parameter | Type | Description

---|---------|---

skip | Integer | How many documents should be skipped before returning results

Specifies how many documents the query should skip before starting returning results.

Could be helpful for pagination purposes when used in conjuction with limit.

QueryBuilder::collation

Parameter | Type | Description

---|------------------------------------|---

collation | com.mongodb.client.model.Collation | The collation to be used in the query

Specifies a collation to be used during the query execution.

A collation in a query refers to the rules that determine how string comparison is performed.

It defines the specific rules for comparing characters, such as whether to consider case sensitivity,

accent sensitivity, and other language-specific sorting rules.

QueryBuilder::allowDiskUse

Parameter | Type | Description

---|---------|---

allow | Boolean | Defines whether the server should use the disk during the query

Specifies if the server is allowed to write files to the disk during the query execution. This could improve performance during long queries.

Defaults to false (not allowed to use disk).

QueryBuilder::batchSize

Parameter | Type | Description

---|---------|---

batchSize | Integer | The batch size to be used for this query

Sets the batch size to be used in this query.

The batch size refers to the maximum number of documents that MongoDB will return to the client in one batch. It's essentially a limit on the number of documents that will be sent back to the client at a time.

When you execute a query that returns a large number of documents, MongoDB divides the result set into batches.

Each batch contains a certain number of documents, determined by the batch size.

The client can then process these batches incrementally, which can help manage memory usage and reduce latency.

Default value is 101.

QueryBuilder::comment

Parameter | Type | Description

---|--------|---

comment | String | A comment to be added to this query

Adds a comment message to this query, used only for documentation purposes. It's ignored by the query engine and doesn't affect results.

QueryBuilder::hint

Parameter | Type | Description

---|-----------|---

hint | org.bson.Document | A document whose fields will be added to current hint criteria

Adds all the key-value pairs contained in the Document passed as parameter to the current hint criteria.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current hint criteria

value | Object | The value associated with the key being passed

Adds a key-value pair to the current hint criteria.

A hint in a query is an optional parameter that allows you to provide an index hint to the query optimizer.

By specifying a hint, you are suggesting to MongoDB which index to use when executing the query.

QueryBuilder::hintString

Parameter | Type | Description

---|--------|---

hintString | String | The name of the index to be used by the query engine

Specifies the name of an index to be used by the query engine during the query execution.

QueryBuilder::maxTime

Parameter | Type | Description

---|------|---

maxTime | Long | Maximum time, in milliseconds, that the query is allowed to run

Specifies the maximum amount of time, in milliseconds, that the server will allow the query to run.

It is commonly referred to as the "query timeout" or "query execution time limit".

When you set maxTime on a query, MongoDB will automatically abort the query if it exceeds the specified time limit.

This is useful for preventing long-running or inefficient queries from consuming excessive server resources

and impacting the performance of other operations.

QueryBuilder::execute

Execute the prepared query operation on the Mongo database.

QueryResponse methods

QueryResponse::getDocuments

Returns a list containing all the documents found during the query, or an empty list if no documents matched the filter criteria.

QueryResponse::getDocumentsAs

Parameter | Type | Description

---|-------------|---

pojo | Class<PoJo> | A PoJo class to be used as template for mapping documents

Returns a list containing all the documents found during the query, mapped to the class passed as a parameter.

The fields in the documents will be mapped to fields with the same name declared in the PoJo class, and converted to

the type that those fields were declared.

QueryResponse::assertDocumentsCount

Parameter | Type | Description

---|------|---

expected | Long | The expected number of documents to be matched and returned by the query

Asserts how many documents were returned by the query. Throws an exception if the numbers don't match.

QueryResponse::printDocuments

Prints all the documents returned by the query in the logs, as JSON objects, one document per line.

QueryResponse::andThen

Returns the initial MongoApplication to be able to continue the flow.

UpdateBuilder methods

UpdateBuilder::filter

Parameter | Type | Description

---|-----------|---

filter | org.bson.Document | A document whose fields will be added to current filters

Adds all the key-value pairs contained in the Document passed as parameter to the current filters.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current filters

value | Object | The value associated with the key being passed

Adds a key-value pair to the current filters.

Those filters will be used to match documents on the server.

The matched documents are then updated.

UpdateBuilder::update

Parameter | Type | Description

---|-----------|---

filter | org.bson.Document | A document whose fields will be added to the current update object

Adds all the key-value pairs contained in the Document passed as parameter to the current update object.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current update object

value | Object | The value associated with the key being passed

Adds a key-value pair to the current update object

This update object, or document, should contain all the changes that should be applied to matched documents.

UpdateBuilder::upsert

Parameter | Type | Description

---|---------|---

upsert | Boolean | Whether a new document should be inserted, if no documents are matched

Specifies if a new document should be created, in case no documents match the filters.

By default, this is set to false (no document should be created).

UpdateBuilder::updateMany

Parameter | Type | Description

---|---------|---

updateMany | Boolean | Whether MongoDB should update one document or more

Tells MongoDB to update only the first document that matches the filters, or if all matched documents should be updated.

By default, this is set to false (which means update only the first matched document).

UpdateBuilder::collation

Parameter | Type | Description

---|------------------------------------|---

collation | com.mongodb.client.model.Collation | The collation to be used in the update execution

Specifies a collation to be used during the update execution.

A collation in a query refers to the rules that determine how string comparison is performed.

It defines the specific rules for comparing characters, such as whether to consider case sensitivity,

accent sensitivity, and other language-specific sorting rules.

UpdateBuilder::bypassDocumentValidation

Parameter | Type | Description

---|---------|---

bypassDocumentValidation | Boolean | Whether MongoDB should ignore schema validation

Specifies if MongoDB should enforce a schema validation on the documents updated.

By default, this is set to false (validations should be enforced).

UpdateBuilder::hint

Parameter | Type | Description

---|-----------|---

hint | org.bson.Document | A document whose fields will be added to current hint criteria

Adds all the key-value pairs contained in the Document passed as parameter to the current hint criteria.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current hint criteria

value | Object | The value associated with the key being passed

Adds a key-value pair to the current hint criteria.

A hint in a query is an optional parameter that allows you to provide an index hint to the query optimizer.

By specifying a hint, you are suggesting to MongoDB which index to use when executing the query.

UpdateBuilder::hintString

Parameter | Type | Description

---|--------|---

hintString | String | The name of the index to be used by the query engine

Specifies the name of an index to be used by the query engine during the query execution.

UpdateBuilder::comment

Parameter | Type | Description

---|--------|---

comment | String | A comment to be added to this update

Adds a comment message to this update, used only for documentation purposes. It's ignored by the query engine and doesn't affect results.

UpdateBuilder::let

Parameter | Type | Description

---|-----------|---

variables | org.bson.Document | A document whose fields will be added to the current list of variables

Adds all the key-value pairs contained in the Document passed as parameter to the current list of variables.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current list of variables

value | Object | The value associated with the key being passed

Adds a key-value pair to the current list of variables.

This allows you to improve command readability by separating the variables from the query text.

UpdateBuilder::execute

Execute the prepared update operation on the Mongo database.

UpdateResponse methods

UpdateResponse::assertWasAcknowledged

Asserts if the update operation was acknowledged by the server. Throws an exception if not.

UpdateResponse::assertMatchedCount

Parameter | Type | Description

---|------|---

expectedCount | Long | The expected number of documents matched during the update operation

Asserts the number of documents matched by the filter criteria during the update execution.

Throws an exception if the numbers don't match.

UpdateResponse::assertModifiedCount

Parameter | Type | Description

---|------|---

expectedCount | Long | The expected number of documents modified during the update operation

Asserts the number of documents modified during the update execution.

Throws an exception if the numbers don't match.

UpdateResponse::assertDocumentWasUpserted

Asserts if a document was inserted during the update execution. Throws an exception if no document was created.

UpdateResponse::getUpsertedId

Returns a String containing the ObjectId that references the document created during the update operation, or null

if no document was inserted.

UpdateResponse::andThen

Returns the initial MongoApplication to be able to continue the flow.

InsertBuilder methods

InsertBuilder::addDocument

Parameter | Type | Description

---|-------------------|---

document | org.bson.Document | Adds one document to the list of documents to be inserted

Adds a single document to the list of documents that are to be created on the server.

InsertBuilder::addDocuments

Parameter | Type | Description

---|-------------------------|---

documents | List<org.bson.Document> | Adds one or more documents from a list, to the list of documents to be inserted

Adds one or more documents to the list of documents to be created on the server.

InsertBuilder::comment

Parameter | Type | Description

---|--------|---

comment | String | A comment to be added to this insertion operation

Adds a comment message to this insertion operation, used only for documentation purposes. It's ignored by the query engine and doesn't affect results.

InsertBuilder::bypassDocumentValidation

Parameter | Type | Description

---|---------|---

bypassDocumentValidation | Boolean | Whether MongoDB should ignore schema validation

Specifies if MongoDB should enforce a schema validation on the inserted documents.

By default, this is set to false (validations should be enforced).

InsertBuilder::isOrdered

Parameter | Type | Description

---|---------|---

isOrdered | Boolean | Whether MongoDB should insert document exactly in the order they were added

Specifies if MongoDB should insert documents in the order they were passed to this operation

By default, this is set to false (documents will be inserted in any random order).

InsertBuilder::execute

Execute the prepared insertion operation on the Mongo database.

InsertResponse methods

InsertResponse::assertWasAcknowledged

Asserts if the insertion operation was acknowledged by the server. Throws an exception if not.

InsertResponse::assertInsertedDocumentsCount

Parameter | Type | Description

---|------|---

expectedCount | Long | The expected number of documents inserted during the update operation

Asserts the number of documents inserted during the insertion execution.

Throws an exception if the numbers don't match.

InsertResponse::insertedDocumentsCount

Returns the number of documents inserted in the server.

InsertResponse::getInsertedIds

Returns a list of strings of all ObjectIds of documents inserted in the server.

InsertResponse::andThen

Returns the initial MongoApplication to be able to continue the flow.

DeleteBuilder methods

DeleteBuilder::filter

Parameter | Type | Description

---|-----------|---

filter | org.bson.Document | A document whose fields will be added to current filters

Adds all the key-value pairs contained in the Document passed as parameter to the current filters.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current filters

value | Object | The value associated with the key being passed

Adds a key-value pair to the current filters.

Those filters will be used to match documents on the server.

The matched documents are then removed.

DeleteBuilder::deleteMany

Parameter | Type | Description

---|---------|---

deleteMany | Boolean | Whether MongoDB should remove one document or more

Tells MongoDB to remove only the first document that matches the filters, or if all matched documents should be removed.

By default, this is set to false (which means remove only the first matched document).

DeleteBuilder::comment

Parameter | Type | Description

---|--------|---

comment | String | A comment to be added to this query

Adds a comment message to this query, used only for documentation purposes. It's ignored by the query engine and doesn't affect results.

DeleteBuilder::hint

Parameter | Type | Description

---|-----------|---

hint | org.bson.Document | A document whose fields will be added to current hint criteria

Adds all the key-value pairs contained in the Document passed as parameter to the current hint criteria.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current hint criteria

value | Object | The value associated with the key being passed

Adds a key-value pair to the current hint criteria.

A hint in a query is an optional parameter that allows you to provide an index hint to the query optimizer.

By specifying a hint, you are suggesting to MongoDB which index to use when executing the query.

DeleteBuilder::hintString

Parameter | Type | Description

---|--------|---

hintString | String | The name of the index to be used by the query engine

Specifies the name of an index to be used by the query engine during the query execution.

DeleteBuilder::collation

Parameter | Type | Description

---|------------------------------------|---

collation | com.mongodb.client.model.Collation | The collation to be used in the query

Specifies a collation to be used during the query execution.

A collation in a query refers to the rules that determine how string comparison is performed.

It defines the specific rules for comparing characters, such as whether to consider case sensitivity,

accent sensitivity, and other language-specific sorting rules.

DeleteBuilder::let

Parameter | Type | Description

---|-----------|---

variables | org.bson.Document | A document whose fields will be added to the current list of variables

Adds all the key-value pairs contained in the Document passed as parameter to the current list of variables.

Parameter | Type | Description

---|--------|---

key | String | A key to be added to the current list of variables

value | Object | The value associated with the key being passed

Adds a key-value pair to the current list of variables.

This allows you to improve command readability by separating the variables from the query text.

DeleteBuilder::execute

Execute the prepared delete operation on the Mongo database.

DeleteResponse methods

DeleteResponse::assertWasAcknowledged

Asserts if the delete operation was acknowledged by the server. Throws an exception if not.

DeleteResponse::assertDeletedCount

Parameter | Type | Description

---|------|---

expectedCount | Long | The expected number of documents removed during the delete operation

Asserts the number of documents matched by the filter criteria and removed during the delete execution.

Throws an exception if the numbers don't match.

DeleteResponse::andThen

Returns the initial MongoApplication to be able to continue the flow.

AggregationBuilder methods

AggregationBuilder::lookup

Parameter | Type | Description

---|-------------------|---

lookup | org.bson.Document | A document containing the details for a $lookup stage in the aggregation pipeline

Adds a $lookup stage to the aggregation pipeline.

The $lookup stage in an aggregation pipeline is used to perform a left outer join between documents from the current

collection (referred to as the "local" collection) and documents from another collection (referred to as the "foreign" collection).

This stage allows you to combine data from multiple collections based on a common field or expression.

AggregationBuilder::match

Parameter | Type | Description

---|-------------------|---

match | org.bson.Document | A document containing the details for a $match stage in the aggregation pipeline

Adds a $match stage to the aggregation pipeline.

The $match stage in an aggregation pipeline is used to filter documents based on specified criteria.

It allows you to select only those documents that match certain conditions, similar to the find() method in regular queries.

AggregationBuilder::project

Parameter | Type | Description

---|-------------------|---

project | org.bson.Document | A document containing the details for a $project stage in the aggregation pipeline

Adds a $project stage to the aggregation pipeline.

The $project stage in an aggregation pipeline is used to reshape documents by including, excluding, or transforming fields.

It allows you to specify which fields to include or exclude from the output documents, as well as perform transformations on existing fields.

AggregationBuilder::group

Parameter | Type | Description

---|-------------------|---

group | org.bson.Document | A document containing the details for a $group stage in the aggregation pipeline

Adds a $group stage to the aggregation pipeline.

The $group stage in an aggregation pipeline is used to group documents by specified criteria and perform aggregation operations on the grouped data.

It allows you to aggregate data across multiple documents and calculate various metrics or statistics within each group.

AggregationBuilder::sort

Parameter | Type | Description

---|-------------------|---

sort | org.bson.Document | A document containing the details for a $sort stage in the aggregation pipeline

Adds a $sort stage to the aggregation pipeline.

The $sort stage in an aggregation pipeline is used to sort the documents in the pipeline's result set.

It allows you to specify one or more fields by which the documents should be sorted and the sort order (ascending or descending).

AggregationBuilder::execute

Execute the prepared aggregation operation on the Mongo database.

AggregationResponse methods

AggregationResponse::getDocuments

Returns the aggregation results in a list of documents.

AggregationResponse::andThen

Returns the initial MongoApplication to be able to continue the flow.

CommandBuilder methods

CommandBuilder::createCollection

Parameter | Type | Description

---|--------|---

collection | String | Name of collection to be created

Creates a new collection with the name passed as parameter.

CommandBuilder::dropCollection

Parameter | Type | Description

---|--------|---

collection | String | Name of collection to be dropped

Drops a collection with the name passed as parameter. If the collection doesn't exist, nothing happens.

CommandBuilder::listCollections

Returns all the user collections that currently exist on the server.

CommandBuilder::dropDatabase

Drops the database passed in the capabilities. If the database doesn't exist, nothing happens.

CommandBuilder::createIndex

Parameter | Type | Description

---|---------------------------------------|---

collection | String | Name of collection where the index should be created

newIndex | org.bson.Document | Document describing the index to be created

options | com.mongodb.client.model.IndexOptions | Specific MongoDB options for creating the index

Creates a new index in a collection. For a complete list of options, please check the official documentation for IndexOptions class.

CommandBuilder::dropIndex

Parameter | Type | Description

---|-------------------------------------------|---

collection | String | Name of collection where the index is located

indexName | String | Name of index to be dropped

options | com.mongodb.client.model.DropIndexOptions | Specific MongoDB options for dropping the index

Drops an existing index in a collection. For a complete list of options, please check the official documentation for DropIndexOptions class.

CommandBuilder::execute

Execute the prepared query operation on the Mongo database.

CommandResponse methods

CommandResponse::assertIsSuccessful

Asserts if the command was executed without errors on the server. Throws an exception if not.

CommandResponse::assertCollectionIsPresent

Parameter | Type | Description

---|---------------------------------------|---

collection | String | Name of collection to be checked

Asserts if a collection exists in the list of collection names returned from the server.

Available after creating, dropping or listing collections.

CommandResponse::assertCollectionIsNotPresent

Parameter | Type | Description

---|---------------------------------------|---

collection | String | Name of collection to be checked

Asserts if a collection doesn't exist in the list of collection names returned from the server.

Available after creating, dropping or listing collections.

CommandResponse::printCollections

Prints the list of currently existing user collections, in the log messages.

Available after creating, dropping or listing collections.

CommandResponse::getNewIndexName

Returns a string containing the name of the created index.

Available after creating a new index.

CommandResponse::assertNewIndexName

Parameter | Type | Description

---|---------------------------------------|---

expectedIndexName | String | Expected name of new index

Asserts a new index was created with the expected name. Throws if the name doesn't match.

QueryResponse::andThen

Returns the initial MongoApplication to be able to continue the flow.