Java Code Examples for org.mockito.ArgumentCaptor

The following examples show how to use org.mockito.ArgumentCaptor. These examples are extracted from open source projects.
Example 1
Project: Moss   File: MailNotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_send_mail_using_custom_template_with_additional_properties() throws IOException, MessagingException {
    notifier.setTemplate("/de/codecentric/boot/admin/server/notify/custom-mail.html");
    notifier.getAdditionalProperties().put("customProperty", "HELLO WORLD!");


    StepVerifier.create(notifier.notify(
        new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown())))
                .verifyComplete();

    ArgumentCaptor<MimeMessage> mailCaptor = ArgumentCaptor.forClass(MimeMessage.class);
    verify(sender).send(mailCaptor.capture());

    MimeMessage mail = mailCaptor.getValue();
    String body = extractBody(mail.getDataHandler());
    assertThat(body).isEqualTo(loadExpectedBody("expected-custom-mail"));
}
 
Example 2
Project: besu   File: BesuCommandTest.java    License: Apache License 2.0 6 votes vote down vote up
private void networkValuesCanBeOverridden(final String network) throws Exception {
  parseCommand(
      "--network",
      network,
      "--network-id",
      "1234567",
      "--bootnodes",
      String.join(",", validENodeStrings));

  final ArgumentCaptor<EthNetworkConfig> networkArg =
      ArgumentCaptor.forClass(EthNetworkConfig.class);

  verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any());
  verify(mockControllerBuilder).build();

  assertThat(networkArg.getValue().getBootNodes())
      .isEqualTo(
          Stream.of(validENodeStrings).map(EnodeURL::fromString).collect(Collectors.toList()));
  assertThat(networkArg.getValue().getNetworkId()).isEqualTo(1234567);

  assertThat(commandOutput.toString()).isEmpty();
  assertThat(commandErrorOutput.toString()).isEmpty();
}
 
Example 3
Project: grpc-nebula-java   File: DeadlineTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void runOnAlreadyExpiredIsExecutedOnExecutor() throws Exception {
  Deadline base = Deadline.after(0, TimeUnit.MICROSECONDS, ticker);
  ScheduledExecutorService mockScheduler = mock(ScheduledExecutorService.class);
  final AtomicBoolean executed = new AtomicBoolean();
  Future<?> unused = base.runOnExpiration(
      new Runnable() {
        @Override
        public void run() {
          executed.set(true);
        }
      }, mockScheduler);
  assertFalse(executed.get());
  ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
  verify(mockScheduler).schedule(runnableCaptor.capture(), eq(0L), eq(TimeUnit.NANOSECONDS));
  runnableCaptor.getValue().run();
  assertTrue(executed.get());
}
 
Example 4
Project: besu   File: BesuCommandTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void privacyMultiTenancyIsConfiguredWhenConfiguredWithNecessaryOptions() {
  parseCommand(
      "--privacy-enabled",
      "--rpc-http-authentication-enabled",
      "--privacy-multi-tenancy-enabled",
      "--rpc-http-authentication-jwt-public-key-file",
      "/non/existent/file");

  final ArgumentCaptor<PrivacyParameters> privacyParametersArgumentCaptor =
      ArgumentCaptor.forClass(PrivacyParameters.class);

  verify(mockControllerBuilder).privacyParameters(privacyParametersArgumentCaptor.capture());
  verify(mockControllerBuilder).build();

  assertThat(privacyParametersArgumentCaptor.getValue().isMultiTenancyEnabled()).isTrue();
}
 
Example 5
Project: java-technology-stack   File: StompBrokerRelayMessageHandlerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void systemSubscription() throws Exception {

	MessageHandler handler = mock(MessageHandler.class);
	this.brokerRelay.setSystemSubscriptions(Collections.singletonMap("/topic/foo", handler));
	this.brokerRelay.start();

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
	accessor.setLeaveMutable(true);
	MessageHeaders headers = accessor.getMessageHeaders();
	this.tcpClient.handleMessage(MessageBuilder.createMessage(new byte[0], headers));

	assertEquals(2, this.tcpClient.getSentMessages().size());
	assertEquals(StompCommand.CONNECT, this.tcpClient.getSentHeaders(0).getCommand());
	assertEquals(StompCommand.SUBSCRIBE, this.tcpClient.getSentHeaders(1).getCommand());
	assertEquals("/topic/foo", this.tcpClient.getSentHeaders(1).getDestination());

	Message<byte[]> message = message(StompCommand.MESSAGE, null, null, "/topic/foo");
	this.tcpClient.handleMessage(message);

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(handler).handleMessage(captor.capture());
	assertSame(message, captor.getValue());
}
 
Example 6
Project: grpc-nebula-java   File: DeadlineTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void runOnEventualExpirationIsExecuted() throws Exception {
  Deadline base = Deadline.after(50, TimeUnit.MICROSECONDS, ticker);
  ScheduledExecutorService mockScheduler = mock(ScheduledExecutorService.class);
  final AtomicBoolean executed = new AtomicBoolean();
  Future<?> unused = base.runOnExpiration(
      new Runnable() {
        @Override
        public void run() {
          executed.set(true);
        }
      }, mockScheduler);
  assertFalse(executed.get());
  ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
  verify(mockScheduler).schedule(runnableCaptor.capture(), eq(50000L), eq(TimeUnit.NANOSECONDS));
  runnableCaptor.getValue().run();
  assertTrue(executed.get());
}
 
