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 File: DefaultProfilerConfigTest.java    From pinpoint with 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 #2
Source File: PageTest.java    From flow with 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 #3
Source File: MultiTenancyBatchTest.java    From camunda-bpm-platform with 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 #4
Source File: MultiTenancyMigrationTest.java    From camunda-bpm-platform with 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 #5
Source File: BootstrapConnectionFactoryITest.java    From mongodb-async-driver with 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 #6
Source File: BluefloodCounterRollupTest.java    From blueflood with 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 #7
Source File: BluefloodCounterRollupTest.java    From blueflood with 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 #8
Source File: Issue42Test.java    From jgitver with 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 #9
Source File: StatusTransitionerTest.java    From ehcache3 with 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 #10
Source File: TestRouterRuntimeList.java    From dapeng-soa with 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 #11
Source File: TypeResolutionStrategyTest.java    From byte-buddy with 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 #12
Source File: KafkaStreamsTest.java    From quarkus with 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 #13
Source File: TestStatementBuilder.java    From crate with 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 #14
Source File: UpdateSQLRevertExecutorTest.java    From opensharding-spi-impl with 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 #15
Source File: SecurityRestApiTest.java    From zeppelin with 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 #16
Source File: RequiredParametersTest.java    From flink with 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 #17
Source File: PathResolutionTest.java    From flink with 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 #18
Source File: TogglePushIT.java    From flow with 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 #19
Source File: NewAccountControllerTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Test
public void create_UsernameAlreadyExists() {
	final Model model = createNiceMock(Model.class);
	final UserForm User = new UserForm();
	final BindingResult errors = createNiceMock(BindingResult.class);
	final String username = "canonical"; //specified username already exists in database
	final String password = "password";
	final String confirmPassword = password;
	final org.apache.rave.model.User existingUser = new UserImpl();
	List<ObjectError> errorList = new ArrayList<ObjectError>();
	final ObjectError error = new ObjectError("username.exists", "Username already exists");

	User.setUsername(username);
	User.setPassword(password);
	User.setConfirmPassword(confirmPassword);

	existingUser.setUsername(username);
	existingUser.setPassword(password);

	errorList.add(error);


	expect(errors.hasErrors()).andReturn(true).anyTimes();
	expect(errors.getAllErrors()).andReturn(errorList).anyTimes();
	replay(errors);

	expect(userService.getUserByUsername(username)).andReturn(existingUser).anyTimes();
	replay(userService);
	replay(model);
	String result = newAccountController.create(User, errors, model, request, redirectAttributes);
	errorList = errors.getAllErrors();

	assertThat(errorList.size(), CoreMatchers.equalTo(1));
	assertThat(errorList.get(0).getDefaultMessage(), CoreMatchers.equalTo("Username already exists"));
	assertThat(result, CoreMatchers.equalTo(ViewNames.NEW_ACCOUNT));
}
 
Example #20
Source File: ServerPojoTest.java    From vind with Apache License 2.0 5 votes vote down vote up
@Test
@RunWithBackend(Solr)
public void testPojoRoundtrip() {
    final SearchServer server = backend.getSearchServer();

    final Pojo doc1 = Pojo.create("doc1", "Eins", "Erstes Dokument", "simple");
    final Pojo doc2 = Pojo.create("doc2", "Zwei", "Zweites Dokument", "simple");
    final Pojo doc3 = Pojo.create("doc3", "Drei", "Dieses ist das dritte Dokument", "complex");
    final Pojo doc4 = Pojo.create("doc3", "Drei", "Dieses ist das dritte Dokument", "complex");

    server.indexBean(doc1);
    server.indexBean(doc2);
    server.indexBean(doc3);
    server.commit();

    final BeanSearchResult<Pojo> dritte = server.execute(Search.fulltext("dritte"), Pojo.class);
    assertThat("#numOfResults", dritte.getNumOfResults(), CoreMatchers.equalTo(1l));
    assertThat("results.size()", dritte.getResults(), IsCollectionWithSize.hasSize(1));
    checkPojo(doc3, dritte.getResults().get(0));

    final BeanSearchResult<Pojo> all = server.execute(Search.fulltext()
            .facet("category")
            .filter(or(eq("title", "Eins"), or(eq("title", "Zwei"),eq("title","Drei"))))
            .sort("_id_", Sort.Direction.Desc), Pojo.class); //TODO create special sort for reserved fields (like score, type, id)
    assertThat("#numOfResults", all.getNumOfResults(), CoreMatchers.equalTo(3l));
    assertThat("results.size()", all.getResults(), IsCollectionWithSize.hasSize(3));
    checkPojo(doc3, all.getResults().get(0));
    checkPojo(doc2, all.getResults().get(1));
    checkPojo(doc1, all.getResults().get(2));

    TermFacetResult<String> facets = all.getFacetResults().getTermFacet("category", String.class);
    assertEquals(2,facets.getValues().size());
    assertEquals("simple", facets.getValues().get(0).getValue());
    assertEquals("complex",facets.getValues().get(1).getValue());
    assertEquals(2,facets.getValues().get(0).getCount());
    assertEquals(1,facets.getValues().get(1).getCount());
}
 
