org.hamcrest.core.Is Java Examples

The following examples show how to use org.hamcrest.core.Is. 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: JacksonRestOperationTest.java    From servicecomb-saga-actuator with Apache License 2.0 6 votes vote down vote up
@Test
public void appendsResponseToForm() throws Exception {
  ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class);
  when(transport.with(eq(address), eq(path), eq(method), argumentCaptor.capture())).thenReturn(
      SagaResponse.EMPTY_RESPONSE);

  SagaResponse response = restOperation.send(address, Operation.SUCCESSFUL_SAGA_RESPONSE);

  assertThat(response, Is.is(SagaResponse.EMPTY_RESPONSE));

  Map<String, Map<String, String>> updatedParams = argumentCaptor.getValue();
  assertThat(null == updatedParams.get("form") ? Collections.<String, String>emptyMap().get("response")
          : updatedParams.get("form").get("response")
      , Is.is(Operation.SUCCESSFUL_SAGA_RESPONSE.body()));
  assertThat(params.isEmpty(), is(true));
}
 
Example #2
Source File: ReadyServiceTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 6 votes vote down vote up
@Test
public void assertGetAllEligibleJobContextsWithRootNode() {
    Mockito.when(regCenter.isExisted("/state/ready")).thenReturn(true);
    Mockito.when(regCenter.getChildrenKeys("/state/ready")).thenReturn(Arrays.asList("not_existed_job", "running_job", "ineligible_job", "eligible_job"));
    Mockito.when(configService.load("not_existed_job")).thenReturn(Optional.<CloudJobConfiguration>absent());
    Mockito.when(configService.load("running_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("running_job")));
    Mockito.when(configService.load("eligible_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("eligible_job")));
    Mockito.when(runningService.isJobRunning("running_job")).thenReturn(true);
    Mockito.when(runningService.isJobRunning("eligible_job")).thenReturn(false);
    Assert.assertThat(readyService.getAllEligibleJobContexts(Collections.singletonList(
            JobContext.from(CloudJobConfigurationBuilder.createCloudJobConfiguration("ineligible_job"), ExecutionType.READY))).size(), Is.is(1));
    Mockito.verify(regCenter).isExisted("/state/ready");
    Mockito.verify(regCenter, Mockito.times(1)).getChildrenKeys("/state/ready");
    Mockito.verify(configService).load("not_existed_job");
    Mockito.verify(configService).load("running_job");
    Mockito.verify(configService).load("eligible_job");
    Mockito.verify(regCenter).remove("/state/ready/not_existed_job");
}
 
Example #3
Source File: InsertResultRequestEncoderTest.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEncodeInsertResultRequest() throws EncodingException {
    String version = Sos2Constants.SERVICEVERSION;
    String service = SosConstants.SOS;
    String templateIdentifier = "test-template-identifier";
    String resultValues = "test-result-values";
    InsertResultRequest request = new InsertResultRequest(service, version);
    request.setTemplateIdentifier(templateIdentifier);
    request.setResultValues(resultValues);

    XmlObject encodedRequest = encoder.create(request);
    assertThat(encodedRequest, Matchers.instanceOf(InsertResultDocument.class));
    assertThat(((InsertResultDocument)encodedRequest).getInsertResult(), Matchers.notNullValue());
    InsertResultType xbRequest = ((InsertResultDocument)encodedRequest).getInsertResult();
    assertThat(xbRequest.getService(), Is.is(service));
    assertThat(xbRequest.getVersion(), Is.is(version));
    assertThat(xbRequest.getTemplate(), Is.is(templateIdentifier));
    assertThat(xbRequest.getResultValues(), Matchers.instanceOf(XmlString.class));
    assertThat(((XmlString)xbRequest.getResultValues()).getStringValue(), Is.is(resultValues));
}
 
Example #4
Source File: DefaultCommandRunnerTest.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
@Test
public void test_large_output() throws Exception {

	// create temp file of about 274k
	final File tmp = File.createTempFile("carnotzet-test", null);
	tmp.deleteOnExit();
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < 10000; i++){
		sb.append("This line is repeated a lot\n");
	}
	String expected = sb.toString();
	FileUtils.write(tmp, expected);

	// When
	String actual = new SimpleTimeLimiter().callWithTimeout(
			() -> DefaultCommandRunner.INSTANCE.runCommandAndCaptureOutput("cat", tmp.getAbsolutePath()),
			2, TimeUnit.SECONDS, true);

	// Then
	Assert.assertThat(actual, Is.is(expected.trim()));
}
 
Example #5
Source File: WmlTVPEncoderv20Test.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetDefaultCumulativeProperty() throws EncodingException {
    XmlObject encodedElement = encoder.encode(mv);

    assertThat(encodedElement, CoreMatchers.instanceOf(MeasurementTimeseriesDocument.class));
    final MeasurementTimeseriesDocument measurementTimeseriesDocument =
            (MeasurementTimeseriesDocument) encodedElement;
    assertThat(measurementTimeseriesDocument.getTimeseries().isSetMetadata(), Is.is(true));
    assertThat(measurementTimeseriesDocument.getTimeseries().getMetadata().getTimeseriesMetadata(),
            CoreMatchers.instanceOf(MeasurementTimeseriesMetadataType.class));
    final MeasurementTimeseriesMetadataType measurementTimeseriesMetadataType =
            (MeasurementTimeseriesMetadataType) measurementTimeseriesDocument.getTimeseries().getMetadata()
                    .getTimeseriesMetadata();
    assertThat(measurementTimeseriesMetadataType.isSetCumulative(), Is.is(true));
    assertThat(measurementTimeseriesMetadataType.getCumulative(), Is.is(false));
}
 
Example #6
Source File: AlphaIntegrationWithRandomPortTest.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Test
public void persistsEvent() {
  asyncStub.onConnected(compensateResponseObserver).onNext(serviceConfig);
  blockingStub.onTxEvent(someGrpcEvent(TxStartedEvent));
  // use the asynchronous stub need to wait for some time
  await().atMost(1, SECONDS).until(() -> !eventRepo.findByGlobalTxId(globalTxId).isEmpty());

  assertThat(receivedCommands.isEmpty(), is(true));

  TxEvent envelope = eventRepo.findByGlobalTxId(globalTxId).get(0);

  assertThat(envelope.serviceName(), is(serviceName));
  assertThat(envelope.instanceId(), is(instanceId));
  assertThat(envelope.globalTxId(), is(globalTxId));
  assertThat(envelope.localTxId(), is(localTxId));
  assertThat(envelope.parentTxId(), is(parentTxId));
  assertThat(envelope.type(), Is.is(TxStartedEvent.name()));
  assertThat(envelope.compensationMethod(), is(compensationMethod));
  assertThat(envelope.payloads(), is(payload.getBytes()));
}
 
Example #7
Source File: ExecutorServiceObjectTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 6 votes vote down vote up
@Test
public void assertCreateExecutorService() {
    executorServiceObject = new ExecutorServiceObject("executor-service-test", 1);
    Assert.assertThat(executorServiceObject.getActiveThreadCount(), Is.is(0));
    Assert.assertThat(executorServiceObject.getWorkQueueSize(), Is.is(0));
    Assert.assertFalse(executorServiceObject.isShutdown());
    ExecutorService executorService = executorServiceObject.createExecutorService();
    executorService.submit(new FooTask());
    BlockUtils.waitingShortTime();
    Assert.assertThat(executorServiceObject.getActiveThreadCount(), Is.is(1));
    Assert.assertThat(executorServiceObject.getWorkQueueSize(), Is.is(0));
    Assert.assertFalse(executorServiceObject.isShutdown());
    executorService.submit(new FooTask());
    BlockUtils.waitingShortTime();
    Assert.assertThat(executorServiceObject.getActiveThreadCount(), Is.is(1));
    Assert.assertThat(executorServiceObject.getWorkQueueSize(), Is.is(1));
    Assert.assertFalse(executorServiceObject.isShutdown());
    executorService.shutdownNow();
    Assert.assertThat(executorServiceObject.getWorkQueueSize(), Is.is(0));
    Assert.assertTrue(executorServiceObject.isShutdown());
}
 
Example #8
Source File: UVFEncoderTest.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEncodeTimeseriesIdentifierAndCenturiesFromStreamingValues() throws
        EncodingException {
    GlobalObservationResponseValues globalValues = new GlobalObservationResponseValues();
    DateTime end = new DateTime(0);
    DateTime start = new DateTime(0);
    Time phenomenonTime = new TimePeriod(start, end);
    globalValues.addPhenomenonTime(phenomenonTime);
    responseToEncode.setGlobalObservationValues(globalValues);
    final String actual = getResponseString()[7];
    final String expected = obsPropIdentifier.substring(
        obsPropIdentifier.length() - UVFConstants.MAX_IDENTIFIER_LENGTH,
        obsPropIdentifier.length()) +
        " " + unit + "     " +
        "1900 1900";

    assertThat(actual, Is.is(expected));
}
 
Example #9
Source File: TsmlTVPEncoderv10Test.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEncodeInterpolationType() throws EncodingException, XmlException {
    final InterpolationType type = TimeseriesMLConstants.InterpolationType.MinPrec;

    mv.setDefaultPointMetadata(new DefaultPointMetadata()
            .setDefaultTVPMeasurementMetadata(new DefaultTVPMeasurementMetadata().setInterpolationtype(type)));

    XmlObject encodedElement = encoder.encode(mv);

    TimeseriesTVPType.DefaultPointMetadata defaultPointMetadata =
            ((TimeseriesTVPDocument) encodedElement).getTimeseriesTVP().getDefaultPointMetadata();
    PointMetadataDocument tvpMeasurementMetadataDocument =
            PointMetadataDocument.Factory.parse(defaultPointMetadata.xmlText());
    ReferenceType interpolationType =
            tvpMeasurementMetadataDocument.getPointMetadata().getInterpolationType();
    MatcherAssert.assertThat(interpolationType.getHref(),
            Is.is("http://www.opengis.net/def/timeseries/InterpolationCode/MinPrec"));
    MatcherAssert.assertThat(interpolationType.getTitle(), Is.is("MinPrec"));
}
 
Example #10
Source File: TccLoadBalanceSenderTest.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Test
public void participateInterruptedFailed() throws InterruptedException {
  Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        await().atLeast(1, SECONDS);
        tccLoadBalanceSender.participationStart(participationStartedEvent);
      } catch (OmegaException e) {
        assertThat(e.getMessage().endsWith("interruption"), Is.is(true));
      }
    }
  });
  thread.start();
  thread.interrupt();
  thread.join();
}
 