Example 7
Project: grpc-nebula-java   File: AbstractClientStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void trailerNotOkWithTruncatedMessage() {
  AbstractClientStream stream =
      new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer);
  stream.start(mockListener);

  stream.transportState().requestMessagesFromDeframer(1);
  stream.transportState().deframe(ReadableBuffers.wrap(new byte[] {0, 0, 0, 0, 2, 1}));
  stream.transportState().inboundTrailersReceived(
      new Metadata(), Status.DATA_LOSS.withDescription("data___loss"));

  ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
  verify(mockListener)
      .closed(statusCaptor.capture(), any(RpcProgress.class), any(Metadata.class));
  assertSame(Status.Code.DATA_LOSS, statusCaptor.getValue().getCode());
  assertEquals("data___loss", statusCaptor.getValue().getDescription());
}
 
Example 8
Project: data-highway   File: KafkaBrokerMonitorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testName() throws Exception {
  doReturn(Collections.singletonList("0")).when(client).getBrokerIds();
  doReturn(new Properties()).when(client).getConfig("0");

  underTest.checkAndUpdateBrokers();

  ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
  verify(client).changeConfig(eq("0"), captor.capture());

  Properties config = captor.getValue();

  assertThat(config.size(), is(2));
  assertThat(config.getProperty("leader.replication.throttled.rate"), is("1"));
  assertThat(config.getProperty("follower.replication.throttled.rate"), is("2"));
}
 
Example 9
Project: grpc-nebula-java   File: NettyClientHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void inboundShouldForwardToStream() throws Exception {
  createStream();

  // Read a headers frame first.
  Http2Headers headers = new DefaultHttp2Headers().status(STATUS_OK)
      .set(CONTENT_TYPE_HEADER, CONTENT_TYPE_GRPC)
      .set(as("magic"), as("value"));
  ByteBuf headersFrame = headersFrame(3, headers);
  channelRead(headersFrame);
  ArgumentCaptor<Metadata> captor = ArgumentCaptor.forClass(Metadata.class);
  verify(streamListener).headersRead(captor.capture());
  assertEquals("value",
      captor.getValue().get(Metadata.Key.of("magic", Metadata.ASCII_STRING_MARSHALLER)));

  streamTransportState.requestMessagesFromDeframer(1);

  // Create a data frame and then trigger the handler to read it.
  ByteBuf frame = grpcDataFrame(3, false, contentAsArray());
  channelRead(frame);
  InputStream message = streamListenerMessageQueue.poll();
  assertArrayEquals(ByteBufUtil.getBytes(content()), ByteStreams.toByteArray(message));
  message.close();
  assertNull("no additional message expected", streamListenerMessageQueue.poll());
}
 
Example 10
Project: data-highway   File: ConsumerRecordWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void write_Close() throws IOException {
  when(outputStreamFactory.create(LOCATION)).thenReturn(abortableOutputStream);
  ArgumentCaptor<OutputStream> captor = ArgumentCaptor.forClass(OutputStream.class);
  when(recordWriterFactory.create(eq(schema1), captor.capture())).thenReturn(recordWriter);

  underTest.getByteCounter().getAndAdd(1L); // fake some written bytes
  ConsumerRecord<Void, Record> record = record(schema1, "foo", 1, 10);
  underTest.write(record);
  underTest.close();

  verify(recordWriter).write(record.value());
  assertThat(underTest.getRecordCounter().get(), is(0L));
  verify(metrics).consumedBytes(10);
  verify(metrics).offsetHighwaterMark(0, 1);
  verify(metrics).uploadedBytes(1L);
  verify(metrics).uploadedEvents(1L);
  assertThat(writers.size(), is(0));
}
 
Example 11
Project: vertx-spring-boot   File: VertxWebSocketClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldAdaptHeaders() {
    HttpHeaders originalHeaders = new HttpHeaders();
    originalHeaders.put("key1", Arrays.asList("value1", "value2"));
    originalHeaders.add("key2", "value3");

    webSocketClient.execute(TEST_URI, originalHeaders, session -> Mono.empty())
        .subscribe();

    ArgumentCaptor<VertxHttpHeaders> headersCaptor = ArgumentCaptor.forClass(VertxHttpHeaders.class);
    verify(mockHttpClient).websocket(anyInt(), anyString(), anyString(), headersCaptor.capture(),
        any(Handler.class), any(Handler.class));

    VertxHttpHeaders actualHeaders = headersCaptor.getValue();
    assertThat(actualHeaders.getAll("key1")).isEqualTo(originalHeaders.get("key1"));
    assertThat(actualHeaders.getAll("key2")).isEqualTo(originalHeaders.get("key2"));
}
 
