From 93b954f8502c990c4814aab9392c97f0dc366e69 Mon Sep 17 00:00:00 2001
From: Pierre-Jean Vardanega <pierrejean.vardanega@gmail.com>
Date: Tue, 17 Mar 2015 16:23:50 +0100
Subject: [PATCH] Insert data in start goal instead of in a new goal
---
pom.xml | 6 +
.../embedmongo/DataInitializer.java | 104 +++++++++++++++
.../embedmongo/InitDataMongoMojo.java | 124 ------------------
.../embedmongo/StartEmbeddedMongoMojo.java | 16 +++
...MojoTest.java => DataInitializerTest.java} | 64 +++++++--
.../embedmongo/PortUtilsTest.java | 1 -
.../java/com/mongodb/EmbedMongoClient.java | 24 ++++
src/test/java/com/mongodb/EmbedMongoDB.java | 85 ++++++++++++
8 files changed, 286 insertions(+), 138 deletions(-)
create mode 100644 src/main/java/com/github/joelittlejohn/embedmongo/DataInitializer.java
delete mode 100644 src/main/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojo.java
rename src/test/java/com/github/joelittlejohn/embedmongo/{InitDataMongoMojoTest.java => DataInitializerTest.java} (56%)
create mode 100644 src/test/java/com/mongodb/EmbedMongoClient.java
create mode 100644 src/test/java/com/mongodb/EmbedMongoDB.java
diff --git a/pom.xml b/pom.xml
index 5449eaa..089b5fb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -116,6 +116,12 @@
<version>4.11</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>1.10.8</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<profiles>
diff --git a/src/main/java/com/github/joelittlejohn/embedmongo/DataInitializer.java b/src/main/java/com/github/joelittlejohn/embedmongo/DataInitializer.java
new file mode 100644
index 0000000..17a3c4c
--- /dev/null
+++ b/src/main/java/com/github/joelittlejohn/embedmongo/DataInitializer.java
@@ -0,0 +1,104 @@
+/**
+ * Copyright © 2012 Joe Littlejohn
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.joelittlejohn.embedmongo;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.net.UnknownHostException;
+import java.util.Scanner;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugin.logging.Log;
+import com.mongodb.CommandResult;
+import com.mongodb.DB;
+import com.mongodb.MongoClient;
+import com.mongodb.MongoException;
+
+/**
+ * When invoked, this goal connects to an instance of mongo and execute some instructions
+ * to add data.
+ *
+ * You should use the same javascript syntax that you would use in the mongo client.
+ */
+public class DataInitializer {
+
+ private File initDirectory;
+ private int port;
+ private String databaseName;
+ private Log logger;
+
+ public DataInitializer(File initDirectory, int port, String databaseName, Log logger) {
+ this.initDirectory = initDirectory;
+ this.port = port;
+ this.databaseName = databaseName;
+ this.logger = logger;
+ }
+
+ public void insertData() throws MojoExecutionException, MojoFailureException {
+ if (initDirectory.isDirectory()) {
+ Scanner scanner = null;
+ StringBuilder instructions = new StringBuilder();
+ File[] files = initDirectory.listFiles();
+ if (files != null && files.length > 0) {
+ logger.info("Folder " + initDirectory.getAbsolutePath() + " contains " + files.length + " file(s):");
+ DB db = getConnectToMongoAndGetDatabase();
+ for (File file : files) {
+ try {
+ scanner = new Scanner(file);
+ while (scanner.hasNextLine()) {
+ instructions.append(scanner.nextLine()).append("\n");
+ }
+ } catch (FileNotFoundException e) {
+ throw new MojoExecutionException("Unable to find file with name '" + file.getName() + "'", e);
+ } finally {
+ if (scanner != null) {
+ scanner.close();
+ }
+ }
+ CommandResult result;
+ try {
+ result = db.doEval("(function() {" + instructions.toString() + "})();", new Object[0]);
+ } catch (MongoException e) {
+ throw new MojoExecutionException("Unable to execute file with name '" + file.getName() + "'", e);
+ }
+ if (!result.ok()) {
+ logger.error("- file " + file.getName() + " parsed with error: " + result.getErrorMessage());
+ throw new MojoExecutionException("Error while executing instructions from file '"+file.getName()+"': " + result.getErrorMessage(), result.getException());
+ }
+ logger.info("- file " + file.getName() + " parsed successfully");
+ }
+ logger.info("Data initialized with success");
+ } else {
+ logger.info("No data to initialize");
+ }
+ }
+ }
+
+ DB getConnectToMongoAndGetDatabase() throws MojoExecutionException {
+ if (databaseName == null || databaseName.trim().length() == 0) {
+ throw new MojoExecutionException("Database name is missing");
+ }
+
+ MongoClient mongoClient;
+ try {
+ mongoClient = new MongoClient("localhost", port);
+ } catch (UnknownHostException e) {
+ throw new MojoExecutionException("Unable to connect to mongo instance", e);
+ }
+ logger.info("Connected to MongoDB");
+ return mongoClient.getDB(databaseName);
+ }
+}
diff --git a/src/main/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojo.java b/src/main/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojo.java
deleted file mode 100644
index f20db30..0000000
--- a/src/main/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojo.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- * Copyright © 2012 Joe Littlejohn
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.github.joelittlejohn.embedmongo;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.UnknownHostException;
-import java.util.Scanner;
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
-import com.mongodb.CommandResult;
-import com.mongodb.DB;
-import com.mongodb.MongoClient;
-import com.mongodb.MongoException;
-
-/**
- * When invoked, this goal connects to an instance of mongo and execute some instructions
- * to add data.
- *
- * You should use the same javascript syntax that you would use in the mongo client.
- *
- * @goal init-data
- * @phase pre-integration-test
- */
-public class InitDataMongoMojo extends AbstractMojo {
-
- /**
- * Folder that contains all scripts to execute.
- * @parameter
- * @required
- */
- private File dataFolder;
-
- /**
- * Optional. Specify the port only if you want have a different one from the default value.
- * Default value is 27017.
- * @parameter
- */
- private int port;
-
- /**
- * The name of the database where data will be stored.
- * @parameter
- * @required
- */
- private String databaseName;
-
- @Override
- public void execute() throws MojoExecutionException, MojoFailureException {
- DB db = getConnectToMongoAndGetDatabase();
-
- if (dataFolder.isDirectory()) {
- Scanner scanner = null;
- StringBuilder instructions = new StringBuilder();
- File[] files = dataFolder.listFiles();
- getLog().info("Folder " + dataFolder.getAbsolutePath() + " contains " + files.length + " file(s):");
- for (File file : files) {
- try {
- scanner = new Scanner(file);
- while (scanner.hasNextLine()) {
- instructions.append(scanner.nextLine()).append("\n");
- }
- } catch (FileNotFoundException e) {
- throw new MojoExecutionException("Unable to find file with name '" + file.getName() + "'", e);
- } finally {
- if (scanner != null) {
- scanner.close();
- }
- }
- CommandResult result;
- try {
- result = db.doEval("(function() {" + instructions.toString() + "})();", new Object[0]);
- } catch (MongoException e) {
- throw new MojoExecutionException("Unable to execute file with name '" + file.getName() + "'", e);
- }
- if (!result.ok()) {
- getLog().error("- file " + file.getName() + " parsed with error: " + result.getErrorMessage());
- throw new MojoExecutionException("Error while executing instructions from file '"+file.getName()+"': " + result.getErrorMessage(), result.getException());
- }
- getLog().info("- file " + file.getName() + " parsed successfully");
- }
- getLog().info("Data initialized with success");
- }
- }
-
- private DB getConnectToMongoAndGetDatabase() throws MojoExecutionException {
- if (databaseName == null || databaseName.trim().length() == 0) {
- throw new MojoExecutionException("Database name is missing");
- }
-
- MongoClient mongoClient;
- try {
- mongoClient = new MongoClient("localhost", port == 0 ? 27017 : port);
- } catch (UnknownHostException e) {
- throw new MojoExecutionException("Unable to connect to mongo instance", e);
- }
- getLog().info("Connected to MongoDB");
- return mongoClient.getDB(databaseName);
- }
-
- protected InitDataMongoMojo setDataFolder(File dataFolder) {
- this.dataFolder = dataFolder;
- return this;
- }
-
- protected InitDataMongoMojo setDatabaseName(String databaseName) {
- this.databaseName = databaseName;
- return this;
- }
-}
diff --git a/src/main/java/com/github/joelittlejohn/embedmongo/StartEmbeddedMongoMojo.java b/src/main/java/com/github/joelittlejohn/embedmongo/StartEmbeddedMongoMojo.java
index d181248..fb0ac37 100644
--- a/src/main/java/com/github/joelittlejohn/embedmongo/StartEmbeddedMongoMojo.java
+++ b/src/main/java/com/github/joelittlejohn/embedmongo/StartEmbeddedMongoMojo.java
@@ -211,6 +211,20 @@ public class StartEmbeddedMongoMojo extends AbstractMojo {
*/
private boolean skip;
+ /**
+ * The name of the database where data will be stored.
+ * @parameter
+ * @required
+ */
+ private String databaseName;
+
+ /**
+ * Folder that contains all scripts to execute.
+ * @parameter
+ * @required
+ */
+ private File initDirectory;
+
@Override
@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException {
@@ -284,6 +298,8 @@ public class StartEmbeddedMongoMojo extends AbstractMojo {
} catch (IOException e) {
throw new MojoExecutionException("Unable to start the mongod", e);
}
+
+ new DataInitializer(initDirectory, port, databaseName, getLog()).insertData();
}
/**
diff --git a/src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java b/src/test/java/com/github/joelittlejohn/embedmongo/DataInitializerTest.java
similarity index 56%
rename from src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java
rename to src/test/java/com/github/joelittlejohn/embedmongo/DataInitializerTest.java
index c537e24..ae7da20 100644
--- a/src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java
+++ b/src/test/java/com/github/joelittlejohn/embedmongo/DataInitializerTest.java
@@ -16,19 +16,31 @@
package com.github.joelittlejohn.embedmongo;
import static org.junit.Assert.fail;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.mock;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
+import java.net.UnknownHostException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
-import org.junit.Ignore;
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.plugin.logging.SystemStreamLog;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.mockito.Matchers;
+import org.mockito.runners.MockitoJUnitRunner;
+import com.mongodb.CommandResult;
+import com.mongodb.DB;
+import com.mongodb.EmbedMongoDB;
-public class InitDataMongoMojoTest {
+@RunWith(MockitoJUnitRunner.class)
+public class DataInitializerTest {
@Rule
public TemporaryFolder createSchemaFolder = new TemporaryFolder();
@@ -36,37 +48,44 @@ public class InitDataMongoMojoTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
+ private final static int PORT = 27017;
+ private final static Log LOGGER = new SystemStreamLog();
private File rootFolder;
private File rootFolderWithError;
- @Ignore("Need an instance of MongoDB to pass")
@Test public void
should_execute_instructions() throws MojoFailureException, MojoExecutionException, IOException {
initFolder();
try {
- new InitDataMongoMojo().setDatabaseName("myDB").setDataFolder(rootFolder).execute();
+ new DataInitializerForTest(rootFolder, PORT, "myDB", LOGGER).insertData();
} catch (Exception e) {
+ e.printStackTrace();
fail("Should not fail!");
}
}
@Test public void
- should_fail_when_database_name_is_not_provided() throws MojoFailureException, MojoExecutionException {
+ should_fail_when_database_name_is_not_provided() throws MojoFailureException, MojoExecutionException, IOException {
+ initFolder();
+
thrown.expect(MojoExecutionException.class);
thrown.expectMessage("Database name is missing");
- new InitDataMongoMojo().execute();
+ new DataInitializer(rootFolder, PORT, null, LOGGER).insertData();
}
- @Ignore("Need an instance of MongoDB to pass")
@Test public void
should_fail_to_execute_instruction_with_error() throws IOException, MojoFailureException, MojoExecutionException {
+ DB database = mock(DB.class);
initFolderWithError();
+ CommandResult result = new EmbedMongoDB("myDB").notOkErrorResult("Error while executing instructions from file '" + rootFolderWithError.listFiles()[0].getName());
+ given(database.doEval(anyString(), Matchers.<Object>anyVararg())).willReturn(result);
+
thrown.expect(MojoExecutionException.class);
thrown.expectMessage("Error while executing instructions from file '" + rootFolderWithError.listFiles()[0].getName());
- new InitDataMongoMojo().setDatabaseName("myDB").setDataFolder(rootFolderWithError).execute();
+ new DataInitializerForTest(rootFolderWithError, PORT, "myDB", LOGGER, database).insertData();
}
private void initFolder() throws IOException {
@@ -87,16 +106,35 @@ public class InitDataMongoMojoTest {
private void initFolderWithError() throws IOException {
File instructionsFile = createSchemaFolder.newFile();
- BufferedWriter out = null;
+ BufferedWriter reader = null;
try {
- out = new BufferedWriter(new FileWriter(instructionsFile));
- out.write("db.unknownInstruction();\n");
+ reader = new BufferedWriter(new FileWriter(instructionsFile));
+ reader.write("db.unknownInstruction();\n");
} finally {
- if (out != null) {
- out.close();
+ if (reader != null) {
+ reader.close();
}
}
rootFolderWithError = instructionsFile.getParentFile();
rootFolderWithError.mkdir();
}
+
+ static class DataInitializerForTest extends DataInitializer {
+
+ private final DB database;
+
+ public DataInitializerForTest(File dataFolder, int port, String databaseName, Log logger) throws UnknownHostException {
+ this(dataFolder, port, databaseName, logger, new EmbedMongoDB("myDB"));
+ }
+
+ public DataInitializerForTest(File dataFolder, int port, String databaseName, Log logger, DB database) {
+ super(dataFolder, port, databaseName, logger);
+ this.database = database;
+ }
+
+ @Override
+ DB getConnectToMongoAndGetDatabase() throws MojoExecutionException {
+ return database;
+ }
+ }
}
diff --git a/src/test/java/com/github/joelittlejohn/embedmongo/PortUtilsTest.java b/src/test/java/com/github/joelittlejohn/embedmongo/PortUtilsTest.java
index fcb9198..63afc42 100644
--- a/src/test/java/com/github/joelittlejohn/embedmongo/PortUtilsTest.java
+++ b/src/test/java/com/github/joelittlejohn/embedmongo/PortUtilsTest.java
@@ -22,7 +22,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-
import org.junit.After;
import org.junit.Test;
diff --git a/src/test/java/com/mongodb/EmbedMongoClient.java b/src/test/java/com/mongodb/EmbedMongoClient.java
new file mode 100644
index 0000000..9011c26
--- /dev/null
+++ b/src/test/java/com/mongodb/EmbedMongoClient.java
@@ -0,0 +1,24 @@
+/**
+ * Copyright © 2012 Joe Littlejohn
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.mongodb;
+
+import java.net.UnknownHostException;
+
+public class EmbedMongoClient extends MongoClient {
+
+ public EmbedMongoClient() throws UnknownHostException {
+ }
+}
diff --git a/src/test/java/com/mongodb/EmbedMongoDB.java b/src/test/java/com/mongodb/EmbedMongoDB.java
new file mode 100644
index 0000000..7314346
--- /dev/null
+++ b/src/test/java/com/mongodb/EmbedMongoDB.java
@@ -0,0 +1,85 @@
+/**
+ * Copyright © 2012 Joe Littlejohn
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.mongodb;
+
+import java.net.UnknownHostException;
+import java.util.Set;
+
+public class EmbedMongoDB extends DB {
+
+ public EmbedMongoDB(String name) throws UnknownHostException {
+ super(new EmbedMongoClient(), name);
+ }
+
+ public CommandResult notOkErrorResult(String message) {
+ try {
+ CommandResult commandResult = new CommandResult(new ServerAddress("localhost"));
+ commandResult.put("errmsg", message);
+ commandResult.put("ok", 0);
+ return commandResult;
+ } catch (UnknownHostException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public CommandResult doEval(String code, Object... args) {
+ CommandResult commandResult;
+ try {
+ commandResult = new CommandResult(new ServerAddress("localhost"));
+ commandResult.put("ok", 1.0);
+ commandResult.put("retval", "null");
+ } catch (UnknownHostException e) {
+ return notOkErrorResult(e.getMessage());
+ }
+ return commandResult;
+ }
+
+ @Override
+ public void requestStart() {
+
+ }
+
+ @Override
+ public void requestDone() {
+
+ }
+
+ @Override
+ public void requestEnsureConnection() {
+
+ }
+
+ @Override
+ protected DBCollection doGetCollection(String name) {
+ return null;
+ }
+
+ @Override
+ public Set<String> getCollectionNames() {
+ return null;
+ }
+
+ @Override
+ CommandResult doAuthenticate(MongoCredential credentials) {
+ return null;
+ }
+
+ @Override
+ public void cleanCursors(boolean force) {
+
+ }
+}
--
GitLab