org.hamcrest.CoreMatchers Java Examples

The following examples show how to use org.hamcrest.CoreMatchers. 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 Project: camunda-bpm-platform   Author: camunda   File: MultiTenancyBatchTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteBatchFailsWithWrongTenant() {
  // given
  Batch batch = batchHelper.migrateProcessInstanceAsync(tenant2Definition, tenant2Definition);

  // when
  identityService.setAuthentication("user", null, singletonList(TENANT_ONE));
  try {
    managementService.deleteBatch(batch.getId(), true);
    Assert.fail("exception expected");
  }
  catch (ProcessEngineException e) {
    // then
    Assert.assertThat(e.getMessage(), CoreMatchers.containsString("Cannot delete batch '"
      + batch.getId() + "' because it belongs to no authenticated tenant"));
  }
  finally {
    identityService.clearAuthentication();
  }
}
 
Example #2
Source Project: mongodb-async-driver   Author: allanbank   File: BootstrapConnectionFactoryITest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link BootstrapConnectionFactory#bootstrap()} .
 */
@Test
public void testBootstrapStandaloneWithAuth() {
    startAuthenticated();

    final MongoClientConfiguration config = new MongoClientConfiguration(
            new InetSocketAddress("127.0.0.1", 27017));
    config.addCredential(Credential.builder().userName(USER_NAME)
            .password(PASSWORD).database(USER_DB)
            .authenticationType(Credential.MONGODB_CR).build());

    myTestFactory = new BootstrapConnectionFactory(config);

    assertThat("Wrong type of myTestFactory.", myTestFactory.getDelegate(),
            CoreMatchers.instanceOf(AuthenticationConnectionFactory.class));
}
 
Example #3
Source Project: camunda-bpm-platform   Author: camunda   File: MultiTenancyMigrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void cannotMigrateInstanceWithoutTenantIdToDifferentTenant() {
  // given
  ProcessDefinition sourceDefinition = testHelper.deployAndGetDefinition(ProcessModels.ONE_TASK_PROCESS);
  ProcessDefinition targetDefinition = testHelper.deployForTenantAndGetDefinition(TENANT_ONE, ProcessModels.ONE_TASK_PROCESS);

  ProcessInstance processInstance = engineRule.getRuntimeService().startProcessInstanceById(sourceDefinition.getId());
  MigrationPlan migrationPlan = engineRule.getRuntimeService().createMigrationPlan(sourceDefinition.getId(), targetDefinition.getId())
      .mapEqualActivities()
      .build();

  // when
  try {
    engineRule.getRuntimeService()
      .newMigration(migrationPlan)
      .processInstanceIds(Arrays.asList(processInstance.getId()))
      .execute();
    Assert.fail("exception expected");
  } catch (ProcessEngineException e) {
    Assert.assertThat(e.getMessage(),
        CoreMatchers.containsString("Cannot migrate process instance '" + processInstance.getId()
            + "' without tenant to a process definition with a tenant ('tenant1')"));
  }
}
 
Example #4
Source Project: blueflood   Author: rackerlabs   File: BluefloodCounterRollupTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void counterRollupBuilderWithSingleInputYieldsZeroRate() throws IOException {

    // given
    Points<SimpleNumber> inputA = new Points<SimpleNumber>();
    inputA.add(new Points.Point<SimpleNumber>(1234L, new SimpleNumber(1L)));
    BluefloodCounterRollup rollupA = BluefloodCounterRollup.buildRollupFromRawSamples(inputA);

    Points<BluefloodCounterRollup> combined = new Points<BluefloodCounterRollup>();
    combined.add(new Points.Point<BluefloodCounterRollup>(1234L, rollupA));

    // when
    BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromCounterRollups(combined);

    // then
    Number count = rollup.getCount();
    assertNotNull(count);
    assertThat(count, is(CoreMatchers.<Number>instanceOf(Long.class)));
    assertEquals(1L, count.longValue());
    assertEquals(0.0d, rollup.getRate(), 0.00001d); // (1)/0=0
    assertEquals(1, rollup.getSampleCount());
}
 