Example #21
Source File: JenkinsMavenEventSpyTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Test
public void testExecutionProjectStarted() throws Exception {
    ExecutionEvent executionEvent = new  ExecutionEvent(){
        @Override
        public Type getType() {
            return Type.ProjectStarted;
        }

        @Override
        public MavenSession getSession() {
            return null;
        }

        @Override
        public MavenProject getProject() {
            return project;
        }

        @Override
        public MojoExecution getMojoExecution() {
            return null;
        }

        @Override
        public Exception getException() {
            return null;
        }
    };

    spy.onEvent(executionEvent);

    String actual = writer.toString();
    System.out.println(actual);
    Assert.assertThat(actual, CoreMatchers.containsString("ProjectStarted"));
    Assert.assertThat(actual, CoreMatchers.containsString("petclinic"));
}
 
Example #22
Source File: ByteArrayClassLoaderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoading() throws Exception {
    Class<?> type = classLoader.loadClass(Foo.class.getName());
    assertThat(type.getClassLoader(), is((ClassLoader) classLoader));
    assertEquals(classLoader.loadClass(Foo.class.getName()), type);
    assertThat(type, not(CoreMatchers.<Class<?>>is(Foo.class)));
}
 
Example #23
Source File: InstantiateInlineWorkflowTemplateTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void instanstiateInlineWorkflowTest() throws IOException, InterruptedException {
  InstantiateInlineWorkflowTemplate.instantiateInlineWorkflowTemplate(PROJECT_ID, REGION);
  String output = bout.toString();

  assertThat(output, CoreMatchers.containsString("successfully"));
}
 
Example #24
Source File: ChangingKeyTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnNewKey() throws Exception
{
    JsonWebKey jwk = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"9el2Km2s5LHVQqUCWIdvwMsclQqQc6CwObMnCpCC8jY\"}");

    JsonWebSignature jws = new JsonWebSignature();
    jws.setCompactSerialization("eyJhbGciOiJIUzI1NiJ9.c2lnaA.2yUt5UtfsRK1pnN0KTTv7gzHTxwDqDz2OkFSqlbQ40A");
    jws.setKey(new HmacKey(new byte[32]));
    Assert.assertThat(false, CoreMatchers.equalTo(jws.verifySignature()));

    // sigh, setting a new key should now clear the little internal signature result cache...
    jws.setKey(jwk.getKey());
    Assert.assertThat(true, CoreMatchers.equalTo(jws.verifySignature()));

    jws.setKey(new HmacKey(ByteUtil.randomBytes(32)));
    Assert.assertThat(false, CoreMatchers.equalTo(jws.verifySignature()));

    jws.setKey(null);
    try
    {
        jws.verifySignature();
    }
    catch (JoseException e)
    {
        // expected
    }
}
 
Example #25
Source File: HttpClientExecuteInterceptorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void assertHttpSpanErrorLog(List<LogDataEntity> logs) {
    assertThat(logs.size(), is(1));
    LogDataEntity logData = logs.get(0);
    Assert.assertThat(logData.getLogs().size(), is(4));
    Assert.assertThat(logData.getLogs().get(0).getValue(), CoreMatchers.<Object>is("error"));
    Assert.assertThat(logData.getLogs()
                             .get(1)
                             .getValue(), CoreMatchers.<Object>is(RuntimeException.class.getName()));
    Assert.assertThat(logData.getLogs().get(2).getValue(), is("testException"));
    assertNotNull(logData.getLogs().get(3).getValue());
}
 
