Skip to content

Commit

Permalink
refactor: tests and code organization for generator labels config
Browse files Browse the repository at this point in the history
Signed-off-by: Marc Nuri <marc@marcnuri.com>
  • Loading branch information
manusa committed Apr 30, 2024
1 parent e35e6be commit 1fd72cd
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 71 deletions.
Expand Up @@ -50,6 +50,8 @@ public abstract class BaseGenerator implements Generator {

public static final String PROPERTY_JKUBE_IMAGE_NAME = "jkube.image.name";
public static final String PROPERTY_JKUBE_GENERATOR_NAME = "jkube.generator.name";
private static final String PROPERTY_JKUBE_GENERATOR_LABELS = "jkube.generator.labels";


private static final String LABEL_SCHEMA_VERSION = "1.0";
private static final String GIT_REMOTE = "origin";
Expand Down Expand Up @@ -257,22 +259,10 @@ private boolean containsBuildConfiguration(List<ImageConfiguration> configs) {
return false;
}


protected void addLabelsFromConfig(Map<String, String> labels) {
String commaSeparatedLabels = getConfigWithFallback(Config.LABELS, "jkube.generator.labels", null);
if (StringUtils.isNotBlank(commaSeparatedLabels)) {
Map<String,String> configLabels = Arrays.stream(commaSeparatedLabels.split(","))
.map(envNameValue -> envNameValue.split("="))
.filter(e -> e.length == 2)
.collect(Collectors.toMap(e -> e[0].trim(), e -> e[1].trim()));
labels.putAll(configLabels);
}
}

protected void addSchemaLabels(BuildConfiguration.BuildConfigurationBuilder buildBuilder, PrefixedLogger log) {
final JavaProject project = getProject();
String docURL = project.getDocumentationUrl();
Map<String, String> labels = new HashMap<>();
final Map<String, String> labels = new HashMap<>(buildBuilder.build().getLabels());

labels.put(BuildLabelAnnotations.BUILD_DATE.value(), getProject().getBuildDate().format(DateTimeFormatter.ISO_DATE));
labels.put(BuildLabelAnnotations.NAME.value(), project.getName());
Expand All @@ -289,8 +279,6 @@ protected void addSchemaLabels(BuildConfiguration.BuildConfigurationBuilder buil
labels.put(BuildLabelAnnotations.VERSION.value(), project.getVersion());
labels.put(BuildLabelAnnotations.SCHEMA_VERSION.value(), LABEL_SCHEMA_VERSION);

addLabelsFromConfig(labels);

try {
Repository repository = GitUtil.getGitRepository(project.getBaseDirectory());
if (repository != null) {
Expand All @@ -310,4 +298,16 @@ protected void addSchemaLabels(BuildConfiguration.BuildConfigurationBuilder buil
}
}

protected void addLabelsFromConfig(BuildConfiguration.BuildConfigurationBuilder buildBuilder) {
final String commaSeparatedLabels = getConfigWithFallback(Config.LABELS, PROPERTY_JKUBE_GENERATOR_LABELS, null);
if (StringUtils.isNotBlank(commaSeparatedLabels)) {
final Map<String, String> labels = new HashMap<>(buildBuilder.build().getLabels());
Arrays.stream(commaSeparatedLabels.split(","))
.map(envNameValue -> envNameValue.split("="))
.filter(e -> e.length == 2)
.forEach(e -> labels.put(e[0].trim(), e[1].trim()));
buildBuilder.labels(labels);
}
}

}
Expand Up @@ -13,17 +13,15 @@
*/
package org.eclipse.jkube.generator.api.support;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Map;
import java.util.LinkedHashMap;

import org.assertj.core.api.InstanceOfAssertFactories;
import org.eclipse.jkube.generator.api.FromSelector;
import org.eclipse.jkube.generator.api.GeneratorContext;
import org.eclipse.jkube.kit.common.JavaProject;
import org.eclipse.jkube.kit.common.KitLogger;
import org.eclipse.jkube.kit.config.image.ImageConfiguration;
import org.eclipse.jkube.kit.config.image.build.BuildConfiguration;
import org.eclipse.jkube.kit.config.resource.ProcessorConfig;
Expand All @@ -37,31 +35,24 @@
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.entry;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
* @author roland
*/

class BaseGeneratorTest {
private GeneratorContext ctx;
private JavaProject project;

private Properties properties;
private GeneratorContext ctx;
private ProcessorConfig config;

@BeforeEach
void setUp() {
ctx = mock(GeneratorContext.class,RETURNS_DEEP_STUBS);
project = mock(JavaProject.class);
properties = new Properties();
config = new ProcessorConfig();

when(project.getProperties()).thenReturn(properties);
when(ctx.getProject()).thenReturn(project);
when(ctx.getConfig()).thenReturn(config);
ctx = GeneratorContext.builder()
.logger(new KitLogger.SilentLogger())
.project(JavaProject.builder()
.properties(properties)
.build())
.config(config)
.build();
}

@AfterEach
Expand Down Expand Up @@ -198,11 +189,6 @@ void getRegistryInOpenshiftShouldReturnNull() {
assertThat(result).isNull();
}

private TestBaseGenerator createGenerator(FromSelector fromSelector) {
return fromSelector != null ? new TestBaseGenerator(ctx, "test-generator", fromSelector)
: new TestBaseGenerator(ctx, "test-generator");
}

@Nested
@DisplayName("add from")
class AddFrom {
Expand Down Expand Up @@ -334,29 +320,20 @@ void addFromWithInvalidModeShouldThrowException() {
@Test
@DisplayName("should add default image")
void shouldAddDefaultImage() {
ImageConfiguration ic1 = mock(ImageConfiguration.class);
ImageConfiguration ic2 = mock(ImageConfiguration.class);
BuildConfiguration bc = mock(BuildConfiguration.class);
when(ic1.getBuildConfiguration()).thenReturn(bc);
when(ic2.getBuildConfiguration()).thenReturn(null);
BaseGenerator generator = createGenerator(null);
BaseGenerator generator = new TestBaseGenerator(ctx, "test-generator");
assertThat(generator)
.returns(true, g -> g.shouldAddGeneratedImageConfiguration(Collections.emptyList()))
.returns(false, g -> g.shouldAddGeneratedImageConfiguration(Arrays.asList(ic1, ic2)))
.returns(true, g -> g.shouldAddGeneratedImageConfiguration(Collections.singletonList(ic2)))
.returns(false, g -> g.shouldAddGeneratedImageConfiguration(Collections.singletonList(ic1)));
.returns(true, g -> g.shouldAddGeneratedImageConfiguration(Collections.emptyList()));
}

@Test
@DisplayName("should add generated image configuration when add enabled via config, should return true")
void shouldAddGeneratedImageConfiguration_whenAddEnabledViaConfig_shouldReturnTrue() {
// Given
when(ctx.getProject()).thenReturn(project);
properties.put("jkube.generator.test-generator.add", "true");
BaseGenerator generator = createGenerator(null);

// When
boolean result = generator.shouldAddGeneratedImageConfiguration(createNewImageConfigurationList());
boolean result = new TestBaseGenerator(ctx, "test-generator")
.shouldAddGeneratedImageConfiguration(createNewImageConfigurationList());

// Then
assertThat(result).isTrue();
Expand All @@ -367,12 +344,11 @@ void shouldAddGeneratedImageConfiguration_whenAddEnabledViaConfig_shouldReturnTr
@DisplayName("should add generated image configuration when enabled via property, should return true")
void shouldAddGeneratedImageConfiguration_whenAddEnabledViaProperty_shouldReturnTrue() {
// Given
when(ctx.getProject()).thenReturn(project);
properties.put("jkube.generator.add", "true");
BaseGenerator generator = createGenerator(null);

// When
boolean result = generator.shouldAddGeneratedImageConfiguration(createNewImageConfigurationList());
boolean result = new TestBaseGenerator(ctx, "test-generator")
.shouldAddGeneratedImageConfiguration(createNewImageConfigurationList());

// Then
assertThat(result).isTrue();
Expand All @@ -381,11 +357,9 @@ void shouldAddGeneratedImageConfiguration_whenAddEnabledViaProperty_shouldReturn
@Test
@DisplayName("add latest tag if project's version is SNAPSHOT")
void addLatestTagIfSnapshot() {
when(ctx.getProject()).thenReturn(project);
when(project.getVersion()).thenReturn("1.2-SNAPSHOT");
ctx = ctx.toBuilder().project(ctx.getProject().toBuilder().version("1.2-SNAPSHOT").build()).build();
BuildConfiguration.BuildConfigurationBuilder builder = BuildConfiguration.builder();
BaseGenerator generator = createGenerator(null);
generator.addLatestTagIfSnapshot(builder);
new TestBaseGenerator(ctx, "test-generator").addLatestTagIfSnapshot(builder);
BuildConfiguration config = builder.build();
List<String> tags = config.getTags();
assertThat(tags)
Expand All @@ -397,11 +371,9 @@ void addLatestTagIfSnapshot() {
@Test
@DisplayName("add tags from config")
void addTagsFromConfig() {
when(ctx.getProject()).thenReturn(project);
BuildConfiguration.BuildConfigurationBuilder builder = BuildConfiguration.builder();
properties.put("jkube.generator.test-generator.tags", " tag-1, tag-2 , other-tag");
BaseGenerator generator = createGenerator(null);
generator.addTagsFromConfig(builder);
new TestBaseGenerator(ctx, "test-generator").addTagsFromConfig(builder);
BuildConfiguration config = builder.build();
assertThat(config.getTags())
.hasSize(3)
Expand All @@ -411,11 +383,9 @@ void addTagsFromConfig() {
@Test
@DisplayName("add tags from property")
void addTagsFromProperty() {
when(ctx.getProject()).thenReturn(project);
BuildConfiguration.BuildConfigurationBuilder builder = BuildConfiguration.builder();
properties.put("jkube.generator.tags", " tag-1, tag-2 , other-tag");
BaseGenerator generator = createGenerator(null);
generator.addTagsFromConfig(builder);
new TestBaseGenerator(ctx, "test-generator").addTagsFromConfig(builder);
BuildConfiguration config = builder.build();
assertThat(config.getTags())
.hasSize(3)
Expand All @@ -425,13 +395,10 @@ void addTagsFromProperty() {
@Test
@DisplayName("add labels from property")
void addLabelsFromProperty() {
when(ctx.getProject()).thenReturn(project);
BuildConfiguration.BuildConfigurationBuilder builder = BuildConfiguration.builder();
properties.put("jkube.generator.labels", " label-1=a, label-2=b , invalid-label");
Map<String, String> extractedLabels = new LinkedHashMap<>();
BaseGenerator generator = createGenerator(null);
generator.addLabelsFromConfig(extractedLabels);
assertThat(extractedLabels)
new TestBaseGenerator(ctx, "test-generator").addLabelsFromConfig(builder);
assertThat(builder.build().getLabels())
.hasSize(2)
.contains(
entry("label-1", "a"),
Expand All @@ -440,11 +407,11 @@ void addLabelsFromProperty() {
}

private void inKubernetes() {
when(ctx.getRuntimeMode()).thenReturn(RuntimeMode.KUBERNETES);
ctx = ctx.toBuilder().runtimeMode(RuntimeMode.KUBERNETES).build();
}

private void inOpenShift() {
when(ctx.getRuntimeMode()).thenReturn(RuntimeMode.OPENSHIFT);
ctx = ctx.toBuilder().runtimeMode(RuntimeMode.OPENSHIFT).build();
}

private static class TestBaseGenerator extends BaseGenerator {
Expand Down
Expand Up @@ -141,6 +141,7 @@ public List<ImageConfiguration> customize(List<ImageConfiguration> configs, bool
protected BuildConfiguration.BuildConfigurationBuilder initImageBuildConfiguration(boolean prePackagePhase) {
final BuildConfiguration.BuildConfigurationBuilder buildBuilder = BuildConfiguration.builder();
addSchemaLabels(buildBuilder, log);
addLabelsFromConfig(buildBuilder);
addFrom(buildBuilder);
if (!prePackagePhase) {
// Only add assembly if not in a pre-package phase where the referenced files
Expand Down
Expand Up @@ -101,4 +101,20 @@ void customize_withDisabledPrometheus_shouldRemovePortAndAddEnv() {
.extracting(BuildConfiguration::getEnv)
.hasFieldOrPropertyWithValue("AB_PROMETHEUS_OFF", "true");
}

@Test
void customize_withCustomLabels_shouldAddLabels() {
// Given
projectProperties.put("jkube.generator.java-exec.labels", "app=MyApp,version=1.0");
projectProperties.put("jkube.generator.java-exec.mainClass", "com.example.Main");
// When
final List<ImageConfiguration> result = new JavaExecGenerator(generatorContext)
.customize(new ArrayList<>(), false);
// Then
assertThat(result).singleElement()
.extracting(ImageConfiguration::getBuildConfiguration)
.extracting(BuildConfiguration::getLabels)
.hasFieldOrPropertyWithValue("app", "MyApp")
.hasFieldOrPropertyWithValue("version", "1.0");
}
}
Expand Up @@ -71,6 +71,7 @@ public List<ImageConfiguration> customize(List<ImageConfiguration> configs, bool
.putEnv("KARAF_HOME", "/deployments/karaf");

addSchemaLabels(buildBuilder, log);
addLabelsFromConfig(buildBuilder);
addFrom(buildBuilder);
if (!prePackagePhase) {
buildBuilder.assembly(createDefaultAssembly());
Expand Down
Expand Up @@ -125,6 +125,7 @@ public List<ImageConfiguration> customize(List<ImageConfiguration> configs, bool
handler.runCmds().forEach(buildBuilder::runCmd);

addSchemaLabels(buildBuilder, log);
addLabelsFromConfig(buildBuilder);
if (!prePackagePhase) {
buildBuilder.assembly(createAssembly(handler));
}
Expand Down
Expand Up @@ -144,6 +144,7 @@ void withOverriddenProperties_shouldAddImageConfiguration() throws IOException {
projectProperties.put("jkube.generator.webapp.ports", "8082,80");
projectProperties.put("jkube.generator.webapp.supportsS2iBuild", "true");
projectProperties.put("jkube.generator.from", "image-to-trigger-custom-app-server-handler");
projectProperties.put("jkube.generator.labels", "app=webapp");

generatorContext = generatorContext.toBuilder()
.runtimeMode(RuntimeMode.OPENSHIFT)
Expand All @@ -167,6 +168,7 @@ void withOverriddenProperties_shouldAddImageConfiguration() throws IOException {
.hasFieldOrPropertyWithValue("ports", Arrays.asList("8082", "80"))
.hasFieldOrPropertyWithValue("env", Collections.singletonMap("DEPLOY_DIR", "/other-dir"))
.hasFieldOrPropertyWithValue("cmd.shell", "sleep 3600")
.hasFieldOrPropertyWithValue("labels.app", "webapp")
.extracting(BuildConfiguration::getAssembly)
.hasFieldOrPropertyWithValue("excludeFinalOutputArtifact", true)
.hasFieldOrPropertyWithValue("user", "root")
Expand Down

0 comments on commit 1fd72cd

Please sign in to comment.