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.locks.ReentrantLock;
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.checkers.ReentrantLockListener;
@RunWith(value = Parameterized.class)
public class ReentrantLockTest {
ReentrantLockListener jarmus;
InOrder inOrder;
ReentrantLock lock;
public ReentrantLockTest(ReentrantLock phaser) {
this.lock = phaser;
}
@Parameters
public static Collection<Object[]> data() {
List<Object[]> result = new ArrayList<>();
result.add(new Object[]{new ReentrantLock()});
//result.add(new Object[]{new pt.ul.jarmus.ext.Phaser(1)});
return result;
}
@Before
public void setUp() throws InstantiationException, IllegalAccessException {
jarmus = Mockito.mock(ReentrantLockListener.class);
inOrder = inOrder(jarmus);
//if (phaser instanceof pt.ul.jarmus.ext.Phaser) {
// ((pt.ul.jarmus.ext.Phaser) phaser).setListener(jarmus);
//}
ReentrantLockObserver.aspectOf().setListener(jarmus);
}
@After
public void checkNoMoreInteractions() {
verifyNoMoreInteractions(jarmus);
}
@Test
public void lock() {
lock.lock();
inOrder.verify(jarmus).beforeLock(lock);
inOrder.verify(jarmus).enterCritical(lock);
inOrder.verify(jarmus).afterLock(lock);
}
@Test
public void lockFails() {
DeadlockInfo deadlock = mock(DeadlockInfo.class);
DeadlockIdentifiedException error = new DeadlockIdentifiedException(deadlock);
doThrow(error).when(jarmus).beforeLock(lock);
try {
lock.lock();
fail();
} catch (DeadlockIdentifiedException e) {
// ok
}
inOrder.verify(jarmus).beforeLock(lock);
}
@Test
public void unlock() {
try {
lock.unlock();
fail();
} catch (IllegalMonitorStateException e) {
// ok
}
inOrder.verify(jarmus).beforeUnlock(lock);
}
}