Example 12
Project: dynein   File: AsyncSqsClientImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddWithDelay() {
  urlSetup("testQueue", "testUrl");
  queueAddSetup();
  sentRequest = ArgumentCaptor.forClass(SendMessageRequest.class);

  CompletableFuture<Void> delay = asyncClient.add("test", "testQueue", 10);
  verify(awsAsyncSqsClient).sendMessage(sentRequest.capture());

  assertEquals(sentRequest.getValue().messageBody(), "test");
  assertEquals(sentRequest.getValue().queueUrl(), "testUrl");
  assertEquals(sentRequest.getValue().delaySeconds(), new Integer(10));

  verify(awsAsyncSqsClient, times(1)).sendMessage(any(SendMessageRequest.class));

  assertNull(delay.join());
}
 
Example 13
Project: client-encryption-java   File: HttpExecuteFieldLevelEncryptionInterceptorTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testIntercept_ShouldEncryptRequestPayloadAndUpdateContentLengthHeader() throws Exception {

    // GIVEN
    FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder()
            .withEncryptionPath("$.foo", "$.encryptedFoo")
            .build();
    HttpRequest request = mock(HttpRequest.class);
    HttpHeaders httpHeaders = new HttpHeaders();
    when(request.getContent()).thenReturn(new ByteArrayContent(JSON_TYPE, "{\"foo\":\"bar\"}".getBytes()));
    when(request.getHeaders()).thenReturn(httpHeaders);

    // WHEN
    HttpExecuteFieldLevelEncryptionInterceptor instanceUnderTest = new HttpExecuteFieldLevelEncryptionInterceptor(config);
    instanceUnderTest.intercept(request);

    // THEN
    ArgumentCaptor<HttpContent> contentCaptor = ArgumentCaptor.forClass(HttpContent.class);
    verify(request).setContent(contentCaptor.capture());
    ByteArrayOutputStream encryptedPayloadStream = new ByteArrayOutputStream();
    contentCaptor.getValue().writeTo(encryptedPayloadStream);
    String encryptedPayload = encryptedPayloadStream.toString(StandardCharsets.UTF_8.name());
    Assert.assertFalse(encryptedPayload.contains("foo"));
    Assert.assertTrue(encryptedPayload.contains("encryptedFoo"));
    assertEquals(encryptedPayload.length(), httpHeaders.getContentLength().intValue());
}
 
Example 14
Project: java-technology-stack   File: SubscriptionMethodReturnValueHandlerTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testHeadersPassedToMessagingTemplate() throws Exception {
	String sessionId = "sess1";
	String subscriptionId = "subs1";
	String destination = "/dest";
	Message<?> inputMessage = createInputMessage(sessionId, subscriptionId, destination, null);

	MessageSendingOperations messagingTemplate = Mockito.mock(MessageSendingOperations.class);
	SubscriptionMethodReturnValueHandler handler = new SubscriptionMethodReturnValueHandler(messagingTemplate);

	handler.handleReturnValue(PAYLOAD, this.subscribeEventReturnType, inputMessage);

	ArgumentCaptor<MessageHeaders> captor = ArgumentCaptor.forClass(MessageHeaders.class);
	verify(messagingTemplate).convertAndSend(eq("/dest"), eq(PAYLOAD), captor.capture());

	SimpMessageHeaderAccessor headerAccessor =
			MessageHeaderAccessor.getAccessor(captor.getValue(), SimpMessageHeaderAccessor.class);

	assertNotNull(headerAccessor);
	assertTrue(headerAccessor.isMutable());
	assertEquals(sessionId, headerAccessor.getSessionId());
	assertEquals(subscriptionId, headerAccessor.getSubscriptionId());
	assertEquals(this.subscribeEventReturnType, headerAccessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER));
}
 
Example 15
Project: grpc-nebula-java   File: ServerCallImplTest.java    License: Apache License 2.0 6 votes vote down vote up
private void sendMessage_serverSendsOne_closeOnSecondCall(
    MethodDescriptor<Long, Long> method) {
  ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<Long, Long>(
      stream,
      method,
      requestHeaders,
      context,
      DecompressorRegistry.getDefaultInstance(),
      CompressorRegistry.getDefaultInstance(),
      serverCallTracer);
  serverCall.sendHeaders(new Metadata());
  serverCall.sendMessage(1L);
  verify(stream, times(1)).writeMessage(any(InputStream.class));
  verify(stream, never()).close(any(Status.class), any(Metadata.class));

  // trying to send a second message causes gRPC to close the underlying stream
  serverCall.sendMessage(1L);
  verify(stream, times(1)).writeMessage(any(InputStream.class));
  ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
  verify(stream, times(1)).cancel(statusCaptor.capture());
  assertEquals(Status.Code.INTERNAL, statusCaptor.getValue().getCode());
  assertEquals(ServerCallImpl.TOO_MANY_RESPONSES, statusCaptor.getValue().getDescription());
}
 