Example #5
Source Project: ehcache3   Author: ehcache   File: StatusTransitionerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTransitionDuringFailures() {
  StatusTransitioner transitioner = new StatusTransitioner(LoggerFactory.getLogger(StatusTransitionerTest.class));
  assertThat(transitioner.currentStatus(), CoreMatchers.is(Status.UNINITIALIZED));
  StatusTransitioner.Transition st = transitioner.init();
  st.failed(new Throwable());
  assertThat(transitioner.currentStatus(), is(Status.UNINITIALIZED));
  try {
    st.failed(new Throwable());
    fail();
  } catch (AssertionError err) {
    assertThat(err.getMessage(), is("Throwable cannot be thrown if Transition is done."));
  }

  st.failed(null);
  assertThat(transitioner.currentStatus(), is(Status.UNINITIALIZED));

  StatusTransitioner.Transition st1 = transitioner.init();
  assertThat(transitioner.currentStatus(), is(Status.AVAILABLE));
  st1.failed(null);
  assertThat(transitioner.currentStatus(), is(Status.UNINITIALIZED));

}
 
Example #6
Source Project: quarkus   Author: quarkusio   File: KafkaStreamsTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testKafkaStreamsAliveAndReady() throws Exception {
    RestAssured.get("/health/ready").then()
            .statusCode(HttpStatus.SC_OK)
            .body("checks[0].name", CoreMatchers.is("Kafka Streams topics health check"))
            .body("checks[0].status", CoreMatchers.is("UP"))
            .body("checks[0].data.available_topics", CoreMatchers.is("streams-test-categories,streams-test-customers"));

    RestAssured.when().get("/health/live").then()
            .statusCode(HttpStatus.SC_OK)
            .body("checks[0].name", CoreMatchers.is("Kafka Streams state health check"))
            .body("checks[0].status", CoreMatchers.is("UP"))
            .body("checks[0].data.state", CoreMatchers.is("RUNNING"));

    RestAssured.when().get("/health").then()
            .statusCode(HttpStatus.SC_OK);
}
 
Example #7
Source Project: flink   Author: flink-tpc-ds   File: RequiredParametersTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPrintHelpForFullySetOption() {
	RequiredParameters required = new RequiredParameters();
	try {
		required.add(new Option("option").defaultValue("some").help("help").alt("o").choices("some", "options"));

		String helpText = required.getHelp();
		Assert.assertThat(helpText, CoreMatchers.allOf(
				containsString("Required Parameters:"),
				containsString("-o, --option"),
				containsString("default: some"),
				containsString("choices: "),
				containsString("some"),
				containsString("options")));

	} catch (RequiredParametersException e) {
		fail("Exception thrown " + e.getMessage());
	}
}
 
Example #8
Source Project: pinpoint   Author: naver   File: DefaultProfilerConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void readList() throws IOException {
    Properties properties = new Properties();
    properties.setProperty("profiler.test.list1", "foo,bar");
    properties.setProperty("profiler.test.list2", "foo, bar");
    properties.setProperty("profiler.test.list3", " foo,bar");
    properties.setProperty("profiler.test.list4", "foo,bar ");
    properties.setProperty("profiler.test.list5", "    foo,    bar   ");

    ProfilerConfig profilerConfig = new DefaultProfilerConfig(properties);

    Assert.assertThat(profilerConfig.readList("profiler.test.list1"), CoreMatchers.hasItems("foo", "bar"));
    Assert.assertThat(profilerConfig.readList("profiler.test.list2"), CoreMatchers.hasItems("foo", "bar"));
    Assert.assertThat(profilerConfig.readList("profiler.test.list3"), CoreMatchers.hasItems("foo", "bar"));
    Assert.assertThat(profilerConfig.readList("profiler.test.list4"), CoreMatchers.hasItems("foo", "bar"));
}
 