Example #11
Source File: CloudJobRestfulApiTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertFindAllFailoverTasks() throws Exception {
    Mockito.when(getRegCenter().isExisted("/state/failover")).thenReturn(true);
    Mockito.when(getRegCenter().getChildrenKeys("/state/failover")).thenReturn(Lists.newArrayList("test_job"));
    Mockito.when(getRegCenter().getChildrenKeys("/state/failover/test_job")).thenReturn(Lists.newArrayList("test_job@-@0"));
    String originalTaskId = UUID.randomUUID().toString();
    Mockito.when(getRegCenter().get("/state/failover/test_job/test_job@-@0")).thenReturn(originalTaskId);
    FailoverTaskInfo expectedFailoverTask = new FailoverTaskInfo(TaskContext.MetaInfo.from("test_job@-@0"), originalTaskId);
    Collection<FailoverTaskInfo> expectedResult = Lists.newArrayList(expectedFailoverTask);
    Assert.assertThat(RestfulTestsUtil.sentGetRequest("http://127.0.0.1:19000/api/job/tasks/failover"), Is.is(GsonFactory.getGson().toJson(expectedResult)));
    Mockito.verify(getRegCenter()).isExisted("/state/failover");
    Mockito.verify(getRegCenter()).getChildrenKeys("/state/failover");
    Mockito.verify(getRegCenter()).getChildrenKeys("/state/failover/test_job");
    Mockito.verify(getRegCenter()).get("/state/failover/test_job/test_job@-@0");
}
 