Example 16
Project: jsonschema-generator   File: SwaggerModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Parameters
public void testDescriptionResolver(String fieldName, boolean asContainerItem, String expectedMemberDescription, String expectedTypeDescription) {
    new SwaggerModule().applyToConfigBuilder(this.configBuilder);

    TestType testType = new TestType(TestClassForDescription.class);
    FieldScope field = testType.getMemberField(fieldName);
    if (asContainerItem) {
        field = field.asFakeContainerItemScope();
    }

    ArgumentCaptor<ConfigFunction<FieldScope, String>> memberCaptor = ArgumentCaptor.forClass(ConfigFunction.class);
    Mockito.verify(this.fieldConfigPart).withDescriptionResolver(memberCaptor.capture());
    String memberDescription = memberCaptor.getValue().apply(field);
    Assert.assertEquals(expectedMemberDescription, memberDescription);

    ArgumentCaptor<ConfigFunction<TypeScope, String>> typeCaptor = ArgumentCaptor.forClass(ConfigFunction.class);
    Mockito.verify(this.typesInGeneralConfigPart).withDescriptionResolver(typeCaptor.capture());
    TypeScope scope = Mockito.mock(TypeScope.class);
    Mockito.when(scope.getType()).thenReturn(field.getType());
    String typeDescription = typeCaptor.getValue().apply(scope);
    Assert.assertEquals(expectedTypeDescription, typeDescription);
}
 
Example 17
Project: kogito-runtimes   File: DecisionTracingListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void test_Listener_MockedEvents_Working() {
    DMNContextImpl context = new DMNContextImpl();
    DecisionExecutionIdUtils.inject(context, () -> TEST_EXECUTION_ID_1);

    DMNResultImpl result = new DMNResultImpl(new DMNModelImpl());
    result.setContext(context);

    BeforeEvaluateAllEvent beforeEvent = new MockBeforeEvaluateAllEvent(MOCKED_MODEL_NAMESPACE, MOCKED_MODEL_NAME, result);
    AfterEvaluateAllEvent afterEvent = new MockAfterEvaluateAllEvent(MOCKED_MODEL_NAMESPACE, MOCKED_MODEL_NAME, result);

    Consumer<EvaluateEvent> eventConsumer = mock(Consumer.class);
    DecisionTracingListener listener = new DecisionTracingListener(eventConsumer);
    listener.beforeEvaluateAll(beforeEvent);
    listener.afterEvaluateAll(afterEvent);

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

    assertEvaluateAllEvents(eventCaptor.getAllValues(), MOCKED_MODEL_NAMESPACE, MOCKED_MODEL_NAME, TEST_EXECUTION_ID_1);
}
 
Example 18
Project: grpc-nebula-java   File: NettyServerStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void writeMessageShouldSendResponse() throws Exception {
  ListMultimap<CharSequence, CharSequence> expectedHeaders =
      ImmutableListMultimap.copyOf(new DefaultHttp2Headers()
          .status(Utils.STATUS_OK)
          .set(Utils.CONTENT_TYPE_HEADER, Utils.CONTENT_TYPE_GRPC));

  stream.writeHeaders(new Metadata());

  ArgumentCaptor<SendResponseHeadersCommand> sendHeadersCap =
      ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
  verify(writeQueue).enqueue(sendHeadersCap.capture(), eq(true));
  SendResponseHeadersCommand sendHeaders = sendHeadersCap.getValue();
  assertThat(sendHeaders.stream()).isSameAs(stream.transportState());
  assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers()))
      .containsExactlyEntriesIn(expectedHeaders);
  assertThat(sendHeaders.endOfStream()).isFalse();

  byte[] msg = smallMessage();
  stream.writeMessage(new ByteArrayInputStream(msg));
  stream.flush();

  verify(writeQueue).enqueue(
      eq(new SendGrpcFrameCommand(stream.transportState(), messageFrame(MESSAGE), false)),
      eq(true));
}
 
Example 19
Project: sdn-rx   File: TransactionHandlingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldCallCloseOnSession() {

	ArgumentCaptor<SessionConfig> configArgumentCaptor = ArgumentCaptor.forClass(SessionConfig.class);

	when(driver.session(any(SessionConfig.class))).thenReturn(session);

	// Make template acquire session
	DefaultNeo4jClient neo4jClient = new DefaultNeo4jClient(driver);
	try (DefaultNeo4jClient.AutoCloseableQueryRunner s = neo4jClient.getQueryRunner("aDatabase")) {
		s.run("MATCH (n) RETURN n");
	}

	verify(driver).session(configArgumentCaptor.capture());
	SessionConfig sessionConfig = configArgumentCaptor.getValue();
	assertThat(sessionConfig.database()).isPresent().contains("aDatabase");

	verify(session).run(any(String.class));
	verify(session).close();

	verifyNoMoreInteractions(driver, session, transaction);
}
 
Example 20
Project: grpc-nebula-java   File: NettyServerStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void writeHeadersShouldSendHeaders() throws Exception {
  Metadata headers = new Metadata();
  ListMultimap<CharSequence, CharSequence> expectedHeaders =
      ImmutableListMultimap.copyOf(Utils.convertServerHeaders(headers));

  stream().writeHeaders(headers);

  ArgumentCaptor<SendResponseHeadersCommand> sendHeadersCap =
      ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
  verify(writeQueue).enqueue(sendHeadersCap.capture(), eq(true));
  SendResponseHeadersCommand sendHeaders = sendHeadersCap.getValue();
  assertThat(sendHeaders.stream()).isSameAs(stream.transportState());
  assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers()))
      .containsExactlyEntriesIn(expectedHeaders);
  assertThat(sendHeaders.endOfStream()).isFalse();
}
 
