├── .gitignore ├── .travis.yml ├── README.md ├── build.gradle ├── doc └── libdoc │ ├── de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.html │ └── de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.xml ├── generateDocs.cmd ├── generateDocs.launch ├── robot-bin ├── commons-io-1.3.2.jar ├── junit-4.10.jar ├── mongo-java-driver-2.10.0.jar └── robotframework-2.7.5.jar ├── runSample.cmd ├── runSampleTests.launch ├── runServer.cmd ├── sample ├── data.json ├── dataMultipleRows.json ├── mongodblibrarySample.txt └── remoteMongodblibrarySample.txt ├── settings.gradle └── src ├── main ├── java │ └── de │ │ └── codecentric │ │ └── robot │ │ └── mongodblibrary │ │ ├── MongodbLibraryException.java │ │ ├── keywords │ │ └── MongodbLibrary.java │ │ └── server │ │ └── MongodbLibraryRemoteServer.java └── resources │ └── de │ └── codecentric │ └── robot │ └── mongodblibrary │ └── keywords │ └── MongodbLibrary.properties └── test ├── data ├── testArray.json ├── testRowSeperated.json └── testSingleObject.json └── java └── de └── codecentric └── robot └── mongodblibrary └── keywords └── MongodbLibraryTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /.settings 2 | /target 3 | /.classpath 4 | /.project 5 | /.gradle 6 | /build 7 | /bin 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk6 4 | 5 | after_script: gradle 'run sample tests' 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Robotframework-Mongodblibrary 2 | ============================= 3 | 4 | The **Robot Framework MongoDB Library** is a library for testing MongoDB applications with the Robotframework. 5 | Please see the [Keyword-Documentation](http://mahartma.github.com/robotframework-mongodblibrary/de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.html) for more information about the provided keywords. 6 | 7 | The library is written in Java using the MongoDB Java Driver. 8 | 9 | Sample test: 10 | 11 | ``` 12 | *** Settings *** 13 | Library de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary 14 | Suite Setup Startup Embedded 2.4.4 15 | Suite TearDown Shutdown Embedded 16 | Test Setup Setup MongoDB 17 | 18 | *** Test Cases *** 19 | should insert given document 20 | Insert Document myCollection {say : 'Hello MongoDb!'} 21 | Collection Should Exist myCollection 22 | Document Should Exist myCollection {say : 'Hello MongoDb!'} 23 | should insert data from file 24 | Import Documents myCollection sample/data.json 25 | Collection Should Exist myCollection 26 | Document Should Exist myCollection {name : 'Mike'} 27 | should insert data from file (row-seperated) 28 | Import Documents Row Seperated myCollection sample/dataMultipleRows.json 29 | Collection Should Exist myCollection 30 | Document Should Exist myCollection {name : 'Mike'} 31 | Document Should Exist myCollection {name : 'Tom'} 32 | Document Should Exist myCollection {name : 'Eric'} 33 | 34 | *** Keywords *** 35 | Setup MongoDB 36 | Connect To Server localhost 27017 robotdb1 37 | Drop Database robotdb1 38 | ``` 39 | 40 | Dependencies 41 | ------------ 42 | - [Robotframework >= 2.7.5 (with Jython)](http://code.google.com/p/robotframework/downloads/list) 43 | - [MongoDB Java Driver >= 2.10.0](http://central.maven.org/maven2/org/mongodb/mongo-java-driver) 44 | - [apache-commons-io 1.3.2](http://search.maven.org/remotecontent?filepath=org/apache/commons/commons-io/1.3.2/commons-io-1.3.2.jar) 45 | - [junit 4.10](http://search.maven.org/remotecontent?filepath=junit/junit/4.10/junit-4.10.jar) 46 | - [MongoDB Server >= 2.2.1](http://www.mongodb.org/downloads) 47 | - [Embedded MongoDB >= 1.31](https://github.com/flapdoodle-oss/embedmongo.flapdoodle.de) 48 | 49 | Install 50 | ------- 51 | - download [robotframework-mongodblibrary-0.2.1-with-dependencies.jar](http://mahartma.github.com/robotframework-mongodblibrary/robotframework-mongodblibrary-0.2-with-dependencies.jar) 52 | - start the mongoDB daemon or use the embedded keywords ( _Startup Embedded_, _Shutdown Embedded_ ) 53 | - add **robotframework-mongodblibrary-0.2.1-with-dependencies.jar** to the CLASSPATH (see runSample.cmd) 54 | - start the Robot-Tests 55 | - this can also be done by a gradle task: 56 | ```groovy 57 | configurations { 58 | robot 59 | } 60 | 61 | dependencies { 62 | robot files("libs/robotframework-mongodblibrary-0.2.1-with-dependencies.jar") 63 | } 64 | 65 | task(type : JavaExec, 'run tests') { 66 | classpath = configurations.robot 67 | main = 'org.robotframework.RobotFramework' 68 | args = [ 69 | '-d', 70 | 'build', 71 | 'sample/mongodblibrarySample.txt' 72 | ] 73 | } 74 | ``` 75 | 76 | Remote-Library 77 | -------------- 78 | - the library also contains the Remote-Server from the Robotframework for executing the keywords on a dedicated JVM (see [Robot-Remote-Library](http://code.google.com/p/robotframework/wiki/RemoteLibrary)) 79 | - it's very useful when you want to use python in the main suite instead of jython 80 | - the server can be started with **java -jar build/libs/robotframework-mongodblibrary-0.2.1-with-dependencies.jar** 81 | - see the example below: 82 | 83 | ``` 84 | *** Settings *** 85 | Library Remote http://localhost:8270 86 | Suite Setup Startup Embedded 2.4.4 87 | Suite TearDown Shutdown Embedded 88 | Test Setup Setup MongoDB 89 | 90 | *** Test Cases *** 91 | should insert given document 92 | Insert Document myCollection {say : 'Hello MongoDb!'} 93 | Collection Should Exist myCollection 94 | Document Should Exist myCollection {say : 'Hello MongoDb!'} 95 | should insert data from file 96 | Import Documents myCollection sample/data.json 97 | Collection Should Exist myCollection 98 | Document Should Exist myCollection {name : 'Mike'} 99 | should insert data from file (row-seperated) 100 | Import Documents Row Seperated myCollection sample/dataMultipleRows.json 101 | Collection Should Exist myCollection 102 | Document Should Exist myCollection {name : 'Mike'} 103 | Document Should Exist myCollection {name : 'Tom'} 104 | Document Should Exist myCollection {name : 'Eric'} 105 | 106 | *** Keywords *** 107 | Setup MongoDB 108 | Connect To Server localhost 27017 robotdb1 109 | Drop Database robotdb1 110 | ``` 111 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | project.version = '0.2.1' 2 | 3 | repositories { mavenCentral() } 4 | 5 | apply plugin: 'java' 6 | apply plugin: 'eclipse' 7 | 8 | configurations { 9 | robot 10 | docs 11 | } 12 | 13 | dependencies { 14 | compile group: 'junit', name: 'junit', version: "4.10" 15 | compile group: 'de.flapdoodle.embed', name: 'de.flapdoodle.embed.mongo', version: "1.31" 16 | compile group: 'org.apache.commons', name: 'commons-io', version: "1.3.2" 17 | compile group: 'com.github.ombre42', name: 'jrobotremoteserver', version: "2.0" 18 | compile group: 'org.mongodb', name: 'mongo-java-driver', version: "2.10.0" 19 | robot group: 'org.robotframework', name: 'robotframework', version: "2.7.5" 20 | robot group: 'org.robotframework', name: 'javalib-core', version: "1.0.3" 21 | docs files("${System.getProperty('java.home')}/../lib/tools.jar") 22 | } 23 | 24 | task(type : Jar, 'jarWithDependencies') { 25 | classifier = 'with-dependencies' 26 | exclude('META-INF/*.RSA') 27 | exclude('META-INF/*.SF') 28 | from { configurations.compile.collect { 29 | if (!it.isDirectory()) { 30 | zipTree(it) 31 | } 32 | } 33 | } 34 | from { sourceSets.main.output } 35 | manifest { attributes 'Main-Class': 'de.codecentric.robot.mongodblibrary.server.MongodbLibraryRemoteServer' } 36 | } 37 | 38 | processResources { 39 | filter(org.apache.tools.ant.filters.ReplaceTokens, 40 | tokens: [version: project.version]) 41 | } 42 | 43 | assemble.dependsOn 'jarWithDependencies' 44 | 45 | task(type : JavaExec, 'runSampleTests') { 46 | classpath = configurations.robot + configurations.compile + sourceSets.main.runtimeClasspath 47 | main = 'org.robotframework.RobotFramework' 48 | args = [ 49 | '-d', 50 | 'build', 51 | 'sample/mongodblibrarySample.txt' 52 | ] 53 | } 54 | 55 | task 'generateDocs' << { 56 | tasks['generateHtmlDoc'].exec() 57 | tasks['generateXmlDoc'].exec() 58 | } 59 | 60 | task(type : JavaExec, 'generateHtmldoc') { 61 | classpath = configurations.docs + configurations.robot + configurations.compile + sourceSets.main.runtimeClasspath 62 | main = 'org.python.util.jython' 63 | args = [ 64 | '-m', 65 | 'robot.libdoc', 66 | 'src/main/java/de/codecentric/robot/mongodblibrary/keywords/MongodbLibrary.java', 67 | 'doc/libdoc/de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.html' 68 | ] 69 | } 70 | 71 | task(type : JavaExec, 'generateXmlDoc') { 72 | classpath = configurations.docs + configurations.robot + configurations.compile + sourceSets.main.runtimeClasspath 73 | main = 'org.python.util.jython' 74 | args = [ 75 | '-m', 76 | 'robot.libdoc', 77 | '--format', 78 | 'XML', 79 | 'src/main/java/de/codecentric/robot/mongodblibrary/keywords/MongodbLibrary.java', 80 | 'doc/libdoc/de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.xml' 81 | ] 82 | } -------------------------------------------------------------------------------- /doc/libdoc/de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 82 | 92 | 114 | 154 | 174 | 186 | 189 | 190 | 191 | 192 | 193 |
194 |

Opening library documentation failed

195 | 200 |
201 | 202 | 206 | 207 | 232 | 233 | 243 | 244 | 259 | 260 | 269 | 270 | 287 | 294 | 295 | 296 | 297 | -------------------------------------------------------------------------------- /doc/libdoc/de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | global 5 | no 6 | This library supports mongodb-related testing using the Robot Framework. 7 | 8 | 9 | collectionName 10 | 11 | Fails if the collection does not exist. 12 | 13 | Arguments: 14 | - _collectionName_: the collection which should exist 15 | 16 | Example: 17 | | Collection Should Exist | myCol | 18 | 19 | 20 | 21 | server 22 | port 23 | database 24 | 25 | connects to the given MongoDB-Server 26 | 27 | Arguments: 28 | - _server_: server to connect 29 | - _port_: port to connect 30 | - _database_: database to connect 31 | 32 | Example: 33 | | Connect To Server | localhost | 27017 | robotdb | 34 | 35 | 36 | 37 | collectionName 38 | 39 | Creates a collection with the given name and options. 40 | 41 | Arguments: 42 | - _collectionName_: the name of the collection to create 43 | 44 | Example: 45 | | Create Collection | myCol | 46 | 47 | 48 | 49 | collectionName 50 | options 51 | 52 | Creates a collection with the given name and options. 53 | 54 | Arguments: 55 | - _collectionName_: the name of the collection to create 56 | - _options_: the options of the collection 57 | 58 | Example: 59 | | Create Collection | myCol | {capped:true, size:10000} | 60 | 61 | 62 | 63 | databaseName 64 | 65 | Fails if the database does not exist. 66 | 67 | Arguments: 68 | - _databaseName_: the database which should exist 69 | 70 | Example: 71 | | Database Should Exist | myDatabase | 72 | 73 | 74 | 75 | collectionName 76 | document 77 | 78 | Fails if the given document does not exist in the given collection. 79 | 80 | Arguments: 81 | - _collectionName_: the collection within the document should exist 82 | - _document_: the document which should exist in the given collection 83 | 84 | Example: 85 | | Document Should Exist | myCol | {say : 'Hello MongoDb!'} | 86 | 87 | 88 | 89 | collectionName 90 | 91 | Drops the given collection. 92 | 93 | Arguments: 94 | - _collectionName_: the name of the collection to drop 95 | 96 | Example: 97 | | Drop Collection | myCollection | 98 | 99 | 100 | 101 | databaseName 102 | 103 | A database in MongoDB is a more lightweight construct compared to RDBMS, 104 | so a cleanup after testing can be done quite easily by dropping the whole database. 105 | 106 | Arguments: 107 | - _databaseName_: the name of the database to delete 108 | 109 | Example: 110 | | Drop Database | myDb | 111 | 112 | 113 | 114 | collectionName 115 | keys 116 | 117 | Creates an index on the given collection, the desired fields of the index are given by the keys parameter. 118 | 119 | Arguments: 120 | - _collectionName_: the name of collection 121 | - _keys_: an object with a key set of the fields desired for the index 122 | 123 | Example: 124 | | Ensure Index | myCol | {name : 1, street : 1} | 125 | 126 | 127 | 128 | indexName 129 | collectionName 130 | keys 131 | 132 | Creates an index with given name on the given collection, the desired fields of the index are given by the keys parameter. 133 | 134 | Arguments: 135 | - _indexName_: the name of the index 136 | - _collectionName_: the name of collection 137 | - _keys_: an object with a key set of the fields desired for the index 138 | 139 | Example: 140 | | Ensure Index | myCol | {name : 1, street : 1} | 141 | 142 | 143 | 144 | collectionName 145 | keys 146 | indexName 147 | 148 | Creates an unique index with given name on the given collection, the desired fields of the index are given by the keys parameter. 149 | 150 | Arguments: 151 | - _indexName_: the name of the index 152 | - _collectionName_: the name of collection 153 | - _keys_: an object with a key set of the fields desired for the index 154 | 155 | Example: 156 | | Ensure Index | myCol | {name : 1, street : 1} | 157 | 158 | 159 | 160 | collectionName 161 | 162 | Returns all documents from the given collection. 163 | 164 | Arguments: 165 | - _collectionName_: the name of the collection 166 | 167 | Example: 168 | | Get All Documents | myCol | 169 | 170 | 171 | 172 | collectionName 173 | 174 | Returns the number of documents in the given collection. 175 | 176 | Arguments: 177 | - _collectionName_: the name of the collection 178 | 179 | Example: 180 | | Get Collection Count | myCol | 181 | 182 | 183 | 184 | 185 | Returns the names of the collections from the connected database. 186 | 187 | Example: 188 | | Get Collections | 189 | 190 | 191 | 192 | 193 | Returns the name of the databases from the server. 194 | 195 | Example: 196 | | Get Databases | 197 | 198 | 199 | 200 | collectionName 201 | jsonString 202 | 203 | Finds some documents in the given collection. 204 | 205 | Arguments: 206 | - _collectionName_: the name of the collection 207 | - _jsonString_: the documents to find as JSON 208 | 209 | Example: 210 | | Get Documents | myCol | { age : { $gte: 23 } } | 211 | 212 | 213 | 214 | collectionName 215 | file 216 | 217 | Imports the documents from the given file into the given collection. 218 | 219 | Arguments: 220 | - _collectionName_: the name of the target collection 221 | - _file_: the file that contains the documents 222 | 223 | Example: 224 | | Import Documents | myCol | /data/documents.json | 225 | 226 | 227 | 228 | collectionName 229 | file 230 | 231 | Imports the documents from the given file into the given collection. This keyword reads the data row-based. 232 | 233 | Arguments: 234 | - _collectionName_: the name of the target collection 235 | - _file_: the file that contains the documents 236 | 237 | Example: 238 | | Import Documents Row Seperated | myCol | /data/documents.json | 239 | 240 | 241 | 242 | collectionName 243 | indexName 244 | 245 | Fails if the given index does not exist in the given collection. 246 | 247 | Arguments: 248 | - _collectionName_: the collection within the index should exist 249 | - _index_: the name of the index which should exist in the given collection 250 | 251 | Example: 252 | | Index Should Exist | myCol | a_1_b_1 | 253 | 254 | 255 | 256 | collectionName 257 | jsonString 258 | 259 | Inserts the given document into the given collection. 260 | 261 | Arguments: 262 | - _collectionName_: the name of the target collection 263 | - _jsonString_: the document to persist as JSON 264 | 265 | Example: 266 | | Insert Document | myCollection | {say : 'Hello MongoDB!'} | 267 | 268 | 269 | 270 | collectionName 271 | 272 | Removes all documents in the given collection. 273 | 274 | Arguments: 275 | - _collectionName_: the name of the collection 276 | 277 | Example: 278 | | Remove All Documents | myCol | 279 | 280 | 281 | 282 | collectionName 283 | jsonString 284 | 285 | Removes some documents in the given collection. 286 | 287 | Arguments: 288 | - _collectionName_: the name of the collection 289 | - _jsonString_: the documents to remove as JSON 290 | 291 | Example: 292 | | Remove Documents | myCol | { age : { $gte: 23 } } | 293 | 294 | 295 | 296 | 297 | stops the previously started MongoDB-Server (counter-part to the keywords: `Startup Embedded` and `Startup Embedded On Port`) 298 | 299 | Example: 300 | | Shutdown Embedded | 301 | 302 | 303 | 304 | version 305 | 306 | starts a MongoDB-Server in the given version 307 | 308 | Arguments: 309 | - _version_: MongoDB-Version 310 | 311 | Example: 312 | | Startup Embedded | 2.4.1 | 313 | 314 | 315 | 316 | version 317 | port 318 | 319 | starts a MongoDB-Server in the given version on the given port 320 | 321 | Arguments: 322 | - _version_: MongoDB-Version 323 | - _port_: port to use 324 | 325 | Example: 326 | | Startup Embedded | 2.4.1 | 27042 | 327 | 328 | 329 | 330 | collectionName 331 | queryJsonString 332 | newObjectJsonString 333 | 334 | Updates some documents in the given collection. 335 | 336 | Arguments: 337 | - _collectionName_: the name of the collection 338 | - _queryJsonString_: the documents to update as JSON 339 | - _newObjectJsonString_: the updated document as JSON 340 | 341 | Example: 342 | | Update Documents | myCollection | { age : { $gte: 23 } } | {name : 'Mike', age : 22} | 343 | 344 | 345 | 346 | databaseName 347 | 348 | All following keywords will operate on the selected database. Same as use 349 | dbname with the Mongo shell. If the database does not exist, it will be 350 | create as soon as needed. 351 | 352 | Arguments: 353 | - _databaseName_: the name of the database 354 | 355 | Example: 356 | | Use Database | myDb | 357 | 358 | 359 | -------------------------------------------------------------------------------- /generateDocs.cmd: -------------------------------------------------------------------------------- 1 | del %~dp0%doc\libdoc\*.html 2 | del %~dp0%doc\libdoc\*.xml 3 | java -cp robot-bin/robotframework-2.7.5.jar;%JAVA_HOME%\lib\tools.jar org.python.util.jython -m robot.libdoc src/main/java/de/codecentric/robot/mongodblibrary/keywords/MongodbLibrary.java doc/libdoc/de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.html 4 | java -cp robot-bin/robotframework-2.7.5.jar;%JAVA_HOME%\lib\tools.jar org.python.util.jython -m robot.libdoc --format XML src/main/java/de/codecentric/robot/mongodblibrary/keywords/MongodbLibrary.java doc/libdoc/de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.xml -------------------------------------------------------------------------------- /generateDocs.launch: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /robot-bin/commons-io-1.3.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mahartma/robotframework-mongodblibrary/821b25f045d2fb6fadb81a66c4f8305d2d905d69/robot-bin/commons-io-1.3.2.jar -------------------------------------------------------------------------------- /robot-bin/junit-4.10.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mahartma/robotframework-mongodblibrary/821b25f045d2fb6fadb81a66c4f8305d2d905d69/robot-bin/junit-4.10.jar -------------------------------------------------------------------------------- /robot-bin/mongo-java-driver-2.10.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mahartma/robotframework-mongodblibrary/821b25f045d2fb6fadb81a66c4f8305d2d905d69/robot-bin/mongo-java-driver-2.10.0.jar -------------------------------------------------------------------------------- /robot-bin/robotframework-2.7.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mahartma/robotframework-mongodblibrary/821b25f045d2fb6fadb81a66c4f8305d2d905d69/robot-bin/robotframework-2.7.5.jar -------------------------------------------------------------------------------- /runSample.cmd: -------------------------------------------------------------------------------- 1 | REM ======= LOCAL ======= 2 | java -jar robot-bin/robotframework-2.7.5.jar -P build/libs/robotframework-mongodblibrary-0.2.1-with-dependencies.jar -d target sample/mongodblibrarySample.txt 3 | REM ======= REMOTE ======= 4 | REM java -jar robot-bin/robotframework-2.7.5.jar -d target sample/remoteMongodblibrarySample.txt -------------------------------------------------------------------------------- /runSampleTests.launch: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /runServer.cmd: -------------------------------------------------------------------------------- 1 | REM ======= starting Remote-Library ======= 2 | java -jar build/libs/robotframework-mongodblibrary-0.2.1-with-dependencies.jar --port 8270 -------------------------------------------------------------------------------- /sample/data.json: -------------------------------------------------------------------------------- 1 | {name : 'Mike'} -------------------------------------------------------------------------------- /sample/dataMultipleRows.json: -------------------------------------------------------------------------------- 1 | {name : 'Mike', age : 22} 2 | {name : 'Tom', age : 25} 3 | {name : 'Eric', age : 40} -------------------------------------------------------------------------------- /sample/mongodblibrarySample.txt: -------------------------------------------------------------------------------- 1 | *** Settings *** 2 | Library de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary 3 | Library Collections 4 | Suite Setup Startup Embedded 2.4.4 5 | Suite TearDown Shutdown Embedded 6 | Test Setup Setup MongoDB 7 | 8 | *** Test Cases *** 9 | should insert given document 10 | Insert Document myCollection {say : 'Hello MongoDb!'} 11 | Collection Should Exist myCollection 12 | Document Should Exist myCollection {say : 'Hello MongoDb!'} 13 | should insert data from file 14 | Import Documents myCollection sample/data.json 15 | Collection Should Exist myCollection 16 | Document Should Exist myCollection {name : 'Mike'} 17 | should insert data from file (row-seperated) 18 | Import Documents Row Seperated myCollection sample/dataMultipleRows.json 19 | Collection Should Exist myCollection 20 | Document Should Exist myCollection {name : 'Mike', age : 22} 21 | Document Should Exist myCollection {name : 'Tom', age : 25} 22 | Document Should Exist myCollection {name : 'Eric', age : 40} 23 | ${allDocuments}= Get All Documents myCollection 24 | ${document1}= Get From List ${allDocuments} 0 25 | ${document1Age}= Get From Dictionary ${document1} age 26 | ${expectedAge}= Convert To Integer 22 27 | Should Be Equal ${expectedAge} ${document1Age} age isn't 22 28 | *** Keywords *** 29 | Setup MongoDB 30 | Connect To Server localhost 27020 robotdb1 31 | Drop Database robotdb1 -------------------------------------------------------------------------------- /sample/remoteMongodblibrarySample.txt: -------------------------------------------------------------------------------- 1 | *** Settings *** 2 | Library Remote http://localhost:8270 3 | Suite Setup Startup Embedded 2.4.4 4 | Suite TearDown Shutdown Embedded 5 | Test Setup Setup MongoDB 6 | 7 | *** Test Cases *** 8 | should insert given document 9 | Insert Document myCollection {say : 'Hello MongoDb!'} 10 | Collection Should Exist myCollection 11 | Document Should Exist myCollection {say : 'Hello MongoDb!'} 12 | should insert data from file 13 | Import Documents myCollection sample/data.json 14 | Collection Should Exist myCollection 15 | Document Should Exist myCollection {name : 'Mike'} 16 | should insert data from file (row-seperated) 17 | Import Documents Row Seperated myCollection sample/dataMultipleRows.json 18 | Collection Should Exist myCollection 19 | Document Should Exist myCollection {name : 'Mike'} 20 | Document Should Exist myCollection {name : 'Tom'} 21 | Document Should Exist myCollection {name : 'Eric'} 22 | 23 | *** Keywords *** 24 | Setup MongoDB 25 | Connect To Server localhost 27020 robotdb1 26 | Drop Database robotdb1 -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'robotframework-mongodblibrary' -------------------------------------------------------------------------------- /src/main/java/de/codecentric/robot/mongodblibrary/MongodbLibraryException.java: -------------------------------------------------------------------------------- 1 | package de.codecentric.robot.mongodblibrary; 2 | 3 | /** 4 | * 5 | * 6 | * @author Max Hartmann 7 | * 8 | */ 9 | public class MongodbLibraryException extends RuntimeException { 10 | 11 | private static final long serialVersionUID = 42L; 12 | 13 | public MongodbLibraryException() { 14 | super(); 15 | } 16 | 17 | public MongodbLibraryException(String message, Throwable cause) { 18 | super(message, cause); 19 | } 20 | 21 | public MongodbLibraryException(String message) { 22 | super(message); 23 | } 24 | 25 | public MongodbLibraryException(Throwable cause) { 26 | super(cause); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/de/codecentric/robot/mongodblibrary/keywords/MongodbLibrary.java: -------------------------------------------------------------------------------- 1 | package de.codecentric.robot.mongodblibrary.keywords; 2 | 3 | import static com.mongodb.util.JSON.parse; 4 | import static de.flapdoodle.embed.process.runtime.Network.localhostIsIPv6; 5 | import static java.lang.Integer.parseInt; 6 | import static org.junit.Assert.assertTrue; 7 | import static org.junit.Assert.fail; 8 | 9 | import java.io.FileReader; 10 | import java.io.IOException; 11 | import java.net.UnknownHostException; 12 | import java.util.ArrayList; 13 | import java.util.Iterator; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.ResourceBundle; 17 | import java.util.Set; 18 | 19 | import org.apache.commons.io.IOUtils; 20 | 21 | import com.mongodb.BasicDBList; 22 | import com.mongodb.BasicDBObject; 23 | import com.mongodb.DB; 24 | import com.mongodb.DBObject; 25 | import com.mongodb.MongoClient; 26 | import com.mongodb.util.JSON; 27 | 28 | import de.codecentric.robot.mongodblibrary.MongodbLibraryException; 29 | import de.flapdoodle.embed.mongo.MongodExecutable; 30 | import de.flapdoodle.embed.mongo.MongodStarter; 31 | import de.flapdoodle.embed.mongo.config.MongodConfig; 32 | import de.flapdoodle.embed.process.distribution.GenericVersion; 33 | 34 | /** 35 | * This library supports mongodb-related testing using the Robot Framework. 36 | */ 37 | public class MongodbLibrary { 38 | 39 | public static final String VERSION = ResourceBundle. 40 | getBundle(MongodbLibrary.class.getName()).getString("lib.version"); 41 | 42 | public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL"; 43 | 44 | private static final int MONGO_DEFAULT_PORT = 27020; 45 | 46 | private MongoClient mongoClient; 47 | private DB db; 48 | private MongodExecutable mongodExecutable; 49 | 50 | /** 51 | * starts a MongoDB-Server in the given version 52 | * 53 | * Arguments: 54 | * - _version_: MongoDB-Version 55 | * 56 | * Example: 57 | * | Startup Embedded | 2.4.1 | 58 | */ 59 | public void startupEmbedded(String version) throws IOException { 60 | MongodConfig mongodConfig = new MongodConfig(new GenericVersion(version), MONGO_DEFAULT_PORT, localhostIsIPv6()); 61 | MongodStarter runtime = MongodStarter.getDefaultInstance(); 62 | mongodExecutable = runtime.prepare(mongodConfig); 63 | mongodExecutable.start(); 64 | } 65 | 66 | /** 67 | * starts a MongoDB-Server in the given version on the given port 68 | * 69 | * Arguments: 70 | * - _version_: MongoDB-Version 71 | * - _port_: port to use 72 | * 73 | * Example: 74 | * | Startup Embedded | 2.4.1 | 27042 | 75 | */ 76 | public void startupEmbeddedOnPort(String version, String port) throws IOException { 77 | MongodConfig mongodConfig = new MongodConfig(new GenericVersion(version), parseInt(port), localhostIsIPv6()); 78 | MongodStarter runtime = MongodStarter.getDefaultInstance(); 79 | mongodExecutable = runtime.prepare(mongodConfig); 80 | mongodExecutable.start(); 81 | } 82 | 83 | /** 84 | * stops the previously started MongoDB-Server (counter-part to the keywords: `Startup Embedded` and `Startup Embedded On Port`) 85 | * 86 | * Example: 87 | * | Shutdown Embedded | 88 | */ 89 | public void shutdownEmbedded() { 90 | if (mongodExecutable != null) { 91 | mongodExecutable.stop(); 92 | } 93 | } 94 | 95 | /** 96 | * connects to the given MongoDB-Server 97 | * 98 | * Arguments: 99 | * - _server_: server to connect 100 | * - _port_: port to connect 101 | * - _database_: database to connect 102 | * 103 | * Example: 104 | * | Connect To Server | localhost | 27017 | robotdb | 105 | */ 106 | public void connectToServer(String server, String port, String database) { 107 | try { 108 | mongoClient = new MongoClient(server, parseInt(port)); 109 | db = mongoClient.getDB(database); 110 | } catch (UnknownHostException e) { 111 | throw new MongodbLibraryException("error connecting mongodb", e); 112 | } 113 | } 114 | 115 | /** 116 | * Inserts the given document into the given collection. 117 | * 118 | * Arguments: 119 | * - _collectionName_: the name of the target collection 120 | * - _jsonString_: the document to persist as JSON 121 | * 122 | * Example: 123 | * | Insert Document | myCollection | {say : 'Hello MongoDB!'} | 124 | */ 125 | public void insertDocument(String collectionName, 126 | String jsonString) { 127 | db.getCollection(collectionName).insert( 128 | (DBObject) parse(jsonString)); 129 | } 130 | 131 | /** 132 | * Updates some documents in the given collection. 133 | * 134 | * Arguments: 135 | * - _collectionName_: the name of the collection 136 | * - _queryJsonString_: the documents to update as JSON 137 | * - _newObjectJsonString_: the updated document as JSON 138 | * 139 | * Example: 140 | * | Update Documents | myCollection | { age : { $gte: 23 } } | {name : 'Mike', age : 22} | 141 | */ 142 | public void updateDocuments(String collectionName, 143 | String queryJsonString, String newObjectJsonString) { 144 | DBObject queryJson = (DBObject) parse(queryJsonString); 145 | DBObject newObjectJson = (DBObject) parse(newObjectJsonString); 146 | db.getCollection(collectionName).update(queryJson, newObjectJson, false, true); 147 | } 148 | 149 | /** 150 | * Imports the documents from the given file into the given collection. 151 | * 152 | * Arguments: 153 | * - _collectionName_: the name of the target collection 154 | * - _file_: the file that contains the documents 155 | * 156 | * Example: 157 | * | Import Documents | myCol | /data/documents.json | 158 | */ 159 | public void importDocuments(String collectionName, String file) { 160 | try { 161 | String documents = IOUtils.toString(new FileReader(file)); 162 | DBObject dbObject = (DBObject) parse(documents); 163 | if (dbObject instanceof BasicDBList) { 164 | Iterator jsonIterator = ((BasicDBList) dbObject).iterator(); 165 | while(jsonIterator.hasNext()) { 166 | DBObject document = (DBObject) jsonIterator.next(); 167 | db.getCollection(collectionName).insert(document); 168 | } 169 | } else { 170 | db.getCollection(collectionName).insert(dbObject); 171 | } 172 | 173 | } catch (IOException e) { 174 | throw new MongodbLibraryException("error reading json-file", e); 175 | } 176 | } 177 | 178 | /** 179 | * Imports the documents from the given file into the given collection. This keyword reads the data row-based. 180 | * 181 | * Arguments: 182 | * - _collectionName_: the name of the target collection 183 | * - _file_: the file that contains the documents 184 | * 185 | * Example: 186 | * | Import Documents Row Seperated | myCol | /data/documents.json | 187 | */ 188 | public void importDocumentsRowSeperated(String collectionName, String file) { 189 | try { 190 | String documents = IOUtils.toString(new FileReader(file)); 191 | String[] documentsAsArray = documents.split("\n"); 192 | for (String json : documentsAsArray) { 193 | db.getCollection(collectionName).insert((DBObject) JSON.parse(json)); 194 | } 195 | 196 | } catch (IOException e) { 197 | throw new MongodbLibraryException("error reading json-file", e); 198 | } 199 | } 200 | 201 | 202 | /** 203 | * Drops the given collection. 204 | * 205 | * Arguments: 206 | * - _collectionName_: the name of the collection to drop 207 | * 208 | * Example: 209 | * | Drop Collection | myCollection | 210 | */ 211 | public void dropCollection(String collectionName) { 212 | db.getCollection(collectionName).drop(); 213 | } 214 | 215 | /** 216 | * All following keywords will operate on the selected database. Same as use 217 | * dbname with the Mongo shell. If the database does not exist, it will be 218 | * create as soon as needed. 219 | * 220 | * Arguments: 221 | * - _databaseName_: the name of the database 222 | * 223 | * Example: 224 | * | Use Database | myDb | 225 | */ 226 | public void useDatabase(String databaseName) { 227 | this.db = mongoClient.getDB(databaseName); 228 | } 229 | 230 | /** 231 | * A database in MongoDB is a more lightweight construct compared to RDBMS, 232 | * so a cleanup after testing can be done quite easily by dropping the whole database. 233 | * 234 | * Arguments: 235 | * - _databaseName_: the name of the database to delete 236 | * 237 | * Example: 238 | * | Drop Database | myDb | 239 | */ 240 | public void dropDatabase(String databaseName) { 241 | mongoClient.dropDatabase(databaseName); 242 | } 243 | 244 | /** 245 | * Creates a collection with the given name and options. 246 | * 247 | * Arguments: 248 | * - _collectionName_: the name of the collection to create 249 | * - _options_: the options of the collection 250 | * 251 | * Example: 252 | * | Create Collection | myCol | {capped:true, size:10000} | 253 | */ 254 | public void createCollectionWithOptions(String collectionName, String options) { 255 | this.db.createCollection(collectionName, (DBObject) JSON.parse(options)); 256 | } 257 | 258 | /** 259 | * Creates a collection with the given name and options. 260 | * 261 | * Arguments: 262 | * - _collectionName_: the name of the collection to create 263 | * 264 | * Example: 265 | * | Create Collection | myCol | 266 | */ 267 | public void createCollection(String collectionName) { 268 | this.db.createCollection(collectionName, new BasicDBObject()); 269 | } 270 | 271 | /** 272 | * Creates an index on the given collection, the desired fields of the index are given by the keys parameter. 273 | * 274 | * Arguments: 275 | * - _collectionName_: the name of collection 276 | * - _keys_: an object with a key set of the fields desired for the index 277 | * 278 | * Example: 279 | * | Ensure Index | myCol | {name : 1, street : 1} | 280 | */ 281 | public void ensureIndex(String collectionName, String keys) { 282 | this.db.getCollection(collectionName).ensureIndex((DBObject) JSON.parse(keys)); 283 | } 284 | 285 | /** 286 | * Creates an index with given name on the given collection, the desired fields of the index are given by the keys parameter. 287 | * 288 | * Arguments: 289 | * - _indexName_: the name of the index 290 | * - _collectionName_: the name of collection 291 | * - _keys_: an object with a key set of the fields desired for the index 292 | * 293 | * Example: 294 | * | Ensure Index | myCol | {name : 1, street : 1} | 295 | */ 296 | public void ensureIndexWithName(String indexName, String collectionName, String keys 297 | ) { 298 | this.db.getCollection(collectionName).ensureIndex((DBObject) JSON.parse(keys), indexName); 299 | } 300 | 301 | /** 302 | * Creates an unique index with given name on the given collection, the desired fields of the index are given by the keys parameter. 303 | * 304 | * Arguments: 305 | * - _indexName_: the name of the index 306 | * - _collectionName_: the name of collection 307 | * - _keys_: an object with a key set of the fields desired for the index 308 | * 309 | * Example: 310 | * | Ensure Index | myCol | {name : 1, street : 1} | 311 | */ 312 | public void ensureUniqueIndex(String collectionName, String keys, 313 | String indexName) { 314 | this.db.getCollection(collectionName).ensureIndex((DBObject) JSON.parse(keys), indexName, true); 315 | } 316 | 317 | /** 318 | * Fails if the database does not exist. 319 | * 320 | * Arguments: 321 | * - _databaseName_: the database which should exist 322 | * 323 | * Example: 324 | * | Database Should Exist | myDatabase | 325 | */ 326 | public void databaseShouldExist(String databaseName) { 327 | assertTrue("Database: " + databaseName + " does not exist.", this.mongoClient.getDatabaseNames().contains(databaseName)); 328 | } 329 | 330 | /** 331 | * Fails if the collection does not exist. 332 | * 333 | * Arguments: 334 | * - _collectionName_: the collection which should exist 335 | * 336 | * Example: 337 | * | Collection Should Exist | myCol | 338 | */ 339 | public void collectionShouldExist(String collectionName) { 340 | assertTrue("Collection: " + collectionName + " does not exist.", this.db.getCollectionNames().contains(collectionName)); 341 | } 342 | 343 | /** 344 | * Fails if the given document does not exist in the given collection. 345 | * 346 | * Arguments: 347 | * - _collectionName_: the collection within the document should exist 348 | * - _document_: the document which should exist in the given collection 349 | * 350 | * Example: 351 | * | Document Should Exist | myCol | {say : 'Hello MongoDb!'} | 352 | */ 353 | public void documentShouldExist(String collectionName, String document) { 354 | assertTrue("Document " + document + " does not exist in Collection " + collectionName + ".", this.db.getCollection(collectionName).find((DBObject) JSON.parse(document)).count() == 1); 355 | } 356 | 357 | /** 358 | * Fails if the given index does not exist in the given collection. 359 | * 360 | * Arguments: 361 | * - _collectionName_: the collection within the index should exist 362 | * - _index_: the name of the index which should exist in the given collection 363 | * 364 | * Example: 365 | * | Index Should Exist | myCol | a_1_b_1 | 366 | */ 367 | public void indexShouldExist(String collectionName, String indexName) { 368 | for (DBObject index : this.db.getCollection(collectionName).getIndexInfo()) { 369 | if(index.get("name").equals(indexName)) { 370 | return; 371 | } 372 | } 373 | fail("Index " + indexName + " does not exist in Collection " + collectionName + "."); 374 | } 375 | 376 | DB getDb() { 377 | return db; 378 | } 379 | 380 | /** 381 | * Returns all documents from the given collection. 382 | * 383 | * Arguments: 384 | * - _collectionName_: the name of the collection 385 | * 386 | * Example: 387 | * | Get All Documents | myCol | 388 | */ 389 | @SuppressWarnings("unchecked") 390 | public List> getAllDocuments(String collectionName) { 391 | List> ret = new ArrayList>(); 392 | for (DBObject document : db.getCollection(collectionName).find()) { 393 | ret.add(document.toMap()); 394 | } 395 | return ret; 396 | } 397 | 398 | /** 399 | * Finds some documents in the given collection. 400 | * 401 | * Arguments: 402 | * - _collectionName_: the name of the collection 403 | * - _jsonString_: the documents to find as JSON 404 | * 405 | * Example: 406 | * | Get Documents | myCol | { age : { $gte: 23 } } | 407 | */ 408 | @SuppressWarnings("unchecked") 409 | public List> getDocuments(String collectionName, String jsonString) { 410 | List> ret = new ArrayList>(); 411 | for (DBObject document : db.getCollection(collectionName).find( 412 | (DBObject) parse(jsonString))) { 413 | ret.add(document.toMap()); 414 | } 415 | return ret; 416 | } 417 | 418 | /** 419 | * Removes some documents in the given collection. 420 | * 421 | * Arguments: 422 | * - _collectionName_: the name of the collection 423 | * - _jsonString_: the documents to remove as JSON 424 | * 425 | * Example: 426 | * | Remove Documents | myCol | { age : { $gte: 23 } } | 427 | */ 428 | public void removeDocuments(String collectionName, String jsonString) { 429 | for (DBObject document : db.getCollection(collectionName).find( 430 | (DBObject) parse(jsonString))) { 431 | db.getCollection(collectionName).remove(document); 432 | } 433 | } 434 | 435 | /** 436 | * Removes all documents in the given collection. 437 | * 438 | * Arguments: 439 | * - _collectionName_: the name of the collection 440 | * 441 | * Example: 442 | * | Remove All Documents | myCol | 443 | */ 444 | public void removeAllDocuments(String collectionName) { 445 | for (DBObject document : db.getCollection(collectionName).find()) { 446 | db.getCollection(collectionName).remove(document); 447 | } 448 | } 449 | 450 | /** 451 | * Returns the number of documents in the given collection. 452 | * 453 | * Arguments: 454 | * - _collectionName_: the name of the collection 455 | * 456 | * Example: 457 | * | Get Collection Count | myCol | 458 | */ 459 | public long getCollectionCount(String collectionName) { 460 | return db.getCollection(collectionName).count(); 461 | } 462 | 463 | /** 464 | * Returns the names of the collections from the connected database. 465 | * 466 | * Example: 467 | * | Get Collections | 468 | */ 469 | public List getCollections() { 470 | Set collectionNames = db.getCollectionNames(); 471 | collectionNames.remove("system.indexes"); 472 | return new ArrayList(collectionNames); 473 | } 474 | 475 | /** 476 | * Returns the name of the databases from the server. 477 | * 478 | * Example: 479 | * | Get Databases | 480 | */ 481 | public List getDatabases() { 482 | return mongoClient.getDatabaseNames(); 483 | } 484 | 485 | 486 | } 487 | -------------------------------------------------------------------------------- /src/main/java/de/codecentric/robot/mongodblibrary/server/MongodbLibraryRemoteServer.java: -------------------------------------------------------------------------------- 1 | package de.codecentric.robot.mongodblibrary.server; 2 | 3 | import static de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary.VERSION; 4 | 5 | import java.text.SimpleDateFormat; 6 | import java.util.Date; 7 | 8 | import org.robotframework.remoteserver.RemoteServer; 9 | 10 | import de.codecentric.robot.mongodblibrary.keywords.MongodbLibrary; 11 | 12 | public class MongodbLibraryRemoteServer { 13 | 14 | public static final int DEFAULT_PORT = 8270; 15 | 16 | public static final String MESSAGE = "MongoDB Library v" + VERSION + " remote server started"; 17 | 18 | private static org.robotframework.remoteserver.RemoteServer server; 19 | 20 | /** 21 | * Remote Server main/startup method. Takes input from command line for Java 22 | * class library (name) to load and invoke with reflection and the port to 23 | * bind the remote server to. Defaults to port 8270 if not supplied. 24 | * 25 | * @param args 26 | */ 27 | public static void main(String[] args) { 28 | 29 | // Setting port and 30 | int port = DEFAULT_PORT; 31 | 32 | // Parse command line arguments 33 | for (int i = 0; i < args.length; i++) { 34 | if (args[i].equalsIgnoreCase("--port") || args[i].equalsIgnoreCase("-p")) { 35 | port = Integer.parseInt(args[i + 1]); 36 | } 37 | if (args[i].equalsIgnoreCase("--help") || args[i].equalsIgnoreCase("-h")) { 38 | displayUsage(); 39 | System.exit(0); 40 | } 41 | } 42 | 43 | // The actual XML-RPC stuff 44 | try { 45 | RemoteServer.configureLogging(); 46 | server = new RemoteServer(); 47 | server.addLibrary(MongodbLibrary.class, port); 48 | server.start(); 49 | SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm"); 50 | System.out.println(MESSAGE + " on port " + port + " at " + dateFormat.format(new Date())); 51 | } catch (Exception e) { 52 | System.out.println("An exception occured when starting the server.\n\n" 53 | + "Stacktrace:\n\n"); 54 | e.printStackTrace(); 55 | } 56 | } 57 | 58 | private static void displayUsage() { 59 | System.out.println("\n" + MESSAGE + "\n"); 60 | System.out.println("Usage Info:\n"); 61 | System.out.println("Ensure that the robotframework-mongodblibrary-" + VERSION + "-with-dependencies.jar JAR is in the classpath, e.g.:\n"); 62 | System.out.println("set CLASSPATH=%CLASSPATH%;./robotframework-mongodblibrary-" + VERSION + "-with-dependencies.jar"); 63 | System.out.println("The start the server as follows:\n"); 64 | System.out.println("java -jar robotframework-mongodblibrary-" + VERSION + "-with-dependencies.jar --port "); 65 | System.out.println(""); 66 | } 67 | } -------------------------------------------------------------------------------- /src/main/resources/de/codecentric/robot/mongodblibrary/keywords/MongodbLibrary.properties: -------------------------------------------------------------------------------- 1 | lib.version=@version@ -------------------------------------------------------------------------------- /src/test/data/testArray.json: -------------------------------------------------------------------------------- 1 | [{name : 'max'}, 2 | {name : 'otto'}] -------------------------------------------------------------------------------- /src/test/data/testRowSeperated.json: -------------------------------------------------------------------------------- 1 | {name : 'peter1', street : 'merscheider str.'} 2 | {name : 'peter2', street : 'merscheider str.'} 3 | {name : 'peter3', street : 'merscheider str.'} 4 | {name : 'peter4', street : 'merscheider str.'} 5 | {name : 'peter5', street : 'merscheider str.'} 6 | {name : 'peter6', street : 'merscheider str.'} 7 | {name : 'peter7', street : 'merscheider str.'} 8 | {name : 'peter8', street : 'merscheider str.'} 9 | {name : 'peter9', street : 'merscheider str.'} 10 | {name : 'peter10', street : 'merscheider str.'} 11 | {name : 'peter11', street : 'merscheider str.'} 12 | {name : 'peter12', street : 'merscheider str.'} 13 | {name : 'peter13', street : 'merscheider str.'} 14 | {name : 'peter14', street : 'merscheider str.'} 15 | {name : 'peter15', street : 'merscheider str.'} 16 | {name : 'peter16', street : 'merscheider str.'} -------------------------------------------------------------------------------- /src/test/data/testSingleObject.json: -------------------------------------------------------------------------------- 1 | {name : 'max', street : 'merscheider str.'} 2 | -------------------------------------------------------------------------------- /src/test/java/de/codecentric/robot/mongodblibrary/keywords/MongodbLibraryTest.java: -------------------------------------------------------------------------------- 1 | package de.codecentric.robot.mongodblibrary.keywords; 2 | 3 | import static com.mongodb.util.JSON.parse; 4 | import static org.hamcrest.CoreMatchers.is; 5 | import static org.hamcrest.CoreMatchers.notNullValue; 6 | import static org.junit.Assert.assertThat; 7 | 8 | import java.io.IOException; 9 | import java.net.UnknownHostException; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | import org.junit.After; 14 | import org.junit.AfterClass; 15 | import org.junit.Before; 16 | import org.junit.BeforeClass; 17 | import org.junit.Test; 18 | 19 | import com.mongodb.BasicDBObject; 20 | import com.mongodb.DB; 21 | import com.mongodb.DBCollection; 22 | import com.mongodb.DBObject; 23 | import com.mongodb.MongoClient; 24 | import com.mongodb.util.JSON; 25 | 26 | import de.flapdoodle.embed.mongo.MongodExecutable; 27 | import de.flapdoodle.embed.mongo.MongodStarter; 28 | import de.flapdoodle.embed.mongo.config.MongodConfig; 29 | import de.flapdoodle.embed.process.distribution.GenericVersion; 30 | import de.flapdoodle.embed.process.runtime.Network; 31 | 32 | /** 33 | * 34 | * Tests for {@link MongodbLibrary} 35 | * 36 | * @author max.hartmann 37 | * 38 | */ 39 | public class MongodbLibraryTest { 40 | 41 | private static final Integer MONGO_TEST_PORT = 27020; 42 | 43 | private MongodbLibrary library; 44 | private MongoClient mongoClient; 45 | private DB db1; 46 | 47 | private static MongodExecutable mongodExecutable; 48 | 49 | @BeforeClass 50 | public static void startMongoDB() throws IOException { 51 | MongodConfig mongodConfig = new MongodConfig(new GenericVersion("2.4.5"), MONGO_TEST_PORT, Network.localhostIsIPv6()); 52 | MongodStarter runtime = MongodStarter.getDefaultInstance(); 53 | mongodExecutable = runtime.prepare(mongodConfig); 54 | mongodExecutable.start(); 55 | } 56 | 57 | @AfterClass 58 | public static void shutdownMongoDB() { 59 | mongodExecutable.stop(); 60 | } 61 | 62 | @Before 63 | public void setUp() throws UnknownHostException { 64 | library = new MongodbLibrary(); 65 | library.connectToServer("localhost", MONGO_TEST_PORT.toString(), "robotdb1"); 66 | mongoClient = new MongoClient("localhost" , MONGO_TEST_PORT ); 67 | db1 = mongoClient.getDB("robotdb1"); 68 | mongoClient.getDB("robotdb2"); 69 | } 70 | 71 | @After 72 | public void tearDown() { 73 | db1.getCollection("testCol").drop(); 74 | mongoClient.dropDatabase("robotdb1"); 75 | mongoClient.dropDatabase("robotdb2"); 76 | } 77 | 78 | @Test 79 | public void shouldReturnVersion() { 80 | //when 81 | String version = MongodbLibrary.VERSION; 82 | //then 83 | assertThat(version, is(notNullValue())); 84 | } 85 | 86 | @Test 87 | public void shouldInsertDocumentIntoCollection() { 88 | //given 89 | DBCollection collection = db1.getCollection("testCol"); 90 | String json = "{say : 'Hello MongoDb!'}"; 91 | //when 92 | library.insertDocument("testCol", json); 93 | //then 94 | DBObject object = collection.find().next(); 95 | assertThat(object, is(notNullValue())); 96 | assertThat(object.containsField("say"), is(Boolean.TRUE)); 97 | assertThat((String)object.get("say"), is("Hello MongoDb!")); 98 | } 99 | 100 | @Test 101 | public void shouldUpdateDocuments() { 102 | //given 103 | db1.getCollection("testCol1").insert((DBObject) JSON.parse("{name : 'Max', age : 22}")); 104 | db1.getCollection("testCol1").insert((DBObject) JSON.parse("{name : 'Peter', age: 40}")); 105 | //when 106 | library.updateDocuments("testCol1", "{ age: 22 }", "{ $inc: { age: 1 } }"); 107 | //then 108 | assertThat((Integer)db1.getCollection("testCol1").findOne((DBObject)parse("{ name : 'Max'}")).get("age"), is(23)); 109 | assertThat((Integer)db1.getCollection("testCol1").findOne((DBObject)parse("{ name : 'Peter'}")).get("age"), is(40)); 110 | } 111 | 112 | @Test 113 | public void shouldImportDocumentsFromArray() throws IOException { 114 | //given 115 | String path = "src/test/data/testArray.json"; 116 | String collectionName = "testCol"; 117 | //when 118 | library.importDocuments(collectionName, path); 119 | //then 120 | assertThat(db1.getCollection("testCol").count(), is(2l)); 121 | } 122 | 123 | @Test 124 | public void shouldImportDocumentsFromSingleObject() throws IOException { 125 | //given 126 | String path = "src/test/data/testSingleObject.json"; 127 | String collectionName = "testCol"; 128 | //when 129 | library.importDocuments(collectionName, path); 130 | //then 131 | assertThat(db1.getCollection("testCol").count(), is(1l)); 132 | } 133 | 134 | @Test 135 | public void shouldImportDocumentsRowSeperated() throws IOException { 136 | //given 137 | String path = "src/test/data/testRowSeperated.json"; 138 | String collectionName = "testCol"; 139 | //when 140 | library.importDocumentsRowSeperated(collectionName, path); 141 | //then 142 | assertThat(db1.getCollection("testCol").count(), is(16l)); 143 | } 144 | 145 | @Test 146 | public void shouldDropCollection() { 147 | //given 148 | DBCollection collection = db1.getCollection("testCol"); 149 | DBObject object = new BasicDBObject("say", "HelloMongoDB"); 150 | collection.insert(object); 151 | //when 152 | library.dropCollection("testCol"); 153 | //then 154 | assertThat(db1.getCollection("testCol").find().hasNext(), is(false)); 155 | } 156 | 157 | @Test 158 | public void shouldUseDatabase() { 159 | //given 160 | String databaseName = "robotdb2"; 161 | //when 162 | library.useDatabase(databaseName); 163 | //then 164 | assertThat(library.getDb().getName(), is(databaseName)); 165 | } 166 | 167 | @Test 168 | public void shouldDropDatabase() { 169 | //given 170 | String databaseName = "robotdb2"; 171 | //when 172 | library.dropDatabase("robotdb2"); 173 | //then 174 | assertThat(mongoClient.getDatabaseNames().contains(databaseName), is(false)); 175 | } 176 | 177 | @Test 178 | public void shouldCreateCollection() { 179 | //given 180 | String collectionName = "newCollection"; 181 | //when 182 | library.createCollection(collectionName); 183 | //then 184 | assertThat(db1.getCollectionNames().contains(collectionName), is(true)); 185 | } 186 | 187 | @Test 188 | public void shouldCreateCollectionWithParameters() { 189 | //given 190 | String collectionName = "newCollection"; 191 | //when 192 | library.createCollectionWithOptions(collectionName, "{size : 1000}"); 193 | //then 194 | assertThat(db1.getCollectionNames().contains(collectionName), is(true)); 195 | } 196 | 197 | @Test 198 | public void shouldEnsureIndex() { 199 | //given 200 | String collectionName = "testCol"; 201 | //when 202 | library.ensureIndex(collectionName, "{a : 1, b : -1}"); 203 | //then 204 | List indexInfo = db1.getCollection(collectionName).getIndexInfo(); 205 | DBObject key = (DBObject) indexInfo.get(1).get("key"); 206 | assertThat(indexInfo.size(), is(2)); 207 | assertThat(key.get("a").toString(), is("1")); 208 | assertThat(key.get("b").toString(), is("-1")); 209 | } 210 | 211 | @Test 212 | public void shouldEnsureUniqueIndexWithGivenName() { 213 | //given 214 | String collectionName = "testCol"; 215 | String indexName = "myIndex"; 216 | //when 217 | library.ensureUniqueIndex(collectionName, "{a : 1, b : -1}", indexName); 218 | //then 219 | List indexInfo = db1.getCollection(collectionName).getIndexInfo(); 220 | String name = (String) indexInfo.get(1).get("name"); 221 | DBObject key = (DBObject) indexInfo.get(1).get("key"); 222 | boolean unique = (Boolean)indexInfo.get(1).get("unique"); 223 | assertThat(name, is(indexName)); 224 | assertThat(key.get("a").toString(), is("1")); 225 | assertThat(key.get("b").toString(), is("-1")); 226 | assertThat(unique, is(true)); 227 | } 228 | 229 | @Test 230 | public void shouldEnsureIndexWithGivenName() { 231 | //given 232 | String collectionName = "testCol"; 233 | String indexName = "myIndex"; 234 | //when 235 | library.ensureIndexWithName(indexName, collectionName, "{a : 1, b : -1}"); 236 | //then 237 | List indexInfo = db1.getCollection(collectionName).getIndexInfo(); 238 | String name = (String) indexInfo.get(1).get("name"); 239 | DBObject key = (DBObject) indexInfo.get(1).get("key"); 240 | assertThat(name, is(indexName)); 241 | assertThat(key.get("a").toString(), is("1")); 242 | assertThat(key.get("b").toString(), is("-1")); 243 | } 244 | 245 | @Test(expected = AssertionError.class) 246 | public void shouldFailIfDatabaseNotExists() { 247 | //given 248 | String database = "newDatabase"; 249 | //when 250 | library.databaseShouldExist(database); 251 | } 252 | 253 | @Test 254 | public void shouldNotFailIfDatabaseExists() { 255 | //given 256 | String database = "robotdb1"; 257 | mongoClient.getDB(database).createCollection("testCol", new BasicDBObject()); 258 | //when 259 | library.databaseShouldExist(database); 260 | } 261 | 262 | @Test(expected = AssertionError.class) 263 | public void shouldFailIfCollectionNotExists() { 264 | //given 265 | String collectionName = "newCollection"; 266 | //when 267 | library.collectionShouldExist(collectionName); 268 | } 269 | 270 | @Test 271 | public void shouldNotFailIfCollectionExists() { 272 | //given 273 | String collectionName = "testCol"; 274 | db1.createCollection("testCol", new BasicDBObject()); 275 | //when 276 | library.collectionShouldExist(collectionName); 277 | } 278 | 279 | @Test 280 | public void shouldPassIfDocumentExists() { 281 | //given 282 | db1.getCollection("testCol").insert( 283 | (DBObject) JSON.parse("{say : 'Hello MongoDb!'}")); 284 | //when 285 | library.documentShouldExist("testCol", "{say : 'Hello MongoDb!'}"); 286 | } 287 | 288 | @Test(expected = AssertionError.class) 289 | public void shouldFailIfDocumentNotExists() { 290 | //given 291 | db1.getCollection("testCol").insert( 292 | (DBObject) JSON.parse("{say : 'Hello MongoDb!'}")); 293 | //when 294 | library.documentShouldExist("testCol", "{say : 'Hello MongoDb1!'}"); 295 | } 296 | 297 | @Test 298 | public void shouldPassIfIndexExists() { 299 | //given 300 | db1.getCollection("testCol").ensureIndex((DBObject) JSON.parse("{a : 1, b : 1}")); 301 | //when 302 | library.indexShouldExist("testCol", "a_1_b_1"); 303 | } 304 | 305 | @Test(expected = AssertionError.class) 306 | public void shouldFailIfIndexNotExists() { 307 | //given 308 | db1.getCollection("testCol").ensureIndex((DBObject) JSON.parse("{a : 1, b : 1}")); 309 | //when 310 | library.indexShouldExist("testCol", "a_1_b_11"); 311 | } 312 | 313 | @Test 314 | public void shouldReturnAllDocumentsFromCollection() { 315 | //given 316 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Max', age : 22}")); 317 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Peter', age: 23}")); 318 | //when 319 | List> allDocuments = library.getAllDocuments("testCol"); 320 | //then 321 | assertThat(allDocuments.size(), is(2)); 322 | assertThat((Integer)allDocuments.get(0).get("age"), is(22)); 323 | assertThat((Integer)allDocuments.get(1).get("age"), is(23)); 324 | } 325 | 326 | @Test 327 | public void shouldReturnDocumentsFromCollection() { 328 | //given 329 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Max', age : 22}")); 330 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Peter', age: 23}")); 331 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Eric', age: 40}")); 332 | String json = "{ age : { $gte: 23 } }"; 333 | //when 334 | List> documents = library.getDocuments("testCol", json); 335 | //then 336 | assertThat(documents.size(), is(2)); 337 | assertThat((Integer)documents.get(0).get("age"), is(23)); 338 | assertThat((Integer)documents.get(1).get("age"), is(40)); 339 | } 340 | 341 | @Test 342 | public void shouldRemoveDocumentsFromCollection() { 343 | //given 344 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Max', age : 22}")); 345 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Peter', age: 23}")); 346 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Eric', age: 40}")); 347 | String json = "{ age : { $gte: 23 } }"; 348 | //when 349 | library.removeDocuments("testCol", json); 350 | //then 351 | assertThat(db1.getCollection("testCol").count(), is(1L)); 352 | } 353 | 354 | @Test 355 | public void shouldRemoveAllDocumentsFromCollection() { 356 | //given 357 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Max', age : 22}")); 358 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Peter', age: 23}")); 359 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Eric', age: 40}")); 360 | //when 361 | library.removeAllDocuments("testCol"); 362 | //then 363 | assertThat(db1.getCollection("testCol").count(), is(0L)); 364 | } 365 | 366 | @Test 367 | public void shouldReturnCountFromCollection() { 368 | //given 369 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Max', age : 22}")); 370 | db1.getCollection("testCol").insert((DBObject) JSON.parse("{name : 'Peter', age: 23}")); 371 | //when 372 | long count = library.getCollectionCount("testCol"); 373 | //then 374 | assertThat(count, is(2L)); 375 | } 376 | 377 | @Test 378 | public void shouldReturnCollectionNames() { 379 | //given 380 | db1.getCollection("testCol1").insert((DBObject) JSON.parse("{name : 'Max', age : 22}")); 381 | db1.getCollection("testCol2").insert((DBObject) JSON.parse("{name : 'Peter', age: 23}")); 382 | //when 383 | List collections = library.getCollections(); 384 | //then 385 | assertThat(collections.size(), is(2)); 386 | } 387 | 388 | @Test 389 | public void shouldReturnDatabaseNames() { 390 | //given 391 | db1.getCollection("testCol1").insert((DBObject) JSON.parse("{name : 'Max', age : 22}")); 392 | db1.getCollection("testCol2").insert((DBObject) JSON.parse("{name : 'Peter', age: 23}")); 393 | //when 394 | List databases = library.getDatabases(); 395 | //then 396 | assertThat(databases.size(), is(2)); 397 | } 398 | } 399 | --------------------------------------------------------------------------------