Example #12
Source File: RunningServiceTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAddWithData() {
    Mockito.when(regCenter.get("/config/job/other_job")).thenReturn(CloudJsonConstants.getJobJson("other_job"));
    TaskNode taskNode = TaskNode.builder().jobName("other_job").build();
    runningService.add(TaskContext.from(taskNode.getTaskNodeValue()));
    Assert.assertThat(runningService.getRunningTasks("other_job").size(), Is.is(1));
    Assert.assertThat(runningService.getRunningTasks("other_job").iterator().next(), Is.is(TaskContext.from(taskNode.getTaskNodeValue())));
}
 
Example #13
Source File: TccStartAnnotationProcessorTest.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendTccStartEventFailed() {
  throwException = true;
  try {
    tccStartAnnotationProcessor
        .preIntercept(null, "TccStartMethod", 0);
    expectFailing(TransactionalException.class);
  } catch (TransactionalException e) {
    Assert.assertThat(e.getMessage(), Is.is("exception"));
    Assert.assertThat(e.getCause(), instanceOf(RuntimeException.class));
    Assert.assertThat(e.getCause().getMessage(), Is.is("runtime exception"));
  }

}
 
Example #14
Source File: TaskContextTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertSetSlaveId() {
    TaskContext actual = new TaskContext("test_job", Lists.newArrayList(0), ExecutionType.READY, "slave-S0");
    Assert.assertThat(actual.getSlaveId(), Is.is("slave-S0"));
    actual.setSlaveId("slave-S1");
    Assert.assertThat(actual.getSlaveId(), Is.is("slave-S1"));
}
 
