Search in sources :

Example 26 with Answer

use of org.mockito.stubbing.Answer in project opentsdb by OpenTSDB.

the class TestUniqueId method renameRaceCondition.

@Test(expected = IllegalStateException.class)
public void renameRaceCondition() throws Exception {
    // Simulate a race between client A(default) and client B.
    // A and B rename same UID to different name.
    // B waits till A start to invoke PutRequest to start.
    uid = new UniqueId(client, table, METRIC, 3);
    HBaseClient client_b = mock(HBaseClient.class);
    final UniqueId uid_b = new UniqueId(client_b, table, METRIC, 3);
    final byte[] foo_id = { 0, 'a', 0x42 };
    final byte[] foo_name = { 'f', 'o', 'o' };
    ArrayList<KeyValue> kvs = new ArrayList<KeyValue>(1);
    kvs.add(new KeyValue(foo_name, ID, METRIC_ARRAY, foo_id));
    when(client_b.get(anyGet())).thenReturn(Deferred.fromResult(kvs)).thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(null));
    when(client_b.put(anyPut())).thenAnswer(answerTrue());
    when(client_b.delete(anyDelete())).thenAnswer(answerTrue());
    final Answer<Deferred<Boolean>> the_race = new Answer<Deferred<Boolean>>() {

        public Deferred<Boolean> answer(final InvocationOnMock inv) throws Exception {
            uid_b.rename("foo", "xyz");
            return Deferred.fromResult(true);
        }
    };
    when(client.get(anyGet())).thenReturn(Deferred.fromResult(kvs)).thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(null));
    when(client.put(anyPut())).thenAnswer(the_race);
    when(client.delete(anyDelete())).thenAnswer(answerTrue());
    uid.rename("foo", "bar");
}
Also used : Answer(org.mockito.stubbing.Answer) KeyValue(org.hbase.async.KeyValue) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HBaseClient(org.hbase.async.HBaseClient) Deferred(com.stumbleupon.async.Deferred) ArrayList(java.util.ArrayList) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 27 with Answer

use of org.mockito.stubbing.Answer in project opentsdb by OpenTSDB.

the class TestUniqueId method getOrCreateIdAssignIdWithRaceCondition.

// Test the creation of an ID with a race condition.
@Test
public void getOrCreateIdAssignIdWithRaceCondition() {
    // Simulate a race between client A and client B.
    // A does a Get and sees that there's no ID for this name.
    // B does a Get and sees that there's no ID too, and B actually goes
    // through the entire process to create the ID.
    // Then A attempts to go through the process and should discover that the
    // ID has already been assigned.
    // Used by client A.
    uid = new UniqueId(client, table, METRIC, 3);
    // For client B.
    HBaseClient client_b = mock(HBaseClient.class);
    final UniqueId uid_b = new UniqueId(client_b, table, METRIC, 3);
    final byte[] id = { 0, 0, 5 };
    final byte[] byte_name = { 'f', 'o', 'o' };
    final ArrayList<KeyValue> kvs = new ArrayList<KeyValue>(1);
    kvs.add(new KeyValue(byte_name, ID, METRIC_ARRAY, id));
    final Deferred<ArrayList<KeyValue>> d = PowerMockito.spy(new Deferred<ArrayList<KeyValue>>());
    when(client.get(anyGet())).thenReturn(d).thenReturn(Deferred.fromResult(kvs));
    final Answer<byte[]> the_race = new Answer<byte[]>() {

        public byte[] answer(final InvocationOnMock unused_invocation) throws Exception {
            // While answering A's first Get, B doest a full getOrCreateId.
            assertArrayEquals(id, uid_b.getOrCreateId("foo"));
            d.callback(null);
            return (byte[]) ((Deferred) d).join();
        }
    };
    // Start the race when answering A's first Get.
    try {
        PowerMockito.doAnswer(the_race).when(d).joinUninterruptibly();
    } catch (Exception e) {
        fail("Should never happen: " + e);
    }
    // null => ID doesn't exist.
    when(client_b.get(anyGet())).thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(null));
    // Watch this! ______,^ I'm writing C++ in Java!
    when(client_b.atomicIncrement(incrementForRow(MAXID))).thenReturn(Deferred.fromResult(5L));
    when(client_b.compareAndSet(anyPut(), emptyArray())).thenReturn(Deferred.fromResult(true)).thenReturn(Deferred.fromResult(true));
    // Now that B is finished, A proceeds and allocates a UID that will be
    // wasted, and creates the reverse mapping, but fails at creating the
    // forward mapping.
    when(client.atomicIncrement(incrementForRow(MAXID))).thenReturn(Deferred.fromResult(6L));
    when(client.compareAndSet(anyPut(), emptyArray())).thenReturn(// Orphan reverse mapping.
    Deferred.fromResult(true)).thenReturn(// Already CAS'ed by A.
    Deferred.fromResult(false));
    // Start the execution.
    assertArrayEquals(id, uid.getOrCreateId("foo"));
    // Verify the order of execution too.
    final InOrder order = inOrder(client, client_b);
    // 1st Get for A.
    order.verify(client).get(anyGet());
    // 1st Get for B.
    order.verify(client_b).get(anyGet());
    order.verify(client_b).atomicIncrement(incrementForRow(MAXID));
    // both mappings.
    order.verify(client_b, times(2)).compareAndSet(// both mappings.
    anyPut(), emptyArray());
    order.verify(client).atomicIncrement(incrementForRow(MAXID));
    // both mappings.
    order.verify(client, times(2)).compareAndSet(// both mappings.
    anyPut(), emptyArray());
    // A retries and gets it.
    order.verify(client).get(anyGet());
}
Also used : Answer(org.mockito.stubbing.Answer) KeyValue(org.hbase.async.KeyValue) InOrder(org.mockito.InOrder) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HBaseClient(org.hbase.async.HBaseClient) ArrayList(java.util.ArrayList) UnitTestException(net.opentsdb.core.BaseTsdbTest.UnitTestException) HBaseException(org.hbase.async.HBaseException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 28 with Answer

use of org.mockito.stubbing.Answer in project sonarqube by SonarSource.

the class StopperThreadTest method stop_timeout.

@Test
public void stop_timeout() {
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Thread.sleep(10000L);
            return null;
        }
    }).when(monitored).stop();
    // max stop timeout is 100 milliseconds
    StopperThread stopper = new StopperThread(monitored, commands, 100L);
    stopper.start();
    verify(monitored, timeout(3000)).stop();
}
Also used : Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Example 29 with Answer