Example #9
Source Project: flink   Author: apache   File: PathResolutionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTableApiPathResolution() {
	List<String> lookupPath = testSpec.getTableApiLookupPath();
	CatalogManager catalogManager = testSpec.getCatalogManager();
	testSpec.getDefaultCatalog().ifPresent(catalogManager::setCurrentCatalog);
	testSpec.getDefaultDatabase().ifPresent(catalogManager::setCurrentDatabase);

	UnresolvedIdentifier unresolvedIdentifier = UnresolvedIdentifier.of(lookupPath);
	ObjectIdentifier identifier = catalogManager.qualifyIdentifier(unresolvedIdentifier);

	assertThat(
		Arrays.asList(identifier.getCatalogName(), identifier.getDatabaseName(), identifier.getObjectName()),
		CoreMatchers.equalTo(testSpec.getExpectedPath()));
	Optional<CatalogManager.TableLookupResult> tableLookup = catalogManager.getTable(identifier);
	assertThat(tableLookup.isPresent(), is(true));
	assertThat(tableLookup.get().isTemporary(), is(testSpec.isTemporaryObject()));
}
 
Example #10
Source Project: crate   Author: crate   File: TestStatementBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectLiteral() {
    Expression emptyObjectLiteral = SqlParser.createExpression("{}");
    assertThat(emptyObjectLiteral, instanceOf(ObjectLiteral.class));
    assertThat(((ObjectLiteral) emptyObjectLiteral).values().size(), is(0));

    ObjectLiteral objectLiteral = (ObjectLiteral) SqlParser.createExpression("{a=1, aa=-1, b='str', c=[], d={}}");
    assertThat(objectLiteral.values().size(), is(5));
    assertThat(objectLiteral.values().get("a"), instanceOf(IntegerLiteral.class));
    assertThat(objectLiteral.values().get("aa"), instanceOf(NegativeExpression.class));
    assertThat(objectLiteral.values().get("b"), instanceOf(StringLiteral.class));
    assertThat(objectLiteral.values().get("c"), instanceOf(ArrayLiteral.class));
    assertThat(objectLiteral.values().get("d"), instanceOf(ObjectLiteral.class));

    ObjectLiteral quotedObjectLiteral = (ObjectLiteral) SqlParser.createExpression("{\"AbC\"=123}");
    assertThat(quotedObjectLiteral.values().size(), is(1));
    assertThat(quotedObjectLiteral.values().get("AbC"), instanceOf(IntegerLiteral.class));
    assertThat(quotedObjectLiteral.values().get("abc"), CoreMatchers.nullValue());
    assertThat(quotedObjectLiteral.values().get("ABC"), CoreMatchers.nullValue());

    SqlParser.createExpression("{a=func('abc')}");
    SqlParser.createExpression("{b=identifier}");
    SqlParser.createExpression("{c=1+4}");
    SqlParser.createExpression("{d=sub['script']}");
}
 
Example #11
Source Project: dapeng-soa   Author: dapeng-soa   File: TestRouterRuntimeList.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMoreThenIp3() {
    try {
        String pattern = "otherwise => ~ip\"192.168.10.126\" , , ~ip\"192.168.10.130\"";
        List<Route> routes = RoutesExecutor.parseAll(pattern);
        InvocationContextImpl ctx = (InvocationContextImpl) InvocationContextImpl.Factory.currentInstance();
        ctx.setCookie("storeId", "118666200");
        ctx.methodName("updateOrderMemberId");

        List<RuntimeInstance> prepare = prepare(ctx, routes);


        List<RuntimeInstance> expectInstances = new ArrayList<>();
        expectInstances.add(runtimeInstance1);
        Assert.assertArrayEquals(expectInstances.toArray(), prepare.toArray());

    } catch (ParsingException ex) {
        Assert.assertThat(ex.getMessage(), CoreMatchers.containsString(
                ("[Validate Token Error]:target token: [(2,'=>')] is not in expects token: [(15,'逗号'), (-1,'文件结束符'), (1,'回车换行符')]")));
    }

}
 
