Skip to content

Commit

Permalink
Improve tests and cleanup code (#80)
Browse files Browse the repository at this point in the history
* Improve tests and cleanup code

* Fix upper bound deps

Co-authored-by: res0nance <[email protected]>
  • Loading branch information
res0nance and res0nance authored Dec 22, 2020
1 parent e9c8abe commit 757de17
Show file tree
Hide file tree
Showing 10 changed files with 154 additions and 39 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ Example Output in Jenkins
## Scripted Pipeline Example

```
properties(
properties([
parameters([
string(name: 'PLANET', defaultValue: 'Earth', description: 'Which planet are we on?'),
string(name: 'GREETING', defaultValue: 'Hello', description: 'How shall we greet?')
Expand All @@ -95,5 +95,5 @@ properties(
parameterizedCron('*/2 * * * * %GREETING=Hola;PLANET=Pluto'),
parameterizedCron('*/3 * * * * %PLANET=Mars')
])
)
])
```
29 changes: 27 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,39 @@
</pluginRepositories>

<dependencies>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-job</artifactId>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>structs</artifactId>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-cps</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-multibranch</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkinsci.plugins</groupId>
<artifactId>pipeline-model-definition</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<!-- Upper bound dependencies -->
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-job</artifactId>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>jackson2-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,14 @@ public long getInitialDelay() {

@Override
protected void doRun() throws Exception {
Jenkins instance = Jenkins.getInstance();
Jenkins instance = Jenkins.get();

if (instance == null) { // soon to be removed, on 2.4 IIRC
throw new IllegalStateException("Jenkins instance cannot really be null at this point");
}

for (AbstractProject<?, ?> project : instance.getAllItems(AbstractProject.class)) {
for (AbstractProject<?, ?> project : instance.allItems(AbstractProject.class)) {
checkTriggers(project.getName(), project.getTriggers().values(), new GregorianCalendar());
}

if (instance.getPlugin("workflow-job") != null) {
for (WorkflowJob workflowJob : instance.getAllItems(WorkflowJob.class)) {
checkTriggers(workflowJob.getName(), workflowJob.getTriggers().values(), new GregorianCalendar());
}
for (WorkflowJob workflowJob : instance.allItems(WorkflowJob.class)) {
checkTriggers(workflowJob.getName(), workflowJob.getTriggers().values(), new GregorianCalendar());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import hudson.triggers.TriggerDescriptor;
import hudson.util.FormValidation;
import org.jenkinsci.Symbol;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.QueryParameter;
Expand All @@ -31,13 +30,9 @@ public DescriptorImpl() {
public boolean isApplicable(Item item) {
boolean result = false;

Jenkins jenkins = Jenkins.getInstance();

if (item instanceof AbstractProject) {
result = ((AbstractProject) item).isParameterized();
} else if (jenkins != null &&
jenkins.getPlugin("workflow-job") != null &&
item instanceof WorkflowJob) {
} else if (item instanceof WorkflowJob) {
result = ((WorkflowJob) item).isParameterized();
}
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
import hudson.model.ParametersDefinitionProperty;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.parameterizedscheduler.Messages;

import com.google.common.base.Splitter;
import com.google.common.collect.Maps;

public class ParameterParser {
/**
Expand All @@ -27,7 +27,7 @@ public class ParameterParser {
*/
public Map<String, String> parse(String nameValuePairFormattedString) {
if (StringUtils.isBlank(nameValuePairFormattedString)) {
return Maps.<String, String> newHashMap();
return Collections.emptyMap();
}
String clean = nameValuePairFormattedString.trim();
if (nameValuePairFormattedString.endsWith(PAIR_SEPARATOR)) {
Expand All @@ -39,16 +39,16 @@ public Map<String, String> parse(String nameValuePairFormattedString) {

public String checkSanity(String cronTabSpec, ParametersDefinitionProperty parametersDefinitionProperty) {
String[] cronTabLines = cronTabSpec.split("\\r?\\n");
for (int i = 0; i < cronTabLines.length; i++) {
String[] split = cronTabLines[i].split(PARAMETER_SEPARATOR);
for (String cronTabLine : cronTabLines) {
String[] split = cronTabLine.split(PARAMETER_SEPARATOR);
if (split.length > 2) {
return Messages.ParameterizedTimerTrigger_MoreThanOnePercent();
}
if (split.length == 2) {
try {
Map<String, String> parsedParameters = parse(split[1]);
List<String> parameterDefinitionNames = parametersDefinitionProperty.getParameterDefinitionNames();
List<String> parsedKeySet = new ArrayList<String>(parsedParameters.keySet());
List<String> parsedKeySet = new ArrayList<>(parsedParameters.keySet());
parsedKeySet.removeAll(parameterDefinitionNames);
if (!parsedKeySet.isEmpty()) {
return Messages.ParameterizedTimerTrigger_UndefinedParameter(parsedKeySet, parameterDefinitionNames);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.google.common.collect.Maps;

import antlr.ANTLRException;
import hudson.scheduler.CronTab;
import hudson.scheduler.CronTabList;
Expand Down Expand Up @@ -38,7 +37,7 @@ public ParameterizedCronTab(CronTab cronTab, Map<String, String> parameters) {
public static ParameterizedCronTab create(String line, int lineNumber, Hash hash) throws ANTLRException {
String[] lineParts = line.split("%");
CronTab cronTab = new CronTab(lineParts[0].trim(), lineNumber, hash);
Map<String, String> parameters = Maps.newHashMap();
Map<String, String> parameters = new HashMap<>();
if (lineParts.length == 2) {
parameters = new ParameterParser().parse(lineParts[1]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static ParameterizedCronTabList create(String cronTabSpecification) throw
}

public static ParameterizedCronTabList create(String cronTabSpecification, Hash hash) throws ANTLRException {
List<ParameterizedCronTab> result = new ArrayList<ParameterizedCronTab>();
List<ParameterizedCronTab> result = new ArrayList<>();
int lineNumber = 0;
for (String line : cronTabSpecification.split("\\r?\\n")) {
lineNumber++;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package org.jenkinsci.plugins.parameterizedscheduler;

import hudson.model.*;
import hudson.model.AbstractProject;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Job;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.scheduler.Hash;
import hudson.triggers.Trigger;

Expand All @@ -11,8 +18,6 @@
import java.util.logging.Level;
import java.util.logging.Logger;

import hudson.triggers.TriggerDescriptor;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.kohsuke.stapler.DataBoundConstructor;

Expand Down Expand Up @@ -46,12 +51,11 @@ public void run() {
* @param parameterValues
* @return the ParameterValues as set from the crontab row or their defaults
*/
@SuppressWarnings("unchecked")
private List<ParameterValue> configurePropertyValues(Map<String, String> parameterValues) {
assert job != null : "job must not be null if this was 'started'";
ParametersDefinitionProperty paramDefProp = (ParametersDefinitionProperty) job
.getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
List<ParameterValue> defValues = new ArrayList<>();

/* Scan for all parameter with an associated default values */
for (ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) {
Expand All @@ -71,15 +75,14 @@ private List<ParameterValue> configurePropertyValues(Map<String, String> paramet
public void checkCronTabsAndRun(Calendar calendar) {
LOGGER.fine("checking and maybe running at " + calendar);
ParameterizedCronTab cronTab = cronTabList.check(calendar);
Jenkins jenkins = Jenkins.getInstance();

if (cronTab != null) {
Map<String, String> parameterValues = cronTab.getParameterValues();
ParametersAction parametersAction = new ParametersAction(configurePropertyValues(parameterValues));
assert job != null : "job must not be null, if this was 'started'";
if (job instanceof AbstractProject) {
((AbstractProject) job).scheduleBuild2(0, (Cause)null, causeAction(parameterValues), parametersAction);
} else if (jenkins != null && jenkins.getPlugin("workflow-job") != null && job instanceof WorkflowJob) {
} else if (job instanceof WorkflowJob) {
((WorkflowJob) job).scheduleBuild2(0, causeAction(parameterValues), parametersAction);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.jenkinsci.plugins.parameterizedscheduler;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
Expand All @@ -9,8 +10,6 @@
import java.util.GregorianCalendar;
import java.util.Map;

import org.jenkinsci.plugins.parameterizedscheduler.ParameterizedCronTab;
import org.jenkinsci.plugins.parameterizedscheduler.ParameterizedCronTabList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
Expand All @@ -31,7 +30,7 @@ public void create() throws Exception {
ParameterizedCronTabList testObject = ParameterizedCronTabList.create("* * * * *%foo=bar");
assertTrue(testObject.checkSanity(), testObject.checkSanity().startsWith("Do you really mean \"every minute\""));
ParameterizedCronTab actualCronTab = testObject.check(new GregorianCalendar());
assertTrue(actualCronTab != null);
assertNotNull(actualCronTab);

Map<String, String> expected = Maps.newHashMap();
expected.put("foo", "bar");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package org.jenkinsci.plugins.parameterizedscheduler;

import hudson.model.FreeStyleProject;
import hudson.model.Job;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.StringParameterDefinition;
import hudson.triggers.Trigger;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;

public class ParameterizedSchedulerTest {

@Rule
public JenkinsRule r = new JenkinsRule();

@Test
public void freestyle() throws Exception {
FreeStyleProject p = r.createFreeStyleProject();
p.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("foo", "lol")));
assertThat(p.getLastCompletedBuild(), is(nullValue()));
Trigger<Job> t = new ParameterizedTimerTrigger("* * * * *%foo=bar");
t.start(p, true);
p.addTrigger(t);
new Cron().doRun();
assertThat(p.isInQueue(), is(true));
r.waitUntilNoActivity();
assertThat(p.getLastCompletedBuild(), is(notNullValue()));
assertThat((String) p.getLastCompletedBuild().getAction(ParametersAction.class).getParameter("foo").getValue(), is("bar"));
}

@Test
public void pipeline() throws Exception {
WorkflowJob p = r.createProject(WorkflowJob.class);
p.setDefinition(new CpsFlowDefinition("", true));
WorkflowRun wfr = p.scheduleBuild2(0).get();
p.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("foo", "lol")));
Trigger<Job> t = new ParameterizedTimerTrigger("* * * * *%foo=bar");
t.start(p, true);
p.addTrigger(t);
new Cron().doRun();
r.waitUntilNoActivity();
assertThat(p.getLastCompletedBuild(), is(not(wfr)));
assertThat((String) p.getLastCompletedBuild().getAction(ParametersAction.class).getParameter("foo").getValue(), is("bar"));
}

@Test
public void scripted() throws Exception {
WorkflowJob p = r.createProject(WorkflowJob.class);
p.setDefinition(new CpsFlowDefinition("properties([\n" +
" parameters([\n" +
" string(name: 'foo', defaultValue: 'lol')\n" +
" ]),\n" +
" pipelineTriggers([\n" +
" parameterizedCron('* * * * *%foo=bar')\n" +
" ])\n" +
"])", true));
WorkflowRun wfr = r.buildAndAssertSuccess(p);
new Cron().doRun();
r.waitUntilNoActivity();
assertThat(p.getLastCompletedBuild(), is(not(wfr)));
assertThat((String) p.getLastCompletedBuild().getAction(ParametersAction.class).getParameter("foo").getValue(), is("bar"));
}

@Test
public void declarative() throws Exception {
WorkflowJob p = r.createProject(WorkflowJob.class);
p.setDefinition(new CpsFlowDefinition("pipeline {\n" +
" agent any\n" +
" parameters {\n" +
" string(name: 'foo', defaultValue: 'lol')\n" +
" }\n" +
" triggers {\n" +
" parameterizedCron('* * * * *%foo=bar')\n" +
" }\n" +
" stages {\n" +
" stage('Test') {\n" +
" steps {\n" +
" echo 'test'\n" +
" }\n" +
" }\n" +
" }\n" +
"}", true));
WorkflowRun wfr = r.buildAndAssertSuccess(p);
new Cron().doRun();
r.waitUntilNoActivity();
assertThat(p.getLastCompletedBuild(), is(not(wfr)));
assertThat((String) p.getLastCompletedBuild().getAction(ParametersAction.class).getParameter("foo").getValue(), is("bar"));
}
}

0 comments on commit 757de17

Please sign in to comment.