|
| 1 | +package hudson.model; |
| 2 | + |
| 3 | +import static org.awaitility.Awaitility.await; |
| 4 | +import static org.hamcrest.MatcherAssert.assertThat; |
| 5 | +import static org.hamcrest.Matchers.is; |
| 6 | +import static org.hamcrest.Matchers.lessThan; |
| 7 | + |
| 8 | +import hudson.ExtensionList; |
| 9 | +import java.time.Duration; |
| 10 | +import java.util.concurrent.TimeUnit; |
| 11 | +import org.junit.Rule; |
| 12 | +import org.junit.Test; |
| 13 | +import org.jvnet.hudson.test.JenkinsRule; |
| 14 | +import org.jvnet.hudson.test.TestExtension; |
| 15 | + |
| 16 | +public class AsyncPeriodicWorkTest { |
| 17 | + @Rule |
| 18 | + public JenkinsRule r = new JenkinsRule(); |
| 19 | + |
| 20 | + @Test |
| 21 | + public void extraCallGetsIgnored() { |
| 22 | + var instance = ExtensionList.lookupSingleton(AsyncPeriodicWorkTestImpl.class); |
| 23 | + assertThat(instance.getCount(), is(0)); |
| 24 | + instance.run(); |
| 25 | + // Gets ignored |
| 26 | + instance.run(); |
| 27 | + await().until(instance::getCount, is(1)); |
| 28 | + await("Should never reach 2 as the second call should be ignored").during(Duration.ofSeconds(2)).until(instance::getCount, lessThan(2)); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + public void extraCallGetsQueued() { |
| 33 | + var instance = ExtensionList.lookupSingleton(AsyncPeriodicWorkTestImpl.class); |
| 34 | + instance.setQueueIfAlreadyRunning(true); |
| 35 | + assertThat(instance.getCount(), is(0)); |
| 36 | + instance.run(); |
| 37 | + // Gets queued |
| 38 | + instance.run(); |
| 39 | + await("The second call has been queued and executed later").until(instance::getCount, is(2)); |
| 40 | + } |
| 41 | + |
| 42 | + @TestExtension({"extraCallGetsIgnored", "extraCallGetsQueued"}) |
| 43 | + public static class AsyncPeriodicWorkTestImpl extends AsyncPeriodicWork { |
| 44 | + private boolean queueIfAlreadyRunning; |
| 45 | + private int count = 0; |
| 46 | + |
| 47 | + public AsyncPeriodicWorkTestImpl() { |
| 48 | + super(AsyncPeriodicWorkTestImpl.class.getSimpleName()); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + protected void execute(TaskListener listener) throws InterruptedException { |
| 53 | + count++; |
| 54 | + Thread.sleep(100); |
| 55 | + } |
| 56 | + |
| 57 | + public int getCount() { |
| 58 | + return count; |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public long getRecurrencePeriod() { |
| 63 | + return TimeUnit.DAYS.toMillis(1); |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public long getInitialDelay() { |
| 68 | + return TimeUnit.DAYS.toMillis(1); |
| 69 | + } |
| 70 | + |
| 71 | + public void setQueueIfAlreadyRunning(boolean queueIfAlreadyRunning) { |
| 72 | + this.queueIfAlreadyRunning = queueIfAlreadyRunning; |
| 73 | + } |
| 74 | + |
| 75 | + @Override |
| 76 | + protected boolean queueIfAlreadyRunning() { |
| 77 | + return queueIfAlreadyRunning; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments