Java Code Examples for org.mockito.ArgumentCaptor#getAllValues()

The following examples show how to use org.mockito.ArgumentCaptor#getAllValues() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PluginLifecycleHandlerImplTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5000)
public void handlePluginEvents_inStartPriority() throws ExecutionException, InterruptedException {
    final ImmutableList<HiveMQPluginEvent> events = ImmutableList.of(
            new HiveMQPluginEvent(HiveMQPluginEvent.Change.ENABLE, "test-extension-100", 100, temporaryFolder.getRoot().toPath()),
            new HiveMQPluginEvent(HiveMQPluginEvent.Change.ENABLE, "test-extension-1", 1, temporaryFolder.getRoot().toPath()),
            new HiveMQPluginEvent(HiveMQPluginEvent.Change.ENABLE, "test-extension-10", 10, temporaryFolder.getRoot().toPath()),
            new HiveMQPluginEvent(HiveMQPluginEvent.Change.ENABLE, "test-extension-1000", 1000, temporaryFolder.getRoot().toPath()
            )
    );

    pluginLifecycleHandler.handlePluginEvents(events).get();

    final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(hiveMQExtensions, times(4)).extensionStart(captor.capture());

    final List<String> allValues = captor.getAllValues();
    assertEquals("test-extension-1000", allValues.get(0));
    assertEquals("test-extension-100", allValues.get(1));
    assertEquals("test-extension-10", allValues.get(2));
    assertEquals("test-extension-1", allValues.get(3));
}
 
Example 2
Source File: DecisionTracingListenerTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private static List<EvaluateEvent> testWithRealRuntime(Map<String, Object> contextVariables, int expectedEvents, BiConsumer<DecisionModel, DMNContext> modelConsumer) {
    final DMNRuntime runtime = createDMNRuntime();

    Consumer<EvaluateEvent> eventConsumer = mock(Consumer.class);
    DecisionTracingListener listener = new DecisionTracingListener(eventConsumer);
    runtime.addListener(listener);

    final DecisionModel model = new DmnDecisionModel(runtime, MODEL_NAMESPACE, MODEL_NAME, () -> TEST_EXECUTION_ID_2);
    final DMNContext context = model.newContext(contextVariables);
    modelConsumer.accept(model, context);

    ArgumentCaptor<EvaluateEvent> eventCaptor = ArgumentCaptor.forClass(EvaluateEvent.class);
    verify(eventConsumer, times(expectedEvents)).accept(eventCaptor.capture());

    return eventCaptor.getAllValues();
}
 
Example 3
Source File: LogsSubscriptionServiceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void singleMatchingLogEvent() {
  final BlockWithReceipts blockWithReceipts = generateBlock(2, 2, 2);
  final Block block = blockWithReceipts.getBlock();
  final List<TransactionReceipt> receipts = blockWithReceipts.getReceipts();

  final int txIndex = 1;
  final int logIndex = 1;
  final Log targetLog = receipts.get(txIndex).getLogs().get(logIndex);

  final LogsSubscription subscription = createSubscription(targetLog.getLogger());
  registerSubscriptions(subscription);
  blockchain.appendBlock(blockWithReceipts.getBlock(), blockWithReceipts.getReceipts());

  final ArgumentCaptor<LogResult> captor = ArgumentCaptor.forClass(LogResult.class);
  verify(subscriptionManager).sendMessage(eq(subscription.getSubscriptionId()), captor.capture());

  final List<LogResult> logResults = captor.getAllValues();

  assertThat(logResults).hasSize(1);
  final LogResult result = logResults.get(0);
  assertLogResultMatches(result, block, receipts, txIndex, logIndex, false);
}
 