use of org.mockito.stubbing.Answer in project sonarqube by SonarSource.

the class QualityProfileEventsStepTest method verify_detection_with_complex_mix_of_qps.

@Test
public void verify_detection_with_complex_mix_of_qps() {
    final Set<Event> events = new HashSet<>();
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            events.add((Event) invocationOnMock.getArguments()[1]);
            return null;
        }
    }).when(eventRepository).add(eq(treeRootHolder.getRoot()), any(Event.class));
    mockMeasures(treeRootHolder.getRoot(), arrayOf(qp(QP_NAME_2, LANGUAGE_KEY_1), qp(QP_NAME_2, LANGUAGE_KEY_2), qp(QP_NAME_1, LANGUAGE_KEY_1, parseDateTime("2011-04-25T01:05:13+0100"))), arrayOf(qp(QP_NAME_1, LANGUAGE_KEY_1, parseDateTime("2011-04-25T01:05:17+0100")), qp(QP_NAME_2, LANGUAGE_KEY_2), qp(QP_NAME_2, LANGUAGE_KEY_3)));
    mockNoLanguageInRepository();
    underTest.execute();
    assertThat(events).extracting("name").containsOnly("Stop using '" + QP_NAME_2 + "' (" + LANGUAGE_KEY_1 + ")", "Use '" + QP_NAME_2 + "' (" + LANGUAGE_KEY_3 + ")", "Changes in '" + QP_NAME_1 + "' (" + LANGUAGE_KEY_1 + ")");
}
Also used : Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Event(org.sonar.server.computation.task.projectanalysis.event.Event) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 30 with Answer

use of org.mockito.stubbing.Answer in project sonarqube by SonarSource.

the class PluginDownloaderTest method before.

@Before
public void before() throws Exception {
    updateCenterMatrixFactory = mock(UpdateCenterMatrixFactory.class);
    updateCenter = mock(UpdateCenter.class);
    when(updateCenterMatrixFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.of(updateCenter));
    httpDownloader = mock(HttpDownloader.class);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock inv) throws Throwable {
            File toFile = (File) inv.getArguments()[1];
            touch(toFile);
            return null;
        }
    }).when(httpDownloader).download(any(URI.class), any(File.class));
    ServerFileSystem fs = mock(ServerFileSystem.class);
    downloadDir = testFolder.newFolder("downloads");
    when(fs.getDownloadedPluginsDir()).thenReturn(downloadDir);
    pluginDownloader = new PluginDownloader(updateCenterMatrixFactory, httpDownloader, fs);
}
Also used : ServerFileSystem(org.sonar.server.platform.ServerFileSystem) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) UpdateCenter(org.sonar.updatecenter.common.UpdateCenter) HttpDownloader(org.sonar.api.utils.HttpDownloader) InvocationOnMock(org.mockito.invocation.InvocationOnMock) File(java.io.File) URI(java.net.URI) Before(org.junit.Before)

Aggregations

Answer (org.mockito.stubbing.Answer)262 InvocationOnMock (org.mockito.invocation.InvocationOnMock)247 Test (org.junit.Test)148 Mockito.doAnswer (org.mockito.Mockito.doAnswer)99 Before (org.junit.Before)36 Matchers.anyString (org.mockito.Matchers.anyString)32 HashMap (java.util.HashMap)31 ArrayList (java.util.ArrayList)30 IOException (java.io.IOException)20 HashSet (java.util.HashSet)16 File (java.io.File)15 AtomicReference (java.util.concurrent.atomic.AtomicReference)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 Map (java.util.Map)13 List (java.util.List)12 Test (org.testng.annotations.Test)12 CountDownLatch (java.util.concurrent.CountDownLatch)11 Configuration (org.apache.hadoop.conf.Configuration)11 RequestFinishedListener (com.android.volley.RequestQueue.RequestFinishedListener)9 MockRequest (com.android.volley.mock.MockRequest)9