Example #15
Source File: CloudAppConfigurationServiceTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertLoadAllWithRootNode() {
    Mockito.when(regCenter.isExisted("/config/app")).thenReturn(true);
    Mockito.when(regCenter.getChildrenKeys(CloudAppConfigurationNode.ROOT)).thenReturn(Arrays.asList("test_app_1", "test_app_2"));
    Mockito.when(regCenter.get("/config/app/test_app_1")).thenReturn(CloudAppJsonConstants.getAppJson("test_app_1"));
    Collection<CloudAppConfiguration> actual = configService.loadAll();
    Assert.assertThat(actual.size(), Is.is(1));
    Assert.assertThat(actual.iterator().next().getAppName(), Is.is("test_app_1"));
    Mockito.verify(regCenter).isExisted("/config/app");
    Mockito.verify(regCenter).getChildrenKeys("/config/app");
    Mockito.verify(regCenter).get("/config/app/test_app_1");
    Mockito.verify(regCenter).get("/config/app/test_app_2");
}
 
Example #16
Source File: StatisticRdbRepositoryTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertFindLatestTaskRunningStatistics() {
    repository.add(new TaskRunningStatistics(100, new Date()));
    repository.add(new TaskRunningStatistics(200, new Date()));
    Optional<TaskRunningStatistics> po = repository.findLatestTaskRunningStatistics();
    Assert.assertThat(po.get().getRunningCount(), Is.is(200));
}
 