Example #26
Source File: DeleteSnapshotAccessorTest.java    From opensharding-spi-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void assertGetSnapshotSQLContext() {
    SnapshotSQLContext actual = deleteSnapshotAccessor.getSnapshotSQLContext(executorContext);
    assertThat(actual.getConnection(), is(connection));
    assertThat(actual.getParameters(), CoreMatchers.<Collection<Object>>is(parameters));
    assertThat(actual.getQueryColumnNames(), CoreMatchers.<Collection<String>>is(Collections.singleton("*")));
    assertThat(actual.getTableName(), is("t_order_0"));
    assertThat(actual.getWhereClause(), is("WHERE order_id = ?"));
}
 
Example #27
Source File: I18NValidationIT.java    From ozark with Apache License 2.0 5 votes vote down vote up
@Test
public void testFrenchValidationMessage() throws Exception {

    HtmlPage page1 = webClient.getPage(webUrl + "resources/validation?lang=fr");
    HtmlForm form1 = page1.getFormByName("form");
    form1.getInputByName("name").setValueAttribute("foo");

    HtmlPage page2 = form1.getInputByName("button").click();
    assertThat(page2.getWebResponse().getContentAsString(),
            CoreMatchers.containsString("entre 5 et 10"));

}
 
Example #28
Source File: SchemaTest.java    From JRediSearch with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void printSchemaTest() throws Exception {
    Schema sc =  new Schema()
            .addTextField(TITLE, 5.0)
            .addSortableTextField(PLOT, 1.0)
            .addSortableTagField(GENRE, ",")
            .addSortableNumericField(RELEASE_YEAR)
            .addSortableNumericField(RATING)
            .addSortableNumericField(VOTES);

    String schemaPrint = sc.toString();
    Assert.assertThat( schemaPrint, CoreMatchers.startsWith("Schema{fields=[TextField{name='title'"));
    Assert.assertThat( schemaPrint, CoreMatchers.containsString("{name='release_year', type=Numeric, sortable=true, noindex=false}"));
}
 
Example #29
Source File: JavassistRegionProxyTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataChange() {
    // 区域对象
    MockRegionObject mockRegion = MockRegionObject.instanceOf(0, 0);
    MockRegionObject proxyRegion = regionProxy.transform(mockRegion);
    Assert.assertTrue(proxyRegion.equals(mockRegion));
    Assert.assertTrue(mockRegion.equals(proxyRegion));

    // 索引不冲突,数据不冲突
    // int oldModifyIndexesTimes = mockProxyManager.getModifyIndexes();
    int oldModifyDatasTimes = mockProxyManager.getModifyDatas();
    proxyRegion.modify(1, true);
    // int newModifyIndexesTimes = mockProxyManager.getModifyIndexes();
    int newModifyDatasTimes = mockProxyManager.getModifyDatas();
    Assert.assertThat(proxyRegion.getOwner(), CoreMatchers.equalTo(1));
    // Assert.assertEquals(0, newModifyIndexesTimes - oldModifyIndexesTimes);
    Assert.assertEquals(1, newModifyDatasTimes - oldModifyDatasTimes);

    // 索引不冲突,数据冲突
    // oldModifyIndexesTimes = mockProxyManager.getModifyIndexes();
    oldModifyDatasTimes = mockProxyManager.getModifyDatas();
    proxyRegion.modify(1, false);
    // newModifyIndexesTimes = mockProxyManager.getModifyIndexes();
    newModifyDatasTimes = mockProxyManager.getModifyDatas();
    Assert.assertThat(proxyRegion.getOwner(), CoreMatchers.equalTo(1));
    // Assert.assertEquals(0, newModifyIndexesTimes - oldModifyIndexesTimes);
    Assert.assertEquals(0, newModifyDatasTimes - oldModifyDatasTimes);
}
 
Example #30
Source File: BinaryUnknownTypeTest.java    From kieker with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoreUnknownRecordType() throws Exception {
	final List<IMonitoringRecord> records = TEST_DATA_REPOSITORY.newTestUnknownRecords();

	final List<IMonitoringRecord> analyzedRecords = this.testUnknownRecordTypes(records, true);

	// we expect that reading abort on the occurrence of EVENT1_UNKNOWN_TYPE, i.e., the remaining lines weren't processed
	Assert.assertThat(analyzedRecords.get(0), CoreMatchers.is(CoreMatchers.equalTo(records.get(0))));
	Assert.assertThat(analyzedRecords.size(), CoreMatchers.is(1));
}