org.hamcrest.Factory#org.hamcrest.CoreMatchers源码实例Demo

下面列出了org.hamcrest.Factory#org.hamcrest.CoreMatchers 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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();
  }
}
 
/**
 * 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));
}
 
@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')"));
  }
}
 
源代码4 项目: blueflood   文件: BluefloodCounterRollupTest.java
@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());
}
 
源代码5 项目: ehcache3   文件: StatusTransitionerTest.java
@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));

}
 
源代码6 项目: quarkus   文件: KafkaStreamsTest.java
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);
}
 
源代码7 项目: flink   文件: RequiredParametersTest.java
@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());
	}
}
 
源代码8 项目: pinpoint   文件: DefaultProfilerConfigTest.java
@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"));
}
 
源代码9 项目: flink   文件: PathResolutionTest.java
@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()));
}
 
源代码10 项目: crate   文件: TestStatementBuilder.java
@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']}");
}
 
源代码11 项目: dapeng-soa   文件: TestRouterRuntimeList.java
@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,'回车换行符')]")));
    }

}
 
源代码12 项目: flow   文件: TogglePushIT.java
@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());

}
 
源代码13 项目: jgitver   文件: Issue42Test.java
@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"));
}
 
源代码14 项目: flow   文件: PageTest.java
@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();"));
}
 
源代码15 项目: blueflood   文件: BluefloodCounterRollupTest.java
@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());
}
 
源代码16 项目: zeppelin   文件: SecurityRestApiTest.java
@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();
}
 
@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++;
    }
}
 
源代码18 项目: byte-buddy   文件: TypeResolutionStrategyTest.java
@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));
    }
}
 
源代码19 项目: nakadi   文件: ExclusiveJobWrapperAT.java
@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));

}
 
源代码20 项目: zt-exec   文件: ProcessExecutorTimeoutTest.java
@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()));
  }
}
 
源代码21 项目: colibri-ui   文件: CheckSteps.java
@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())
        ));

    });
}
 
源代码22 项目: kieker   文件: TestSpringMethodInterceptor.java
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);
}
 
源代码23 项目: cloudhopper-commons   文件: SxmpParserTest.java
@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());
    }
}
 
源代码24 项目: camunda-bpm-platform   文件: BatchSuspensionTest.java
@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"));
  }
}
 
@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));
}
 
源代码26 项目: ozark   文件: LocaleIT.java
@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>"));

}
 
源代码27 项目: localization_nifi   文件: TestDebugFlow.java
@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);
}
 
源代码28 项目: nifi   文件: TestDebugFlow.java
@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);
}
 
源代码29 项目: kieker   文件: GenericTextFileWriterTest.java
/**
 * 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));
}
 
源代码30 项目: jstarcraft-ai   文件: MatrixTestCase.java
@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();
}