Example #17
Source File: JobEventRdbStorageTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAddJobStatusTraceEventWhenFailoverWithTaskStagingState() throws SQLException {
    JobStatusTraceEvent jobStatusTraceEvent = new JobStatusTraceEvent("test_job", "fake_failover_task_id", "fake_slave_id", JobStatusTraceEvent.Source.LITE_EXECUTOR, ExecutionType.FAILOVER, "0",
            JobStatusTraceEvent.State.TASK_STAGING, "message is empty.");
    jobStatusTraceEvent.setOriginalTaskId("original_fake_failover_task_id");
    Assert.assertThat(storage.getJobStatusTraceEvents("fake_failover_task_id").size(), Is.is(0));
    storage.addJobStatusTraceEvent(jobStatusTraceEvent);
    Assert.assertThat(storage.getJobStatusTraceEvents("fake_failover_task_id").size(), Is.is(1));
}
 
Example #18
Source File: StatisticRdbRepositoryTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertFindTaskResultStatisticsWithDifferentFromDate() {
    Date now = new Date();
    Date yesterday = getYesterday();
    for (StatisticInterval each : StatisticInterval.values()) {
        Assert.assertTrue(repository.add(new TaskResultStatistics(100, 0, each, yesterday)));
        Assert.assertTrue(repository.add(new TaskResultStatistics(100, 0, each, now)));
        Assert.assertThat(repository.findTaskResultStatistics(yesterday, each).size(), Is.is(2));
        Assert.assertThat(repository.findTaskResultStatistics(now, each).size(), Is.is(1));
    }
}
 
Example #19
Source File: SosInsertionMetadataTypeEncoderTest.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEncodeObservationTypes() throws EncodingException {
    SosInsertionMetadataType encoded = encoder.encode(insertionMetadata);

    MatcherAssert.assertThat(encoded.getObservationTypeArray().length, Is.is(2));
    List<String> observationTypes = Arrays.asList(encoded.getObservationTypeArray());
    Collections.sort(observationTypes);
    MatcherAssert.assertThat(observationTypes, Matchers.contains("type-1", "type-2"));
}
 
Example #20
Source File: InsertResultTemplateRequestEncoderTest.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEncodeResultEncoding() throws EncodingException, DecodingException {
    ResultTemplateType template = ((InsertResultTemplateDocument) encoder.create(request))
            .getInsertResultTemplate().getProposedTemplate().getResultTemplate();

    XmlHelper.validateDocument(template);

    assertThat(template.getResultEncoding(), Matchers.notNullValue());
    assertThat(template.getResultEncoding().getAbstractEncoding(), Matchers.notNullValue());
    AbstractEncodingType resultEncoding = template.getResultEncoding().getAbstractEncoding();
    assertThat(resultEncoding, Matchers.instanceOf(TextEncodingType.class));
    TextEncodingType xbTextEncoding = (TextEncodingType) resultEncoding;
    assertThat(xbTextEncoding.getBlockSeparator(), Is.is(blockSeparator));
    assertThat(xbTextEncoding.getTokenSeparator(), Is.is(tokenSeparator));
}
 
Example #21
Source File: StatisticManagerTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertFindLatestTaskResultStatisticsWhenRdbIsNotConfigured() throws NoSuchFieldException {
    ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", null);
    for (StatisticInterval each : StatisticInterval.values()) {
        TaskResultStatistics actual = statisticManager.findLatestTaskResultStatistics(each);
        Assert.assertThat(actual.getSuccessCount(), Is.is(0));
        Assert.assertThat(actual.getFailedCount(), Is.is(0));
    }
}
 
Example #22
Source File: SchedulerEngineTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertResourceOffers() {
    SchedulerDriver schedulerDriver = Mockito.mock(SchedulerDriver.class);
    List<Protos.Offer> offers = Arrays.asList(OfferBuilder.createOffer("offer_0"), OfferBuilder.createOffer("offer_1"));
    schedulerEngine.resourceOffers(schedulerDriver, offers);
    Assert.assertThat(LeasesQueue.getInstance().drainTo().size(), Is.is(2));
}
 