Example #12
Source Project: flow   Author: vaadin   File: TogglePushIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void togglePushInInit() throws Exception {
    // Open with push disabled
    open("push=disabled");

    assertFalse(getPushToggle().isSelected());

    getDelayedCounterUpdateButton().click();
    Thread.sleep(2000);
    Assert.assertEquals("Counter has been updated 0 times",
            getCounterText());

    // Open with push enabled
    open("push=enabled");
    Assert.assertThat(getPushToggle().getText(),
            CoreMatchers.containsString("Push enabled"));

    getDelayedCounterUpdateButton().click();
    Thread.sleep(2000);
    Assert.assertEquals("Counter has been updated 1 times",
            getCounterText());

}
 
Example #13
Source Project: jgitver   Author: jgitver   File: Issue42Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void check_metadatas_on_tag_3_2_1() {
    unchecked(() -> git.checkout().setName(TAG_3_2_1).call());

    GitVersionCalculator gvc = GitVersionCalculator.location(s.getRepositoryLocation());
    gvc.setMavenLike(true);
    Version versionObject = gvc.getVersionObject();

    assertThat(versionObject.getMajor(), CoreMatchers.is(3));
    assertThat(gvc.meta(Metadatas.CURRENT_VERSION_MAJOR).get(), CoreMatchers.is("3"));

    assertThat(versionObject.getMinor(), CoreMatchers.is(2));
    assertThat(gvc.meta(Metadatas.CURRENT_VERSION_MINOR).get(), CoreMatchers.is("2"));

    assertThat(versionObject.getPatch(), CoreMatchers.is(1));
    assertThat(gvc.meta(Metadatas.CURRENT_VERSION_PATCH).get(), CoreMatchers.is("1"));
}
 
Example #14
Source Project: flow   Author: vaadin   File: PageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void open_openInSameWindow_closeTheClientApplication() {
    AtomicReference<String> capture = new AtomicReference<>();
    List<Serializable> params = new ArrayList<>();
    Page page = new Page(new MockUI()) {
        @Override
        public PendingJavaScriptResult executeJs(String expression,
                Serializable[] parameters) {
            capture.set(expression);
            params.addAll(Arrays.asList(parameters));
            return Mockito.mock(PendingJavaScriptResult.class);
        }
    };

    page.setLocation("foo");

    // self check
    Assert.assertEquals("_self", params.get(1));

    Assert.assertThat(capture.get(), CoreMatchers
            .startsWith("if ($1 == '_self') this.stopApplication();"));
}
 
Example #15
Source Project: blueflood   Author: rackerlabs   File: BluefloodCounterRollupTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void counterRollupBuilderWithSingleThreeInputYieldsRate() throws IOException {

    // given
    Points<SimpleNumber> inputA = new Points<SimpleNumber>();
    inputA.add(new Points.Point<SimpleNumber>(1234L, new SimpleNumber(1L)));
    inputA.add(new Points.Point<SimpleNumber>(1235L, new SimpleNumber(2L)));
    inputA.add(new Points.Point<SimpleNumber>(1236L, new SimpleNumber(3L)));
    BluefloodCounterRollup rollupA = BluefloodCounterRollup.buildRollupFromRawSamples(inputA);

    Points<BluefloodCounterRollup> combined = new Points<BluefloodCounterRollup>();
    combined.add(new Points.Point<BluefloodCounterRollup>(1234L, rollupA));

    // when
    BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromCounterRollups(combined);

    // then
    Number count = rollup.getCount();
    assertNotNull(count);
    assertThat(count, is(CoreMatchers.<Number>instanceOf(Long.class)));
    assertEquals(6L, count.longValue()); // 1+2+3
    assertEquals(3.0d, rollup.getRate(), 0.00001d); // (1+2+3)/( (1236-1234) + 0 ) = 3
    assertEquals(3, rollup.getSampleCount());
}
 
