package pt.ul.jarmus.inst;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.InOrder;
import org.mockito.Mockito;
import pt.ul.armus.DeadlockInfo;
import pt.ul.jarmus.DeadlockIdentifiedException;
import pt.ul.jarmus.JArmus;
import pt.ul.jarmus.checkers.CountDownLatchListener;
@RunWith(value = Parameterized.class)
public class CountDownLatchTest {
CountDownLatchListener jarmus;
InOrder inOrder;
CountDownLatch latch;
public CountDownLatchTest(CountDownLatch phaser) {
this.latch = phaser;
}
@Parameters
public static Collection<Object[]> data() {
List<Object[]> result = new ArrayList<>();
result.add(new Object[] { new CountDownLatch(1) });
result.add(new Object[] { new pt.ul.jarmus.ext.CountDownLatch(1) });
return result;
}
@Before
public void setUp() throws InstantiationException, IllegalAccessException {
jarmus = Mockito.mock(CountDownLatchListener.class);
inOrder = inOrder(jarmus);
if (latch instanceof pt.ul.jarmus.ext.CountDownLatch) {
((pt.ul.jarmus.ext.CountDownLatch) latch).setListener(jarmus);
}
CountDownLatchObserver.aspectOf().setListener(jarmus);
}
@After
public void checkNoMoreInteractions() {
verifyNoMoreInteractions(jarmus);
}
@Test
public void countDownLatchCountDown() {
JArmus.register(latch);
latch.countDown();
verify(jarmus).onCountDown(latch);
}
@Test
public void countDownLatchAwait() throws InterruptedException {
JArmus.register(latch);
latch.await();
inOrder.verify(jarmus).beforeAwait(latch);
inOrder.verify(jarmus).afterAwait();
}
@Test
public void unregistredShouldWork() throws InterruptedException {
latch.await();
inOrder.verify(jarmus).beforeAwait(latch);
inOrder.verify(jarmus).afterAwait();
}
@Test
public void countDownLatchAwaitException() throws InterruptedException {
DeadlockInfo deadlock = mock(DeadlockInfo.class);
doThrow(new DeadlockIdentifiedException(deadlock)).when(jarmus).beforeAwait(latch);
JArmus.register(latch);
try {
latch.await();
fail();
} catch (DeadlockIdentifiedException e) {
// ok
}
inOrder.verify(jarmus).beforeAwait(latch);
}
}