Example #23
Source File: SagaIntegrationTest.java    From servicecomb-saga-actuator with Apache License 2.0 5 votes vote down vote up
@Test
public void retriesFailedTransactionTillMaximum() {
  RequestProcessTask processTask = requestProcessTask(new ForwardRecovery());
  tasks.put(SAGA_REQUEST_TASK, processTask);

  when(transaction2.send(request2.serviceName(), transactionResponse1)).thenThrow(exception);
  when(transaction2.retries()).thenReturn(2);
  when(transaction2.toString()).thenReturn("transaction2");

  try {
    saga.run();
  } catch (TransactionAbortedException e) {
    assertThat(e.getMessage(),
        Is.is("Too many failures in transaction transaction2 of service " + request2.serviceName() + ", stop transaction!"));
  }

  assertThat(eventStore, contains(
      eventWith(sagaId, SAGA_START_TRANSACTION, SagaStartedEvent.class),
      eventWith(sagaId, transaction1, TransactionStartedEvent.class),
      eventWith(sagaId, transaction1, TransactionEndedEvent.class),
      eventWith(sagaId, transaction2, TransactionStartedEvent.class)
  ));

  verify(transaction1).send(request1.serviceName(), EMPTY_RESPONSE);
  verify(transaction2, times(3)).send(request2.serviceName(), transactionResponse1);

  verify(compensation1, never()).send(anyString(), any(SagaResponse.class));
  verify(compensation2, never()).send(anyString(), any(SagaResponse.class));
}
 
Example #24
Source File: BootstrapEnvironmentTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertGetMesosConfiguration() throws NoSuchFieldException {
    MesosConfiguration mesosConfig = bootstrapEnvironment.getMesosConfiguration();
    Assert.assertThat(mesosConfig.getHostname(), Is.is("localhost"));
    Assert.assertThat(mesosConfig.getUser(), Is.is(""));
    Assert.assertThat(mesosConfig.getUrl(), Is.is("zk://localhost:2181/mesos"));
}
 
Example #25
Source File: SimpleEventsProcessorTest.java    From exchange-core with Apache License 2.0 5 votes vote down vote up
private void verifyOriginalFields(OrderCommand source, OrderCommand result) {

        assertThat(source.command, Is.is(result.command));
        assertThat(source.orderId, Is.is(result.orderId));
        assertThat(source.symbol, Is.is(result.symbol));
        assertThat(source.price, Is.is(result.price));
        assertThat(source.size, Is.is(result.size));
        assertThat(source.reserveBidPrice, Is.is(result.reserveBidPrice));
        assertThat(source.action, Is.is(result.action));
        assertThat(source.orderType, Is.is(result.orderType));
        assertThat(source.uid, Is.is(result.uid));
        assertThat(source.timestamp, Is.is(result.timestamp));
        assertThat(source.userCookie, Is.is(result.userCookie));
        assertThat(source.resultCode, Is.is(result.resultCode));
    }
 
Example #26
Source File: LocalServiceRegistryClientImplTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadRegistryFile() {
  Assert.assertNotNull(registryClient);
  Assert.assertThat(registryClient.getAllMicroservices().size(), Is.is(2));
  List<MicroserviceInstance> m =
      registryClient.findServiceInstance("", "default", "ms2", DefinitionConst.VERSION_RULE_ALL);
  Assert.assertEquals(1, m.size());

  MicroserviceInstances microserviceInstances =
      registryClient.findServiceInstances("", "default", "ms2", DefinitionConst.VERSION_RULE_ALL, null);
  List<MicroserviceInstance> mi = microserviceInstances.getInstancesResponse().getInstances();
  Assert.assertEquals(1, mi.size());
}
 