Example 21
Project: grpc-nebula-java   File: RetriableStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void throttledStream_FailWithRetriableStatusCode_WithoutPushback() {
  Throttle throttle = new Throttle(4f, 0.8f);
  RetriableStream<String> retriableStream = newThrottledRetriableStream(throttle);

  ClientStream mockStream = mock(ClientStream.class);
  doReturn(mockStream).when(retriableStreamRecorder).newSubstream(anyInt());
  retriableStream.start(masterListener);
  ArgumentCaptor<ClientStreamListener> sublistenerCaptor =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream).start(sublistenerCaptor.capture());

  // mimic some other call in the channel triggers a throttle countdown
  assertTrue(throttle.onQualifiedFailureThenCheckIsAboveThreshold()); // count = 3

  sublistenerCaptor.getValue().closed(Status.fromCode(RETRIABLE_STATUS_CODE_1), new Metadata());
  verify(retriableStreamRecorder).postCommit();
  assertFalse(throttle.isAboveThreshold()); // count = 2
}
 
Example 22
Project: grpc-nebula-java   File: RetriableStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void headersRead_cancel() {
  ClientStream mockStream1 = mock(ClientStream.class);
  doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0);
  InOrder inOrder = inOrder(retriableStreamRecorder);

  retriableStream.start(masterListener);

  ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream1).start(sublistenerCaptor1.capture());

  sublistenerCaptor1.getValue().headersRead(new Metadata());

  inOrder.verify(retriableStreamRecorder).postCommit();

  retriableStream.cancel(Status.CANCELLED);

  inOrder.verify(retriableStreamRecorder, never()).postCommit();
}
 
Example 23
Project: grpc-nebula-java   File: CallCredentials2ApplyingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void fail_delayed() {
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);

  // Will call applyRequestMetadata(), which is no-op.
  DelayedStream stream = (DelayedStream) transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<MetadataApplier> applierCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(
      any(RequestInfo.class), same(mockExecutor), applierCaptor.capture());

  Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
  applierCaptor.getValue().fail(error);

  verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
  FailingClientStream failingStream = (FailingClientStream) stream.getRealStream();
  assertSame(error, failingStream.getError());
}
 
Example 24
Project: grpc-nebula-java   File: RetriableStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void messageAvailable() {
  ClientStream mockStream1 = mock(ClientStream.class);
  doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0);

  retriableStream.start(masterListener);

  ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream1).start(sublistenerCaptor1.capture());

  ClientStreamListener listener = sublistenerCaptor1.getValue();
  listener.headersRead(new Metadata());
  MessageProducer messageProducer = mock(MessageProducer.class);
  listener.messagesAvailable(messageProducer);
  verify(masterListener).messagesAvailable(messageProducer);
}
 
Example 25
Project: aws-glue-data-catalog-client-for-apache-hive-metastore   File: GlueMetastoreClientDelegateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPartitionByValuesWithCatalogId() throws Exception {
  List<String> values = Lists.newArrayList("foo", "bar");
  Partition partition = new Partition().withDatabaseName(testDb.getName())
    .withTableName(testTbl.getName())
    .withValues(values)
    .withStorageDescriptor(TestObjects.getTestStorageDescriptor());
  GetPartitionRequest request = new GetPartitionRequest()
    .withDatabaseName(testDb.getName())
    .withTableName(testTbl.getName())
    .withPartitionValues(values).
    withCatalogId(CATALOG_ID);
  when(glueClient.getPartition(request)).thenReturn(new GetPartitionResult().withPartition(partition));
  org.apache.hadoop.hive.metastore.api.Partition result = metastoreClientDelegateCatalogId.getPartition(testDb.getName(), testTbl.getName(), values);

  ArgumentCaptor<GetPartitionRequest> captor = ArgumentCaptor.forClass(GetPartitionRequest.class);
  verify(glueClient, times(1)).getPartition(captor.capture());
  assertThat(result.getValues(), is(values));
  assertEquals(CATALOG_ID, captor.getValue().getCatalogId());
}
 
Example 26
Project: XS2A-Sandbox   File: AISControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void aisDone() {
    // Given
    when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
    when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(FINALISED, ConsentStatus.VALID));
    when(responseUtils.redirect(anyString(), any())).thenReturn(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED)));
    when(authService.resolveAuthConfirmationCodeRedirectUri(anyString(), anyString())).thenReturn(OK_URI);

    // When
    ResponseEntity<ConsentAuthorizeResponse> result = controller.aisDone(ENCRYPTED_ID, AUTH_ID, COOKIE, false, "code");

    // Then
    assertEquals(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED)), result);
    ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);
    verify(responseUtils).redirect(urlCaptor.capture(), any());
    assertEquals(OK_URI, urlCaptor.getValue());
}
 