Example #16
Source Project: zeppelin   Author: apache   File: SecurityRestApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetUserList() throws IOException {
  GetMethod get = httpGet("/security/userlist/admi", "admin", "password1");
  get.addRequestHeader("Origin", "http://localhost");
  Map<String, Object> resp = gson.fromJson(get.getResponseBodyAsString(),
      new TypeToken<Map<String, Object>>(){}.getType());
  List<String> userList = (List) ((Map) resp.get("body")).get("users");
  collector.checkThat("Search result size", userList.size(),
      CoreMatchers.equalTo(1));
  collector.checkThat("Search result contains admin", userList.contains("admin"),
      CoreMatchers.equalTo(true));
  get.releaseConnection();

  GetMethod notUser = httpGet("/security/userlist/randomString", "admin", "password1");
  notUser.addRequestHeader("Origin", "http://localhost");
  Map<String, Object> notUserResp = gson.fromJson(notUser.getResponseBodyAsString(),
      new TypeToken<Map<String, Object>>(){}.getType());
  List<String> emptyUserList = (List) ((Map) notUserResp.get("body")).get("users");
  collector.checkThat("Search result size", emptyUserList.size(),
      CoreMatchers.equalTo(0));

  notUser.releaseConnection();
}
 
Example #17
Source Project: opensharding-spi-impl   Author: OpenSharding   File: UpdateSQLRevertExecutorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void assertFillParametersWithoutSetUpdatePrimaryKey() throws SQLException {
    setUpdateAssignments("t_order", "user_id", "status");
    setSnapshot(10, "user_id", "status", "order_id");
    sqlRevertExecutor = new UpdateSQLRevertExecutor(executorContext, snapshotAccessor);
    sqlRevertExecutor.fillParameters(revertSQLResult);
    assertThat(revertSQLResult.getParameters().size(), is(10));
    int offset = 1;
    for (Collection<Object> each : revertSQLResult.getParameters()) {
        assertThat(each.size(), is(3));
        List<Object> parameterRow = Lists.newArrayList(each);
        assertThat(parameterRow.get(0), CoreMatchers.<Object>is("user_id_" + offset));
        assertThat(parameterRow.get(1), CoreMatchers.<Object>is("status_" + offset));
        assertThat(parameterRow.get(2), CoreMatchers.<Object>is("order_id_" + offset));
        offset++;
    }
}
 
Example #18
Source Project: byte-buddy   Author: raphw   File: TypeResolutionStrategyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testActive() throws Exception {
    TypeResolutionStrategy.Resolved resolved = new TypeResolutionStrategy.Active().resolve();
    Field field = TypeResolutionStrategy.Active.Resolved.class.getDeclaredField("identification");
    field.setAccessible(true);
    int identification = (Integer) field.get(resolved);
    when(typeInitializer.expandWith(matchesPrototype(new NexusAccessor.InitializationAppender(identification)))).thenReturn(otherTypeInitializer);
    assertThat(resolved.injectedInto(typeInitializer), is(otherTypeInitializer));
    assertThat(resolved.initialize(dynamicType, classLoader, classLoadingStrategy),
            is(Collections.<TypeDescription, Class<?>>singletonMap(typeDescription, Foo.class)));
    try {
        verify(classLoadingStrategy).load(classLoader, Collections.singletonMap(typeDescription, FOO));
        verifyNoMoreInteractions(classLoadingStrategy);
        verify(loadedTypeInitializer).isAlive();
        verifyNoMoreInteractions(loadedTypeInitializer);
    } finally {
        Field initializers = Nexus.class.getDeclaredField("TYPE_INITIALIZERS");
        initializers.setAccessible(true);
        Constructor<Nexus> constructor = Nexus.class.getDeclaredConstructor(String.class, ClassLoader.class, ReferenceQueue.class, int.class);
        constructor.setAccessible(true);
        Object value = ((Map<?, ?>) initializers.get(null)).remove(constructor.newInstance(Foo.class.getName(), Foo.class.getClassLoader(), null, identification));
        assertThat(value, CoreMatchers.is((Object) loadedTypeInitializer));
    }
}
 