Example #27
Source File: MonitoringEventListenerProviderTest.java    From keycloak-monitoring-prometheus with MIT License 5 votes vote down vote up
@Test
public void shouldGenerateFilesWithCorrectNamesForMaliciousEvents() throws IOException {
    MonitoringEventListenerProvider listener = new MonitoringEventListenerProvider(tmp.getRoot().getAbsolutePath());

    listener.onEvent(maliciousEvent());

    File expectedFile = new File(tmp.getRoot().getAbsolutePath() + File.separator + "keycloak_events_total;realm=test-realm;client_id=a_a__b_c_________c__________cake_;ip_address=4.4.4.4;type=LOGIN");

    MatcherAssert.assertThat(expectedFile.exists(), Is.is(true));
    MatcherAssert.assertThat(FileUtils.readFileToString(expectedFile), Is.is("1"));
}
 
Example #28
Source File: ReadyServiceTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertGetAllTasksWithRootNode() {
    Mockito.when(regCenter.isExisted(ReadyNode.ROOT)).thenReturn(true);
    Mockito.when(regCenter.getChildrenKeys(ReadyNode.ROOT)).thenReturn(Lists.newArrayList("test_job_1", "test_job_2"));
    Mockito.when(regCenter.get(ReadyNode.getReadyJobNodePath("test_job_1"))).thenReturn("1");
    Mockito.when(regCenter.get(ReadyNode.getReadyJobNodePath("test_job_2"))).thenReturn("5");
    Map<String, Integer> result = readyService.getAllReadyTasks();
    Assert.assertThat(result.size(), Is.is(2));
    Assert.assertThat(result.get("test_job_1"), Is.is(1));
    Assert.assertThat(result.get("test_job_2"), Is.is(5));
    Mockito.verify(regCenter).isExisted(ReadyNode.ROOT);
    Mockito.verify(regCenter).getChildrenKeys(ReadyNode.ROOT);
    Mockito.verify(regCenter, Mockito.times(2)).get((String) ArgumentMatchers.any());
}
 
Example #29
Source File: DetermineServiceCreateUpdateServiceActionsStepTest.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private void validateActions() {
    List<ServiceAction> serviceActionsToExecute = context.getVariable(Variables.SERVICE_ACTIONS_TO_EXCECUTE);
    if (stepInput.shouldCreateService) {
        collector.checkThat("Actions should contain " + ServiceAction.CREATE, serviceActionsToExecute.contains(ServiceAction.CREATE),
                            Is.is(true));
    }
    if (stepInput.shouldRecreateService) {
        collector.checkThat("Actions should contain " + ServiceAction.RECREATE,
                            serviceActionsToExecute.contains(ServiceAction.RECREATE), Is.is(true));
    }
    if (stepInput.shouldUpdateServicePlan) {
        collector.checkThat("Actions should contain " + ServiceAction.UPDATE_PLAN,
                            serviceActionsToExecute.contains(ServiceAction.UPDATE_PLAN), Is.is(true));
    }
    if (stepInput.shouldUpdateServiceTags) {
        collector.checkThat("Actions should contain " + ServiceAction.UPDATE_TAGS,
                            serviceActionsToExecute.contains(ServiceAction.UPDATE_TAGS), Is.is(true));
    }
    if (stepInput.shouldUpdateServiceCredentials) {
        collector.checkThat("Actions should contain " + ServiceAction.UPDATE_CREDENTIALS,
                            serviceActionsToExecute.contains(ServiceAction.UPDATE_CREDENTIALS), Is.is(true));
    }
    if (stepInput.shouldUpdateServiceKeys) {
        collector.checkThat("Actions should contain " + ServiceAction.UPDATE_KEYS,
                            serviceActionsToExecute.contains(ServiceAction.UPDATE_KEYS), Is.is(true));
    }
}
 
Example #30
Source File: CloudJobConfigurationServiceTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertLoadWithConfig() {
    Mockito.when(regCenter.get("/config/job/test_job")).thenReturn(CloudJsonConstants.getJobJson());
    Optional<CloudJobConfiguration> actual = configService.load("test_job");
    Assert.assertTrue(actual.isPresent());
    Assert.assertThat(actual.get().getJobName(), Is.is("test_job"));
}