From 2edfb6f1187e69a497959b3835329ed64944055a Mon Sep 17 00:00:00 2001 From: shemuwel Date: Mon, 8 Jan 2024 02:54:25 +0200 Subject: [PATCH] Add parameter expansion for custom labels - deprecate verified/code-review minimum vote calculation methods - create string based label methods for minimum voting calcs and aggregate all categories (verified & code-review included) into the templated command allowing them to be expanded later all together - remove redundant test (in which the scenario was testing the min. voting calculation for the Verified label by using its associated method instead of testing the scenario via getBuildCompletedCommand) - update tests to check for the newly added custom label --- .../gerrit/trigger/VerdictCategory.java | 16 ++ .../plugins/gerrit/trigger/config/Config.java | 25 +-- .../gerrit/trigger/config/Constants.java | 23 +++ .../gerritnotifier/ParameterExpander.java | 124 +++++++++--- .../GerritTriggerDescriptor.java | 3 +- .../gerritnotifier/ParameterExpanderTest.java | 182 +++++++++++------- .../mock/MockGerritHudsonTriggerConfig.java | 5 + .../plugins/gerrit/trigger/mock/Setup.java | 72 ++++--- .../SpecGerritVerifiedSetterTest.java | 6 +- 9 files changed, 303 insertions(+), 153 deletions(-) diff --git a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/VerdictCategory.java b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/VerdictCategory.java index b85fd2bd7..ccc28c624 100644 --- a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/VerdictCategory.java +++ b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/VerdictCategory.java @@ -234,6 +234,22 @@ public void setVerdictVote(BuildStatus status, Integer vote) { } } + /** + * Returns the value formatted as a placeholder. + * @return the value formatted as a placeholder. + */ + public String getPlaceholderValue() { + return verdictValue.toUpperCase().replace("-", "_"); + } + + /** + * Returns the original verdict category name + * @param placeholderValue the value to convert + * @return original verdict category name + */ + public static String fromPlaceholderValue(String placeholderValue) { + return placeholderValue.toLowerCase().replace("_", "-"); + } /** * The Descriptor for a VerdictCategory. diff --git a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/config/Config.java b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/config/Config.java index 0e39654f5..fef1b50d1 100644 --- a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/config/Config.java +++ b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/config/Config.java @@ -50,8 +50,7 @@ import java.util.concurrent.TimeUnit; //CS IGNORE LineLength FOR NEXT 11 LINES. REASON: static import. -import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.CODE_REVIEW_LABEL; -import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.VERIFIED_LABEL; +import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.*; import static com.sonymobile.tools.gerrit.gerritevents.GerritDefaultValues.DEFAULT_BUILD_SCHEDULE_DELAY; import static com.sonymobile.tools.gerrit.gerritevents.GerritDefaultValues.DEFAULT_GERRIT_AUTH_KEY_FILE; import static com.sonymobile.tools.gerrit.gerritevents.GerritDefaultValues.DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD; @@ -162,26 +161,6 @@ public class Config implements IGerritHudsonTriggerConfig { /** * Global default for notification level. */ - public static final Notify DEFAULT_NOTIFICATION_LEVEL = Notify.ALL; - - private static final String GERRIT_CMD_BUILD_STARTED_DEFAULT_VALUE = "gerrit review , " - + "--message 'Build Started ' " - + "--verified --code-review --tag " + Constants.TAG_VALUE; - private static final String GERRIT_CMD_BUILD_SUCCESSFUL_DEFAULT_VALUE = "gerrit review , " - + "--message 'Build Successful ' " - + "--verified --code-review --tag " + Constants.TAG_VALUE; - private static final String GERRIT_CMD_BUILD_FAILED_DEFAULT_VALUE = "gerrit review , " - + "--message 'Build Failed ' " - + "--verified --code-review --tag " + Constants.TAG_VALUE; - private static final String GERRIT_CMD_BUILD_UNSTABLE_DEFAULT_VALUE = "gerrit review , " - + "--message 'Build Unstable ' " - + "--verified --code-review --tag " + Constants.TAG_VALUE; - private static final String GERRIT_CMD_BUILD_NOT_BUILT_DEFAULT_VALUE = "gerrit review , " - + "--message 'No Builds Executed ' " - + "--verified --code-review --tag " + Constants.TAG_VALUE; - private static final String GERRIT_CMD_BUILD_ABORTED_DEFAULT_VALUE = "gerrit review , " - + "--message 'Build Aborted ' " - + "--verified --code-review --tag " + Constants.TAG_VALUE; private String gerritHostName; private int gerritSshPort; @@ -305,7 +284,7 @@ public void setValues(JSONObject formData) { gerritUserName = formData.optString("gerritUserName", DEFAULT_GERRIT_USERNAME); gerritEMail = formData.optString("gerritEMail", ""); notificationLevel = Notify.valueOf(formData.optString("notificationLevel", - Config.DEFAULT_NOTIFICATION_LEVEL.toString())); + Constants.DEFAULT_NOTIFICATION_LEVEL.toString())); String file = formData.optString("gerritAuthKeyFile", null); if (file != null) { gerritAuthKeyFile = new File(file); diff --git a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/config/Constants.java b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/config/Constants.java index 04a9f3976..e1e071782 100644 --- a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/config/Constants.java +++ b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/config/Constants.java @@ -24,6 +24,8 @@ */ package com.sonyericsson.hudson.plugins.gerrit.trigger.config; +import com.sonymobile.tools.gerrit.gerritevents.dto.rest.Notify; + /** * Global constants. */ @@ -42,6 +44,27 @@ public final class Constants { * Verified review label */ public static final String VERIFIED_LABEL = "Verified"; + + public static final Notify DEFAULT_NOTIFICATION_LEVEL = Notify.ALL; + + public static final String GERRIT_CMD_BUILD_STARTED_DEFAULT_VALUE = "gerrit review , " + + "--message 'Build Started ' " + + "--verified --code-review --tag " + Constants.TAG_VALUE; + public static final String GERRIT_CMD_BUILD_SUCCESSFUL_DEFAULT_VALUE = "gerrit review , " + + "--message 'Build Successful ' " + + "--verified --code-review --tag " + Constants.TAG_VALUE; + public static final String GERRIT_CMD_BUILD_FAILED_DEFAULT_VALUE = "gerrit review , " + + "--message 'Build Failed ' " + + "--verified --code-review --tag " + Constants.TAG_VALUE; + public static final String GERRIT_CMD_BUILD_UNSTABLE_DEFAULT_VALUE = "gerrit review , " + + "--message 'Build Unstable ' " + + "--verified --code-review --tag " + Constants.TAG_VALUE; + public static final String GERRIT_CMD_BUILD_NOT_BUILT_DEFAULT_VALUE = "gerrit review , " + + "--message 'No Builds Executed ' " + + "--verified --code-review --tag " + Constants.TAG_VALUE; + public static final String GERRIT_CMD_BUILD_ABORTED_DEFAULT_VALUE = "gerrit review , " + + "--message 'Build Aborted ' " + + "--verified --code-review --tag " + Constants.TAG_VALUE; /** Internal */ private Constants() { } diff --git a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/gerritnotifier/ParameterExpander.java b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/gerritnotifier/ParameterExpander.java index 876869c26..695ad08cd 100644 --- a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/gerritnotifier/ParameterExpander.java +++ b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/gerritnotifier/ParameterExpander.java @@ -56,6 +56,7 @@ import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.CODE_REVIEW_LABEL; import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.VERIFIED_LABEL; +import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.DEFAULT_NOTIFICATION_LEVEL; import static com.sonyericsson.hudson.plugins.gerrit.trigger.utils.Logic.shouldSkip; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -112,16 +113,7 @@ public String getBuildStartedCommand(Run r, TaskListener taskListener, GerritTrigger trigger = GerritTrigger.getTrigger(r.getParent()); String gerritCmd = config.getGerritCmdBuildStarted(); - Map parameters = createStandardParameters(r, event, - getBuildStartedCodeReviewValue(r), - getBuildStartedVerifiedValue(r), - Notify.ALL.name()); - - for (VerdictCategory category : config.getCategories()) { - String value = category.getVerdictValue(); - String voteValue = String.valueOf(getBuildStatusVote(r, value, BuildStatus.STARTED)); - parameters.put(category.getVerdictValue(), voteValue); - } + Map parameters = createStartedCommandParameters(r, event, Notify.ALL.name()); StringBuilder startedStats = new StringBuilder(); if (stats.getTotalBuildsToStart() > 1) { @@ -256,13 +248,10 @@ public Integer getBuildStatusVote(Run r, String gerritLabel, BuildStatus buildSt * * @param r the build. * @param gerritEvent the event. - * @param codeReview the code review vote. - * @param verified the verified vote. * @param notifyLevel the notify level. * @return the parameters and their values. */ - private Map createStandardParameters(Run r, GerritTriggeredEvent gerritEvent, - Integer codeReview, Integer verified, String notifyLevel) { + private Map createStandardParameters(Run r, GerritTriggeredEvent gerritEvent, String notifyLevel) { // VERIFIED CODE_REVIEW Map map = new HashMap(DEFAULT_PARAMETERS_COUNT); if (gerritEvent instanceof ChangeBasedEvent) { @@ -283,13 +272,30 @@ private Map createStandardParameters(Run r, GerritTriggeredEvent if (r != null) { map.put("BUILDURL", jenkins.getRootUrl() + r.getUrl()); } - map.put("VERIFIED", String.valueOf(verified)); - map.put("CODE_REVIEW", String.valueOf(codeReview)); map.put("NOTIFICATION_LEVEL", notifyLevel); return map; } + /** + * Creates a map of parameters and their values for a started command. + * @param r the build. + * @param gerritEvent the event. + * @param notifyLevel the notify level. + * @return the parameters and their values. + */ + private Map createStartedCommandParameters(Run r, GerritTriggeredEvent gerritEvent, String notifyLevel) { + Map standardParameters = createStandardParameters(r, gerritEvent, notifyLevel); + + for (VerdictCategory category : config.getCategories()) { + System.out.println("Adding verdict category: " + category.getVerdictValue() + " into started command parameters map"); + String voteValue = String.valueOf(getBuildStatusVote(r, category.getVerdictValue(), BuildStatus.STARTED)); + standardParameters.put(category.getPlaceholderValue(), voteValue); + } + + return standardParameters; + } + /** * Expands all types of parameters in the string and returns the "replaced" string. * Both types means both $ENV_VARS and <PLUGIN_VARS> @@ -312,17 +318,63 @@ private String expandParameters(String gerritCommand, Run r, TaskListener taskLi } for (Map.Entry param : parameters.entrySet()) { - command = command.replace("<" + param.getKey() + ">", param.getValue()); + if (param.getValue().equals("null") || param.getValue().equals(String.valueOf(Integer.MAX_VALUE))) { + String labelName = VerdictCategory.fromPlaceholderValue(param.getKey()); + command = command.replace("--" + labelName, ""); + command = command.replace("<" + param.getKey() + ">", ""); + } else { + command = command.replace("<" + param.getKey() + ">", param.getValue()); + } } - //replace null and Integer.MAX_VALUE code review value - command = command.replace("--code-review null", ""); - command = command.replace("--code-review " + Integer.MAX_VALUE, ""); - command = command.replace("--verified null", ""); - command = command.replace("--verified " + Integer.MAX_VALUE, ""); return command; } + /** + * Returns the minimum of the given label vote value for the build results in the memory. + * If no builds have contributed to label's value, this method returns null + * + * @param memoryImprint the memory. + * @param onlyBuilt only count builds that completed (no NOT_BUILT builds) + * @param label the label to get the vote value for. + * @return the lowest verified value. + */ + @CheckForNull + public Integer getMinimumLabelVoteValue(MemoryImprint memoryImprint, + boolean onlyBuilt, + String label) { + Integer minVoteValue = Integer.MAX_VALUE; + for (Entry entry : memoryImprint.getEntries()) { + if (entry == null) { + continue; + } + + Run build = entry.getBuild(); + if (build == null) { + continue; + } + Result result = build.getResult(); + if (onlyBuilt && result == Result.NOT_BUILT) { + continue; + } + + GerritTrigger trigger = GerritTrigger.getTrigger(entry.getProject()); + if (shouldSkip(trigger.getSkipVote(), result)) { + continue; + } + Integer labelVoteValue = getLabelVoteValue(result, trigger, label); + if (labelVoteValue != null) { + minVoteValue = Math.min(minVoteValue, labelVoteValue); + } + } + + if (minVoteValue == Integer.MAX_VALUE) { + return null; + } + + return minVoteValue; + } + /** * Finds the vote value for the specified label and build result on the configured trigger. * @param result the build result. @@ -351,8 +403,10 @@ protected Integer getLabelVoteValue(Result result, * @param onlyBuilt only count builds that completed (no NOT_BUILT builds) * @param maxAllowedVerifiedValue Upper boundary on verified value. * @return the lowest verified value. + * @deprecated use {@link #getMinimumLabelVoteValue(MemoryImprint, boolean, String)}} instead. */ @CheckForNull + @Deprecated public Integer getMinimumVerifiedValue(MemoryImprint memoryImprint, boolean onlyBuilt, Integer maxAllowedVerifiedValue) { Integer verified = Integer.MAX_VALUE; @@ -392,8 +446,10 @@ public Integer getMinimumVerifiedValue(MemoryImprint memoryImprint, boolean only * @param memoryImprint the memory * @param onlyBuilt only count builds that completed (no NOT_BUILT builds) * @return the lowest code review value. + * @deprecated use {@link #getMinimumLabelVoteValue(MemoryImprint, boolean, String)}} instead. */ @CheckForNull + @Deprecated public Integer getMinimumCodeReviewValue(MemoryImprint memoryImprint, boolean onlyBuilt) { Integer codeReview = Integer.MAX_VALUE; for (Entry entry : memoryImprint.getEntries()) { @@ -473,7 +529,7 @@ public Notify getNotificationLevel(GerritTrigger trigger) { if (serverLevel != null) { return serverLevel; } - return Config.DEFAULT_NOTIFICATION_LEVEL; + return DEFAULT_NOTIFICATION_LEVEL; } /** @@ -520,17 +576,27 @@ public String getBuildCompletedCommand(MemoryImprint memoryImprint, TaskListener maxAllowedVerifiedValue = config.getLabelVote(VERIFIED_LABEL, BuildStatus.FAILED); } - Integer verified = null; - Integer codeReview = null; Notify notifyLevel = Notify.ALL; if (memoryImprint.getEvent().isScorable()) { - verified = getMinimumVerifiedValue(memoryImprint, onlyCountBuilt, maxAllowedVerifiedValue); - codeReview = getMinimumCodeReviewValue(memoryImprint, onlyCountBuilt); notifyLevel = getHighestNotificationLevel(memoryImprint, onlyCountBuilt); } - Map parameters = createStandardParameters(null, event, - codeReview, verified, notifyLevel.name()); + Map parameters = createStandardParameters(null, event, notifyLevel.name()); + for (VerdictCategory category : config.getCategories()) { + if (!memoryImprint.getEvent().isScorable()) { + parameters.put(category.getPlaceholderValue(), "null"); + continue; + } + + System.out.println("Adding verdict category: " + category.getVerdictValue() + " into completed build parameters map"); + + Integer voteValue = getMinimumLabelVoteValue(memoryImprint, onlyCountBuilt, category.getVerdictValue()); + if (category.getVerdictValue().equals(Constants.VERIFIED_LABEL) && voteValue != null) { + voteValue = Math.min(voteValue, maxAllowedVerifiedValue); + } + + parameters.put(category.getPlaceholderValue(), String.valueOf(voteValue)); + } // escapes ' as '"'"' in order to avoid breaking command line param // Details: http://stackoverflow.com/a/26165123/99834 diff --git a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/hudsontrigger/GerritTriggerDescriptor.java b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/hudsontrigger/GerritTriggerDescriptor.java index 3092014e2..7c8912e50 100644 --- a/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/hudsontrigger/GerritTriggerDescriptor.java +++ b/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/hudsontrigger/GerritTriggerDescriptor.java @@ -4,6 +4,7 @@ import com.sonyericsson.hudson.plugins.gerrit.trigger.Messages; import com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl; import com.sonyericsson.hudson.plugins.gerrit.trigger.config.Config; +import com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants; import com.sonyericsson.hudson.plugins.gerrit.trigger.config.ReplicationConfig; import com.sonyericsson.hudson.plugins.gerrit.trigger.dependency.DependencyQueueTaskDispatcher; import com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.CompareType; @@ -317,7 +318,7 @@ private static ListBoxModel.Option getOptionForNotificationLevelDefault( } // fall back to global default - String defaultText = levelTextsById.get(Config.DEFAULT_NOTIFICATION_LEVEL); + String defaultText = levelTextsById.get(Constants.DEFAULT_NOTIFICATION_LEVEL); return new ListBoxModel.Option(Messages.NotificationLevel_DefaultValueFromServer(defaultText), ""); } diff --git a/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/gerritnotifier/ParameterExpanderTest.java b/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/gerritnotifier/ParameterExpanderTest.java index 70b628983..2a91dde39 100644 --- a/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/gerritnotifier/ParameterExpanderTest.java +++ b/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/gerritnotifier/ParameterExpanderTest.java @@ -24,8 +24,10 @@ */ package com.sonyericsson.hudson.plugins.gerrit.trigger.gerritnotifier; +import com.sonyericsson.hudson.plugins.gerrit.trigger.VerdictCategory; import com.sonyericsson.hudson.plugins.gerrit.trigger.config.BuildStatus; import com.sonyericsson.hudson.plugins.gerrit.trigger.config.Config; +import com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants; import com.sonyericsson.hudson.plugins.gerrit.trigger.config.IGerritHudsonTriggerConfig; import com.sonyericsson.hudson.plugins.gerrit.trigger.gerritnotifier.model.BuildMemory.MemoryImprint; import com.sonyericsson.hudson.plugins.gerrit.trigger.gerritnotifier.model.BuildsStartedStats; @@ -48,19 +50,28 @@ import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import java.util.stream.Stream; import jenkins.model.Jenkins; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.MockedStatic; +import org.openjdk.jmh.annotations.Param; import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.CODE_REVIEW_LABEL; import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.VERIFIED_LABEL; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat; @@ -86,6 +97,7 @@ public class ParameterExpanderTest { * Mock Jenkins. */ @Before + @BeforeEach public void setup() { jenkinsMockedStatic = mockStatic(Jenkins.class); jenkins = mock(Jenkins.class); @@ -94,6 +106,7 @@ public void setup() { } @After + @AfterEach public void tearDown() throws Exception { jenkinsMockedStatic.close(); } @@ -110,6 +123,7 @@ public void testGetBuildStartedCommand() throws Exception { when(trigger.getLabelVote(VERIFIED_LABEL, BuildStatus.STARTED)).thenReturn(null); when(trigger.getLabelVote(CODE_REVIEW_LABEL, BuildStatus.STARTED)).thenReturn(32); when(trigger.getBuildStartMessage()).thenReturn("${START_MESSAGE_VAR}"); + when(trigger.getLabelVote("Custom-Label", BuildStatus.STARTED)).thenReturn(3); AbstractProject project = mock(AbstractProject.class); Setup.setTrigger(trigger, project); @@ -134,16 +148,17 @@ public void testGetBuildStartedCommand() throws Exception { System.out.println("result: " + result); assertTrue("Missing START_MESSAGE_VAL from getBuildStartMessage()", result.contains("START_MESSAGE_VAL")); - assertTrue("Missing CHANGE_ID", result.contains("CHANGE_ID=Iddaaddaa123456789")); - assertTrue("Missing PATCHSET", result.contains("PATCHSET=1")); - assertTrue("Missing VERIFIED", result.contains("VERIFIED=1")); - assertTrue("Missing CODEREVIEW", result.contains("CODEREVIEW=32")); - assertTrue("Missing NOTIFICATION_LEVEL", result.contains("NOTIFICATION_LEVEL=ALL")); - assertTrue("Missing REFSPEC", result.contains("REFSPEC=" + expectedRefSpec)); - assertTrue("Missing ENV_BRANCH", result.contains("ENV_BRANCH=branch")); - assertTrue("Missing ENV_CHANGE", result.contains("ENV_CHANGE=1000")); - assertTrue("Missing ENV_REFSPEC", result.contains("ENV_REFSPEC=" + expectedRefSpec)); - assertTrue("Missing ENV_CHANGEURL", result.contains("ENV_CHANGEURL=http://gerrit/1000")); + assertTrue("Missing CHANGE_ID", result.contains("change-id Iddaaddaa123456789")); + assertTrue("Missing PATCHSET or CHANGE", result.contains("1000,1")); + assertTrue("Missing VERIFIED", result.contains("--verified 1")); + assertTrue("Missing CODEREVIEW", result.contains("--code-review 32")); + assertTrue("Missing CUSTOMLABEL", result.contains("--custom-label 3")); + assertTrue("Missing NOTIFICATION_LEVEL", result.contains("notification-level ALL")); + assertTrue("Missing REFSPEC", result.contains("refspec " + expectedRefSpec)); + assertTrue("Missing ENV_BRANCH", result.contains("ENV_BRANCH branch")); + assertTrue("Missing ENV_CHANGE", result.contains("ENV_CHANGE 1000")); + assertTrue("Missing ENV_REFSPEC", result.contains("ENV_REFSPEC " + expectedRefSpec)); + assertTrue("Missing ENV_CHANGEURL", result.contains("ENV_CHANGEURL http://gerrit/1000")); assertTrue("Missing CUSTOM_MESSAGE", result.contains("CUSTOM_MESSAGE_BUILD_STARTED")); assertTrue("Newlines are stripped", result.contains("Message\nwith newline")); } @@ -180,12 +195,12 @@ public void testGetMinimumVerifiedValue() { // When not all results are NOT_BUILT, we should ignore NOT_BUILT. int expResult = -1; - int result = instance.getMinimumVerifiedValue(memoryImprint, true, Integer.MAX_VALUE); + int result = instance.getMinimumLabelVoteValue(memoryImprint, true, VERIFIED_LABEL); assertEquals(expResult, result); // Otherwise, we should use NOT_BUILT. expResult = -4; - result = instance.getMinimumVerifiedValue(memoryImprint, false, Integer.MAX_VALUE); + result = instance.getMinimumLabelVoteValue(memoryImprint, false, VERIFIED_LABEL); assertEquals(expResult, result); } @@ -219,17 +234,17 @@ public void testGetMinimumCodeReviewValue() { when(memoryImprint.getEntries()).thenReturn(entries); // When not all results are NOT_BUILT, we should ignore NOT_BUILT. - Integer result = instance.getMinimumCodeReviewValue(memoryImprint, true); + Integer result = instance.getMinimumLabelVoteValue(memoryImprint, true, CODE_REVIEW_LABEL); assertEquals(Integer.valueOf(-1), result); // Otherwise, we should use NOT_BUILT. - result = instance.getMinimumCodeReviewValue(memoryImprint, false); + result = instance.getMinimumLabelVoteValue(memoryImprint, false, CODE_REVIEW_LABEL); assertEquals(Integer.valueOf(-4), result); } /** - * Tests {@link ParameterExpander#getMinimumCodeReviewValue(MemoryImprint, boolean)} with one - * unstable build vote skipped. + * Tests {@link ParameterExpander#getMinimumLabelVoteValue(MemoryImprint, boolean, String)} with one + * unstable build vote skipped for Code-Review label. * * @see com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritTrigger#getSkipVote() */ @@ -258,13 +273,13 @@ public void testGetMinimumCodeReviewValueOneUnstableSkipped() { when(memoryImprint.getEntries()).thenReturn(entries); - Integer result = instance.getMinimumCodeReviewValue(memoryImprint, true); + Integer result = instance.getMinimumLabelVoteValue(memoryImprint, true, CODE_REVIEW_LABEL); assertEquals(Integer.valueOf(1), result); } /** - * Tests {@link ParameterExpander#getMinimumCodeReviewValue(MemoryImprint, boolean)} with one - * successful build vote skipped. + * Tests {@link ParameterExpander#getMinimumLabelVoteValue(MemoryImprint, boolean, String)} with one + * successful build vote skipped for Code-Review label. * * @see com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritTrigger#getSkipVote() */ @@ -284,13 +299,13 @@ public void testGetMinimumCodeReviewValueOneSuccessfulSkipped() { when(memoryImprint.getEntries()).thenReturn(entries); - Integer result = instance.getMinimumCodeReviewValue(memoryImprint, true); + Integer result = instance.getMinimumLabelVoteValue(memoryImprint, true, CODE_REVIEW_LABEL); assertNull(result); } /** - * Tests {@link ParameterExpander#getMinimumCodeReviewValue(MemoryImprint, boolean)} with one - * job that has override core review value on build successful. + * Tests {@link ParameterExpander#getMinimumLabelVoteValue(MemoryImprint, boolean, String)} with one + * job that has override core review value on build successful for Code-Review label. * * @see com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritTrigger#getSkipVote() */ @@ -314,13 +329,13 @@ public void testGetMinimumCodeReviewValueForOneJobOverridenBuildSuccessful() { // Since one job has overriden CR value, it is the only one inspected // and therefore the only one that contributes. - Integer result = instance.getMinimumCodeReviewValue(memoryImprint, false); + Integer result = instance.getMinimumLabelVoteValue(memoryImprint, false, CODE_REVIEW_LABEL); assertEquals(Integer.valueOf(2), result); } /** - * Tests {@link ParameterExpander#getMinimumCodeReviewValue(MemoryImprint, boolean)} with one - * job that has override core review value on build successful. + * Tests {@link ParameterExpander#getMinimumLabelVoteValue(MemoryImprint, boolean, String)} with one + * job that has override core review value on build successful for Code-Review label. * * @see com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritTrigger#getSkipVote() */ @@ -344,13 +359,13 @@ public void testGetMinimumCodeReviewValueForOneJobOverridenBuildFailed() { // Since one job has overriden CR value, it is the only one inspected // and therefore the only one that contributes. - Integer result = instance.getMinimumCodeReviewValue(memoryImprint, false); + Integer result = instance.getMinimumLabelVoteValue(memoryImprint, false, CODE_REVIEW_LABEL); assertEquals(Integer.valueOf(-2), result); } /** - * Tests {@link ParameterExpander#getMinimumCodeReviewValue(MemoryImprint, boolean)} with one - * job that has override core review value on build successful. + * Tests {@link ParameterExpander#getMinimumLabelVoteValue(MemoryImprint, boolean, String)} with one + * job that has override core review value on build successful for Code-Review label. * * @see com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritTrigger#getSkipVote() */ @@ -374,39 +389,10 @@ public void testGetMinimumCodeReviewValueForOneJobOverridenMixed() { // Since one job has overriden CR value, it is the only one inspected // and therefore the only one that contributes. - Integer result = instance.getMinimumCodeReviewValue(memoryImprint, false); + Integer result = instance.getMinimumLabelVoteValue(memoryImprint, false, CODE_REVIEW_LABEL); assertEquals(Integer.valueOf(2), result); } - /** - * Tests {@link ParameterExpander#getMinimumVerifiedValue(MemoryImprint, boolean, Integer)} with two - * jobs. One successful build, the other failed missing build (null). - * - */ - @Test - public void testGetVerifiedValueOneSuccessJobAndMissingFailedJob() { - IGerritHudsonTriggerConfig config = Setup.createMockableConfig(); - - ParameterExpander instance = new ParameterExpander(config, jenkins); - MemoryImprint memoryImprint = mock(MemoryImprint.class); - MemoryImprint.Entry[] entries = new MemoryImprint.Entry[2]; - - GerritTrigger trigger = mock(GerritTrigger.class); - when(trigger.getLabelVote(VERIFIED_LABEL, BuildStatus.FAILED)).thenReturn(Integer.valueOf(2)); - entries[0] = Setup.createAndSetupMemoryImprintEntry(trigger, Result.SUCCESS); - - trigger = mock(GerritTrigger.class); - entries[1] = Setup.createAndSetupMemoryImprintEntryWithEmptyBuild(trigger); - - when(memoryImprint.getEntries()).thenReturn(entries); - - // The only verified value available is of successful build, - // but score should be saturated to Failed verified value from config. - Integer result = instance.getMinimumVerifiedValue(memoryImprint, false, - config.getLabelVote(VERIFIED_LABEL, BuildStatus.FAILED)); - assertEquals(config.getLabelVote(VERIFIED_LABEL, BuildStatus.FAILED), result); - } - /** * test. * @throws IOException IOException @@ -431,7 +417,7 @@ public void testGetBuildCompletedCommandSuccessful() throws IOException, Interru public void testGetBuildCompletedCommandNotBuilt() throws IOException, InterruptedException { tryGetBuildCompletedCommandEventWithResults("", new String[] {}, new Result[] {Result.NOT_BUILT}, Setup.createPatchsetCreated(), - null, null, "NONE", false); + null, null, null, "NONE", false); } /** @@ -495,7 +481,7 @@ public void testGetBuildCompletedCommandMulipleBuildsMessageOrder() throws IOExc "\n\nhttp://localhost/test/ : UNSTABLE", "\n\nhttp://localhost/test/ : SUCCESS", }, new Result[] {Result.SUCCESS, Result.FAILURE, Result.UNSTABLE}, - Setup.createPatchsetCreated(), -1, 0); + Setup.createPatchsetCreated(), -1, 0, 0); } /** @@ -530,7 +516,7 @@ public void testGetBuildCompletedMissingFailedBuild() throws IOException, Interr ParameterExpander instance = new ParameterExpander(config, jenkins); String result = instance.getBuildCompletedCommand(memoryImprint, taskListener, null); - assertThat("Missing VERIFIED", result, containsString("VERIFIED=" + expectedVerifiedVote)); + assertThat("Missing VERIFIED", result, containsString("--verified " + expectedVerifiedVote)); } /** @@ -604,7 +590,7 @@ public void tryGetBuildCompletedCommandSuccessfulEvent(String customUrl, String GerritTriggeredEvent event, Integer expectedVerifiedVote, Integer expectedCodeReviewVote) throws IOException, InterruptedException { tryGetBuildCompletedCommandEventWithResults(customUrl, new String[] {expectedBuildsStats}, - new Result[] {Result.SUCCESS}, Setup.createChangeRestored(), null, null); + new Result[] {Result.SUCCESS}, Setup.createChangeRestored(), null, null, null); } /** @@ -624,13 +610,75 @@ public void tryGetBuildCompletedCommandSuccessfulEvent(String customUrl, String */ public void tryGetBuildCompletedCommandEventWithResults(String customUrl, String[] expectedBuildsStats, Result[] expectedBuildResults, GerritTriggeredEvent event, - Integer expectedVerifiedVote, Integer expectedCodeReviewVote) + Integer expectedVerifiedVote, Integer expectedCodeReviewVote, Integer expectedCustomLabelVote) throws IOException, InterruptedException { tryGetBuildCompletedCommandEventWithResults(customUrl, expectedBuildsStats, - expectedBuildResults, event, expectedVerifiedVote, expectedCodeReviewVote, + expectedBuildResults, event, expectedVerifiedVote, expectedCodeReviewVote, expectedCustomLabelVote, "ALL", true); } + private static Stream gerritCommandsWithVariousConfigsCases() { + return Stream.of( + Arguments.of(-1, 2, 3, Setup.createChangeMerged(), Result.SUCCESS, + not(containsStrings("--verified")), + not(containsString("--code-review")), + not(containsString("--custom-label"))), + Arguments.of(null, 2, 3, Setup.createPatchsetCreated(), Result.SUCCESS, + containsStrings("--verified 3"), + containsStrings("--code-review 2"), + containsStrings("--custom-label 3")), + Arguments.of(null, null, 3, Setup.createPatchsetCreated(), Result.SUCCESS, + containsStrings("--verified 3"), + containsStrings("--code-review 4"), + containsStrings("--custom-label 3")), + Arguments.of(null, null, null, Setup.createPatchsetCreated(), Result.SUCCESS, + containsStrings("--verified 3"), + containsStrings("--code-review 4"), + containsStrings("--custom-label 0")) + ); + } + + @ParameterizedTest + @MethodSource("gerritCommandsWithVariousConfigsCases") + public void testGerritCommandsWithVariousConfigs( + Integer givenVerifiedVote, + Integer givenCodeReviewVote, + Integer givenCustomLabelVote, + GerritTriggeredEvent event, + Result givenBuildResult, + Matcher expectedCodeReviewVote, + Matcher expectedVerifiedVote, + Matcher expectedCustomLabelVote) throws IOException, InterruptedException { + + IGerritHudsonTriggerConfig config = Setup.createMockableConfig(); + TaskListener taskListener = mock(TaskListener.class); + + GerritTrigger trigger = mock(GerritTrigger.class); + when(trigger.getLabelVote(VERIFIED_LABEL, BuildStatus.SUCCESSFUL)).thenReturn(givenVerifiedVote); + when(trigger.getLabelVote(CODE_REVIEW_LABEL, BuildStatus.SUCCESSFUL)).thenReturn(givenCodeReviewVote); + when(trigger.getLabelVote("Custom-Label", BuildStatus.SUCCESSFUL)).thenReturn(givenCustomLabelVote); + when(trigger.getCustomUrl()).thenReturn(""); + AbstractProject project = mock(AbstractProject.class); + Setup.setTrigger(trigger, project); + + EnvVars envVars = Setup.createEnvVars(); + AbstractBuild build = Setup.createBuild(project, taskListener, envVars); + when(build.getResult()).thenReturn(givenBuildResult); + MemoryImprint.Entry entry = Setup.createImprintEntry(project, build); + + MemoryImprint memoryImprint = mock(MemoryImprint.class); + when(memoryImprint.getEvent()).thenReturn(event); + when(memoryImprint.getEntries()).thenReturn(new MemoryImprint.Entry[] {entry}); + when(memoryImprint.wereAllBuildsSuccessful()).thenReturn(true); + + ParameterExpander instance = new ParameterExpander(config, jenkins); + String result = instance.getBuildCompletedCommand(memoryImprint, taskListener, null); + + assertThat("Incorrect Verified vote value", result, expectedVerifiedVote); + assertThat("Incorrect Code-Review vote value", result, expectedCodeReviewVote); + assertThat("Incorrect Custom label vote value", result, expectedCustomLabelVote); + } + /** * Sub test for {@link #testGetBuildCompletedCommandSuccessful()} and * {@link #testGetBuildCompletedCommandSuccessfulChangeMerged()}. @@ -648,8 +696,8 @@ public void tryGetBuildCompletedCommandEventWithResults(String customUrl, String */ public void tryGetBuildCompletedCommandEventWithResults(String customUrl, String[] expectedBuildsStats, Result[] expectedBuildResults, GerritTriggeredEvent event, - Integer expectedVerifiedVote, Integer expectedCodeReviewVote, String expectedNotificationLevel, - boolean createBuild) + Integer expectedVerifiedVote, Integer expectedCodeReviewVote, Integer expectedCustomLabelVote, + String expectedNotificationLevel, boolean createBuild) throws IOException, InterruptedException { IGerritHudsonTriggerConfig config = Setup.createConfig(); @@ -660,6 +708,7 @@ public void tryGetBuildCompletedCommandEventWithResults(String customUrl, String GerritTrigger trigger = mock(GerritTrigger.class); when(trigger.getLabelVote(VERIFIED_LABEL, BuildStatus.SUCCESSFUL)).thenReturn(null); when(trigger.getLabelVote(CODE_REVIEW_LABEL, BuildStatus.SUCCESSFUL)).thenReturn(32); + when(trigger.getLabelVote("Custom-Label", BuildStatus.SUCCESSFUL)).thenReturn(2); when(trigger.getCustomUrl()).thenReturn(customUrl); AbstractProject project = mock(AbstractProject.class); Setup.setTrigger(trigger, project); @@ -721,6 +770,7 @@ public void tryGetBuildCompletedCommandEventWithResults(String customUrl, String } assertThat("Missing VERIFIED", result, containsString("VERIFIED=" + expectedVerifiedVote)); assertThat("Missing CODEREVIEW", result, containsString("CODEREVIEW=" + expectedCodeReviewVote)); + assertThat("Missing CUSTOMLABEL", result, containsString("CUSTOMLABEL=" + expectedCustomLabelVote)); } } diff --git a/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/MockGerritHudsonTriggerConfig.java b/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/MockGerritHudsonTriggerConfig.java index 473d1f046..d0456452f 100644 --- a/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/MockGerritHudsonTriggerConfig.java +++ b/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/MockGerritHudsonTriggerConfig.java @@ -44,6 +44,9 @@ import org.apache.http.auth.Credentials; +import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.CODE_REVIEW_LABEL; +import static com.sonyericsson.hudson.plugins.gerrit.trigger.config.Constants.VERIFIED_LABEL; + /** * Mock class of a Config. * @author Robert Sandell <robert.sandell@sonyericsson.com> @@ -418,6 +421,8 @@ public List getCategories() { "Custom-Label", -1,-2,-3,-4,-5,-6); return new LinkedList<>() { { + add(new VerdictCategory(VERIFIED_LABEL, VERIFIED_LABEL, 1, 2, 3, 4, 5, 6)); + add(new VerdictCategory(CODE_REVIEW_LABEL, CODE_REVIEW_LABEL, -1, -2, -3, -4, -5, -6)); add(verdictCategory); } }; diff --git a/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/Setup.java b/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/Setup.java index 4ab3ef316..e5a9ee270 100644 --- a/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/Setup.java +++ b/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/Setup.java @@ -148,39 +148,49 @@ public static IGerritHudsonTriggerConfig createMockableConfig() { when(config.getLabelVote(VERIFIED_LABEL, BuildStatus.NOT_BUILT)).thenReturn(-5); when(config.getLabelVote(VERIFIED_LABEL, BuildStatus.ABORTED)).thenReturn(-2); - when(config.getGerritCmdBuildFailed()).thenReturn("CHANGE=" - + " CHANGE_ID=" - + " PATCHSET=" - + " VERIFIED=-1" - + " CODEREVIEW=" - + " CUSTOMLABEL=" - + " NOTIFICATION_LEVEL=" - + " REFSPEC= MSG='Build Failed '" - + " BUILDURL=" - + " STARTED_STATS=" - + " ENV_BRANCH=$BRANCH" - + " ENV_CHANGE=$CHANGE" - + " ENV_PATCHSET=$PATCHSET" - + " ENV_REFSPEC=$REFSPEC" - + " ENV_CHANGEURL=$CHANGE_URL"); - when(config.getGerritCmdBuildStarted()).thenReturn("CHANGE=" - + " CHANGE_ID=" - + " PATCHSET=" - + " VERIFIED=" - + " CODEREVIEW=" - + " CUSTOMLABEL=" - + " NOTIFICATION_LEVEL=" - + " REFSPEC= MSG=I started a build." - + " BUILDURL=" - + " STARTED_STATS=" - + " ENV_BRANCH=$BRANCH" - + " ENV_CHANGE=$CHANGE" - + " ENV_PATCHSET=$PATCHSET" - + " ENV_REFSPEC=$REFSPEC" - + " ENV_CHANGEURL=$CHANGE_URL" - + " Message\nwith newline"); + when(config.getGerritCmdBuildFailed()).thenReturn(Constants.GERRIT_CMD_BUILD_FAILED_DEFAULT_VALUE + + " --custom-label " + + " change-id " + + " notification-level " + + " refspec " + + " ENV_BRANCH $BRANCH" + + " ENV_CHANGE $CHANGE" + + " ENV_PATCHSET $PATCHSET" + + " ENV_REFSPEC $REFSPEC" + + " ENV_CHANGEURL $CHANGE_URL" + + " Message\nwith newline"); + when(config.getGerritCmdBuildStarted()).thenReturn(Constants.GERRIT_CMD_BUILD_STARTED_DEFAULT_VALUE + + " --custom-label " + + " change-id " + + " notification-level " + + " refspec " + + " ENV_BRANCH $BRANCH" + + " ENV_CHANGE $CHANGE" + + " ENV_PATCHSET $PATCHSET" + + " ENV_REFSPEC $REFSPEC" + + " ENV_CHANGEURL $CHANGE_URL" + + " Message\nwith newline"); + when(config.getGerritCmdBuildSuccessful()).thenReturn(Constants.GERRIT_CMD_BUILD_SUCCESSFUL_DEFAULT_VALUE + + " --custom-label " + + " change-id " + + " notification-level " + + " refspec " + + " ENV_BRANCH $BRANCH" + + " ENV_CHANGE $CHANGE" + + " ENV_PATCHSET $PATCHSET" + + " ENV_REFSPEC $REFSPEC" + + " ENV_CHANGEURL $CHANGE_URL" + + " Message\nwith newline"); when(config.isEnablePluginMessages()).thenReturn(true); + when(config.getCategories()).thenReturn( + new LinkedList<>() { + { + add(new VerdictCategory(VERIFIED_LABEL, VERIFIED_LABEL, 1, 2, 3, 4, 5, 6)); + add(new VerdictCategory(CODE_REVIEW_LABEL, CODE_REVIEW_LABEL, -1, -2, -3, -4, -5, -6)); + add(new VerdictCategory("Custom-Label", "Custom-Label", -1, -2, -3, -4, -5, -6)); + } + }); return config; } diff --git a/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/spec/gerritnotifier/SpecGerritVerifiedSetterTest.java b/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/spec/gerritnotifier/SpecGerritVerifiedSetterTest.java index 840c0264a..a9d9bfa58 100644 --- a/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/spec/gerritnotifier/SpecGerritVerifiedSetterTest.java +++ b/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/spec/gerritnotifier/SpecGerritVerifiedSetterTest.java @@ -146,7 +146,7 @@ public void shouldCallGerritWithVerifiedOkFlagWhenBuildWasSuccessful() BuildMemory memory = new BuildMemory(); memory.completed(event, build); - IGerritHudsonTriggerConfig config = mock(IGerritHudsonTriggerConfig.class); + IGerritHudsonTriggerConfig config = Setup.createMockableConfig(); String parameterString = "gerrit review MSG=OK VERIFIED= CODEREVIEW="; when(config.getGerritCmdBuildSuccessful()).thenReturn(parameterString); @@ -176,7 +176,7 @@ public void shouldCallGerritWithVerifiedRejectFlagWhenBuildWasNotSuccessful() memory.completed(event, build); - IGerritHudsonTriggerConfig config = mock(IGerritHudsonTriggerConfig.class); + IGerritHudsonTriggerConfig config = Setup.createMockableConfig(); String parameterString = "gerrit review MSG=Failed VERIFIED= CODEREVIEW="; when(config.getGerritCmdBuildFailed()).thenReturn(parameterString); @@ -227,7 +227,7 @@ public void shouldCallGerritWithVerifiedFailedFlagWhenBuildOneBuildFailedAndAnot memory.completed(event, build); - IGerritHudsonTriggerConfig config = mock(IGerritHudsonTriggerConfig.class); + IGerritHudsonTriggerConfig config = Setup.createMockableConfig(); String parameterString = "gerrit review MSG=FAILED VERIFIED= CODEREVIEW="; when(config.getGerritCmdBuildFailed()).thenReturn(parameterString);