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.verifyNoMoreInteractions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
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.CyclicBarrierListener;
@RunWith(value = Parameterized.class)
public class CyclicBarrierTest {
CyclicBarrierListener listener;
InOrder inOrder;
CyclicBarrier barrier;
public CyclicBarrierTest(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Parameters
public static Collection<Object[]> data() {
List<Object[]> result = new ArrayList<>();
result.add(new Object[]{new CyclicBarrier(1)});
result.add(new Object[]{new pt.ul.jarmus.ext.CyclicBarrier(1)});
return result;
}
@Before
public void setUp() throws InstantiationException, IllegalAccessException {
listener = Mockito.mock(CyclicBarrierListener.class);
inOrder = inOrder(listener);
if (barrier instanceof pt.ul.jarmus.ext.CyclicBarrier) {
((pt.ul.jarmus.ext.CyclicBarrier) barrier).setListener(listener);
}
CyclicBarrierObserver.aspectOf().setListener(listener);
}
@After
public void checkNoMoreInteractions() {
verifyNoMoreInteractions(listener);
}
@Test
public void cyclicBarrierAwait() throws InterruptedException,
BrokenBarrierException {
JArmus.register(barrier);
barrier.await();
inOrder.verify(listener).beforeAwait(barrier);
inOrder.verify(listener).afterAwait();
}
@Test
public void cyclicBarrierAwaitException() throws InterruptedException, BrokenBarrierException {
DeadlockInfo deadlock = mock(DeadlockInfo.class);
doThrow(new DeadlockIdentifiedException(deadlock)).when(listener).beforeAwait(barrier);
try {
barrier.await();
fail();
} catch (DeadlockIdentifiedException e) {
// should have thrown an exception
}
inOrder.verify(listener).beforeAwait(barrier);
}
@Test
public void unregistredShouldWork() throws InterruptedException,
BrokenBarrierException {
barrier.await();
inOrder.verify(listener).beforeAwait(barrier);
inOrder.verify(listener).afterAwait();
}
}