This is an automated email from the ASF dual-hosted git repository.
sgoeschl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/freemarker-generator.git
The following commit(s) were added to refs/heads/master by this push:
new 4962dcb FREEMARKER-156 [freemarker-generator] The Maven plugin unit
tests failed randomly (#26)
4962dcb is described below
commit 4962dcb184226a63d991d57c53e98edd2adb1088
Author: Siegfried Goeschl <[email protected]>
AuthorDate: Wed Jan 27 09:39:51 2021 +0100
FREEMARKER-156 [freemarker-generator] The Maven plugin unit tests failed
randomly (#26)
---
.../generator/base/util/PropertiesFactory.java | 13 +
.../generator/cli/config/SuppliersTest.java | 1 +
freemarker-generator-maven-plugin/CHANGELOG.md | 6 +-
freemarker-generator-maven-plugin/pom.xml | 37 +-
.../generator/maven/ConfigurationSupplier.java | 72 ++++
.../freemarker/generator/maven/FactoryUtil.java | 50 ---
.../freemarker/generator/maven/FreeMarkerMojo.java | 44 +--
.../generator/maven/GeneratingFileVisitor.java | 11 +-
.../generator/maven/JsonPropertiesProvider.java | 1 -
.../generator/maven/OutputGenerator.java | 4 +-
.../maven/OutputGeneratorPropertiesProvider.java | 1 -
.../data/mydir/invalid-json.json | 1 +
.../generator/maven/ConfigurationSupplierTest.java | 54 +++
.../generator/maven/FreeMarkerMojoTest.java | 396 ++++++---------------
.../generator/maven/GeneratingFileVisitorTest.java | 219 +++++-------
.../maven/JsonPropertiesProviderTest.java | 126 +++----
.../generator/maven/OperatingSystem.java | 40 ---
.../generator/maven/OutputGeneratorTest.java | 240 +++++--------
.../freemarker/generator/maven/UnitTestHelper.java | 67 ++++
freemarker-generator-tools/pom.xml | 6 +
pom.xml | 5 +
21 files changed, 609 insertions(+), 785 deletions(-)
diff --git
a/freemarker-generator-base/src/main/java/org/apache/freemarker/generator/base/util/PropertiesFactory.java
b/freemarker-generator-base/src/main/java/org/apache/freemarker/generator/base/util/PropertiesFactory.java
index 8805150..b077cf3 100644
---
a/freemarker-generator-base/src/main/java/org/apache/freemarker/generator/base/util/PropertiesFactory.java
+++
b/freemarker-generator-base/src/main/java/org/apache/freemarker/generator/base/util/PropertiesFactory.java
@@ -16,14 +16,27 @@
*/
package org.apache.freemarker.generator.base.util;
+import java.io.File;
+import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Map;
import java.util.Properties;
+/**
+ * Various helper methods to load property files.
+ */
public class PropertiesFactory {
+ public static Properties create(File file) {
+ try (InputStream is = new FileInputStream(file)) {
+ return create(is);
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to load properties file: " +
file.getAbsolutePath());
+ }
+ }
+
public static Properties create(InputStream is) {
try {
final Properties properties = new Properties();
diff --git
a/freemarker-generator-cli/src/test/java/org/apache/freemarker/generator/cli/config/SuppliersTest.java
b/freemarker-generator-cli/src/test/java/org/apache/freemarker/generator/cli/config/SuppliersTest.java
index c59c955..78b6d68 100644
---
a/freemarker-generator-cli/src/test/java/org/apache/freemarker/generator/cli/config/SuppliersTest.java
+++
b/freemarker-generator-cli/src/test/java/org/apache/freemarker/generator/cli/config/SuppliersTest.java
@@ -141,6 +141,7 @@ public class SuppliersTest {
assertNotNull(outputGenerator.getTemplateOutput().getWriter());
assertNull(outputGenerator.getTemplateOutput().getFile());
}
+
private static String fixSeparators(String str) {
if (OperatingSystem.isWindows()) {
return FilenameUtils.separatorsToWindows(str);
diff --git a/freemarker-generator-maven-plugin/CHANGELOG.md
b/freemarker-generator-maven-plugin/CHANGELOG.md
index 133edea..49e8cfd 100644
--- a/freemarker-generator-maven-plugin/CHANGELOG.md
+++ b/freemarker-generator-maven-plugin/CHANGELOG.md
@@ -9,8 +9,12 @@ All notable changes to this project will be documented in this
file. We try to a
* [FREEMARKER-128] Update `freemarker-maven-plugin` to Apache FreeMarker 2.3.29
### Fixed
-* [FREEMARKER-151] Ensure that build and and examples are running on Windows
+* [FREEMARKER-151] Ensure that build and examples are running on Windows
+
+### Internal
+* [FREEMARKER-156] Replaced JMockit and TestNG with Mockito and JUnit
[FREEMARKER-128]: https://issues.apache.org/jira/browse/FREEMARKER-128
[FREEMARKER-129]: https://issues.apache.org/jira/browse/FREEMARKER-129
[FREEMARKER-151]: https://issues.apache.org/jira/browse/FREEMARKER-151
+[FREEMARKER-156]: https://issues.apache.org/jira/browse/FREEMARKER-156
diff --git a/freemarker-generator-maven-plugin/pom.xml
b/freemarker-generator-maven-plugin/pom.xml
index 0d7635c..d1f9515 100644
--- a/freemarker-generator-maven-plugin/pom.xml
+++ b/freemarker-generator-maven-plugin/pom.xml
@@ -32,14 +32,12 @@
<description>Maven plugin for Apache FreeMarker</description>
<properties>
- <maven-core.version>3.5.2</maven-core.version>
- <maven-plugin-api.version>3.5.2</maven-plugin-api.version>
-
<maven-plugin-annotations.version>3.5</maven-plugin-annotations.version>
- <fastutil.version>8.1.0</fastutil.version>
+ <maven-core.version>3.6.3</maven-core.version>
+ <maven-plugin-api.version>3.6.3</maven-plugin-api.version>
+
<maven-plugin-annotations.version>3.6.0</maven-plugin-annotations.version>
<gson.version>2.8.6</gson.version>
- <jmockit.version>1.32</jmockit.version>
- <org.testng.version>6.8</org.testng.version>
- <assertj-core.version>3.8.0</assertj-core.version>
+ <mockito.version>3.7.7</mockito.version>
+ <assertj-core.version>3.18.1</assertj-core.version>
</properties>
<dependencies>
@@ -80,7 +78,7 @@
<dependency>
<groupId>org.eclipse.sisu</groupId>
<artifactId>org.eclipse.sisu.plexus</artifactId>
- <version>0.3.3</version>
+ <version>0.3.4</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.plexus</groupId>
@@ -89,12 +87,6 @@
</exclusions>
</dependency>
<dependency>
- <groupId>org.jmockit</groupId>
- <artifactId>jmockit</artifactId>
- <version>${jmockit.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
@@ -104,9 +96,14 @@
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>${org.testng.version}</version>
+ <groupId>org.apache.freemarker.generator</groupId>
+ <artifactId>freemarker-generator-base</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <!-- Testing -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -115,6 +112,12 @@
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>${mockito.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
diff --git
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/ConfigurationSupplier.java
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/ConfigurationSupplier.java
new file mode 100644
index 0000000..ed44a3a
--- /dev/null
+++
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/ConfigurationSupplier.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.freemarker.generator.maven;
+
+import freemarker.cache.FileTemplateLoader;
+import freemarker.template.Configuration;
+import freemarker.template.Version;
+import org.apache.freemarker.generator.base.util.PropertiesFactory;
+import org.apache.freemarker.generator.base.util.Validate;
+
+import java.io.File;
+import java.util.Properties;
+import java.util.function.Supplier;
+
+import static java.util.Objects.requireNonNull;
+
+public class ConfigurationSupplier implements Supplier<Configuration> {
+
+ private final String freeMarkerVersion;
+ private final File templateDirectory;
+ private final File sourceDirectory;
+
+ public ConfigurationSupplier(String freeMarkerVersion, File
templateDirectory, File sourceDirectory) {
+ Validate.notEmpty(freeMarkerVersion, "freeMarkerVersion is required");
+ Validate.fileExists(templateDirectory, "Required template directory
does not exist");
+
+ this.freeMarkerVersion = requireNonNull(freeMarkerVersion);
+ this.templateDirectory = requireNonNull(templateDirectory);
+ this.sourceDirectory = requireNonNull(sourceDirectory);
+ }
+
+ @Override
+ public Configuration get() {
+ final Configuration configuration = new Configuration(new
Version(freeMarkerVersion));
+ configuration.setDefaultEncoding("UTF-8");
+
+ try {
+ configuration.setTemplateLoader(new
FileTemplateLoader(templateDirectory));
+ } catch (Throwable t) {
+ throw new RuntimeException("Could not establish file template
loader for directory: " + templateDirectory, t);
+ }
+
+ final File freeMarkerProps = new File(sourceDirectory,
"freemarker.properties");
+
+ if (freeMarkerProps.isFile()) {
+ final Properties configProperties =
PropertiesFactory.create(freeMarkerProps);
+ try {
+ configuration.setSettings(configProperties);
+ } catch (Throwable t) {
+ throw new RuntimeException("Invalid setting(s) in " +
freeMarkerProps, t);
+ }
+ }
+
+ return configuration;
+ }
+}
diff --git
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/FactoryUtil.java
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/FactoryUtil.java
deleted file mode 100644
index a255d3f..0000000
---
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/FactoryUtil.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.freemarker.generator.maven;
-
-import freemarker.template.Configuration;
-import freemarker.template.Version;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-
-/**
- * Simple utility class to call various constructors.
- * Needed because some jmockit features don't work well with constructors.
- */
-public class FactoryUtil {
-
- public static Configuration createConfiguration(String freeMarkerVersion) {
- return new Configuration(new Version(freeMarkerVersion));
- }
-
- public static File createFile(File parent, String child) {
- return new File(parent, child);
- }
-
- public static FileInputStream createFileInputStream(File file) throws
FileNotFoundException {
- return new FileInputStream(file);
- }
-
- public static File createFile(String name) {
- return new File(name);
- }
-}
diff --git
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/FreeMarkerMojo.java
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/FreeMarkerMojo.java
index 4add19b..8137cdf 100644
---
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/FreeMarkerMojo.java
+++
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/FreeMarkerMojo.java
@@ -16,26 +16,21 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
-import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import java.io.File;
-import java.io.InputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
-import java.util.Properties;
@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class FreeMarkerMojo extends AbstractMojo {
@@ -63,46 +58,21 @@ public class FreeMarkerMojo extends AbstractMojo {
private MojoExecution mojo;
@Override
- public void execute() throws MojoExecutionException, MojoFailureException {
+ public void execute() throws MojoExecutionException {
if (freeMarkerVersion == null || freeMarkerVersion.isEmpty()) {
throw new MojoExecutionException("freeMarkerVersion is required");
}
if (!generatorDirectory.isDirectory()) {
- throw new MojoExecutionException("Required directory does not
exist: " + generatorDirectory);
+ throw new MojoExecutionException("Required generator directory
does not exist: " + generatorDirectory);
}
- final Configuration config =
FactoryUtil.createConfiguration(freeMarkerVersion);
-
- config.setDefaultEncoding("UTF-8");
-
if (!templateDirectory.isDirectory()) {
- throw new MojoExecutionException("Required directory does not
exist: " + templateDirectory);
- }
- try {
- config.setTemplateLoader(new
FileTemplateLoader(templateDirectory));
- } catch (Throwable t) {
- getLog().error("Could not establish file template loader for
directory: " + templateDirectory, t);
- throw new MojoExecutionException("Could not establish file
template loader for directory: " + templateDirectory);
+ throw new MojoExecutionException("Required template directory does
not exist: " + templateDirectory);
}
- final File freeMarkerProps = FactoryUtil.createFile(sourceDirectory,
"freemarker.properties");
- if (freeMarkerProps.isFile()) {
- final Properties configProperties = new Properties();
- try (InputStream is =
FactoryUtil.createFileInputStream(freeMarkerProps)) {
- configProperties.load(is);
- } catch (Throwable t) {
- getLog().error("Failed to load " + freeMarkerProps, t);
- throw new MojoExecutionException("Failed to load " +
freeMarkerProps);
- }
- try {
- config.setSettings(configProperties);
- } catch (Throwable t) {
- getLog().error("Invalid setting(s) in " + freeMarkerProps, t);
- throw new MojoExecutionException("Invalid setting(s) in " +
freeMarkerProps);
- }
- }
+ final Configuration configuration = configuration();
if ("generate-sources".equals(mojo.getLifecyclePhase())) {
session.getCurrentProject().addCompileSourceRoot(outputDirectory.toString());
@@ -113,7 +83,7 @@ public class FreeMarkerMojo extends AbstractMojo {
final Map<String, OutputGeneratorPropertiesProvider>
extensionToBuilders = new HashMap<>(1);
extensionToBuilders.put(".json",
JsonPropertiesProvider.create(generatorDirectory, templateDirectory,
outputDirectory));
- final GeneratingFileVisitor fileVisitor =
GeneratingFileVisitor.create(config, session, extensionToBuilders);
+ final GeneratingFileVisitor fileVisitor =
GeneratingFileVisitor.create(configuration, session, extensionToBuilders);
try {
Files.walkFileTree(generatorDirectory.toPath(), fileVisitor);
} catch (Throwable t) {
@@ -121,4 +91,8 @@ public class FreeMarkerMojo extends AbstractMojo {
throw new MojoExecutionException("Failed to process files in
generator dir: " + generatorDirectory);
}
}
+
+ private Configuration configuration() {
+ return new ConfigurationSupplier(freeMarkerVersion, templateDirectory,
sourceDirectory).get();
+ }
}
diff --git
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/GeneratingFileVisitor.java
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/GeneratingFileVisitor.java
index 7f1fc51..e6796c6 100644
---
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/GeneratingFileVisitor.java
+++
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/GeneratingFileVisitor.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
import freemarker.template.Configuration;
@@ -30,7 +29,7 @@ import java.util.Map;
/**
* FileVisitor designed to process json data files. The json file parsed into
- * a map and given to FreeMarker to
+ * a map and given to FreeMarker to.
*/
public class GeneratingFileVisitor extends SimpleFileVisitor<Path> {
@@ -52,8 +51,8 @@ public class GeneratingFileVisitor extends
SimpleFileVisitor<Path> {
/**
* Factory method that calls constructor, added to facilitate testing with
jmockit.
*
- * @param config FreeMarker configuration
- * @param session Maven session
+ * @param config FreeMarker configuration
+ * @param session Maven session
* @param extensionToBuilder builder extension
* @return GeneratingFileVisitor instance
*/
@@ -68,8 +67,8 @@ public class GeneratingFileVisitor extends
SimpleFileVisitor<Path> {
.addGeneratorLocation(path)
.addPomLastModifiedTimestamp(pomLastModifiedTimestamp);
final String fileName = path.getFileName().toString();
- final String extenstion =
fileName.substring(fileName.lastIndexOf('.'));
- final OutputGeneratorPropertiesProvider pathProcessor =
extensionToBuilder.get(extenstion);
+ final String extension =
fileName.substring(fileName.lastIndexOf('.'));
+ final OutputGeneratorPropertiesProvider pathProcessor =
extensionToBuilder.get(extension);
if (pathProcessor == null) {
throw new RuntimeException("Unknown file extension: " + path);
}
diff --git
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/JsonPropertiesProvider.java
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/JsonPropertiesProvider.java
index 1d16822..5b8757d 100644
---
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/JsonPropertiesProvider.java
+++
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/JsonPropertiesProvider.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
import com.google.gson.Gson;
diff --git
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/OutputGenerator.java
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/OutputGenerator.java
index 2ac3b4f..fabb1fe 100644
---
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/OutputGenerator.java
+++
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/OutputGenerator.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
import freemarker.template.Configuration;
@@ -141,8 +140,7 @@ class OutputGenerator {
* @param config Used to load the template from the template name.
*/
public void generate(Configuration config) {
- //Use "createFile" for testing purposes only
- final File outputFile =
FactoryUtil.createFile(outputLocation.toFile().toString());
+ final File outputFile = new
File(outputLocation.toFile().getAbsolutePath());
final File templateFile = templateLocation.toFile();
final File generatorFile = generatorLocation.toFile();
if (outputFile.exists()) {
diff --git
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/OutputGeneratorPropertiesProvider.java
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/OutputGeneratorPropertiesProvider.java
index 25b929b..97710c1 100644
---
a/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/OutputGeneratorPropertiesProvider.java
+++
b/freemarker-generator-maven-plugin/src/main/java/org/apache/freemarker/generator/maven/OutputGeneratorPropertiesProvider.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
import java.nio.file.Path;
diff --git
a/freemarker-generator-maven-plugin/src/test/data/generating-file-visitor/data/mydir/invalid-json.json
b/freemarker-generator-maven-plugin/src/test/data/generating-file-visitor/data/mydir/invalid-json.json
new file mode 100644
index 0000000..955d6bd
--- /dev/null
+++
b/freemarker-generator-maven-plugin/src/test/data/generating-file-visitor/data/mydir/invalid-json.json
@@ -0,0 +1 @@
+This is not a valid JSON file
\ No newline at end of file
diff --git
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/ConfigurationSupplierTest.java
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/ConfigurationSupplierTest.java
new file mode 100644
index 0000000..ab16e19
--- /dev/null
+++
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/ConfigurationSupplierTest.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.freemarker.generator.maven;
+
+import freemarker.template.Configuration;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.assertj.core.api.Assertions.*;
+
+public class ConfigurationSupplierTest {
+
+ private static final String FREEMARKER_VERSION = "2.3.30";
+ private static final File SOURCE_DIR = new
File("src/test/data/freemarker-mojo/data");
+ private static final File SOURCE_DIR_WITH_FREEMARKER_PROPS = new
File("src/test/data/freemarker-mojo");
+ private static final File TEMPLATE_DIR = new
File("src/test/data/freemarker-mojo/template");
+
+ @Test
+ public void shouldCreateConfiguration() {
+ final Configuration configuration = configuration(FREEMARKER_VERSION,
TEMPLATE_DIR, SOURCE_DIR);
+
+ assertThat(configuration.getDefaultEncoding()).isEqualTo("UTF-8");
+ assertThat(configuration.getBooleanFormat()).isEqualTo("true,false");
+ }
+
+ @Test
+ public void shouldCreateConfigurationUsingFreeMarkerPropertiesFile() {
+ final Configuration configuration = configuration(FREEMARKER_VERSION,
TEMPLATE_DIR, SOURCE_DIR_WITH_FREEMARKER_PROPS);
+
+ assertThat(configuration.getDefaultEncoding()).isEqualTo("UTF-8");
+ assertThat(configuration.getBooleanFormat()).isEqualTo("T,F");
+ }
+
+ private static Configuration configuration(String freeMarkerVersion, File
templateDirectory, File sourceDirectory) {
+ return new ConfigurationSupplier(freeMarkerVersion, templateDirectory,
sourceDirectory).get();
+ }
+}
diff --git
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/FreeMarkerMojoTest.java
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/FreeMarkerMojoTest.java
index 9ac1734..b8f8fed 100644
---
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/FreeMarkerMojoTest.java
+++
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/FreeMarkerMojoTest.java
@@ -16,346 +16,166 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
-import freemarker.cache.FileTemplateLoader;
-import freemarker.cache.TemplateLoader;
-import freemarker.template.Configuration;
-import mockit.Deencapsulation;
-import mockit.Expectations;
-import mockit.Mocked;
-import mockit.Verifications;
+import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.freemarker.generator.base.util.OperatingSystem;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.junit.Assert;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
+import org.junit.BeforeClass;
+import org.junit.Test;
import java.io.File;
import java.io.IOException;
-import java.nio.file.FileVisitor;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Comparator;
-import java.util.Map;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Properties;
import static org.assertj.core.api.Assertions.*;
+import static org.mockito.Mockito.*;
public class FreeMarkerMojoTest extends Assert {
private static final File TEST_OUTPUT_DIR = new
File("target/test-output/freemarker-mojo");
- private static final String FREEMARKER_VERSION = "2.3.29";
+ private static final String FREEMARKER_VERSION = "2.3.30";
@BeforeClass
public static void beforeClass() throws IOException {
- // Clean output dir before each run.
- if (TEST_OUTPUT_DIR.exists()) {
- // Recursively delete output from previous run.
- Files.walk(TEST_OUTPUT_DIR.toPath())
- .sorted(Comparator.reverseOrder())
- .map(Path::toFile)
- .forEach(File::delete);
- }
+ UnitTestHelper.deleteTestOutputDir(TEST_OUTPUT_DIR);
}
@Test
- public void executeTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked MojoExecution mojoExecution,
- @Mocked GeneratingFileVisitor generatingFileVisitor,
- @Mocked Files files
- ) throws MojoExecutionException, MojoFailureException, IOException {
-
- new Expectations(mojoExecution, generatingFileVisitor) {{
- mojoExecution.getLifecyclePhase();
- result = "generate-sources";
- session.getCurrentProject();
- result = project;
- }};
-
- FreeMarkerMojo mojo = new FreeMarkerMojo();
-
- // Validate freeMarkerVersion is required.
- assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(()
-> {
- mojo.execute();
- }).withMessage("freeMarkerVersion is required");
+ public void execute_generateSourceTest() throws MojoExecutionException,
IOException, IllegalAccessException {
- Deencapsulation.setField(mojo, "freeMarkerVersion", "");
- assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(()
-> {
- mojo.execute();
- }).withMessage("freeMarkerVersion is required");
+ final File mockFile = mock(File.class);
+ final MavenSession session = mock(MavenSession.class);
+ final MavenProject project = mock(MavenProject.class);
+ final MojoExecution mojoExecution = mock(MojoExecution.class);
- final File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"executeTest");
- Deencapsulation.setField(mojo, "freeMarkerVersion",
FREEMARKER_VERSION);
- Deencapsulation.setField(mojo, "sourceDirectory", testCaseOutputDir);
- Deencapsulation.setField(mojo, "templateDirectory", new
File(testCaseOutputDir, "template"));
- Deencapsulation.setField(mojo, "generatorDirectory", new
File(testCaseOutputDir, "data"));
- Deencapsulation.setField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"));
- Deencapsulation.setField(mojo, "mojo", mojoExecution);
- Deencapsulation.setField(mojo, "session", session);
+ final List<MavenProject> projects = new ArrayList<>();
+ projects.add(project);
- // Validate source directory.
- assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(()
-> {
- mojo.execute();
- })
- .withMessageStartingWith("Required directory does not exist");
-
- new File(testCaseOutputDir, "data").mkdirs();
- assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(()
-> {
- mojo.execute();
- })
- .withMessageStartingWith("Required directory does not exist");
- new File(testCaseOutputDir, "template").mkdirs();
+ when(session.getAllProjects()).thenReturn(projects);
+ when(session.getCurrentProject()).thenReturn(project);
+ when(session.getCurrentProject().getProperties()).thenReturn(new
Properties());
+ when(project.getFile()).thenReturn(mockFile);
+ when(mockFile.lastModified()).thenReturn(10L);
+ when(mojoExecution.getLifecyclePhase()).thenReturn("generate-sources");
- // Validate minimum configuration.
- mojo.execute();
-
- new Verifications() {{
-
project.addCompileSourceRoot(fixSeparators("target/test-output/freemarker-mojo/executeTest/generated-files"));
- times = 1;
-
- Configuration config;
- MavenSession capturedSession;
- Map<String, OutputGeneratorPropertiesProvider> builders;
-
- GeneratingFileVisitor.create(
- config = withCapture(),
- capturedSession = withCapture(),
- builders = withCapture());
- times = 1;
+ final FreeMarkerMojo mojo = new FreeMarkerMojo();
+ final File sourceDirectory = new File("src/test/data/freemarker-mojo");
+ final File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"executeTest");
- assertEquals("UTF-8", config.getDefaultEncoding());
- assertEquals(session, capturedSession);
- TemplateLoader loader = config.getTemplateLoader();
- assertTrue(loader instanceof FileTemplateLoader);
+ FieldUtils.writeField(mojo, "freeMarkerVersion", "", true);
+ FieldUtils.writeField(mojo, "freeMarkerVersion", FREEMARKER_VERSION,
true);
+ FieldUtils.writeField(mojo, "sourceDirectory", sourceDirectory, true);
+ FieldUtils.writeField(mojo, "templateDirectory", new
File(testCaseOutputDir, "template"), true);
+ FieldUtils.writeField(mojo, "generatorDirectory", new
File(testCaseOutputDir, "data"), true);
+ FieldUtils.writeField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"), true);
+ FieldUtils.writeField(mojo, "mojo", mojoExecution, true);
+ FieldUtils.writeField(mojo, "session", session, true);
- Path path;
- FileVisitor<Path> fileVisitor;
+ FileUtils.forceMkdir(new File(testCaseOutputDir, "data"));
+ FileUtils.forceMkdir(new File(testCaseOutputDir, "template"));
- Files.walkFileTree(path = withCapture(), fileVisitor =
withCapture());
- times = 1;
+ mojo.execute();
- assertEquals(new File(testCaseOutputDir, "data").toPath(), path);
- assertTrue(fileVisitor instanceof GeneratingFileVisitor);
- }};
+
verify(project).addCompileSourceRoot(fixSeparators("target/test-output/freemarker-mojo/executeTest/generated-files"));
+ verify(project, times(0)).addTestCompileSourceRoot(anyString());
}
@Test
- public void execute_generateTestSourceTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked MojoExecution mojoExecution,
- @Mocked GeneratingFileVisitor generatingFileVisitor,
- @Mocked Files files
- ) throws MojoExecutionException, MojoFailureException, IOException {
-
- new Expectations(mojoExecution, generatingFileVisitor) {{
- mojoExecution.getLifecyclePhase();
- result = "generate-test-sources";
- session.getCurrentProject();
- result = project;
- }};
-
- FreeMarkerMojo mojo = new FreeMarkerMojo();
-
- File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"generateTestSourceTest");
- Deencapsulation.setField(mojo, "freeMarkerVersion",
FREEMARKER_VERSION);
- Deencapsulation.setField(mojo, "sourceDirectory", testCaseOutputDir);
- Deencapsulation.setField(mojo, "templateDirectory", new
File(testCaseOutputDir, "template"));
- Deencapsulation.setField(mojo, "generatorDirectory", new
File(testCaseOutputDir, "data"));
- Deencapsulation.setField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"));
- Deencapsulation.setField(mojo, "mojo", mojoExecution);
- Deencapsulation.setField(mojo, "session", session);
-
- new File(testCaseOutputDir, "data").mkdirs();
- new File(testCaseOutputDir, "template").mkdirs();
+ public void execute_generateTestSourceTest() throws
MojoExecutionException, IOException, IllegalAccessException {
+
+ final File mockFile = mock(File.class);
+ final MavenSession session = mock(MavenSession.class);
+ final MavenProject project = mock(MavenProject.class);
+ final MojoExecution mojoExecution = mock(MojoExecution.class);
+
+ final List<MavenProject> projects = new ArrayList<>();
+ projects.add(project);
+
+ when(session.getAllProjects()).thenReturn(projects);
+ when(session.getCurrentProject()).thenReturn(project);
+ when(session.getCurrentProject().getProperties()).thenReturn(new
Properties());
+ when(project.getFile()).thenReturn(mockFile);
+ when(mockFile.lastModified()).thenReturn(10L);
+
when(mojoExecution.getLifecyclePhase()).thenReturn("generate-test-sources");
+
+ final FreeMarkerMojo mojo = new FreeMarkerMojo();
+ final File sourceDirectory = new File("src/test/data/freemarker-mojo");
+ final File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"generateTestSourceTest");
+
+ FieldUtils.writeField(mojo, "freeMarkerVersion", "", true);
+ FieldUtils.writeField(mojo, "freeMarkerVersion", FREEMARKER_VERSION,
true);
+ FieldUtils.writeField(mojo, "sourceDirectory", sourceDirectory, true);
+ FieldUtils.writeField(mojo, "templateDirectory", new
File(testCaseOutputDir, "template"), true);
+ FieldUtils.writeField(mojo, "generatorDirectory", new
File(testCaseOutputDir, "data"), true);
+ FieldUtils.writeField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"), true);
+ FieldUtils.writeField(mojo, "mojo", mojoExecution, true);
+ FieldUtils.writeField(mojo, "session", session, true);
+
+ FileUtils.forceMkdir(new File(testCaseOutputDir, "data"));
+ FileUtils.forceMkdir(new File(testCaseOutputDir, "template"));
mojo.execute();
- new Verifications() {{
-
project.addTestCompileSourceRoot(fixSeparators("target/test-output/freemarker-mojo/generateTestSourceTest/generated-files"));
- times = 1;
- }};
+ verify(project, times(0)).addCompileSourceRoot(anyString());
+
verify(project).addTestCompileSourceRoot(fixSeparators("target/test-output/freemarker-mojo/generateTestSourceTest/generated-files"));
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void execute_walkFileTreeExceptionTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked MojoExecution mojoExecution,
- @Mocked GeneratingFileVisitor generatingFileVisitor,
- @Mocked Files files
- ) throws MojoExecutionException, MojoFailureException, IOException {
-
- new Expectations(mojoExecution, generatingFileVisitor) {{
- mojoExecution.getLifecyclePhase();
- result = "generate-test-sources";
- session.getCurrentProject();
- result = project;
- Files.walkFileTree((Path) any, (FileVisitor) any);
- result = new RuntimeException("test exception");
- }};
-
- FreeMarkerMojo mojo = new FreeMarkerMojo();
-
- File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"generateTestSourceTest");
- Deencapsulation.setField(mojo, "freeMarkerVersion",
FREEMARKER_VERSION);
- Deencapsulation.setField(mojo, "sourceDirectory", testCaseOutputDir);
- Deencapsulation.setField(mojo, "templateDirectory", new
File(testCaseOutputDir, "template"));
- Deencapsulation.setField(mojo, "generatorDirectory", new
File(testCaseOutputDir, "data"));
- Deencapsulation.setField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"));
- Deencapsulation.setField(mojo, "mojo", mojoExecution);
- Deencapsulation.setField(mojo, "session", session);
-
- new File(testCaseOutputDir, "data").mkdirs();
- new File(testCaseOutputDir, "template").mkdirs();
-
- assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(()
-> {
- mojo.execute();
- })
- .withMessageStartingWith("Failed to process files in generator
dir");
- }
+ public void execute_checkPluginParametersTest()
+ throws MojoExecutionException, IOException, IllegalAccessException
{
- @Test
- public void execute_setTemplateLoaderExceptionTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked MojoExecution mojoExecution,
- @Mocked FactoryUtil factoryUtil,
- @Mocked Configuration config) {
-
- new Expectations(config, FactoryUtil.class) {{
- FactoryUtil.createConfiguration(FREEMARKER_VERSION);
- result = config;
- config.setTemplateLoader((TemplateLoader) any);
- result = new RuntimeException("test exception");
- }};
-
- FreeMarkerMojo mojo = new FreeMarkerMojo();
-
- File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"setTemplateLoaderException");
-
- Deencapsulation.setField(mojo, "freeMarkerVersion",
FREEMARKER_VERSION);
- Deencapsulation.setField(mojo, "sourceDirectory", testCaseOutputDir);
- Deencapsulation.setField(mojo, "templateDirectory", new
File(testCaseOutputDir, "template"));
- Deencapsulation.setField(mojo, "generatorDirectory", new
File(testCaseOutputDir, "data"));
- Deencapsulation.setField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"));
- Deencapsulation.setField(mojo, "mojo", mojoExecution);
- Deencapsulation.setField(mojo, "session", session);
-
- new File(testCaseOutputDir, "data").mkdirs();
- new File(testCaseOutputDir, "template").mkdirs();
-
- assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(()
-> {
- mojo.execute();
- })
- .withMessageStartingWith("Could not establish file template
loader for directory");
- }
+ UnitTestHelper.deleteTestOutputDir(TEST_OUTPUT_DIR);
- @Test
- public void execute_loadFreemarkerPropertiesTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked MojoExecution mojoExecution,
- @Mocked Configuration config) throws Exception {
+ final MavenSession session = mock(MavenSession.class);
+ final MojoExecution mojoExecution = mock(MojoExecution.class);
+ final FreeMarkerMojo mojo = new FreeMarkerMojo();
- FreeMarkerMojo mojo = new FreeMarkerMojo();
+ // Validate freeMarkerVersion is required.
- File sourceDirectory = new File("src/test/data/freemarker-mojo");
- File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"loadFreemarkerProperties");
+ FieldUtils.writeField(mojo, "freeMarkerVersion", null, true);
+ assertThatExceptionOfType(MojoExecutionException.class)
+ .isThrownBy(mojo::execute)
+ .withMessage("freeMarkerVersion is required");
- Deencapsulation.setField(mojo, "freeMarkerVersion",
FREEMARKER_VERSION);
- Deencapsulation.setField(mojo, "sourceDirectory", sourceDirectory);
- Deencapsulation.setField(mojo, "templateDirectory", new
File(sourceDirectory, "template"));
- Deencapsulation.setField(mojo, "generatorDirectory", new
File(sourceDirectory, "data"));
- Deencapsulation.setField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"));
- Deencapsulation.setField(mojo, "mojo", mojoExecution);
- Deencapsulation.setField(mojo, "session", session);
+ FieldUtils.writeField(mojo, "freeMarkerVersion", "", true);
+ assertThatExceptionOfType(MojoExecutionException.class)
+ .isThrownBy(mojo::execute)
+ .withMessage("freeMarkerVersion is required");
- mojo.execute();
+ final File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"executeTest");
+ FieldUtils.writeField(mojo, "freeMarkerVersion", FREEMARKER_VERSION,
true);
+ FieldUtils.writeField(mojo, "sourceDirectory", testCaseOutputDir,
true);
+ FieldUtils.writeField(mojo, "templateDirectory", new
File(testCaseOutputDir, "template"), true);
+ FieldUtils.writeField(mojo, "generatorDirectory", new
File(testCaseOutputDir, "data"), true);
+ FieldUtils.writeField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"), true);
+ FieldUtils.writeField(mojo, "mojo", mojoExecution, true);
+ FieldUtils.writeField(mojo, "session", session, true);
- new Verifications() {{
- Properties properties;
+ // Validate source directory.
- config.setSettings(properties = withCapture());
- times = 1;
+ assertThatExceptionOfType(MojoExecutionException.class)
+ .isThrownBy(mojo::execute)
+ .withMessageStartingWith("Required generator directory does
not exist");
- assertEquals("T,F", properties.getProperty("boolean_format"));
- }};
- }
+ FileUtils.forceMkdir(new File(testCaseOutputDir, "data"));
+ assertThatExceptionOfType(MojoExecutionException.class)
+ .isThrownBy(mojo::execute)
+ .withMessageStartingWith("Required template directory does not
exist");
- @Test
- public void execute_loadFreemarkerPropertiesExceptionTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked MojoExecution mojoExecution,
- @Mocked FactoryUtil factoryUtil,
- @Mocked Configuration config) throws Exception {
-
- new Expectations(FactoryUtil.class) {{
- FactoryUtil.createFileInputStream((File) any);
- result = new RuntimeException("test exception");
- }};
-
- FreeMarkerMojo mojo = new FreeMarkerMojo();
-
- File sourceDirectory = new File("src/test/data/freemarker-mojo");
- File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"loadFreemarkerPropertiesExceptionTest");
-
- Deencapsulation.setField(mojo, "freeMarkerVersion",
FREEMARKER_VERSION);
- Deencapsulation.setField(mojo, "sourceDirectory", sourceDirectory);
- Deencapsulation.setField(mojo, "templateDirectory", new
File(sourceDirectory, "template"));
- Deencapsulation.setField(mojo, "generatorDirectory", new
File(sourceDirectory, "data"));
- Deencapsulation.setField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"));
- Deencapsulation.setField(mojo, "mojo", mojoExecution);
- Deencapsulation.setField(mojo, "session", session);
-
- System.out.println("==== before mojo execute");
- try {
-
assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
- mojo.execute();
- }).withMessage(fixSeparators("Failed to load
src/test/data/freemarker-mojo/freemarker.properties"));
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
+ FileUtils.forceMkdir(new File(testCaseOutputDir, "template"));
- @Test
- public void execute_setSettingsExceptionTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked MojoExecution mojoExecution,
- @Mocked Configuration config) throws Exception {
-
- new Expectations() {{
- config.setSettings((Properties) any);
- result = new RuntimeException("test exception");
- }};
-
- FreeMarkerMojo mojo = new FreeMarkerMojo();
-
- File sourceDirectory = new File("src/test/data/freemarker-mojo");
- File testCaseOutputDir = new File(TEST_OUTPUT_DIR,
"loadFreemarkerProperties");
-
- Deencapsulation.setField(mojo, "freeMarkerVersion",
FREEMARKER_VERSION);
- Deencapsulation.setField(mojo, "sourceDirectory", sourceDirectory);
- Deencapsulation.setField(mojo, "templateDirectory", new
File(sourceDirectory, "template"));
- Deencapsulation.setField(mojo, "generatorDirectory", new
File(sourceDirectory, "data"));
- Deencapsulation.setField(mojo, "outputDirectory", new
File(testCaseOutputDir, "generated-files"));
- Deencapsulation.setField(mojo, "mojo", mojoExecution);
- Deencapsulation.setField(mojo, "session", session);
-
- assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(()
-> {
- mojo.execute();
- }).withMessage(fixSeparators("Invalid setting(s) in
src/test/data/freemarker-mojo/freemarker.properties"));
+ // Validate minimum configuration.
+
+ mojo.execute();
}
private static String fixSeparators(String str) {
diff --git
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/GeneratingFileVisitorTest.java
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/GeneratingFileVisitorTest.java
index d2c9803..2b33462 100644
---
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/GeneratingFileVisitorTest.java
+++
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/GeneratingFileVisitorTest.java
@@ -16,191 +16,156 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
-import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
-import mockit.Expectations;
-import mockit.Mocked;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.project.MavenProject;
import org.junit.Assert;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
+import org.junit.BeforeClass;
+import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
-import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
-import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.assertj.core.api.Assertions.*;
+import static org.mockito.Mockito.*;
public class GeneratingFileVisitorTest extends Assert {
- private static File testDir = new
File("src/test/data/generating-file-visitor");
- private static File dataDir = new File(testDir, "data");
- private static File templateDir = new File(testDir, "template");
- private static File outputDir = new
File("target/test-output/generating-file-visitor");
- private static Map<String, OutputGeneratorPropertiesProvider> builders =
new HashMap<>();
- private Configuration config;
- private Properties pomProperties = new Properties();
+ private static final File TEST_DIR = new
File("src/test/data/generating-file-visitor");
+ private static final File DATA_DIR = new File(TEST_DIR, "data");
+ private static final File TEMPLATE_DIR = new File(TEST_DIR, "template");
+ private static final File OUTPUT_DIR = new
File("target/test-output/generating-file-visitor");
+ private static final Map<String, OutputGeneratorPropertiesProvider>
BUILDERS = new HashMap<>();
+ private final Configuration config;
+ private final Properties pomProperties = new Properties();
@BeforeClass
- public static void beforeClass() throws IOException {
- builders.put(".json", JsonPropertiesProvider.create(dataDir,
templateDir, outputDir));
- // Clean output dir before each run.
- File outputDir = new
File("target/test-output/generating-file-visitor");
- if (outputDir.exists()) {
- // Recursively delete output from previous run.
- Files.walk(outputDir.toPath())
- .sorted(Comparator.reverseOrder())
- .map(Path::toFile)
- .forEach(File::delete);
- }
+ public static void beforeClass() {
+ UnitTestHelper.checkTestDir(TEST_DIR);
+ UnitTestHelper.deleteTestOutputDir(OUTPUT_DIR);
+ BUILDERS.put(".json", JsonPropertiesProvider.create(DATA_DIR,
TEMPLATE_DIR, OUTPUT_DIR));
}
- @BeforeMethod
- public void before() throws IOException {
- if (!testDir.isDirectory()) {
- throw new RuntimeException("Can't find required test data
directory. "
- + "If running test outside of maven, make sure working
directory is the project directory. "
- + "Looking for: " + testDir);
- }
-
- config = new Configuration(Configuration.VERSION_2_3_23);
- config.setDefaultEncoding("UTF-8");
- config.setTemplateLoader(new FileTemplateLoader(templateDir));
+ public GeneratingFileVisitorTest() {
+ config = UnitTestHelper.configuration(TEMPLATE_DIR);
pomProperties.put("pomVar", "pom value");
}
@Test
- public void functionalHappyPathTestNoDataModel(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked File mockFile,
- @Mocked BasicFileAttributes attrs) throws IOException {
- List<MavenProject> projects = new ArrayList<>();
+ public void functionalHappyPathTestNoDataModel() throws IOException {
+
+ final MavenSession session = mock(MavenSession.class);
+ final MavenProject project = mock(MavenProject.class);
+ final File mockFile = mock(File.class);
+ final BasicFileAttributes attrs = mock(BasicFileAttributes.class);
+ final List<MavenProject> projects = new ArrayList<>();
projects.add(project);
- new Expectations(session, project, mockFile) {{
- session.getCurrentProject();
- result = project;
- session.getAllProjects();
- result = projects;
- project.getProperties();
- result = pomProperties;
- attrs.isRegularFile();
- result = true;
- project.getFile();
- result = mockFile;
- mockFile.lastModified();
- result = 10;
- }};
-
- File file = new File(dataDir, "mydir/success-test-2.txt.json");
- GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config,
session, builders);
+
+ when(session.getCurrentProject()).thenReturn(project);
+ when(session.getAllProjects()).thenReturn(projects);
+ when(project.getProperties()).thenReturn(pomProperties);
+ when(attrs.isRegularFile()).thenReturn(true);
+ when(project.getFile()).thenReturn(mockFile);
+ when(mockFile.lastModified()).thenReturn(10L);
+
+ final File file = new File(DATA_DIR, "mydir/success-test-2.txt.json");
+ final GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config,
session, BUILDERS);
+
assertEquals(FileVisitResult.CONTINUE, gfv.visitFile(file.toPath(),
attrs));
- File outputFile = new File(outputDir, "mydir/success-test-2.txt");
+ final File outputFile = new File(OUTPUT_DIR,
"mydir/success-test-2.txt");
+
assertTrue(outputFile.isFile());
- List<String> lines = Files.readAllLines(outputFile.toPath(),
StandardCharsets.UTF_8);
+
+ final List<String> lines = Files.readAllLines(outputFile.toPath(),
StandardCharsets.UTF_8);
assertEquals(17, lines.size());
assertEquals("This is a test freemarker template. Test pom data: 'pom
value'.", lines.get(16));
}
@Test
- public void functionalHappyPathTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked File mockFile,
- @Mocked BasicFileAttributes attrs) throws IOException {
- List<MavenProject> projects = new ArrayList<>();
+ public void functionalHappyPathTest() throws IOException {
+
+ final MavenSession session = mock(MavenSession.class);
+ final MavenProject project = mock(MavenProject.class);
+ final File mockFile = mock(File.class);
+ final BasicFileAttributes attrs = mock(BasicFileAttributes.class);
+ final List<MavenProject> projects = new ArrayList<>();
projects.add(project);
- new Expectations(session, project, mockFile) {{
- session.getCurrentProject();
- result = project;
- session.getAllProjects();
- result = projects;
- project.getProperties();
- result = pomProperties;
- attrs.isRegularFile();
- result = true;
- project.getFile();
- result = mockFile;
- mockFile.lastModified();
- result = 10;
- }};
-
- File file = new File(dataDir, "mydir/success-test.txt.json");
- GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config,
session, builders);
+
+ when(session.getCurrentProject()).thenReturn(project);
+ when(session.getAllProjects()).thenReturn(projects);
+ when(project.getProperties()).thenReturn(pomProperties);
+ when(attrs.isRegularFile()).thenReturn(true);
+ when(project.getFile()).thenReturn(mockFile);
+ when(mockFile.lastModified()).thenReturn(10L);
+
+ final File file = new File(DATA_DIR, "mydir/success-test.txt.json");
+ final GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config,
session, BUILDERS);
assertEquals(FileVisitResult.CONTINUE, gfv.visitFile(file.toPath(),
attrs));
- File outputFile = new File(outputDir, "mydir/success-test.txt");
+ final File outputFile = new File(OUTPUT_DIR, "mydir/success-test.txt");
assertTrue(outputFile.isFile());
- List<String> lines = Files.readAllLines(outputFile.toPath(),
StandardCharsets.UTF_8);
+
+ final List<String> lines = Files.readAllLines(outputFile.toPath(),
StandardCharsets.UTF_8);
assertEquals(17, lines.size());
assertEquals("This is a test freemarker template. Test json data:
'test value'. Test pom data: 'pom value'.", lines
.get(16));
}
@Test
- public void visitFile_badExtensionTest(
- @Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked File mockFile,
- @Mocked BasicFileAttributes attrs) throws IOException {
- List<MavenProject> projects = new ArrayList<>();
+ public void visitFile_badExtensionTest() {
+
+ final MavenSession session = mock(MavenSession.class);
+ final MavenProject project = mock(MavenProject.class);
+ final File mockFile = mock(File.class);
+ final BasicFileAttributes attrs = mock(BasicFileAttributes.class);
+ final List<MavenProject> projects = new ArrayList<>();
projects.add(project);
- new Expectations(session, project, mockFile) {{
- attrs.isRegularFile();
- result = true;
- session.getAllProjects();
- result = projects;
- project.getFile();
- result = mockFile;
- mockFile.lastModified();
- result = 10;
- }};
+
+ when(attrs.isRegularFile()).thenReturn(true);
+ when(session.getAllProjects()).thenReturn(projects);
+ when(project.getFile()).thenReturn(mockFile);
+ when(mockFile.lastModified()).thenReturn(10L);
+
// Test file without .json suffix.
- File file = new File(dataDir, "mydir/bad-extension-test.txt");
- GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config,
session, builders);
- assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
- gfv.visitFile(file.toPath(), attrs);
- }).withMessage("Unknown file extension: " + file.toPath());
+ final File file = new File(DATA_DIR, "mydir/bad-extension-test.txt");
+ final GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config,
session, BUILDERS);
+ assertThatExceptionOfType(RuntimeException.class)
+ .isThrownBy(() -> gfv.visitFile(file.toPath(), attrs))
+ .withMessage("Unknown file extension: " + file.toPath());
}
@Test
- public void visitFile_notRegularFileTest(@Mocked MavenSession session,
- @Mocked MavenProject project,
- @Mocked BasicFileAttributes attrs,
- @Mocked File mockFile
- ) {
- List<MavenProject> projects = new ArrayList<>();
+ public void visitFile_notRegularFileTest() {
+
+ final MavenSession session = mock(MavenSession.class);
+ final MavenProject project = mock(MavenProject.class);
+ final File mockFile = mock(File.class);
+ final BasicFileAttributes attrs = mock(BasicFileAttributes.class);
+ final List<MavenProject> projects = new ArrayList<>();
projects.add(project);
- new Expectations(session, project, mockFile) {{
- attrs.isRegularFile();
- result = false;
- session.getAllProjects();
- result = projects;
- project.getFile();
- result = mockFile;
- mockFile.lastModified();
- result = 10;
- }};
+
+ when(attrs.isRegularFile()).thenReturn(false);
+ when(session.getAllProjects()).thenReturn(projects);
+ when(project.getFile()).thenReturn(mockFile);
+ when(mockFile.lastModified()).thenReturn(10L);
+
// FYI: if you change above result to true, test will fail trying to
read the 'mydir' directory
// as a json file.
- File dir = new File(dataDir, "mydir");
- GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config,
session, builders);
+ final File dir = new File(DATA_DIR, "mydir");
+ final GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config,
session, BUILDERS);
+
assertEquals(FileVisitResult.CONTINUE, gfv.visitFile(dir.toPath(),
attrs));
}
}
diff --git
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/JsonPropertiesProviderTest.java
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/JsonPropertiesProviderTest.java
index bef999e..bbf481a 100644
---
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/JsonPropertiesProviderTest.java
+++
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/JsonPropertiesProviderTest.java
@@ -16,109 +16,95 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
-import com.google.gson.Gson;
-import com.google.gson.stream.JsonReader;
-import mockit.Expectations;
-import mockit.Mocked;
-import mockit.Verifications;
-import org.testng.annotations.Test;
+import
org.apache.freemarker.generator.maven.OutputGenerator.OutputGeneratorBuilder;
+import org.junit.Test;
import java.io.File;
-import java.lang.reflect.Type;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.AssertionsForClassTypes.*;
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.*;
public class JsonPropertiesProviderTest {
- private File testDir = new File("src/test/data/generating-file-visitor");
- private File dataDir = new File(testDir, "data");
- private File templateDir = new File(testDir, "template");
- private File outputDir = new
File("target/test-output/generating-file-visitor");
+ private final File testDir = new
File("src/test/data/generating-file-visitor");
+ private final File dataDir = new File(testDir, "data");
+ private final File templateDir = new File(testDir, "template");
+ private final File outputDir = new
File("target/test-output/generating-file-visitor");
@Test
- public void testSuccess(@Mocked OutputGenerator.OutputGeneratorBuilder
builder) {
- Path path = dataDir.toPath().resolve("mydir/success-test.txt.json");
- Path expectedTemplateLocation =
templateDir.toPath().resolve("test.ftl");
- Path expectedOutputLocation =
outputDir.toPath().resolve("mydir/success-test.txt");
- Map<String, Object> expectedMap = new HashMap<>(4);
+ public void testSuccess() {
+ final OutputGeneratorBuilder builder = OutputGenerator.builder();
+ builder.addPomLastModifiedTimestamp(10L);
+ builder.addGeneratorLocation(outputDir.toPath());
+ final Path path =
dataDir.toPath().resolve("mydir/success-test.txt.json");
+ final Path expectedTemplateLocation =
templateDir.toPath().resolve("test.ftl");
+ final Path expectedOutputLocation =
outputDir.toPath().resolve("mydir/success-test.txt");
+ final Map<String, Object> expectedMap = new HashMap<>(4);
expectedMap.put("testVar", "test value");
- JsonPropertiesProvider toTest = JsonPropertiesProvider.create(dataDir,
templateDir, outputDir);
+ final JsonPropertiesProvider toTest =
JsonPropertiesProvider.create(dataDir, templateDir, outputDir);
toTest.providePropertiesFromFile(path, builder);
- new Verifications() {{
- Path templateLocation;
- builder.addTemplateLocation(templateLocation = withCapture());
- Path outputLocation;
- builder.addOutputLocation(outputLocation = withCapture());
- Map<String, Object> actualMap;
- builder.addDataModel(actualMap = withCapture());
- assertEquals(expectedTemplateLocation, templateLocation);
- assertEquals(expectedOutputLocation, outputLocation);
- assertArrayEquals(expectedMap.entrySet().toArray(),
actualMap.entrySet().toArray());
- }};
+ final OutputGenerator outputGenerator = builder.create();
+
+ assertEquals(expectedTemplateLocation,
outputGenerator.templateLocation);
+ assertEquals(expectedOutputLocation, outputGenerator.outputLocation);
+ assertArrayEquals(expectedMap.entrySet().toArray(),
outputGenerator.dataModel.entrySet().toArray());
}
@Test
- public void testSuccessNoDataModel(@Mocked
OutputGenerator.OutputGeneratorBuilder builder) {
- Path path = dataDir.toPath().resolve("mydir/success-test-2.txt.json");
- Path expectedTemplateLocation =
templateDir.toPath().resolve("test-pom-only.ftl");
- Path expectedOutputLocation =
outputDir.toPath().resolve("mydir/success-test-2.txt");
- Map<String, Object> expectedMap = new HashMap<>(4);
- JsonPropertiesProvider toTest = JsonPropertiesProvider.create(dataDir,
templateDir, outputDir);
+ public void testSuccessNoDataModel() {
+ final OutputGeneratorBuilder builder = OutputGenerator.builder();
+ builder.addPomLastModifiedTimestamp(10L);
+ builder.addGeneratorLocation(outputDir.toPath());
+ final Path path =
dataDir.toPath().resolve("mydir/success-test-2.txt.json");
+ final Path expectedTemplateLocation =
templateDir.toPath().resolve("test-pom-only.ftl");
+ final Path expectedOutputLocation =
outputDir.toPath().resolve("mydir/success-test-2.txt");
+ final Map<String, Object> expectedMap = new HashMap<>(4);
+ final JsonPropertiesProvider toTest =
JsonPropertiesProvider.create(dataDir, templateDir, outputDir);
toTest.providePropertiesFromFile(path, builder);
- new Verifications() {{
- Path templateLocation;
- builder.addTemplateLocation(templateLocation = withCapture());
- Path outputLocation;
- builder.addOutputLocation(outputLocation = withCapture());
- Map<String, Object> actualMap;
- builder.addDataModel(actualMap = withCapture());
- assertEquals(expectedTemplateLocation, templateLocation);
- assertEquals(expectedOutputLocation, outputLocation);
- assertArrayEquals(expectedMap.entrySet().toArray(),
actualMap.entrySet().toArray());
- }};
+ final OutputGenerator outputGenerator = builder.create();
+
+ assertEquals(expectedTemplateLocation,
outputGenerator.templateLocation);
+ assertEquals(expectedOutputLocation, outputGenerator.outputLocation);
+ assertArrayEquals(expectedMap.entrySet().toArray(),
outputGenerator.dataModel.entrySet().toArray());
}
@Test
- public void testParsingException(@Mocked
OutputGenerator.OutputGeneratorBuilder builder, @Mocked Gson gson) {
- Path path = dataDir.toPath().resolve("mydir/success-test.txt.json");
- new Expectations() {{
- gson.fromJson((JsonReader) any, (Type) any);
- result = new RuntimeException("test exception");
- }};
- JsonPropertiesProvider toTest = JsonPropertiesProvider.create(dataDir,
templateDir, outputDir);
+ public void testParsingException() {
+ final OutputGeneratorBuilder builder =
mock(OutputGeneratorBuilder.class);
+ final Path path = dataDir.toPath().resolve("mydir/invalid-json.json");
+ final JsonPropertiesProvider toTest =
JsonPropertiesProvider.create(dataDir, templateDir, outputDir);
- assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
- toTest.providePropertiesFromFile(path, builder);
- })
+ assertThatExceptionOfType(RuntimeException.class)
+ .isThrownBy(() -> toTest.providePropertiesFromFile(path,
builder))
.withMessageStartingWith("Could not parse json data file");
}
@Test
- public void testMissingTemplateName(@Mocked
OutputGenerator.OutputGeneratorBuilder builder) {
- Path path =
dataDir.toPath().resolve("mydir/missing-template-name.txt.json");
- JsonPropertiesProvider toTest = JsonPropertiesProvider.create(dataDir,
templateDir, outputDir);
+ public void testMissingTemplateName() {
+ final OutputGeneratorBuilder builder =
mock(OutputGeneratorBuilder.class);
+ final Path path =
dataDir.toPath().resolve("mydir/missing-template-name.txt.json");
+ final JsonPropertiesProvider toTest =
JsonPropertiesProvider.create(dataDir, templateDir, outputDir);
- assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
- toTest.providePropertiesFromFile(path, builder);
- }).withMessage("Require json data property not found: templateName");
+ assertThatExceptionOfType(RuntimeException.class)
+ .isThrownBy(() -> toTest.providePropertiesFromFile(path,
builder))
+ .withMessage("Require json data property not found:
templateName");
}
@Test
- public void testBadPath(@Mocked OutputGenerator.OutputGeneratorBuilder
builder) {
- Path path = testDir.toPath().resolve("badPath/success-test.txt.json");
- JsonPropertiesProvider toTest = JsonPropertiesProvider.create(dataDir,
templateDir, outputDir);
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- toTest.providePropertiesFromFile(path, builder);
- })
+ public void testBadPath() {
+ final OutputGeneratorBuilder builder =
mock(OutputGeneratorBuilder.class);
+ final Path path =
testDir.toPath().resolve("badPath/success-test.txt.json");
+ final JsonPropertiesProvider toTest =
JsonPropertiesProvider.create(dataDir, templateDir, outputDir);
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(() -> toTest.providePropertiesFromFile(path,
builder))
.withMessageStartingWith("visitFile() given file not in
sourceDirectory");
}
}
diff --git
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/OperatingSystem.java
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/OperatingSystem.java
deleted file mode 100644
index 4575238..0000000
---
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/OperatingSystem.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.freemarker.generator.maven;
-
-import java.util.Locale;
-
-/**
- * Helper class to detect the operting system (mostly Windows).
- *
- * TODO should be moved to "freemarker-generator-base"
- */
-public class OperatingSystem {
- private static final String OS = System.getProperty("os.name",
"unknown").toLowerCase(Locale.ROOT);
-
- public static boolean isWindows() {
- return OS.contains("win");
- }
-
- public static boolean isMac() {
- return OS.contains("mac");
- }
-
- public static boolean isUnix() {
- return OS.contains("nux");
- }
-}
diff --git
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/OutputGeneratorTest.java
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/OutputGeneratorTest.java
index 11308bb..d577a83 100644
---
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/OutputGeneratorTest.java
+++
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/OutputGeneratorTest.java
@@ -16,110 +16,80 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.freemarker.generator.maven;
-import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
-import mockit.Expectations;
-import mockit.Mocked;
-import org.apache.commons.io.FilenameUtils;
import org.assertj.core.api.*;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
+import org.junit.BeforeClass;
+import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static junit.framework.Assert.assertEquals;
import static org.assertj.core.api.AssertionsForClassTypes.*;
import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class OutputGeneratorTest {
- private File testDir = new File("src/test/data/generating-file-visitor");
- private File dataDir = new File(testDir, "data");
- private File templateDir = new File(testDir, "template");
- private File outputDir = new
File("target/test-output/generating-file-visitor");
+ private static final File TEST_DIR = new
File("src/test/data/generating-file-visitor");
+ private static final File DATA_DIR = new File(TEST_DIR, "data");
+ private static final File TEMPLATE_DIR = new File(TEST_DIR, "template");
+ private static final File OUTPUT_DIR = new
File("target/test-output/generating-file-visitor");
+ private Map<String, Object> dataModel;
+
private Configuration config;
- private Map<String, Object> dataModel = new HashMap<String, Object>();
-
- @BeforeMethod
- public void setupDataModel() {
- dataModel.clear();
- dataModel.put("testVar", "test value");
- dataModel.put("pomProperties", new HashMap<String, String>());
- ((Map<String, String>) dataModel.get("pomProperties")).put("pomVar",
"pom value");
- }
@BeforeClass
- public static void cleanFields() throws IOException {
- // Clean output dir before each run.
- File outputDir = new
File("target/test-output/generating-file-visitor");
- if (outputDir.exists()) {
- // Recursively delete output from previous run.
- Files.walk(outputDir.toPath())
- .sorted(Comparator.reverseOrder())
- .map(Path::toFile)
- .forEach(File::delete);
- }
+ public static void beforeClass() throws IOException {
+ UnitTestHelper.checkTestDir(TEST_DIR);
+ UnitTestHelper.deleteTestOutputDir(OUTPUT_DIR);
}
- @BeforeMethod
- public void before() throws IOException {
- if (!testDir.isDirectory()) {
- throw new RuntimeException("Can't find required test data
directory. "
- + "If running test outside of maven, make sure working
directory is the project directory. "
- + "Looking for: " + testDir);
- }
-
- config = new Configuration(Configuration.VERSION_2_3_23);
- config.setDefaultEncoding("UTF-8");
- config.setTemplateLoader(new FileTemplateLoader(templateDir));
+ public OutputGeneratorTest() {
+ config = UnitTestHelper.configuration(TEMPLATE_DIR);
+ dataModel = dataModel();
}
@Test
public void createTest() {
- OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set the pomModifiedTimestamp");
+ final OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set the pomModifiedTimestamp");
builder.addPomLastModifiedTimestamp(0);
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set a non-null generatorLocation");
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set a non-null generatorLocation");
- File file = new File(dataDir, "mydir/success-test.txt.json");
- builder.addGeneratorLocation(file.toPath());
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set a non-null templateLocation");
+ final File file = new File(DATA_DIR, "mydir/success-test.txt.json");
+ builder.addGeneratorLocation(new File(DATA_DIR,
"mydir/success-test.txt.json").toPath());
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set a non-null templateLocation");
- File templateFile = new File(templateDir, "test.ftl");
+ final File templateFile = new File(TEMPLATE_DIR, "test.ftl");
builder.addTemplateLocation(templateFile.toPath());
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set a non-null outputLocation");
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set a non-null outputLocation");
- File outputFile = new File(outputDir, "mydir/success-test.txt");
+ final File outputFile = new File(OUTPUT_DIR, "mydir/success-test.txt");
builder.addOutputLocation(outputFile.toPath());
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set a non-null dataModel");
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set a non-null dataModel");
builder.addDataModel(dataModel);
- OutputGenerator generator = builder.create();
+ final OutputGenerator generator = builder.create();
assertEquals(0, generator.pomModifiedTimestamp);
assertEquals(file.toPath(), generator.generatorLocation);
@@ -131,34 +101,34 @@ public class OutputGeneratorTest {
@Test
public void addToDataModelTest() {
- OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set the pomModifiedTimestamp");
+ final OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set the pomModifiedTimestamp");
builder.addPomLastModifiedTimestamp(0);
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set a non-null generatorLocation");
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set a non-null generatorLocation");
- File file = new File(dataDir, "mydir/success-test.txt.json");
+ final File file = new File(DATA_DIR, "mydir/success-test.txt.json");
builder.addGeneratorLocation(file.toPath());
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set a non-null templateLocation");
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set a non-null templateLocation");
- File templateFile = new File(templateDir, "test.ftl");
+ final File templateFile = new File(TEMPLATE_DIR, "test.ftl");
builder.addTemplateLocation(templateFile.toPath());
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set a non-null outputLocation");
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set a non-null outputLocation");
- File outputFile = new File(outputDir, "mydir/success-test.txt");
+ final File outputFile = new File(OUTPUT_DIR, "mydir/success-test.txt");
builder.addOutputLocation(outputFile.toPath());
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(()
-> {
- builder.create();
- }).withMessage("Must set a non-null dataModel");
+ assertThatExceptionOfType(IllegalStateException.class)
+ .isThrownBy(builder::create)
+ .withMessage("Must set a non-null dataModel");
builder.addToDataModel("testVar", "testVal");
OutputGenerator generator = builder.create();
@@ -179,20 +149,20 @@ public class OutputGeneratorTest {
@Test
public void generate_SuccessTest()
throws IOException {
- OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
+ final OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
builder.addPomLastModifiedTimestamp(0);
- File file = new File(dataDir, "mydir/success-test.txt.json");
+ final File file = new File(DATA_DIR, "mydir/success-test.txt.json");
builder.addGeneratorLocation(file.toPath());
- File outputFile = new File(outputDir, "mydir/success-test.txt");
+ final File outputFile = new File(OUTPUT_DIR, "mydir/success-test.txt");
builder.addOutputLocation(outputFile.toPath());
- File templateFile = new File(templateDir, "test.ftl");
+ final File templateFile = new File(TEMPLATE_DIR, "test.ftl");
builder.addTemplateLocation(templateFile.toPath());
builder.addDataModel(dataModel);
- OutputGenerator generator = builder.create();
+ final OutputGenerator generator = builder.create();
generator.generate(config);
assertTrue(outputFile.isFile());
- List<String> lines = Files.readAllLines(outputFile.toPath(),
StandardCharsets.UTF_8);
+ final List<String> lines = Files.readAllLines(outputFile.toPath(),
StandardCharsets.UTF_8);
assertEquals(17, lines.size());
assertEquals("This is a test freemarker template. Test json data:
'test value'. Test pom data: 'pom value'.", lines
.get(16));
@@ -217,90 +187,68 @@ public class OutputGeneratorTest {
@Test
public void generate_badTemplateNameTest() {
- OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
+ final OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
builder.addPomLastModifiedTimestamp(0);
- File file = new File(dataDir, "mydir/bad-template-name.txt.json");
+ final File file = new File(DATA_DIR,
"mydir/bad-template-name.txt.json");
builder.addGeneratorLocation(file.toPath());
- File outputFile = new File(outputDir, "mydir/bad-template-name.txt");
+ final File outputFile = new File(OUTPUT_DIR,
"mydir/bad-template-name.txt");
builder.addOutputLocation(outputFile.toPath());
- File templateFile = new File(templateDir, "missing.ftl"); //this
doesn't exist
+ final File templateFile = new File(TEMPLATE_DIR, "missing.ftl");
//this doesn't exist
builder.addTemplateLocation(templateFile.toPath());
builder.addDataModel(dataModel);
- OutputGenerator generator = builder.create();
-
Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
- generator.generate(config);
- }).withMessage("Could not read template: missing.ftl");
+ final OutputGenerator generator = builder.create();
+
+ Assertions.assertThatExceptionOfType(RuntimeException.class)
+ .isThrownBy(() -> generator.generate(config))
+ .withMessage("Could not read template: missing.ftl");
}
@Test
public void generate_missingVarTest() {
- OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
+ final OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
builder.addPomLastModifiedTimestamp(0);
- File file = new File(dataDir, "mydir/missing-var-test.txt.json");
+ final File file = new File(DATA_DIR,
"mydir/missing-var-test.txt.json");
builder.addGeneratorLocation(file.toPath());
- File outputFile = new File(outputDir, "mydir/missing-var-test.txt");
+ final File outputFile = new File(OUTPUT_DIR,
"mydir/missing-var-test.txt");
builder.addOutputLocation(outputFile.toPath());
- File templateFile = new File(templateDir, "test.ftl"); //this is
missing a
+ final File templateFile = new File(TEMPLATE_DIR, "test.ftl"); //this
is missing a
builder.addTemplateLocation(templateFile.toPath());
dataModel.remove("testVar");
builder.addDataModel(dataModel);
- OutputGenerator generator = builder.create();
+ final OutputGenerator generator = builder.create();
+
Assertions.assertThatExceptionOfType(RuntimeException.class)
- .isThrownBy(() -> {
- generator.generate(config);
- })
+ .isThrownBy(() -> generator.generate(config))
.withMessageStartingWith("Could not process template
associated with data file");
}
@Test
public void generate_badParentTest() throws IOException {
- OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
+ final OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
builder.addPomLastModifiedTimestamp(0);
- File file = new File(dataDir, "badParent/bad-parent-test.txt.json");
+ final File file = new File(DATA_DIR,
"badParent/bad-parent-test.txt.json");
builder.addGeneratorLocation(file.toPath());
- File outputFile = new File(outputDir, "badParent/bad-parent-test.txt");
+ final File outputFile = new File(OUTPUT_DIR,
"badParent/bad-parent-test.txt");
builder.addOutputLocation(outputFile.toPath());
- File templateFile = new File(templateDir, "test.ftl"); //this is
missing a
+ final File templateFile = new File(TEMPLATE_DIR, "test.ftl"); //this
is missing a
builder.addTemplateLocation(templateFile.toPath());
builder.addDataModel(dataModel);
- OutputGenerator generator = builder.create();
- outputDir.mkdirs();
+ final OutputGenerator generator = builder.create();
+ OUTPUT_DIR.mkdirs();
outputFile.getParentFile().createNewFile();
-
Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
- generator.generate(config);
- }).withMessage("Parent directory of output file is a file: " +
outputFile.getParentFile().getAbsolutePath());
+ Assertions.assertThatExceptionOfType(RuntimeException.class)
+ .isThrownBy(() -> generator.generate(config))
+ .withMessage("Parent directory of output file is a file: " +
outputFile.getParentFile()
+ .getAbsolutePath());
}
- @Test
- public void generate_cantCreateOutputFileParentDirTest(
- @Mocked FactoryUtil factoryUtil,
- @Mocked File mockOutputFile) throws IOException {
-
- File parentDir = new
File("target/test-output/generating-file-visitor/mydir");
- new Expectations(mockOutputFile, parentDir) {{
- FactoryUtil.createFile(anyString);
- result = mockOutputFile;
- mockOutputFile.exists();
- result = false;
- mockOutputFile.getParentFile();
- result = parentDir;
- parentDir.isDirectory();
- result = false;
- }};
-
- OutputGenerator.OutputGeneratorBuilder builder =
OutputGenerator.builder();
- builder.addPomLastModifiedTimestamp(0);
- File file = new File(dataDir, "mydir/missing-var-test.txt.json");
- builder.addGeneratorLocation(file.toPath());
- File outputFile = new File(outputDir, "mydir/missing-var-test.txt");
- builder.addOutputLocation(outputFile.toPath());
- File templateFile = new File(templateDir, "test.ftl"); //this is
missing a
- builder.addTemplateLocation(templateFile.toPath());
- builder.addDataModel(dataModel);
- OutputGenerator generator = builder.create();
-
Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
- generator.generate(config);
- }).withMessage("Could not create directory: " +
parentDir.getAbsoluteFile().toString());
+ @SuppressWarnings("unchecked")
+ private static Map<String, Object> dataModel() {
+ final HashMap<String, Object> result = new HashMap<>();
+ result.put("testVar", "test value");
+ result.put("pomProperties", new HashMap<String, String>());
+ ((Map<String, String>) result.get("pomProperties")).put("pomVar", "pom
value");
+ return result;
}
}
diff --git
a/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/UnitTestHelper.java
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/UnitTestHelper.java
new file mode 100644
index 0000000..96c70df
--- /dev/null
+++
b/freemarker-generator-maven-plugin/src/test/java/org/apache/freemarker/generator/maven/UnitTestHelper.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.freemarker.generator.maven;
+
+import freemarker.cache.FileTemplateLoader;
+import freemarker.template.Configuration;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Comparator;
+
+public class UnitTestHelper {
+
+ public static Configuration configuration(File testDir) {
+ try {
+ final Configuration configuration = new
Configuration(Configuration.VERSION_2_3_30);
+ configuration.setDefaultEncoding("UTF-8");
+ configuration.setTemplateLoader(new FileTemplateLoader(testDir));
+ return configuration;
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to create Freemarker
configuration", e);
+ }
+ }
+
+ public static void checkTestDir(File testDir) {
+ if (!testDir.isDirectory()) {
+ throw new RuntimeException("Can't find required test data
directory. "
+ + "If running test outside of maven, make sure working
directory is the project directory. "
+ + "Looking for: " + testDir);
+ }
+
+ }
+
+ public static void deleteTestOutputDir(File outputDir) {
+ try {
+ if (outputDir.exists()) {
+ // Recursively delete output from previous run.
+ Files.walk(outputDir.toPath())
+ .sorted(Comparator.reverseOrder())
+ .map(Path::toFile)
+ .forEach(File::delete);
+ }
+ }
+ catch (IOException e) {
+ throw new RuntimeException("Failed to delete output directory", e);
+ }
+
+ }
+}
diff --git a/freemarker-generator-tools/pom.xml
b/freemarker-generator-tools/pom.xml
index 635b9c1..5d1bcba 100644
--- a/freemarker-generator-tools/pom.xml
+++ b/freemarker-generator-tools/pom.xml
@@ -42,6 +42,12 @@
<artifactId>freemarker-generator-base</artifactId>
<version>${project.version}</version>
</dependency>
+ <!-- General -->
+ <dependency>
+ <!-- Overwrite version pulled in by fava-faker -->
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </dependency>
<!-- CommonsCSVTool -->
<dependency>
<groupId>org.apache.commons</groupId>
diff --git a/pom.xml b/pom.xml
index 8512bf7..7c44d98 100644
--- a/pom.xml
+++ b/pom.xml
@@ -111,6 +111,11 @@
<version>${freemarker.version}</version>
</dependency>
<dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.7</version>
+ </dependency>
+ <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>