Skip to content

Commit

Permalink
test: refactor CRD generator tests to use final var for local variables
Browse files Browse the repository at this point in the history
Signed-off-by: David Sondermann <[email protected]>
  • Loading branch information
Donnerbart committed Nov 25, 2024
1 parent 66fe542 commit 2c13e8d
Show file tree
Hide file tree
Showing 7 changed files with 162 additions and 173 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
* Fix #6282: Allow annotated types with Pattern, Min, and Max with Lists and Maps and CRD generation
* Fix #5480: Move `io.fabric8:zjsonpatch` to KubernetesClient project
* Fix #6240: Support for multiple files listed in the KUBECONFIG env var
* Refactor: Cleanup CRD generator tests

#### Dependency Upgrade
* Fix #2632: Bumped OkHttp from 3.12.12 to 4.12.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,15 @@
import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition;
import io.fabric8.kubernetes.client.utils.Serialization;
import org.approvaltests.Approvals;
import org.approvaltests.namer.NamedEnvironment;
import org.approvaltests.namer.NamerFactory;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import static io.fabric8.java.generator.CRGeneratorRunner.groupToPackage;
Expand All @@ -47,33 +46,32 @@ private static Stream<Arguments> getCRDGenerationInputData() {
new Config()),
Arguments.of("testCalicoIPPoolCrd", "calico-ippool-crd.yml", "IPPool", "CalicoIPPoolCr", new Config()),
Arguments.of("testExistingJavaType", "existing-java-type-crd.yml", "ExistingJavaType", "ExistingJavaTypeCr",
Config.builder().existingJavaTypes(Collections.singletonMap(
"org.test.v1.existingjavatypespec.Affinity", "io.fabric8.kubernetes.api.model.Affinity")).build()));
Config.builder().existingJavaTypes(
Map.of("org.test.v1.existingjavatypespec.Affinity", "io.fabric8.kubernetes.api.model.Affinity")).build()));
}