Example #19
Source Project: nakadi   Author: zalando   File: ExclusiveJobWrapperAT.java    License: MIT License 5 votes vote down vote up
@Test
public void whenExecuteJobThenOk() throws Exception {
    jobWrapper.runJobLocked(dummyJob);
    assertThat(jobExecuted.get(), CoreMatchers.is(true));

    assertThat("lock node should be removed", CURATOR.checkExists().forPath(lockPath),
            CoreMatchers.is(CoreMatchers.nullValue()));

    final byte[] data = CURATOR.getData().forPath(latestPath);
    final DateTime lastCleaned = objectMapper.readValue(new String(data, Charsets.UTF_8), DateTime.class);
    final long msSinceCleaned = new DateTime().getMillis() - lastCleaned.getMillis();
    assertThat("job was executed less than 5 seconds ago", msSinceCleaned, lessThan(5000L));

}
 
Example #20
Source Project: zt-exec   Author: zeroturnaround   File: ProcessExecutorTimeoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExecuteTimeout() throws Exception {
  try {
    // Use timeout in case we get stuck
    List<String> args = getWriterLoopCommand();
    new ProcessExecutor().command(args).timeout(1, TimeUnit.SECONDS).execute();
    Assert.fail("TimeoutException expected.");
  }
  catch (TimeoutException e) {
    Assert.assertThat(e.getMessage(), CoreMatchers.containsString("1 second"));
    Assert.assertThat(e.getMessage(), CoreMatchers.containsString(Loop.class.getName()));
  }
}
 
Example #21
Source Project: colibri-ui   Author: alfa-laboratory   File: CheckSteps.java    License: Apache License 2.0 5 votes vote down vote up
@Step
@Then("каждый элемент \"$elementName\" содержит любое из значений \"$template1\" или \"$template2\" без учета регистра")
public void eachElementContainsOneOfTwoValues(@Named("$elementName") String elementName, @Named("$template1") String templateOne, @Named("$template2") String templateTwo) {
    IElement element = getCurrentPage().getElementByName(elementName);
    List<WebElement> elementsFound = finder.findWebElements(element);
    String expectedValueOne = propertyUtils.injectProperties(templateOne);
    String expectedValueTwo = propertyUtils.injectProperties(templateTwo);
    elementsFound.forEach(elem -> {
        assertThat("Элемент не содержит ни одно из заданных значений", elem.getText().toLowerCase(), CoreMatchers.anyOf(
                containsString(expectedValueOne.toLowerCase()),
                containsString(expectedValueTwo.toLowerCase())
        ));

    });
}
 
