aboutsummaryrefslogtreecommitdiffstats
path: root/service-monitor/src/test/java/com/yahoo/vespa/service/executor/CancellableImplTest.java
blob: 8fdb7f6028369d37df1b3a8f4757e15d5f94f352 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.service.executor;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.time.Duration;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * @author hakonhall
 */
public class CancellableImplTest {
    private final TestExecutor executor = new TestExecutor();
    private final TestRunlet runlet = new TestRunlet();
    private final Cancellable cancellable = executor.scheduleWithFixedDelay(runlet, Duration.ofSeconds(1));

    @After
    public void tearDown() {
        executor.close();
    }

    @Before
    public void setUp() {
        assertEquals(0, runlet.getRunsStarted());
        executor.runToCompletion(1);
        assertEquals(1, runlet.getRunsStarted());
        executor.runToCompletion(2);
        assertEquals(2, runlet.getRunsStarted());
        assertTrue(executor.isExecutionRunning());
        assertFalse(runlet.isClosed());
        assertTrue(executor.isExecutionRunning());
        assertFalse(runlet.isClosed());
    }

    @Test
    public void testCancelWhileIdle() {
        // Cancel while runlet is not running and verify closure and executor cancellation
        cancellable.cancel();
        assertFalse(executor.isExecutionRunning());
        assertTrue(runlet.isClosed());

        // Ensure a spurious run is ignored.
        executor.runAsync();
        executor.runToCompletion(3);
        assertEquals(2, runlet.getRunsStarted());
    }

    @Test
    public void testCancelWhileRunning() {
        // halt execution in runlet
        runlet.shouldWaitInRun(true);
        executor.runAsync();
        runlet.waitUntilInRun();
        assertEquals(3, runlet.getRunsStarted());
        assertEquals(2, runlet.getRunsCompleted());
        assertTrue(executor.isExecutionRunning());
        assertFalse(runlet.isClosed());

        // Cancel now
        cancellable.cancel();
        assertTrue(executor.isExecutionRunning());
        assertFalse(runlet.isClosed());

        // Complete the runlet.run(), and verify the close and executor cancellation takes effect
        runlet.shouldWaitInRun(false);
        executor.waitUntilRunCompleted(3);
        assertFalse(executor.isExecutionRunning());
        assertTrue(runlet.isClosed());

        // Ensure a spurious run is ignored.
        executor.runToCompletion(4);
        assertEquals(3, runlet.getRunsStarted());
    }
}