Skip to content

Commit

Permalink
Extract MojoMocker + reduce TestUtils methods
Browse files Browse the repository at this point in the history
  • Loading branch information
abelsromero committed Jan 25, 2024
1 parent 118f74c commit d3fa92f
Show file tree
Hide file tree
Showing 17 changed files with 206 additions and 110 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ Build / Infrastructure::
* Use latest Maven and remove Dependabot exclusion (CI test ensure backward compatibility) (#722)
* Test artifact's signature with Maven in CI (#736)
* Automate release using GH Actions (#141)
* Ensure Mojos use correct default values in unit tests (#609)


Maintenance::
* Replace use of reflection by direct JavaExtensionRegistry calls to register extensions (#596)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ public class AsciidoctorHttpMojo extends AsciidoctorRefreshMojo {

public static final String PREFIX = AsciidoctorMaven.PREFIX + "http.";

@Parameter(property = PREFIX + "port")
protected int port = 2000;
@Parameter(property = PREFIX + "port", defaultValue = "2000")
protected int port;

@Parameter(property = PREFIX + "home", defaultValue = "index")
protected String home;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,32 @@
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.asciidoctor.maven.refresh.*;
import org.asciidoctor.maven.refresh.AdditionalSourceFileAlterationListenerAdaptor;
import org.asciidoctor.maven.refresh.AsciidoctorConverterFileAlterationListenerAdaptor;
import org.asciidoctor.maven.refresh.ResourceCopyFileAlterationListenerAdaptor;
import org.asciidoctor.maven.refresh.ResourcesPatternBuilder;
import org.asciidoctor.maven.refresh.TimeCounter;

import java.io.File;
import java.io.FileFilter;
import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.Scanner;
import java.util.StringJoiner;

import static org.asciidoctor.maven.commons.StringUtils.isNotBlank;
import static org.asciidoctor.maven.process.SourceDocumentFinder.*;
import static org.asciidoctor.maven.process.SourceDocumentFinder.CUSTOM_FILE_EXTENSIONS_PATTERN_PREFIX;
import static org.asciidoctor.maven.process.SourceDocumentFinder.CUSTOM_FILE_EXTENSIONS_PATTERN_SUFFIX;
import static org.asciidoctor.maven.process.SourceDocumentFinder.STANDARD_FILE_EXTENSIONS_PATTERN;

@Mojo(name = "auto-refresh")
public class AsciidoctorRefreshMojo extends AsciidoctorMojo {

public static final String PREFIX = AsciidoctorMaven.PREFIX + "refresher.";

@Parameter(property = PREFIX + "interval")
protected int interval = 2000; // 2s
@Parameter(property = PREFIX + "interval", defaultValue = "2000")
protected int interval;

@Parameter(property = PREFIX + "refreshOn")
protected String refreshOn;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
package org.asciidoctor.maven;

import lombok.SneakyThrows;
import org.assertj.core.api.AbstractFileAssert;
import org.assertj.core.api.AbstractStringAssert;
import org.assertj.core.api.Assertions;

import java.io.File;
import java.nio.file.Files;

public class AsciidoctorAsserter {

private final AbstractFileAssert<?> fileAssert;
private final AbstractStringAssert<?> contentAssert;

@SneakyThrows
private AsciidoctorAsserter(File generatedFile) {
this.fileAssert = Assertions.assertThat(generatedFile);
this.contentAssert = Assertions.assertThat(TestUtils.readAsString(generatedFile));
this.contentAssert = Assertions.assertThat(Files.readString(generatedFile.toPath()));
}

public static AsciidoctorAsserter assertThat(File file) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import java.net.URL;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asciidoctor.maven.TestUtils.mockAsciidoctorHttpMojo;
import static org.asciidoctor.maven.test.TestUtils.mockAsciidoctorHttpMojo;
import static org.assertj.core.api.Assertions.assertThat;

class AsciidoctorHttpMojoTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
import java.util.Map;

import static org.asciidoctor.maven.AsciidoctorAsserter.assertThat;
import static org.asciidoctor.maven.TestUtils.ResourceBuilder.excludeAll;
import static org.asciidoctor.maven.TestUtils.mockAsciidoctorMojo;
import static org.asciidoctor.maven.test.TestUtils.ResourceBuilder.excludeAll;
import static org.asciidoctor.maven.test.TestUtils.mockAsciidoctorMojo;
import static org.asciidoctor.maven.io.TestFilesHelper.newOutputTestDirectory;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import java.util.Map;

import static java.util.Collections.singletonList;
import static org.asciidoctor.maven.TestUtils.mockAsciidoctorMojo;
import static org.asciidoctor.maven.test.TestUtils.mockAsciidoctorMojo;
import static org.asciidoctor.maven.io.TestFilesHelper.newOutputTestDirectory;
import static org.assertj.core.api.Assertions.assertThat;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import static org.asciidoctor.log.Severity.ERROR;
import static org.asciidoctor.log.Severity.WARN;
import static org.asciidoctor.maven.TestUtils.mockAsciidoctorMojo;
import static org.asciidoctor.maven.test.TestUtils.mockAsciidoctorMojo;
import static org.asciidoctor.maven.io.TestFilesHelper.newOutputTestDirectory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,28 @@
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import static java.nio.file.Files.writeString;
import static java.util.Collections.singletonList;
import static org.asciidoctor.maven.AsciidoctorAsserter.assertThat;
import static org.asciidoctor.maven.TestUtils.*;
import static org.asciidoctor.maven.TestUtils.ResourceBuilder.excludeAll;
import static org.asciidoctor.maven.io.TestFilesHelper.newOutputTestDirectory;
import static org.asciidoctor.maven.test.TestUtils.ResourceBuilder;
import static org.asciidoctor.maven.test.TestUtils.ResourceBuilder.excludeAll;
import static org.asciidoctor.maven.test.TestUtils.assertEqualsStructure;
import static org.asciidoctor.maven.test.TestUtils.mockAsciidoctorMojo;


class AsciidoctorMojoTest {
Expand Down Expand Up @@ -156,7 +167,6 @@ void should_convert_to_html_with_attributes() throws MojoFailureException, MojoE
mojo.sourceDocumentName = "sample.asciidoc";
mojo.resources = excludeAll();
mojo.outputDirectory = outputDir;
mojo.standalone = true;
mojo.attributes = Map.of("toc", "",
"linkcss!", "",
"source-highlighter", "coderay");
Expand Down Expand Up @@ -283,15 +293,16 @@ void should_override_output_directory_with_output_file_with_absolute_path() thro
}

@Test
void should_set_file_extension() throws MojoFailureException, MojoExecutionException {
void should_set_file_extension() throws MojoFailureException, MojoExecutionException, IOException {
// given
File outputDir = newOutputTestDirectory();
Assertions.assertThat(outputDir).doesNotExist();

File srcDir = new File(DEFAULT_SOURCE_DIRECTORY);
outputDir.mkdirs();
writeToFile(srcDir, "sample1.foo", "= Document Title\n\nfoo");
writeToFile(srcDir, "sample2.bar", "= Document Title\n\nbar");

writeString(Path.of(DEFAULT_SOURCE_DIRECTORY, "sample1.foo"), "= Document Title\n\nfoo");
writeString(Path.of(DEFAULT_SOURCE_DIRECTORY, "sample2.bar"), "= Document Title\n\nbar");

// when
AsciidoctorMojo mojo = mockAsciidoctorMojo();
Expand Down Expand Up @@ -795,7 +806,6 @@ void should_embed_resources() throws MojoFailureException, MojoExecutionExceptio
.contains("i class=\"fa icon-tip\"");
}


// issue-78
@Test
void should_embed_image_in_included_adoc() throws MojoFailureException, MojoExecutionException {
Expand All @@ -817,7 +827,7 @@ void should_embed_image_in_included_adoc() throws MojoFailureException, MojoExec
assertThat(outputDir, "main.html")
.contains("<p>Here&#8217;s an image:</p>")
.contains("<img src=\"data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4gzESUNDX1BST0ZJTEUAAQEAAA");
assertThat(new File(outputDir, "halliburton_lab.jpg")).isNotEmpty();
Assertions.assertThat(new File(outputDir, "halliburton_lab.jpg")).isNotEmpty();
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.asciidoctor.maven.TestUtils.ResourceBuilder;
import org.asciidoctor.maven.test.TestUtils.ResourceBuilder;
import org.asciidoctor.maven.io.ConsoleHolder;
import org.asciidoctor.maven.model.Resource;
import org.junit.jupiter.api.Test;
Expand All @@ -19,7 +19,7 @@
import java.util.stream.Collectors;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asciidoctor.maven.TestUtils.newFakeRefreshMojo;
import static org.asciidoctor.maven.test.TestUtils.newFakeRefreshMojo;
import static org.asciidoctor.maven.io.TestFilesHelper.createFileWithContent;
import static org.asciidoctor.maven.io.TestFilesHelper.newOutputTestDirectory;
import static org.assertj.core.api.Assertions.assertThat;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import java.util.zip.ZipFile;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asciidoctor.maven.TestUtils.mockAsciidoctorZipMojo;
import static org.asciidoctor.maven.test.TestUtils.mockAsciidoctorZipMojo;
import static org.assertj.core.api.Assertions.assertThat;


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import org.apache.commons.io.FileUtils;
import org.asciidoctor.maven.AsciidoctorMojo;
import org.asciidoctor.maven.TestUtils.ResourceBuilder;
import org.asciidoctor.maven.test.TestUtils.ResourceBuilder;
import org.asciidoctor.maven.model.Resource;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package org.asciidoctor.maven.test;

import lombok.SneakyThrows;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.apache.maven.project.MavenProject;
import org.asciidoctor.maven.AsciidoctorMojo;
import org.asciidoctor.maven.log.LogHandler;
import org.mockito.Mockito;

import java.io.File;
import java.util.Map;
import java.util.Properties;

import static org.codehaus.plexus.util.ReflectionUtils.setVariableValueInObject;
import static org.mockito.Mockito.when;

class MojoMocker {

private static final ParametersInitializer parametersInitializer = new ParametersInitializer();

@SneakyThrows
@SuppressWarnings("unchecked")
<T> T mock(Class<T> clazz, Map<String, String> mavenProperties, LogHandler logHandler) {

final AsciidoctorMojo mojo = (AsciidoctorMojo) clazz.getConstructor(new Class[]{}).newInstance();

parametersInitializer.initialize(mojo);
setVariableValueInObject(mojo, "log", new SystemStreamLog());
setVariableValueInObject(mojo, "project", mockMavenProject(mavenProperties));
if (logHandler != null)
setVariableValueInObject(mojo, "logHandler", logHandler);

return (T) mojo;
}

private MavenProject mockMavenProject(Map<String, String> mavenProperties) {
final MavenProject mavenProject = Mockito.mock(MavenProject.class);
when(mavenProject.getBasedir()).thenReturn(new File("."));
if (mavenProperties != null) {
final Properties properties = new Properties();
properties.putAll(mavenProperties);
when(mavenProject.getProperties()).thenReturn(properties);
}
return mavenProject;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package org.asciidoctor.maven.test;

import org.asciidoctor.maven.AsciidoctorMojo;
import org.asciidoctor.maven.log.LogHandler;
import org.junit.jupiter.api.Test;

import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

class MojoMockerTest {

private final MojoMocker mojoMocker = new MojoMocker();

@Test
void should_mock_mojo() {
AsciidoctorMojo mock = mojoMocker.mock(AsciidoctorMojo.class, null, null);

assertThat(mock).isNotNull();
}

@Test
void should_mock_mojo_with_properties() {
Map<String, String> properties = Map.of("a-key", "a-value");
AsciidoctorMojo mock = mojoMocker.mock(AsciidoctorMojo.class, properties, null);

assertThat(mock).isNotNull();
}

@Test
void should_mock_mojo_with_logHandler() {
AsciidoctorMojo mock = mojoMocker.mock(AsciidoctorMojo.class, null, new LogHandler());

assertThat(mock).isNotNull();
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.asciidoctor.maven;
package org.asciidoctor.maven.test;

import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.description.annotation.AnnotationValue;
Expand All @@ -12,7 +12,7 @@
import static org.codehaus.plexus.util.ReflectionUtils.setVariableValueInObject;

/**
*
* Initialize values for properties in class using {@link Parameter} annotation.
*/
class ParametersInitializer {

Expand All @@ -22,7 +22,7 @@ class ParametersInitializer {
* Returns instance of input class with fields initialized according to its
* respective {@link org.apache.maven.plugins.annotations.Parameter}.
*/
public <T> T initialize(T instance) {
<T> T initialize(T instance) {
try {
// Use ByteBuddy because annotations is Class retention, not Runtime
TypePool typePool = TypePool.Default.of(CLASS_LOADER);
Expand All @@ -42,19 +42,25 @@ private <T> void initParameterFields(T instance, TypeDescription typeDescription
for (FieldDescription field : declaredFields) {
String value = getAnnotationByType(field);
if (value != null) {
if (field.getType().getTypeName().equals(String.class.getName())) {
final String typeName = field.getType().getTypeName();
if (typeName.equals(String.class.getName())) {
if (value.length() > 0 && !value.startsWith("$")) {
// TODO support Maven variable: pass Map<String, Object> ?
setVariableValueInObject(instance, field.getName(), value);
}
}
if (field.getType().getTypeName().equals("boolean")) {
// false is already the default
// TODO for PR, the booleans default should appear in XML plugin descriptor now
if (typeName.equals("boolean")) {
if (value.equals("true")) {
setVariableValueInObject(instance, field.getName(), Boolean.TRUE);
} else if (!value.equals("false")) {
throw new RuntimeException("Invalid boolean default: not-a-boolean");
throw new RuntimeException("Invalid boolean default: " + value);
}
}
if (typeName.equals("int")) {
try {
setVariableValueInObject(instance, field.getName(), Integer.valueOf(value));
} catch (Exception e) {
throw new RuntimeException("Invalid boolean default: " + value);
}
}
// TODO
Expand Down
Loading

0 comments on commit d3fa92f

Please sign in to comment.