Example #22
Source Project: kieker   Author: kieker-monitoring   File: TestSpringMethodInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
public void ignoretestIt() throws IOException, InterruptedException {
	// Assert.assertNotNull(this.ctx);
	Assert.assertThat(this.ctx.isRunning(), CoreMatchers.is(true));

	final IMonitoringController monitoringController = MonitoringController.getInstance();
	Assume.assumeThat(monitoringController.getName(), CoreMatchers.is(CTRLNAME));

	final String getBookPattern = "public kieker.test.monitoring.junit.probe.spring.executions.jetty.bookstore.Book "
			+ "kieker.test.monitoring.junit.probe.spring.executions.jetty.bookstore.Catalog.getBook(boolean)";
	final String searchBookPattern = "public kieker.test.monitoring.junit.probe.spring.executions.jetty.bookstore.Book "
			+ "kieker.test.monitoring.junit.probe.spring.executions.jetty.bookstore.Bookstore.searchBook(java.lang.String)";

	NamedListWriter.awaitListSize(this.recordListFilledByListWriter, 0, TIMEOUT_IN_MS);

	UrlUtil.ping(BOOKSTORE_SEARCH_ANY_URL);
	NamedListWriter.awaitListSize(this.recordListFilledByListWriter, 3, TIMEOUT_IN_MS);

	monitoringController.deactivateProbe(getBookPattern);
	UrlUtil.ping(BOOKSTORE_SEARCH_ANY_URL);
	NamedListWriter.awaitListSize(this.recordListFilledByListWriter, 4, TIMEOUT_IN_MS);

	monitoringController.deactivateProbe(searchBookPattern);
	UrlUtil.ping(BOOKSTORE_SEARCH_ANY_URL);
	NamedListWriter.awaitListSize(this.recordListFilledByListWriter, 4, TIMEOUT_IN_MS);

	monitoringController.activateProbe(getBookPattern);
	UrlUtil.ping(BOOKSTORE_SEARCH_ANY_URL);
	NamedListWriter.awaitListSize(this.recordListFilledByListWriter, 6, TIMEOUT_IN_MS);

	monitoringController.activateProbe(searchBookPattern);
	UrlUtil.ping(BOOKSTORE_SEARCH_ANY_URL);
	NamedListWriter.awaitListSize(this.recordListFilledByListWriter, 9, TIMEOUT_IN_MS);
}
 
Example #23
Source Project: cloudhopper-commons   Author: twitter   File: SxmpParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void parseSubmitUnsupportedChildElement1() throws Exception {
    StringBuilder string0 = new StringBuilder(200)
        .append("<?xml version=\"1.0\"?>\n")
        .append("<operation type=\"submit\">\n")
        .append(" <account username=\"customer1\" password=\"test1\"/>\n")
        .append(" <submitRequest referenceId=\"MYREF102020022\">\n")
        .append("  <destinationAddress type=\"international\">+12065551212</destinationAddress>\n")
        .append("  <text encoding=\"ISO-8859-1\">48")
        .append("<badelement />\n")
        .append("</text>\n")
        .append(" </submitRequest>\n")
        .append("</operation>\n")
        .append("");

    ByteArrayInputStream is = new ByteArrayInputStream(string0.toString().getBytes());
    SxmpParser parser = new SxmpParser();

    try {
        Operation operation = parser.parse(is);
        Assert.fail();
    } catch (SxmpParsingException e) {
         // correct behavior
        Assert.assertEquals(SxmpErrorCode.UNSUPPORTED_ELEMENT, e.getErrorCode());
        Assert.assertThat(e.getMessage(), CoreMatchers.containsString("Unsupported [badelement] element found at depth"));
        Assert.assertNotNull(e.getOperation());
        SubmitRequest submitRequest = (SubmitRequest)e.getOperation();
        Assert.assertEquals(Operation.Type.SUBMIT, submitRequest.getType());
    }
}
 
Example #24
Source Project: camunda-bpm-platform   Author: camunda   File: BatchSuspensionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailWhenActivatingUsingUnknownId() {
  try {
    managementService.activateBatchById("unknown");
    fail("Exception expected");
  }
  catch (BadUserRequestException e) {
    assertThat(e.getMessage(), CoreMatchers.containsString("Batch for id 'unknown' cannot be found"));
  }
}
 
Example #25
Source Project: livingdoc-confluence   Author: testIT-LivingDoc   File: LivingDocRestServiceTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getAllRunners() throws Exception {

    when(clientService.getAllRunners()).thenReturn(runners);

    String expected = "{\"runners\":" + objectMapper.writeValueAsString(runners) + "}";
    String result = ldRestService.dispatchCommand(credentials, "getAllRunners", null);
    assertThat(result, CoreMatchers.is(expected));
}
 
