java.nio.channels.AsynchronousByteChannel#org.mockito.ArgumentCaptor源码实例Demo

下面列出了java.nio.channels.AsynchronousByteChannel#org.mockito.ArgumentCaptor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Moss   文件: MailNotifierTest.java
@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"));
}
 
源代码2 项目: besu   文件: BesuCommandTest.java
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();
}
 
源代码3 项目: grpc-nebula-java   文件: DeadlineTest.java
@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());
}
 
源代码4 项目: besu   文件: BesuCommandTest.java
@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();
}
 
@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());
}
 
源代码6 项目: grpc-nebula-java   文件: DeadlineTest.java
@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());
}
 
@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());
}
 
源代码8 项目: data-highway   文件: KafkaBrokerMonitorTest.java
@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"));
}
 
源代码9 项目: grpc-nebula-java   文件: NettyClientHandlerTest.java
@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());
}
 
源代码10 项目: data-highway   文件: ConsumerRecordWriterTest.java
@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));
}
 
@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"));
}
 
源代码12 项目: dynein   文件: AsyncSqsClientImplTest.java
@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());
}
 
@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());
}
 
@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));
}
 
源代码15 项目: grpc-nebula-java   文件: ServerCallImplTest.java
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());
}
 
源代码16 项目: jsonschema-generator   文件: SwaggerModuleTest.java
@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);
}
 
@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);
}
 
源代码18 项目: grpc-nebula-java   文件: NettyServerStreamTest.java
@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));
}
 
源代码19 项目: sdn-rx   文件: TransactionHandlingTest.java
@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);
}
 
源代码20 项目: grpc-nebula-java   文件: NettyServerStreamTest.java
@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();
}
 
源代码21 项目: grpc-nebula-java   文件: RetriableStreamTest.java
@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
}
 
源代码22 项目: grpc-nebula-java   文件: RetriableStreamTest.java
@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();
}
 
@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());
}
 
源代码24 项目: grpc-nebula-java   文件: RetriableStreamTest.java
@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);
}
 
@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());
}
 
源代码26 项目: XS2A-Sandbox   文件: AISControllerTest.java
@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());
}
 
源代码27 项目: XS2A-Sandbox   文件: AISControllerTest.java
@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());
}
 
源代码28 项目: sofa-jraft   文件: AbstractClientServiceTest.java
@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());
}
 
@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());
}
 
源代码30 项目: plugins   文件: TimersPluginTest.java
@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());
}