Example 27
Project: XS2A-Sandbox   File: AISControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void aisDone_nok() {
    // Given
    when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
    when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(RECEIVED, ConsentStatus.REJECTED));
    when(responseUtils.redirect(anyString(), any())).thenReturn(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED)));
    when(authService.resolveAuthConfirmationCodeRedirectUri(anyString(), anyString())).thenReturn("");

    // When
    ResponseEntity<ConsentAuthorizeResponse> result = controller.aisDone(ENCRYPTED_ID, AUTH_ID, COOKIE, false, "code");

    // Then
    assertEquals(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED)), result);

    ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);

    verify(responseUtils).redirect(urlCaptor.capture(), any());
    assertEquals(NOK_URI, urlCaptor.getValue());
}
 
Example 28
Project: sofa-jraft   File: AbstractClientServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCancel() throws Exception {
    ArgumentCaptor<InvokeCallback> callbackArg = ArgumentCaptor.forClass(InvokeCallback.class);
    PingRequest request = TestUtils.createPingRequest();

    MockRpcResponseClosure<ErrorResponse> done = new MockRpcResponseClosure<>();
    Future<Message> future = this.clientService.invokeWithDone(this.endpoint, request, done, -1);
    Mockito.verify(this.rpcClient).invokeAsync(eq(this.endpoint), eq(request), Mockito.any(),
        callbackArg.capture(), eq((long) this.rpcOptions.getRpcDefaultTimeout()));
    InvokeCallback cb = callbackArg.getValue();
    assertNotNull(cb);
    assertNotNull(future);

    assertNull(done.getResponse());
    assertNull(done.status);
    assertFalse(future.isDone());

    future.cancel(true);
    ErrorResponse response = (ErrorResponse) this.rpcResponseFactory.newResponse(null, Status.OK());
    cb.complete(response, null);

    // The closure should be notified with ECANCELED error code.
    done.latch.await();
    assertNotNull(done.status);
    assertEquals(RaftError.ECANCELED.getNumber(), done.status.getCode());
}
 
Example 29
Project: spring-analysis-note   File: StandardWebSocketClientTests.java    License: MIT License 5 votes vote down vote up
@Test
public void clientEndpointConfig() throws Exception {

	URI uri = new URI("ws://localhost/abc");
	List<String> protocols = Collections.singletonList("abc");
	this.headers.setSecWebSocketProtocol(protocols);

	this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get();

	ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class);
	verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class));
	ClientEndpointConfig endpointConfig = captor.getValue();

	assertEquals(protocols, endpointConfig.getPreferredSubprotocols());
}
 
Example 30
Project: plugins   File: TimersPluginTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testDmmHalfTb()
{
	when(timersConfig.showTeleblock()).thenReturn(true);
	ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", DMM_HALF_TELEBLOCK_MESSAGE, "", 0);
	timersPlugin.onChatMessage(chatMessage);

	ArgumentCaptor<InfoBox> captor = ArgumentCaptor.forClass(InfoBox.class);
	verify(infoBoxManager).addInfoBox(captor.capture());
	TimerTimer infoBox = (TimerTimer) captor.getValue();
	assertEquals(GameTimer.DMM_HALFTB, infoBox.getTimer());
}
 
Example 31
Project: flink   File: JobLeaderIdServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests that the initial job registration registers a timeout which will call
 * {@link JobLeaderIdActions#notifyJobTimeout(JobID, UUID)} when executed.
 */
@Test
public void testInitialJobTimeout() throws Exception {
	final JobID jobId = new JobID();
	TestingHighAvailabilityServices highAvailabilityServices = new TestingHighAvailabilityServices();
	SettableLeaderRetrievalService leaderRetrievalService = new SettableLeaderRetrievalService(
		null,
		null);

	highAvailabilityServices.setJobMasterLeaderRetriever(jobId, leaderRetrievalService);

	ScheduledExecutor scheduledExecutor = mock(ScheduledExecutor.class);
	Time timeout = Time.milliseconds(5000L);
	JobLeaderIdActions jobLeaderIdActions = mock(JobLeaderIdActions.class);

	JobLeaderIdService jobLeaderIdService = new JobLeaderIdService(
		highAvailabilityServices,
		scheduledExecutor,
		timeout);

	jobLeaderIdService.start(jobLeaderIdActions);

	jobLeaderIdService.addJob(jobId);

	assertTrue(jobLeaderIdService.containsJob(jobId));

	ArgumentCaptor<Runnable> runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class);
	verify(scheduledExecutor).schedule(runnableArgumentCaptor.capture(), anyLong(), any(TimeUnit.class));

	Runnable timeoutRunnable = runnableArgumentCaptor.getValue();
	timeoutRunnable.run();

	ArgumentCaptor<UUID> timeoutIdArgumentCaptor = ArgumentCaptor.forClass(UUID.class);

	verify(jobLeaderIdActions, times(1)).notifyJobTimeout(eq(jobId), timeoutIdArgumentCaptor.capture());

	assertTrue(jobLeaderIdService.isValidTimeout(jobId, timeoutIdArgumentCaptor.getValue()));
}
 