Example 4
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void writeAndVerifyReceived(ByteBuf message, Channel sendChannel, CountDownLatch receiverLatch,
                                           MessageReceiver receiver) throws Exception {
    List<ByteBuf> dataCapture = null;
    try {
        sendChannel.writeAndFlush(message);
        receiverLatch.await(5, TimeUnit.SECONDS);
        message.resetReaderIndex();
        ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class);
        verify(receiver).messageReceived(captor.capture());
        dataCapture = captor.getAllValues();
        assertEquals(message, dataCapture.get(0));
    } finally {
        if (dataCapture != null) {
            for (ByteBuf data : dataCapture) {
                data.release();
            }
        }
    }
}
 
Example 5
Source File: InboundHttp2ToHttpAdapterTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void clientRequestSingleHeaderNoDataFrames() throws Exception {
    boostrapEnv(1, 1, 1);
    final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "/some/path/resource2", true);
    try {
        HttpHeaders httpHeaders = request.headers();
        httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "https");
        httpHeaders.set(HttpHeaderNames.HOST, "example.org");
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).
                scheme(new AsciiString("https")).authority(new AsciiString("example.org"))
                .path(new AsciiString("/some/path/resource2"));
        runInChannel(clientChannel, new Http2Runnable() {
            @Override
            public void run() throws Http2Exception {
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests();
        ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(serverListener).messageReceived(requestCaptor.capture());
        capturedRequests = requestCaptor.getAllValues();
        assertEquals(request, capturedRequests.get(0));
    } finally {
        request.release();
    }
}
 
Example 6
Source File: InboundHttp2ToHttpAdapterTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void clientRequestSingleHeaderCookieSplitIntoMultipleEntries2() throws Exception {
    boostrapEnv(1, 1, 1);
    final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "/some/path/resource2", true);
    try {
        HttpHeaders httpHeaders = request.headers();
        httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "https");
        httpHeaders.set(HttpHeaderNames.HOST, "example.org");
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        httpHeaders.set(HttpHeaderNames.COOKIE, "a=b; c=d; e=f");
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).
                scheme(new AsciiString("https")).authority(new AsciiString("example.org"))
                .path(new AsciiString("/some/path/resource2"))
                .add(HttpHeaderNames.COOKIE, "a=b; c=d")
                .add(HttpHeaderNames.COOKIE, "e=f");
        runInChannel(clientChannel, new Http2Runnable() {
            @Override
            public void run() throws Http2Exception {
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests();
        ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(serverListener).messageReceived(requestCaptor.capture());
        capturedRequests = requestCaptor.getAllValues();
        assertEquals(request, capturedRequests.get(0));
    } finally {
        request.release();
    }
}
 
Example 7
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 5 votes vote down vote up
private BluetoothGattCallback connectAndGetCallback() {
    peripheral.connect();

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    ArgumentCaptor<BluetoothGattCallback> bluetoothGattCallbackCaptor = ArgumentCaptor.forClass(BluetoothGattCallback.class);
    verify(device).connectGatt(any(Context.class), anyBoolean(), bluetoothGattCallbackCaptor.capture(), anyInt());

    List<BluetoothGattCallback> capturedGatts = bluetoothGattCallbackCaptor.getAllValues();
    return capturedGatts.get(0);
}
 
Example 8
Source File: RecordFileParserTest.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
private void assertOnEnd(RecordFile... recordFiles) {
    ArgumentCaptor<RecordFile> captor = ArgumentCaptor.forClass(RecordFile.class);
    verify(recordStreamFileListener, times(recordFiles.length)).onEnd(captor.capture());
    List<RecordFile> actualArgs = captor.getAllValues();
    for (int i = 0; i < recordFiles.length; i++) {
        RecordFile actual = actualArgs.get(i);
        RecordFile expected = recordFiles[i];
        assertThat(actual).isEqualToIgnoringGivenFields(expected, "id", "loadEnd", "loadStart", "recordItems");
    }
}
 
Example 9
Source File: BatchRequestServiceTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void batchPolicy_fromConfiguration_batchSize_default() throws Exception {
  int batchCount = 2;
  setupConfig.initConfig(new Properties());
  BatchPolicy batchPolicy = BatchPolicy.fromConfiguration();
  int batchSize = batchPolicy.getMaxBatchSize();

  ExecutorService batchExecutor = Mockito.mock(ExecutorService.class);
  when(executorFactory.getExecutor()).thenReturn(batchExecutor);
  when(executorFactory.getScheduledExecutor()).thenReturn(scheduleExecutorService);

  BatchRequestService batchService =
      new BatchRequestService.Builder(service)
          .setExecutorFactory(executorFactory)
          .setBatchRequestHelper(batchRequestHelper)
          .setGoogleCredential(credential)
          .setBatchPolicy(batchPolicy)
          .build();
  batchService.startAsync().awaitRunning();
  for (int i = 0; i < batchSize * batchCount; i++) {
    batchService.add(asyncRequest);
  }
  batchService.stopAsync().awaitTerminated();

  ArgumentCaptor<BatchRequestService.SnapshotRunnable> captor =
      ArgumentCaptor.forClass(BatchRequestService.SnapshotRunnable.class);
  verify(batchExecutor, times(batchCount)).execute(captor.capture());
  for (BatchRequestService.SnapshotRunnable batch : captor.getAllValues()) {
    assertEquals(batchSize, batch.snapshotRequests.size());
  }
}
 
Example 10
Source File: InboundHttp2ToHttpAdapterTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void clientRequestMultipleDataFrames() throws Exception {
    boostrapEnv(1, 1, 1);
    final String text = "hello world big time data!";
    final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
    final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "/some/path/resource2", content, true);
    try {
        HttpHeaders httpHeaders = request.headers();
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(
                new AsciiString("/some/path/resource2"));
        final int midPoint = text.length() / 2;
        runInChannel(clientChannel, new Http2Runnable() {
            @Override
            public void run() throws Http2Exception {
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
                clientHandler.encoder().writeData(
                        ctxClient(), 3, content.retainedSlice(0, midPoint), 0, false, newPromiseClient());
                clientHandler.encoder().writeData(
                        ctxClient(), 3, content.retainedSlice(midPoint, text.length() - midPoint),
                        0, true, newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests();
        ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(serverListener).messageReceived(requestCaptor.capture());
        capturedRequests = requestCaptor.getAllValues();
        assertEquals(request, capturedRequests.get(0));
    } finally {
        request.release();
    }
}
 
Example 11
Source File: LogsSubscriptionServiceTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void multipleSubscriptionsForSingleMatchingLog() {
  final BlockWithReceipts blockWithReceipts = generateBlock(2, 2, 2);
  final Block block = blockWithReceipts.getBlock();
  final List<TransactionReceipt> receipts = blockWithReceipts.getReceipts();

  final int txIndex = 1;
  final int logIndex = 1;
  final Log targetLog = receipts.get(txIndex).getLogs().get(logIndex);

  final List<LogsSubscription> subscriptions =
      Stream.generate(() -> createSubscription(targetLog.getLogger()))
          .limit(3)
          .collect(Collectors.toList());
  registerSubscriptions(subscriptions);
  blockchain.appendBlock(blockWithReceipts.getBlock(), blockWithReceipts.getReceipts());

  for (LogsSubscription subscription : subscriptions) {
    final ArgumentCaptor<LogResult> captor = ArgumentCaptor.forClass(LogResult.class);
    verify(subscriptionManager)
        .sendMessage(eq(subscription.getSubscriptionId()), captor.capture());

    final List<LogResult> logResults = captor.getAllValues();

    assertThat(logResults).hasSize(1);
    final LogResult result = logResults.get(0);
    assertLogResultMatches(result, block, receipts, txIndex, logIndex, false);
  }
}
 
Example 12
Source File: TransactionsMessageSenderTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSendTransactionsInBatchesWithLimit() throws Exception {
  final Set<Transaction> transactions = generator.transactions(6000);

  transactions.forEach(transaction -> transactionTracker.addToPeerSendQueue(peer1, transaction));

  messageSender.sendTransactionsToPeers();
  final ArgumentCaptor<MessageData> messageDataArgumentCaptor =
      ArgumentCaptor.forClass(MessageData.class);
  verify(peer1, times(2)).send(messageDataArgumentCaptor.capture());

  final List<MessageData> sentMessages = messageDataArgumentCaptor.getAllValues();

  assertThat(sentMessages).hasSize(2);
  assertThat(sentMessages).allMatch(message -> message.getCode() == EthPV62.TRANSACTIONS);
  final Set<Transaction> firstBatch = getTransactionsFromMessage(sentMessages.get(0));
  final Set<Transaction> secondBatch = getTransactionsFromMessage(sentMessages.get(1));

  final int expectedFirstBatchSize = 5219, expectedSecondBatchSize = 781, toleranceDelta = 50;
  assertThat(firstBatch)
      .hasSizeBetween(
          expectedFirstBatchSize - toleranceDelta, expectedFirstBatchSize + toleranceDelta);
  assertThat(secondBatch)
      .hasSizeBetween(
          expectedSecondBatchSize - toleranceDelta, expectedSecondBatchSize + toleranceDelta);

  assertThat(Sets.union(firstBatch, secondBatch)).isEqualTo(transactions);
}
 
Example 13
Source File: PendingTransactionsMessageSenderTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSendTransactionsInBatchesWithLimit() throws Exception {
  final Set<Hash> transactions =
      generator.transactions(6000).stream().map(Transaction::getHash).collect(Collectors.toSet());

  transactions.forEach(transaction -> transactionTracker.addToPeerSendQueue(peer1, transaction));

  messageSender.sendTransactionsToPeers();
  final ArgumentCaptor<MessageData> messageDataArgumentCaptor =
      ArgumentCaptor.forClass(MessageData.class);
  verify(peer1, times(2)).send(messageDataArgumentCaptor.capture());

  final List<MessageData> sentMessages = messageDataArgumentCaptor.getAllValues();

  assertThat(sentMessages).hasSize(2);
  assertThat(sentMessages)
      .allMatch(message -> message.getCode() == EthPV65.NEW_POOLED_TRANSACTION_HASHES);
  final Set<Hash> firstBatch = getTransactionsFromMessage(sentMessages.get(0));
  final Set<Hash> secondBatch = getTransactionsFromMessage(sentMessages.get(1));

  final int expectedFirstBatchSize = 4096, expectedSecondBatchSize = 1904, toleranceDelta = 0;
  assertThat(firstBatch)
      .hasSizeBetween(
          expectedFirstBatchSize - toleranceDelta, expectedFirstBatchSize + toleranceDelta);
  assertThat(secondBatch)
      .hasSizeBetween(
          expectedSecondBatchSize - toleranceDelta, expectedSecondBatchSize + toleranceDelta);

  assertThat(Sets.union(firstBatch, secondBatch)).isEqualTo(transactions);
}
 
Example 14
Source File: Http2FrameRoundtripTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private ByteBuf captureWrites() {
    ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class);
    verify(ctx, atLeastOnce()).write(captor.capture(), isA(ChannelPromise.class));
    CompositeByteBuf composite = releaseLater(Unpooled.compositeBuffer());
    for (ByteBuf buf : captor.getAllValues()) {
        buf = releaseLater(buf.retain());
        composite.addComponent(true, buf);
    }
    return composite;
}
 
Example 15
Source File: WeightedFairQueueByteDistributorTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private int captureWrites(Http2Stream stream) {
    ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);
    verify(writer, atLeastOnce()).write(same(stream), captor.capture());
    int total = 0;
    for (Integer x : captor.getAllValues()) {
        total += x;
    }
    return total;
}
 
Example 16
Source File: InboundHttp2ToHttpAdapterTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void clientRequestMultipleEmptyDataFrames() throws Exception {
    boostrapEnv(1, 1, 1);
    final String text = "";
    final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
    final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "/some/path/resource2", content, true);
    try {
        HttpHeaders httpHeaders = request.headers();
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(
                new AsciiString("/some/path/resource2"));
        runInChannel(clientChannel, new Http2Runnable() {
            @Override
            public void run() throws Http2Exception {
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
                clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
                clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
                clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests();
        ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(serverListener).messageReceived(requestCaptor.capture());
        capturedRequests = requestCaptor.getAllValues();
        assertEquals(request, capturedRequests.get(0));
    } finally {
        request.release();
    }
}
 
Example 17
Source File: DiscordStateTest.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testStatusTimeout()
{
	when(discordConfig.actionTimeout()).thenReturn(0);
	when(discordConfig.hideElapsedTime()).thenReturn(false);

	discordState.triggerEvent(DiscordGameEventType.IN_MENU);
	verify(discordService).updatePresence(any(DiscordPresence.class));

	discordState.checkForTimeout();
	ArgumentCaptor<DiscordPresence> captor = ArgumentCaptor.forClass(DiscordPresence.class);
	verify(discordService, times(2)).updatePresence(captor.capture());
	List<DiscordPresence> captured = captor.getAllValues();
	assertNull(captured.get(captured.size() - 1).getEndTimestamp());
}
 
Example 18
Source File: NestedAccessorsTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testNestedAccessors2() throws Exception {
    final String rule = "package org.drools.compiler\n" +
            "rule 'rule1'" +
            "    salience 10\n" +
            "when\n" +
            "    Cheesery( typedCheeses[0].type == 'stilton' );\n" +
            "then\n" +
            "end\n" +
            "rule 'rule2'\n" +
            "when\n" +
            "    Cheesery( typedCheeses[0].price == 10 );\n" +
            "then\n" +
            "end";

    final KieBase kbase = loadKnowledgeBaseFromString(rule);
    final KieSession ksession = createKnowledgeSession(kbase);
    final org.kie.api.event.rule.AgendaEventListener ael = mock(org.kie.api.event.rule.AgendaEventListener.class);
    ksession.addEventListener(ael);

    final Cheesery c1 = new Cheesery();
    c1.addCheese(new Cheese("stilton", 20));
    final Cheesery c2 = new Cheesery();
    c2.addCheese(new Cheese("brie", 10));
    final Cheesery c3 = new Cheesery();
    c3.addCheese(new Cheese("muzzarella", 30));

    ksession.insert(c1);
    ksession.insert(c2);
    ksession.insert(c3);
    ksession.fireAllRules();

    final ArgumentCaptor<AfterMatchFiredEvent> captor = ArgumentCaptor.forClass(org.kie.api.event.rule.AfterMatchFiredEvent.class);
    verify(ael, times(2)).afterMatchFired(captor.capture());

    final List<org.kie.api.event.rule.AfterMatchFiredEvent> values = captor.getAllValues();
    assertThat(values.get(0).getMatch().getObjects()).first().isEqualTo(c1);
    assertThat(values.get(1).getMatch().getObjects()).first().isEqualTo(c2);

    ksession.dispose();
}
 
Example 19
Source File: LogsSubscriptionServiceTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void singleMatchingLogEmittedThenMovedInReorg() {
  // Create block that emits an event
  final BlockWithReceipts blockWithReceipts = generateBlock(2, 2, 2);
  final Block block = blockWithReceipts.getBlock();
  final List<TransactionReceipt> receipts = blockWithReceipts.getReceipts();

  final int txIndex = 1;
  final int logIndex = 1;
  final Log targetLog = receipts.get(txIndex).getLogs().get(logIndex);

  final LogsSubscription subscription = createSubscription(targetLog.getLogger());
  registerSubscriptions(subscription);
  blockchain.appendBlock(blockWithReceipts.getBlock(), blockWithReceipts.getReceipts());

  // Cause a reorg that removes the block which emitted an event
  BlockHeader parentHeader = blockchain.getGenesisBlock().getHeader();
  while (!blockchain.getChainHeadHash().equals(parentHeader.getHash())) {
    final BlockWithReceipts newBlock = generateBlock(parentHeader, 2, 0, 0);
    parentHeader = newBlock.getBlock().getHeader();
    blockchain.appendBlock(newBlock.getBlock(), newBlock.getReceipts());
  }

  // Now add another block that re-emits the target log
  final BlockWithReceipts newBlockWithLog =
      generateBlock(1, () -> Collections.singletonList(targetLog));
  blockchain.appendBlock(newBlockWithLog.getBlock(), newBlockWithLog.getReceipts());
  // Sanity check
  assertThat(blockchain.getChainHeadHash()).isEqualTo(newBlockWithLog.getBlock().getHash());

  final ArgumentCaptor<LogResult> captor = ArgumentCaptor.forClass(LogResult.class);
  verify(subscriptionManager, times(3))
      .sendMessage(eq(subscription.getSubscriptionId()), captor.capture());

  final List<LogResult> logResults = captor.getAllValues();

  assertThat(logResults).hasSize(3);
  final LogResult originalLog = logResults.get(0);
  assertLogResultMatches(originalLog, block, receipts, txIndex, logIndex, false);
  final LogResult removedLog = logResults.get(1);
  assertLogResultMatches(removedLog, block, receipts, txIndex, logIndex, true);
  final LogResult updatedLog = logResults.get(2);
  assertLogResultMatches(
      updatedLog, newBlockWithLog.getBlock(), newBlockWithLog.getReceipts(), 0, 0, false);
}
 
Example 20
Source File: EthProtocolManagerTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void newBlockMinedSendsNewBlockMessageToAllPeers() {
  try (final EthProtocolManager ethManager =
      EthProtocolManagerTestUtil.create(
          blockchain,
          () -> false,
          protocolContext.getWorldStateArchive(),
          transactionPool,
          EthProtocolConfiguration.defaultConfig())) {
    // Define handler to validate response
    final PeerSendHandler onSend = mock(PeerSendHandler.class);
    final List<PeerConnection> peers = Lists.newArrayList();

    final int PEER_COUNT = 5;
    for (int i = 0; i < PEER_COUNT; i++) {
      peers.add(setupPeer(ethManager, onSend));
    }

    final Hash chainHeadHash = blockchain.getChainHeadHash();
    final Block minedBlock =
        new Block(
            blockchain.getBlockHeader(chainHeadHash).get(),
            blockchain.getBlockBody(chainHeadHash).get());

    final Difficulty expectedTotalDifficulty = blockchain.getChainHead().getTotalDifficulty();

    reset(onSend);

    ethManager.blockMined(minedBlock);

    final ArgumentCaptor<NewBlockMessage> messageSentCaptor =
        ArgumentCaptor.forClass(NewBlockMessage.class);
    final ArgumentCaptor<PeerConnection> receivingPeerCaptor =
        ArgumentCaptor.forClass(PeerConnection.class);
    final ArgumentCaptor<Capability> capabilityCaptor = ArgumentCaptor.forClass(Capability.class);

    verify(onSend, times(PEER_COUNT))
        .exec(
            capabilityCaptor.capture(),
            messageSentCaptor.capture(),
            receivingPeerCaptor.capture());

    // assert that all entries in capability param were Eth63
    assertThat(capabilityCaptor.getAllValues().stream().distinct().collect(Collectors.toList()))
        .isEqualTo(Collections.singletonList(EthProtocol.ETH63));

    // assert that all messages transmitted contain the expected block & total difficulty.
    final ProtocolSchedule protocolSchdeule = MainnetProtocolSchedule.create();
    for (final NewBlockMessage msg : messageSentCaptor.getAllValues()) {
      assertThat(msg.block(protocolSchdeule)).isEqualTo(minedBlock);
      assertThat(msg.totalDifficulty(protocolSchdeule)).isEqualTo(expectedTotalDifficulty);
    }

    assertThat(receivingPeerCaptor.getAllValues().containsAll(peers)).isTrue();
  }
}