Skip to content

Commit

Permalink
Add tests for crd-generator-maven-plugin and fix code smells
Browse files Browse the repository at this point in the history
  • Loading branch information
baloo42 committed May 8, 2024
1 parent a138400 commit dc50235
Show file tree
Hide file tree
Showing 8 changed files with 258 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ private ClassLoader getClassLoader() {
try {
return new File(s).toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
throw new CustomResourceCollectorException("Could not transform file to URL: " + s, e);
}
}).toArray(URL[]::new);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,14 @@ public JandexIndexer withMaxJarEntries(int maxJarEntries) {

public JandexIndexer withMaxClassFileSize(int maxClassFileSize) {
if (maxClassFileSize < 10)
throw new IllegalArgumentException("maxClassFileSize must be greater than 10 B (1 KB)");
throw new IllegalArgumentException("maxClassFileSize must be greater than 10");
this.maxClassFileSize = maxClassFileSize;
return this;
}

public JandexIndexer withMaxBytesReadFromJar(long maxBytesReadFromJar) {
if (maxBytesReadFromJar < 10)
throw new IllegalArgumentException("maxBytesReadFromJar must be greater than 10 B (1 KB)");
throw new IllegalArgumentException("maxBytesReadFromJar must be greater than 10");
this.maxBytesReadFromJar = maxBytesReadFromJar;
return this;
}
Expand Down Expand Up @@ -204,7 +204,7 @@ public long getBytesRead() {
@Override
public int read() throws IOException {
if (bytesRead >= maxBytes) {
throw new IOException("Read limit of " + maxBytes + " bytes reached");
throw new IOException("Read limit of " + maxBytes + " bytes exceeded");
}
int result = inputStream.read();
if (result != -1) {
Expand All @@ -213,6 +213,33 @@ public int read() throws IOException {
return result;
}

@Override
public int read(byte[] b, int off, int len) throws IOException {
if (bytesRead >= maxBytes) {
throw new IOException("Read limit of " + maxBytes + " bytes exceeded");
}
long bytesRemaining = maxBytes - bytesRead;
if (len > bytesRemaining) {
len = (int) bytesRemaining; // Reduce len to the maximum allowable bytes
}
int count = inputStream.read(b, off, len);
if (count > 0) {
bytesRead += count;
}
return count;
}

@Override
public int available() throws IOException {
long available = inputStream.available();
long bytesRemaining = maxBytes - bytesRead;
if (available > bytesRemaining) {
return (int) bytesRemaining;
} else {
return (int) available;
}
}

@Override
public void close() throws IOException {
inputStream.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class CustomResourceClassLoaderTest {
class CustomResourceClassLoaderTest {

@Test
void checkNullsafe() {
Expand All @@ -35,7 +35,7 @@ void checkNullsafe() {
loader.withClasspathElement((String) null);
loader.withClasspathElements(null);
loader.withParentClassLoader(null);
loader.loadCustomResourceClass(MyCustomResource.class.getName());
assertNotNull(loader.loadCustomResourceClass(MyCustomResource.class.getName()));
}

@Test
Expand All @@ -49,8 +49,9 @@ void loadNotExisting_thenError() {
@Test
void loadNotCustomResource_thenError() {
CustomResourceClassLoader loader = new CustomResourceClassLoader();
CustomResourceCollectorException e = assertThrows(CustomResourceCollectorException.class,
() -> loader.loadCustomResourceClass(String.class.getName()));
String notACustomResourceClassName = String.class.getName();
assertThrows(CustomResourceCollectorException.class,
() -> loader.loadCustomResourceClass(notACustomResourceClassName));
}

@Test
Expand Down
18 changes: 18 additions & 0 deletions crd-generator/maven-plugin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@
<artifactId>crd-generator-collector</artifactId>
<version>${project.version}</version>
</dependency>

<!-- Testing -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.project.MavenProject;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public enum ClasspathType {
/**
Expand All @@ -44,34 +43,30 @@ public enum ClasspathType {
*/
WITH_ALL_DEPENDENCIES_AND_TESTS;

public Collection<String> getClasspathElements(MavenProject project) {
Collection<String> classpathElements;
public Set<String> getClasspathElements(MavenProject project) {
Set<String> classpathElements = new HashSet<>();
try {
switch (this) {
case PROJECT_ONLY:
classpathElements = Collections.singleton(project.getBuild().getOutputDirectory());
classpathElements.add(project.getBuild().getOutputDirectory());
break;
case WITH_COMPILE_DEPENDENCIES:
classpathElements = project.getCompileClasspathElements();
classpathElements.addAll(project.getCompileClasspathElements());
break;
case WITH_RUNTIME_DEPENDENCIES:
classpathElements = project.getRuntimeClasspathElements();
classpathElements.addAll(project.getRuntimeClasspathElements());
break;
case WITH_ALL_DEPENDENCIES:
// to remove duplicates
classpathElements = new HashSet<>();
classpathElements.addAll(project.getRuntimeClasspathElements());
classpathElements.addAll(project.getCompileClasspathElements());
break;
case WITH_ALL_DEPENDENCIES_AND_TESTS:
// to remove duplicates
classpathElements = new HashSet<>();
classpathElements.addAll(project.getRuntimeClasspathElements());
classpathElements.addAll(project.getCompileClasspathElements());
classpathElements.addAll(project.getTestClasspathElements());
break;
default:
throw new IllegalArgumentException("ClasspathType " + this + " not supported");
}
} catch (DependencyResolutionRequiredException e) {
throw new IllegalStateException("Failed to resolve classpathType elements", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@
public class CrdGeneratorMojo extends AbstractMojo {

@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject mavenProject;
MavenProject mavenProject;

/**
* The input directory to be used to scan for Custom Resource classes
*/
@Parameter(property = "fabric8.crd-generator.classesToIndex", defaultValue = "${project.build.outputDirectory}", readonly = true)
private File classesToIndex;
File classesToIndex;

/**
* Custom Resource classes, which should be considered to generate the CRDs.
Expand All @@ -60,7 +60,7 @@ public class CrdGeneratorMojo extends AbstractMojo {
* Dependencies which should be scanned for Custom Resources.
*/
@Parameter(property = "fabric8.crd-generator.dependenciesToIndex")
private List<Dependency> dependenciesToIndex = new LinkedList<>();
List<Dependency> dependenciesToIndex = new LinkedList<>();

/**
* Inclusions, used to filter Custom Resource classes after scanning.
Expand Down Expand Up @@ -88,13 +88,13 @@ public class CrdGeneratorMojo extends AbstractMojo {
* </ul>
*/
@Parameter(property = "fabric8.crd-generator.classpath", defaultValue = "WITH_RUNTIME_DEPENDENCIES")
private ClasspathType classpath;
ClasspathType classpath;

/**
* The output directory where the CRDs are emitted.
*/
@Parameter(property = "fabric8.crd-generator.outputDirectory", defaultValue = "${project.build.outputDirectory}/META-INF/fabric8/")
private File outputDirectory;
File outputDirectory;

/**
* If true, a Jandex index will be created even if the directory or JAR file contains an existing index.
Expand All @@ -114,12 +114,6 @@ public class CrdGeneratorMojo extends AbstractMojo {
@Parameter(property = "fabric8.crd-generator.implicitPreserveUnknownFields", defaultValue = "false")
private boolean implicitPreserveUnknownFields;

/**
* Print verbose output (debug output without needing to enable -X for the whole build).
*/
@Parameter(property = "fabric8.crd-generator.verbose", defaultValue = "false")
private boolean verbose;

/**
* Skip execution if set.
*/
Expand Down Expand Up @@ -174,10 +168,6 @@ public void execute() throws MojoExecutionException {
});
}

private boolean isVerbose() {
return verbose || getLog().isDebugEnabled();
}

/**
* Returns a list of archive files derived from the given dependencies.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.crd.generator.maven.plugin;

import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.model.Build;
import org.apache.maven.project.MavenProject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.util.Collections;
import java.util.Set;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;

public class ClasspathTypeTest {

private static final String RUNTIME_PATH = "/runtime";
private static final String COMPILE_PATH = "/compile";
private static final String TEST_PATH = "/test";
private static final String PROJECT_PATH = "/project";

private MavenProject project;

@BeforeEach
public void setUp() throws DependencyResolutionRequiredException {
this.project = Mockito.mock(MavenProject.class);
when(this.project.getRuntimeClasspathElements())
.thenReturn(Collections.singletonList(RUNTIME_PATH));
when(this.project.getCompileClasspathElements())
.thenReturn(Collections.singletonList(COMPILE_PATH));
when(this.project.getTestClasspathElements())
.thenReturn(Collections.singletonList(TEST_PATH));

Build build = new Build();
build.setOutputDirectory(PROJECT_PATH);
when(this.project.getBuild()).thenReturn(build);
}

@Test
public void testGetUrlsCompile() {
Set<String> urls = ClasspathType.WITH_COMPILE_DEPENDENCIES.getClasspathElements(this.project);
assertEquals(1, urls.size());
assertTrue(urls.contains(COMPILE_PATH));
}

@Test
public void testGetUrlsRuntime() {
Set<String> urls = ClasspathType.WITH_RUNTIME_DEPENDENCIES.getClasspathElements(this.project);
assertEquals(1, urls.size());
assertTrue(urls.contains(RUNTIME_PATH));
}

@Test
public void testGetUrlsAll() {
Set<String> urls = ClasspathType.WITH_ALL_DEPENDENCIES.getClasspathElements(this.project);
assertEquals(2, urls.size());
assertTrue(urls.contains(RUNTIME_PATH));
assertTrue(urls.contains(COMPILE_PATH));
}

@Test
public void testGetUrlsAllAndTests() {
Set<String> urls = ClasspathType.WITH_ALL_DEPENDENCIES_AND_TESTS.getClasspathElements(this.project);
assertEquals(3, urls.size());
assertTrue(urls.contains(RUNTIME_PATH));
assertTrue(urls.contains(COMPILE_PATH));
assertTrue(urls.contains(TEST_PATH));
}

@Test
public void testGetUrlsProject() {
Set<String> urls = ClasspathType.PROJECT_ONLY.getClasspathElements(this.project);
assertEquals(1, urls.size());
assertTrue(urls.contains(PROJECT_PATH));
}

}
Loading

0 comments on commit dc50235

Please sign in to comment.