org.mockito.ArgumentCaptor Java Examples

The following examples show how to use org.mockito.ArgumentCaptor. 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: StompBrokerRelayMessageHandlerTests.java    From java-technology-stack with MIT License 7 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 #2
Source File: AbstractClientServiceTest.java    From sofa-jraft with 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 #3
Source File: KafkaBrokerMonitorTest.java    From data-highway with 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 #4
Source File: BesuCommandTest.java    From besu with 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
Source File: AbstractClientStreamTest.java    From grpc-nebula-java with 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 #6
Source File: NettyClientHandlerTest.java    From grpc-nebula-java with 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 #7
Source File: DeadlineTest.java    From grpc-nebula-java with 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 #8
Source File: DeadlineTest.java    From grpc-nebula-java with 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 #9
Source File: MailNotifierTest.java    From Moss with 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 #10
Source File: ConsumerRecordWriterTest.java    From data-highway with 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
Source File: VertxWebSocketClientTest.java    From vertx-spring-boot with 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
Source File: AsyncSqsClientImplTest.java    From dynein with 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
Source File: HttpExecuteFieldLevelEncryptionInterceptorTest.java    From client-encryption-java with 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
Source File: SubscriptionMethodReturnValueHandlerTests.java    From java-technology-stack with 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
Source File: ServerCallImplTest.java    From grpc-nebula-java with 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
Source File: SwaggerModuleTest.java    From jsonschema-generator with 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
Source File: DecisionTracingListenerTest.java    From kogito-runtimes with 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
Source File: NettyServerStreamTest.java    From grpc-nebula-java with 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
Source File: TransactionHandlingTest.java    From sdn-rx with 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
Source File: NettyServerStreamTest.java    From grpc-nebula-java with 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
Source File: RetriableStreamTest.java    From grpc-nebula-java with 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
Source File: RetriableStreamTest.java    From grpc-nebula-java with 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
Source File: CallCredentials2ApplyingTest.java    From grpc-nebula-java with 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
Source File: RetriableStreamTest.java    From grpc-nebula-java with 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
Source File: GlueMetastoreClientDelegateTest.java    From aws-glue-data-catalog-client-for-apache-hive-metastore with 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
Source File: AISControllerTest.java    From XS2A-Sandbox with 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
Source File: AISControllerTest.java    From XS2A-Sandbox with 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
Source File: BesuCommandTest.java    From besu with 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 #29
Source File: TestOzoneManagerServiceProviderImpl.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncDataFromOMFullSnapshot() throws Exception {

  // Empty OM DB to start with.
  ReconOMMetadataManager omMetadataManager = getTestReconOmMetadataManager(
      initializeEmptyOmMetadataManager(temporaryFolder.newFolder()),
      temporaryFolder.newFolder());
  ReconTaskStatusDao reconTaskStatusDaoMock =
      mock(ReconTaskStatusDao.class);
  doNothing().when(reconTaskStatusDaoMock)
      .update(any(ReconTaskStatus.class));

  ReconTaskController reconTaskControllerMock = getMockTaskController();
  when(reconTaskControllerMock.getReconTaskStatusDao())
      .thenReturn(reconTaskStatusDaoMock);
  doNothing().when(reconTaskControllerMock)
      .reInitializeTasks(omMetadataManager);

  OzoneManagerServiceProviderImpl ozoneManagerServiceProvider =
      new MockOzoneServiceProvider(configuration, omMetadataManager,
          reconTaskControllerMock, new ReconUtils(), ozoneManagerProtocol);

  OzoneManagerSyncMetrics metrics = ozoneManagerServiceProvider.getMetrics();
  assertEquals(0, metrics.getNumSnapshotRequests().value());

  // Should trigger full snapshot request.
  ozoneManagerServiceProvider.syncDataFromOM();

  ArgumentCaptor<ReconTaskStatus> captor =
      ArgumentCaptor.forClass(ReconTaskStatus.class);
  verify(reconTaskStatusDaoMock, times(1))
      .update(captor.capture());
  assertTrue(captor.getValue().getTaskName()
      .equals(OmSnapshotRequest.name()));
  verify(reconTaskControllerMock, times(1))
      .reInitializeTasks(omMetadataManager);
  assertEquals(1, metrics.getNumSnapshotRequests().value());
}
 
Example #30
Source File: HelloWorldClientTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * To test the client, call from the client against the fake server, and verify behaviors or state
 * changes from the server side.
 */
@Test
public void greet_messageDeliveredToServer() {
  ArgumentCaptor<HelloRequest> requestCaptor = ArgumentCaptor.forClass(HelloRequest.class);

  client.greet("test name");

  verify(serviceImpl)
      .sayHello(requestCaptor.capture(), Matchers.<StreamObserver<HelloReply>>any());
  assertEquals("test name", requestCaptor.getValue().getName());
}