Example 32
Project: grpc-nebula-java   File: NettyClientStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void deadlineExceededCancelShouldSendCommand() {
  // Set stream id to indicate it has been created
  stream().transportState().setId(STREAM_ID);
  stream().cancel(Status.DEADLINE_EXCEEDED);
  ArgumentCaptor<CancelClientStreamCommand> commandCaptor =
      ArgumentCaptor.forClass(CancelClientStreamCommand.class);
  verify(writeQueue).enqueue(commandCaptor.capture(), eq(true));
  assertEquals(commandCaptor.getValue().reason(), Status.DEADLINE_EXCEEDED);
}
 
Example 33
Project: hedera-mirror-node   File: RecordFileParserTest.java    License: 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 34
Project: plugins   File: TimersPluginTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testTransparentChatboxTb()
{
	when(timersConfig.showTeleblock()).thenReturn(true);
	ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", TRANSPARENT_CHATBOX_FULL_TELEBLOCK_MESSAGE, "", 0);
	timersPlugin.onChatMessage(chatMessage);

	ArgumentCaptor<InfoBox> captor = ArgumentCaptor.forClass(InfoBox.class);
	verify(infoBoxManager).addInfoBox(captor.capture());
	TimerTimer infoBox = (TimerTimer) captor.getValue();
	assertEquals(GameTimer.FULLTB, infoBox.getTimer());
}
 
Example 35
Project: realworld-serverless-application   File: ApplicationsServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void updateApplication_homePageUrl() {
  String userId = UUID.randomUUID().toString();
  String applicationId = UUID.randomUUID().toString();
  String homePageUrl = UUID.randomUUID().toString();
  Long version = 1L;
  Map<String, AttributeValue> recordMap = keyMap(userId, applicationId);
  recordMap.put("version", AttributeValue.builder().n(version.toString()).build());
  GetItemResponse response = GetItemResponse.builder()
        .item(recordMap)
        .build();
  Map<String, AttributeValue> updateMap = new HashMap<>();
  updateMap.put(":nv", AttributeValue.builder().n("2").build());
  updateMap.put(":v", AttributeValue.builder().n("1").build());
  updateMap.put(":h", AttributeValue.builder().s(homePageUrl).build());

  when(principal.getName()).thenReturn(userId);
  when(dynamodb.getItem(any(GetItemRequest.class))).thenReturn(response);

  UpdateApplicationInput input = new UpdateApplicationInput().homePageUrl(homePageUrl);
  UpdateItemRequest expectedUpdateItemRequest = UpdateItemRequest.builder()
        .tableName(TABLE_NAME)
        .key(keyMap(userId, applicationId))
        .updateExpression("SET homePageUrl = :h,version = :nv")
        .expressionAttributeValues(updateMap)
        .conditionExpression("version = :v")
        .build();

  Application application = service.updateApplication(input, applicationId);
  ArgumentCaptor<UpdateItemRequest> updateItemRequestArgumentCaptor = ArgumentCaptor.forClass(UpdateItemRequest.class);
  verify(dynamodb).updateItem(updateItemRequestArgumentCaptor.capture());

  UpdateItemRequest updateItemRequest = updateItemRequestArgumentCaptor.getValue();
  assertThat(updateItemRequest).isEqualTo(expectedUpdateItemRequest);
  assertThat(application.getApplicationId()).isEqualTo(applicationId);
  assertThat(application.getHomePageUrl()).isEqualTo(homePageUrl);
}
 
Example 36
Project: netty-4.1.22   File: Http2FrameRoundtripTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void largeDataFrameShouldMatch() throws Exception {
    // Create a large message to force chunking.
    final ByteBuf originalData = data(1024 * 1024);
    final int originalPadding = 100;
    final boolean endOfStream = true;

    writer.writeData(ctx, STREAM_ID, originalData.slice(), originalPadding,
            endOfStream, ctx.newPromise());
    readFrames();

    // Verify that at least one frame was sent with eos=false and exactly one with eos=true.
    verify(listener, atLeastOnce()).onDataRead(eq(ctx), eq(STREAM_ID), any(ByteBuf.class),
            anyInt(), eq(false));
    verify(listener).onDataRead(eq(ctx), eq(STREAM_ID), any(ByteBuf.class),
            anyInt(), eq(true));

    // Capture the read data and padding.
    ArgumentCaptor<ByteBuf> dataCaptor = ArgumentCaptor.forClass(ByteBuf.class);
    ArgumentCaptor<Integer> paddingCaptor = ArgumentCaptor.forClass(Integer.class);
    verify(listener, atLeastOnce()).onDataRead(eq(ctx), eq(STREAM_ID), dataCaptor.capture(),
            paddingCaptor.capture(), anyBoolean());

    // Make sure the data matches the original.
    for (ByteBuf chunk : dataCaptor.getAllValues()) {
        ByteBuf originalChunk = originalData.readSlice(chunk.readableBytes());
        assertEquals(originalChunk, chunk);
    }
    assertFalse(originalData.isReadable());

    // Make sure the padding matches the original.
    int totalReadPadding = 0;
    for (int framePadding : paddingCaptor.getAllValues()) {
        totalReadPadding += framePadding;
    }
    assertEquals(originalPadding, totalReadPadding);
}
 