@ParameterizedTest
@MethodSource("getCRDGenerationInputData")
void generate_withValidCrd_shouldGeneratePojos(String parameter, String crdYaml, String customResourceName,
String approvalLabel, Config config) {
try (NamedEnvironment en = NamerFactory.withParameters(parameter)) {
try (var ignored = NamerFactory.withParameters(parameter)) {
// Arrange
CRGeneratorRunner runner = new CRGeneratorRunner(config);
CustomResourceDefinition crd = getCRD(crdYaml);
final var runner = new CRGeneratorRunner(config);
final var crd = getCRD(crdYaml);

// Act
List<WritableCRCompilationUnit> writables = runner.generate(crd, groupToPackage("test.org"));
final var writables = runner.generate(crd, groupToPackage("test.org"));

// Assert
assertThat(writables).hasSize(1);

WritableCRCompilationUnit writable = writables.get(0);

List<String> underTest = new ArrayList<>();
List<GeneratorResult.ClassResult> crl = writable.getClassResults();
final var writable = writables.get(0);
final var underTest = new ArrayList<>();
final var crl = writable.getClassResults();
underTest.add(getJavaClass(crl, customResourceName));
underTest.add(getJavaClass(crl, customResourceName + "Spec"));
// not all the tested CRDs have a status definition, e.g. see calico-ippool-crd.yml
final String statusCrlName = customResourceName + "Status";
final var statusCrlName = customResourceName + "Status";
if (crl.stream().anyMatch(c -> c.getName().equals(statusCrlName))) {
underTest.add(getJavaClass(crl, statusCrlName));
}
Expand All @@ -82,13 +80,10 @@ void generate_withValidCrd_shouldGeneratePojos(String parameter, String crdYaml,
}

private CustomResourceDefinition getCRD(String name) {
return Serialization.unmarshal(
this.getClass().getClassLoader().getResourceAsStream(name),
CustomResourceDefinition.class);
return Serialization.unmarshal(getClass().getClassLoader().getResourceAsStream(name), CustomResourceDefinition.class);
}

private String getJavaClass(List<GeneratorResult.ClassResult> classResults, String name) {
GeneratorResult.ClassResult cr = classResults.stream().filter(c -> c.getName().equals(name)).findFirst().get();
return cr.getJavaSource();
return classResults.stream().filter(c -> c.getName().equals(name)).findFirst().orElseThrow().getJavaSource();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@
import org.junit.jupiter.params.provider.MethodSource;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -82,11 +79,11 @@ private static Stream<Arguments> compilationTestData() {
@MethodSource("compilationTestData")
void yamlCompiles(String yamlFile, int expectedGeneratedSourceFiles) throws Exception {
// Arrange
File crd = getCRD(yamlFile);
final var crd = getCRD(yamlFile);

// Act
new FileJavaGenerator(config, crd).run(tempDir);
Compilation compilation = javac().compile(getSources(tempDir));
final var compilation = javac().compile(getSources(tempDir));

// Assert
assertThat(compilation.errors()).isEmpty();
Expand All @@ -98,14 +95,14 @@ void yamlCompiles(String yamlFile, int expectedGeneratedSourceFiles) throws Exce
@Test
void testCrontabCRDCompilesWithExtraAnnotations() throws Exception {
// Arrange
File crd = getCRD("crontab-crd.yml");
final var crd = getCRD("crontab-crd.yml");
config = config.toBuilder()
.objectExtraAnnotations(true)
.build();

// Act
new FileJavaGenerator(config, crd).run(tempDir);
Compilation compilation = javac()
final var compilation = javac()
.withProcessors(new BuildableProcessor())
.compile(getSources(tempDir));

Expand All @@ -118,7 +115,7 @@ void testCrontabCRDCompilesWithExtraAnnotations() throws Exception {
@Test
void testCalicoIPPoolCRDDoesNotCompileWhenDuplicatesAreNotDeprecated() throws Exception {
// Arrange
File crd = getCRD("calico-ippool-broken-crd.yml");
final var crd = getCRD("calico-ippool-broken-crd.yml");
config = config.toBuilder()
.objectExtraAnnotations(true)
.build();
Expand All @@ -132,11 +129,11 @@ void testCalicoIPPoolCRDDoesNotCompileWhenDuplicatesAreNotDeprecated() throws Ex
.isInstanceOf(JavaGeneratorException.class);
}

static List<JavaFileObject> getSources(File basePath) throws IOException {
List<JavaFileObject> sources = new ArrayList<>();
try (Stream<Path> pathStream = Files.list(basePath.toPath())) {
for (Path path : pathStream.collect(Collectors.toList())) {
File file = path.toFile();
static List<JavaFileObject> getSources(File basePath) throws Exception {
final var sources = new ArrayList<JavaFileObject>();
try (final var pathStream = Files.list(basePath.toPath())) {
for (final var path : pathStream.collect(Collectors.toList())) {
final var file = path.toFile();
if (file.isDirectory()) {
sources.addAll(getSources(file));
} else {
Expand All @@ -148,7 +145,7 @@ static List<JavaFileObject> getSources(File basePath) throws IOException {
}

static File getCRD(String name) throws Exception {
URL resource = CompilationTest.class.getClassLoader().getResource(name);
final var resource = CompilationTest.class.getClassLoader().getResource(name);
assertThat(resource).isNotNull();
return Paths.get(resource.toURI()).toFile();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class ConfigTest {

@Test
void defaultValuesWithAllArgsConstructor() {
final Config result = new Config(null, null, null, null, null, null, null, null, null);
final var result = new Config(null, null, null, null, null, null, null, null, null);
assertThat(result)
.returns(Config.DEFAULT_UPPERCASE_ENUM, Config::isUppercaseEnums)
.returns(Config.DEFAULT_ADD_EXTRA_ANNOTATIONS, Config::isObjectExtraAnnotations)
Expand All @@ -37,7 +37,7 @@ void defaultValuesWithAllArgsConstructor() {

@Test
void defaultValuesWithNoArgsConstructor() {
final Config result = new Config();
final var result = new Config();
assertThat(result)
.returns(Config.DEFAULT_UPPERCASE_ENUM, Config::isUppercaseEnums)
.returns(Config.DEFAULT_ADD_EXTRA_ANNOTATIONS, Config::isObjectExtraAnnotations)
Expand All @@ -51,7 +51,7 @@ void defaultValuesWithNoArgsConstructor() {

@Test
void defaultValuesWithBuilder() {
final Config result = Config.builder().build();
final var result = Config.builder().build();
assertThat(result)
.returns(Config.DEFAULT_UPPERCASE_ENUM, Config::isUppercaseEnums)
.returns(Config.DEFAULT_ADD_EXTRA_ANNOTATIONS, Config::isObjectExtraAnnotations)
Expand Down
Loading

0 comments on commit 2c13e8d

Please sign in to comment.