Example #26
Source Project: ozark   Author: mvc-spec   File: LocaleIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomLocaleResolverWins() throws Exception {

    // the default resolver would resolve "it"
    webClient.addRequestHeader("Accept-Language", "it");

    // custom resolver uses "lang" query parameter
    HtmlPage page = webClient.getPage(webUrl + "resources/locale?lang=pl");

    // the customer resolver wins
    assertThat(page.getWebResponse().getContentAsString(),
            CoreMatchers.containsString("<p>Locale: pl</p>"));

}
 
Example #27
Source Project: localization_nifi   Author: wangrenlei   File: TestDebugFlow.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFlowFileNonDefaultException() {
    runner.setProperty(DebugFlow.FF_EXCEPTION_ITERATIONS, "1");
    runner.setProperty(DebugFlow.FF_EXCEPTION_CLASS, "java.lang.RuntimeException");
    runner.assertValid();

    runner.enqueue(contents.get(0).getBytes(), attribs.get(0));

    exception.expectMessage(CoreMatchers.containsString("forced by org.apache.nifi.processors.standard.DebugFlow"));
    exception.expectCause(CoreMatchers.isA(RuntimeException.class));
    runner.run(2);
}
 
Example #28
Source Project: nifi   Author: apache   File: TestDebugFlow.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFlowFileExceptionRollover() {
    runner.setProperty(DebugFlow.FF_EXCEPTION_ITERATIONS, "2");
    runner.assertValid();

    for (int n = 0; n < 6; n++) {
        runner.enqueue(contents.get(n).getBytes(), attribs.get(n));
    }

    exception.expectMessage(CoreMatchers.containsString("forced by org.apache.nifi.processors.standard.DebugFlow"));
    exception.expectCause(CoreMatchers.isA(RuntimeException.class));
    runner.run(8);
}
 
Example #29
Source Project: kieker   Author: kieker-monitoring   File: GenericTextFileWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test valid log directory.
 */
@Test
public void testValidLogFolder() throws IOException {
	final String passedConfigPathName = this.tmpFolder.getRoot().getAbsolutePath();
	this.configuration.setProperty(FileWriter.CONFIG_PATH, passedConfigPathName);

	new FileWriter(this.configuration);

	final Path kiekerPath = Files.list(Paths.get(passedConfigPathName)).findFirst().get();

	Assert.assertThat(kiekerPath.toAbsolutePath().toString(), CoreMatchers.startsWith(passedConfigPathName));
}
 
Example #30
Source Project: jstarcraft-ai   Author: HongZhaoHua   File: MatrixTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFourArithmeticOperation() throws Exception {
    EnvironmentContext context = EnvironmentFactory.getContext();
    Future<?> task = context.doTask(() -> {
        RandomUtility.setSeed(0L);
        int dimension = 10;
        MathMatrix dataMatrix = getZeroMatrix(dimension);
        dataMatrix.iterateElement(MathCalculator.SERIAL, (scalar) -> {
            scalar.setValue(RandomUtility.randomFloat(10F));
        });
        MathMatrix copyMatrix = getZeroMatrix(dimension);
        float sum = dataMatrix.getSum(false);

        copyMatrix.copyMatrix(dataMatrix, false);
        Assert.assertThat(copyMatrix.getSum(false), CoreMatchers.equalTo(sum));

        dataMatrix.subtractMatrix(copyMatrix, false);
        Assert.assertThat(dataMatrix.getSum(false), CoreMatchers.equalTo(0F));

        dataMatrix.addMatrix(copyMatrix, false);
        Assert.assertThat(dataMatrix.getSum(false), CoreMatchers.equalTo(sum));

        dataMatrix.divideMatrix(copyMatrix, false);
        Assert.assertThat(dataMatrix.getSum(false), CoreMatchers.equalTo(dataMatrix.getElementSize() + 0F));

        dataMatrix.multiplyMatrix(copyMatrix, false);
        Assert.assertThat(dataMatrix.getSum(false), CoreMatchers.equalTo(sum));
    });
    task.get();
}