Example 37
Project: grpc-nebula-java   File: KeepAliveManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void transportGoesIdleAfterPingSent() {
  // Transport becomes active. We should schedule keepalive pings.
  keepAliveManager.onTransportActive();
  ArgumentCaptor<Runnable> sendPingCaptor = ArgumentCaptor.forClass(Runnable.class);
  verify(scheduler, times(1)).schedule(sendPingCaptor.capture(), isA(Long.class),
      isA(TimeUnit.class));
  Runnable sendPing = sendPingCaptor.getValue();

  ScheduledFuture<?> shutdownFuture = mock(ScheduledFuture.class);
  doReturn(shutdownFuture)
      .when(scheduler).schedule(isA(Runnable.class), isA(Long.class), isA(TimeUnit.class));
  // Mannually running the Runnable will send the ping. Shutdown task should be scheduled.
  // TODO(zdapeng): user FakeClock.ScheduledExecutorService
  ticker.time = 1000;
  sendPing.run();
  verify(keepAlivePinger).ping();
  verify(scheduler, times(2)).schedule(isA(Runnable.class), isA(Long.class), isA(TimeUnit.class));

  // Transport becomes idle. No more ping should be scheduled after we receive a ping response.
  keepAliveManager.onTransportIdle();
  ticker.time = 1100;
  keepAliveManager.onDataReceived();
  verify(scheduler, times(2)).schedule(isA(Runnable.class), isA(Long.class), isA(TimeUnit.class));
  // Shutdown task has been cancelled.
  verify(shutdownFuture).cancel(isA(Boolean.class));

  // Transport becomes active again. Another ping is scheduled.
  keepAliveManager.onTransportActive();
  verify(scheduler, times(3)).schedule(isA(Runnable.class), isA(Long.class), isA(TimeUnit.class));
}
 
Example 38
Project: grpc-nebula-java   File: NettyClientStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void nonGrpcResponseShouldSetStatus() throws Exception {
  stream().transportState().transportDataReceived(Unpooled.copiedBuffer(MESSAGE, UTF_8), true);
  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
  verify(listener).closed(captor.capture(), same(PROCESSED), any(Metadata.class));
  assertEquals(Status.Code.INTERNAL, captor.getValue().getCode());
}
 
Example 39
Project: data-highway   File: ContentDecompressionFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
  when(request.getHeader(HttpHeaders.CONTENT_ENCODING)).thenReturn(contentEncoding);
  when(request.getInputStream()).thenReturn(new ServletInputStreamWrapper(new ByteArrayInputStream(inputBytes)));

  ArgumentCaptor<HttpServletRequest> requestCaptor = ArgumentCaptor.forClass(HttpServletRequest.class);
  doNothing().when(chain).doFilter(requestCaptor.capture(), any(ServletResponse.class));

  filter.doFilter(request, response, chain);

  HttpServletRequest outputRequest = requestCaptor.getValue();
  byte[] outputBytes = toByteArray(outputRequest.getInputStream());

  assertTrue(Arrays.equals(outputBytes, TEST_BYTES));
}
 
Example 40
Project: hivemq-community-edition   File: SubscribeHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_subscribe_multiple_all_not_authorized() throws Exception {

    final ArgumentCaptor<ImmutableSet> captor = ArgumentCaptor.forClass(ImmutableSet.class);
    final Topic topic1 = new Topic("test1", QoS.AT_LEAST_ONCE);
    final Topic topic2 = new Topic("test2", QoS.AT_MOST_ONCE);
    final Topic topic3 = new Topic("test3", QoS.EXACTLY_ONCE);

    final SUBSCRIBE subscribe = new SUBSCRIBE(ImmutableList.copyOf(Lists.newArrayList(topic1, topic2, topic3)), 10);

    final ModifiableDefaultPermissionsImpl permissions = new ModifiableDefaultPermissionsImpl();
    permissions.add(new TopicPermissionBuilderImpl(new TestConfigurationBootstrap().getFullConfigurationService()).topicFilter("#").type(TopicPermission.PermissionType.DENY).build());

    channel.attr(ChannelAttributes.AUTH_PERMISSIONS).set(permissions);

    channel.writeInbound(subscribe);

    final SUBACK response = channel.readOutbound();
    assertEquals(3, response.getReasonCodes().size());
    assertEquals(Mqtt5SubAckReasonCode.NOT_AUTHORIZED, response.getReasonCodes().get(0));
    assertEquals(Mqtt5SubAckReasonCode.NOT_AUTHORIZED, response.getReasonCodes().get(1));
    assertEquals(Mqtt5SubAckReasonCode.NOT_AUTHORIZED, response.getReasonCodes().get(2));
    assertEquals("Not authorized to subscribe to topic 'test1' with QoS '1'. " +
            "Not authorized to subscribe to topic 'test2' with QoS '0'. " +
            "Not authorized to subscribe to topic 'test3' with QoS '2'. ", response.getReasonString());

    verify(clientSessionSubscriptionPersistence).addSubscriptions(eq("client"), captor.capture());
    assertEquals(0, captor.getValue().size());
}