Java 类org.hamcrest.core.IsInstanceOf 实例源码

项目:orizuru-java    文件:MessageTest.java   
@Test
public void decodeFromTransport_shouldThrowADecodeMessageExceptionWithAClassNotFoundExceptionIfTheMessageSchemaNameClassDoesNotExist()
        throws Exception {

    // expect
    exception.expect(DecodeMessageException.class);
    exception.expectMessage("Failed to consume message: Failed to decode message");
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(ClassNotFoundException.class));

    // given
    Transport transport = new Transport();
    transport.setMessageSchemaName("invalid");

    Message message = new Message();

    // when
    message.decodeFromTransport(transport);

}
项目:orizuru-java    文件:AbstractConsumerTest.java   
@Test
public void consume_throwsAHandleMessageExceptionForAnInvalidMessage() throws Exception {

    // expect
    exception.expect(HandleMessageException.class);
    exception.expectMessage("Failed to consume message: Failed to handle message");
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));

    // given
    byte[] body = VALID_MESSAGE.getBytes();

    IConsumer consumer = new ErrorConsumer(QUEUE_NAME);

    // when
    consumer.consume(body);

}
项目:orizuru-java    文件:AbstractConsumerTest.java   
@Test
public void consume_throwsAHandleMessageExceptionWithAnAlteredInvalidMessage() throws Exception {

    // expect
    exception.expect(HandleMessageException.class);
    exception.expectMessage("Failed to consume message: Failed to handle message: test");
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));

    // given
    byte[] body = VALID_MESSAGE.getBytes();

    IConsumer consumer = new ErrorConsumer2(QUEUE_NAME);

    // when
    consumer.consume(body);

}
项目:orizuru-java    文件:AbstractPublisherTest.java   
@Test
public void publish_shouldThrowAnEncodeTransportExceptionForAnInvalidTransportMessage() throws Exception {

    // expect
    exception.expect(EncodeMessageContentException.class);
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(ClassCastException.class));
    exception.expectMessage("Failed to publish message: Failed to encode message content");

    // given
    Context context = mock(Context.class);
    when(context.getSchema())
            .thenReturn(new Schema.Parser().parse("{\"name\":\"test\",\"type\":\"record\",\"fields\":[]}"));
    when(context.getDataBuffer()).thenReturn(ByteBuffer.wrap("{}".getBytes()));

    GenericRecordBuilder builder = new GenericRecordBuilder(schema);
    builder.set("testString", Boolean.TRUE);
    Record record = builder.build();

    // when
    publisher.publish(context, record);

}
项目:orizuru-java    文件:AbstractPublisherTest.java   
@Test
public void publish_shouldThrowAnEncodeTransportExceptionForAnInvalidTransportContext() throws Exception {

    // expect
    exception.expect(EncodeTransportException.class);
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));
    exception.expectMessage("Failed to publish message: Failed to encode transport");

    // given
    Context context = mock(Context.class);
    when(context.getSchema())
            .thenReturn(new Schema.Parser().parse("{\"name\":\"test\",\"type\":\"record\",\"fields\":[]}"));
    when(context.getDataBuffer()).thenReturn(null);

    GenericRecordBuilder builder = new GenericRecordBuilder(schema);
    builder.set("testString", "testString");
    Record record = builder.build();

    // when
    publisher.publish(context, record);

}
项目:oscm    文件:RestTriggerResourceTest.java   
@Test
public void testAction() throws Exception {
    RestTriggerResource.Action action = new RestTriggerResource()
            .redirectToAction();

    RequestParameters params = new RequestParameters();
    params.setId(1L);

    UriInfo uri = Mockito.mock(UriInfo.class);
    MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
    map.putSingle(PARAM_VERSION, "v" + VERSION_1);
    when(uri.getPathParameters()).thenReturn(map);

    Response response = action.getCollection(uri, params);
    assertThat(response.getEntity(),
            IsInstanceOf.instanceOf(RepresentationCollection.class));

    assertNull(action.getItem(uri, params));
}
项目:cdversion-maven-extension    文件:CDVersionLifecycleParticipantTest.java   
@Test
public void testAfterSessionStart_nullRevision()
        throws MavenExecutionException,
        RevisionGeneratorException {
    String revision = null;
    exceptions.expect(MavenExecutionException.class);
    exceptions.expectMessage("RevisionGenerator returned a null revision value");
    exceptions.expectCause(IsInstanceOf.any(RevisionGeneratorException.class));
    when(revisionGenerator.getRevision()).thenReturn(revision);

    try {
        item.afterSessionStart(session);
    } finally {
        verify(revisionGenerator).init(eq(session), any(Logger.class));
        verify(revisionGenerator).getRevision();
        verifyNoMoreInteractions(revisionGenerator);
        verifyZeroInteractions(session);
        verifyZeroInteractions(pluginMerger);
        verifyZeroInteractions(plugins);
    }
}
项目:pac4j-async    文件:DefaultAsyncSecurityLogicTest.java   
@Test(timeout = 1000)
public void testAlreadyAuthenticatedNotAuthorized(final TestContext testContext) throws Exception {
    simulatePreviousAuthenticationSuccess();
    final AsyncClient<TestCredentials, TestProfile> indirectClient = getMockIndirectClient(NAME);
    final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = new Clients<>(CALLBACK_URL, indirectClient);
    when(config.getClients()).thenReturn(clients);
    final String authorizers = NAME;
    addSingleAuthorizerToConfig((context, prof) -> prof.get(0).getId().equals(BAD_USERNAME));
    asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, false, config, httpActionAdapter);
    final Async async = testContext.async();
    final CompletableFuture<Object> result = simulatePreviousAuthenticationSuccess()
            .thenCompose(v -> asyncSecurityLogic.perform(webContext, accessGrantedAdapter, null, authorizers, null));

    exception.expect(CompletionException.class);
    exception.expectCause(allOf(IsInstanceOf.instanceOf(HttpAction.class),
            hasProperty("message", is("forbidden")),
            hasProperty("code", is(403))));
    assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
        assertThat(o, is(nullValue()));
        assertThat(status.get(), is(403));
        verify(accessGrantedAdapter, times(0)).adapt(webContext);
    }), async);
}
项目:pac4j-async    文件:DefaultAsyncSecurityLogicTest.java   
@Test(timeout = 1000)
public void testAuthorizerThrowsRequiresHttpAction(final TestContext testContext) throws Exception {
    simulatePreviousAuthenticationSuccess();
    final AsyncClient<TestCredentials, TestProfile> indirectClient = getMockIndirectClient(NAME);
    final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = new Clients<>(CALLBACK_URL, indirectClient);
    when(config.getClients()).thenReturn(clients);
    final String authorizers = NAME;
    addSingleAuthorizerToConfig((context, prof) -> { throw HttpAction.status("bad request", 400, context); });
    asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, false, config, httpActionAdapter);
    final Async async = testContext.async();
    final CompletableFuture<Object> result = simulatePreviousAuthenticationSuccess()
            .thenCompose(v -> asyncSecurityLogic.perform(webContext, accessGrantedAdapter, null, authorizers, null));
    exception.expect(CompletionException.class);
    exception.expectCause(allOf(IsInstanceOf.instanceOf(HttpAction.class),
            hasProperty("message", is("bad request")),
            hasProperty("code", is(400))));
    assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
        assertThat(o, is(nullValue()));
        assertThat(status.get(), is(400));
        verify(accessGrantedAdapter, times(0)).adapt(webContext);
    }), async);
}
项目:pac4j-async    文件:DefaultAsyncSecurityLogicTest.java   
@Test
public void testDirectClientThrowsRequiresHttpAction(final TestContext testContext) throws Exception {
    final AsyncClient directClient = getMockDirectClient(NAME, TEST_CREDENTIALS);
    final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = new Clients<>(CALLBACK_URL, directClient);
    when(config.getClients()).thenReturn(clients);
    final String clientNames = NAME;
    asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, false, config, httpActionAdapter);
    when(directClient.getCredentials(eq(webContext))).thenReturn(delayedException(250,
            (() -> HttpAction.status("bad request", 400, webContext))));
    final Async async = testContext.async();
    final CompletableFuture<Object> result = asyncSecurityLogic.perform(webContext, accessGrantedAdapter, clientNames, null, null);
    exception.expect(CompletionException.class);
    exception.expectCause(allOf(IsInstanceOf.instanceOf(HttpAction.class),
            hasProperty("message", is("bad request")),
            hasProperty("code", is(400))));

    assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
        assertThat(o, is(nullValue()));
        assertThat(status.get(), is(400));
        verify(accessGrantedAdapter, times(0)).adapt(webContext);
    }), async);
}
项目:pac4j-async    文件:DefaultAsyncSecurityLogicTest.java   
@Test
public void testDoubleDirectClientChooseBadDirectClient(final TestContext testContext) throws Exception {
    final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = doubleDirectClients();
    when(config.getClients()).thenReturn(clients);
    final String clientNames = NAME;
    when(webContext.getRequestParameter(eq(Clients.DEFAULT_CLIENT_NAME_PARAMETER))).thenReturn(VALUE);
    asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, true, config, httpActionAdapter);
    final Async async = testContext.async();

    exception.expect(CompletionException.class);
    exception.expectCause(allOf(IsInstanceOf.instanceOf(TechnicalException.class),
            hasProperty("message", is("Client not allowed: " + VALUE))));
    final CompletableFuture<Object> result = asyncSecurityLogic.perform(webContext, accessGrantedAdapter, clientNames, null, null);
    assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
        assertThat(o, is(nullValue()));
        verify(accessGrantedAdapter, times(0)).adapt(webContext);
    }), async);

}
项目:pac4j-async    文件:DefaultAsyncSecurityLogicTest.java   
@Test
public void testDoubleIndirectClientBadOneChosen(final TestContext testContext) throws Exception {
    final AsyncClient<TestCredentials, TestProfile> indirectClient = getMockIndirectClient(NAME, PAC4J_URL);
    final AsyncClient<TestCredentials, TestProfile> indirectClient2 = getMockIndirectClient(VALUE, PAC4J_BASE_URL);

    final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = new Clients<>(CALLBACK_URL, indirectClient, indirectClient2);

    when(config.getClients()).thenReturn(clients);
    final String clientNames = NAME;
    when(webContext.getRequestParameter(eq(Clients.DEFAULT_CLIENT_NAME_PARAMETER))).thenReturn(VALUE);

    asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, false, config, httpActionAdapter);

    final Async async = testContext.async();

    exception.expect(CompletionException.class);
    exception.expectCause(allOf(IsInstanceOf.instanceOf(TechnicalException.class),
            hasProperty("message", is("Client not allowed: " + VALUE))));
    final CompletableFuture<Object> result = asyncSecurityLogic.perform(webContext, accessGrantedAdapter, clientNames, null, null);
    assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
        assertThat(o, is(nullValue()));
        verify(accessGrantedAdapter, times(0)).adapt(webContext);
    }), async);
}
项目:TurboChat    文件:TeamActivityStartTest.java   
@Test
public void shouldHaveTitleAndSubtitle() {
    ViewInteraction textView = onView(
            allOf(withText("Turbo Chat"),
                    childAtPosition(
                            allOf(withId(R.id.toolbar),
                                    childAtPosition(
                                            IsInstanceOf.<View>instanceOf(android.widget.LinearLayout.class),
                                            0)),
                            0),
                    isDisplayed()));
    textView.check(matches(withText("Turbo Chat")));

    ViewInteraction textView2 = onView(
            allOf(withText("Teams"),
                    childAtPosition(
                            allOf(withId(R.id.toolbar),
                                    childAtPosition(
                                            IsInstanceOf.<View>instanceOf(android.widget.LinearLayout.class),
                                            0)),
                            1),
                    isDisplayed()));
    textView2.check(matches(withText("Teams")));

}
项目:hive-broker    文件:KerberosDataSourceTest.java   
@Test
public void getConnectionTest_registerDriver_returnsConnection() throws SQLException {
  //given
  DataSource ds = KerberosDataSource.Builder.create()
      .connectTo("jdbc:hive2://localhost:10000/")
      .asWho("jojo")
      .useKeyTab("/some/path/to/keytab.file")
      .with(hadoopConf)
      .with(loginManager).build();
  ((KerberosDataSource)ds).JDBC_DRIVER = MockedJdbcDriver.class.getCanonicalName();

  //when
  Connection conn = ds.getConnection();

  //then
  Assert.assertThat(conn, IsInstanceOf.instanceOf(MockConnection.class));
}
项目:che-gradle-plugin    文件:GradleProjectTypeUnitTest.java   
@Test
public void testShouldVerifyRegisteredProjectType() throws Exception {
    ProjectTypeRegistry registry = injector.getInstance(ProjectTypeRegistry.class);

    ProjectTypeDef projectType = registry.getProjectType(PROJECT_TYPE_ID);

    assertNotNull(projectType);
    assertThat(projectType, new IsInstanceOf(GradleProjectType.class));
    assertEquals(projectType.getId(), PROJECT_TYPE_ID);
    assertEquals(projectType.getDisplayName(), PROJECT_TYPE_DISPLAY_NAME);
    assertEquals(projectType.getParents().size(), 1);
    assertEquals(projectType.getParents().get(0), PROJECT_TYPE_PARENT);
    assertEquals(projectType.isMixable(), PROJECT_TYPE_MIXABLE);
    assertEquals(projectType.isPrimaryable(), PROJECT_TYPE_PRIMARY);
    assertEquals(projectType.isPersisted(), PROJECT_TYPE_PERSISTED);
}
项目:quandoo    文件:MainActivityTest.java   
@Test
public void shouldBeAbleToShowTestCustomer() {
    // Launch the activity
    mainActivity.launchActivity(new Intent());

    // Check that the view is what we expect it to be
    ViewInteraction firstName = onView(
            allOf(withId(R.id.first), withText(TEST_CUSTOMER_FIRST_NAME),
                    childAtPosition(
                            childAtPosition(
                                    IsInstanceOf.instanceOf(android.widget.FrameLayout.class),
                                    0),
                            1),
                    isDisplayed()));
    firstName.check(matches(withText(TEST_CUSTOMER_FIRST_NAME)));

    ViewInteraction lastName = onView(
            allOf(withId(R.id.last), withText(TEST_CUSTOMER_LAST_NAME),
                    childAtPosition(
                            childAtPosition(
                                    IsInstanceOf.instanceOf(android.widget.FrameLayout.class),
                                    0),
                            2),
                    isDisplayed()));
    lastName.check(matches(withText(TEST_CUSTOMER_LAST_NAME)));
}
项目:development    文件:RestTriggerResourceTest.java   
@Test
public void testAction() throws Exception {
    RestTriggerResource.Action action = new RestTriggerResource()
            .redirectToAction();

    TriggerParameters params = new TriggerParameters();
    params.setId(new Long(1L));

    ContainerRequest request = Mockito.mock(ContainerRequest.class);
    Mockito.when(request.getProperty(Mockito.anyString()))
            .thenReturn(new Integer(CommonParams.VERSION_1));

    Response response = action.getCollection(request, params);
    assertThat(response.getEntity(),
            IsInstanceOf.instanceOf(RepresentationCollection.class));

    assertNull(action.getItem(request, params));
}
项目:triplea    文件:JTabbedPaneBuilderTest.java   
@Test
public void addTab() {
  final JLabel label = new JLabel("value");
  final JComponent component = new JTextField("sample component");
  final JTabbedPane pane = JTabbedPaneBuilder.builder()
      .addTab("tab", label)
      .addTab("second tab", component)
      .build();

  MatcherAssert.assertThat("we added two tabs",
      pane.getTabCount(), Is.is(2));
  MatcherAssert.assertThat("first tab we added was a label",
      pane.getTabComponentAt(0), IsInstanceOf.instanceOf(JLabel.class));
  MatcherAssert.assertThat("second tab had a component",
      pane.getTabComponentAt(1), IsInstanceOf.instanceOf(JComponent.class));
}
项目:confd-maven-plugin    文件:DictionaryUtilTest.java   
@Test
public void shouldFailDueToMalFormedKeyDictionary() throws Exception {
    String[] lines = {
        "/web/mediaserver/url=http://media01.server.com/",
        "",
        "# Missing the first /",
        "web/database/username=user01",
        "",
        "/web/database/password=pwd01",
    };

    File testFile = createTestFile(lines);

    exception.expect(DictionaryException.class);
    exception.expectCause(CoreMatchers.is(IsInstanceOf.<Throwable>instanceOf(InvalidKeyFormatException.class)));

    DictionaryUtil.readDictionaryAsEnvVariables(testFile, ENCODING);

}
项目:dataflow-java    文件:AnnotateVariantsITCase.java   
@Test
public void testBadCallSetName() throws Exception {
  thrown.expect(IsInstanceOf.<IllegalArgumentException>instanceOf(NullPointerException.class));
  thrown.expectMessage(containsString("Call set name 'NotInVariantSet' does not correspond to a call "
      + "set id in variant set id 3049512673186936334"));

  String[] ARGS = {
      "--project=" + helper.getTestProject(),
      "--references=chr17:40700000:40800000",
      "--variantSetId=" + helper.PLATINUM_GENOMES_DATASET,
      "--transcriptSetIds=CIjfoPXj9LqPlAEQ5vnql4KewYuSAQ",
      "--variantAnnotationSetIds=CILSqfjtlY6tHxC0nNH-4cu-xlQ",
      "--callSetNames=NotInVariantSet",
      "--output=" + outputPrefix,
      };

  System.out.println(ARGS);

  testBase(ARGS, EXPECTED_RESULT);
}
项目:owf-security    文件:LdapAuthorityGroupContextMapperTest.java   
/**
 * Test mapping functionality, ensure the proper fields get mapped.
 * @throws Exception
 */
@Test
public void testContextMapper() throws Exception {

    DirContextAdapter contextAdapter = mock(DirContextAdapter.class);
    when(contextAdapter.getDn()).thenReturn(new LdapName("cn=user,ou=groups,o=OWF,st=Maryland,c=us"));
    when(contextAdapter.getStringAttribute("cn")).thenReturn("user");
    when(contextAdapter.getStringAttributes("member")).thenReturn(new String[]{ "cn=jsmith,ou=OWF,o=OWFDevelopment,l=Columbia,st=Maryland,c=US",
                                                                                "cn=jdoe,ou=OWF,o=OWFDevelopment,l=Columbia,st=Maryland,c=US"
                                                                              });

    Object oLdapAuthorityGroup = ldapAuthorityGroupContextMapper.mapFromContext(contextAdapter);

    assertTrue(new IsInstanceOf(LdapAuthorityGroup.class).matches(oLdapAuthorityGroup));
    LdapAuthorityGroup ldapAuthorityGroup = (LdapAuthorityGroup)oLdapAuthorityGroup;

    assertEquals("cn=user,ou=groups,o=OWF,st=Maryland,c=us",ldapAuthorityGroup.getDn());
    assertEquals("user",ldapAuthorityGroup.getCn());
    assertEquals(2,ldapAuthorityGroup.getMembers().length);
}
项目:ews-java-api    文件:TaskTest.java   
/**
 * Test for checking if the value changes in case of a thrown exception
 *
 * @throws Exception
 */
@Test
public void testDontChangeValueOnException() throws Exception {
  // set valid value
  final Double targetValue = 50.5;
  taskMock.setPercentComplete(targetValue);

  assertThat(taskMock.getPercentComplete(), IsNot.not(IsNull.nullValue()));
  assertThat(taskMock.getPercentComplete(), IsInstanceOf.instanceOf(Double.class));
  assertThat(taskMock.getPercentComplete(), IsEqual.equalTo(targetValue));

  final Double invalidValue = -0.1;
  try {
    taskMock.setPercentComplete(invalidValue);
  } catch (IllegalArgumentException ex) {
    // ignored
  }

  assertThat(taskMock.getPercentComplete(), IsNot.not(IsNull.nullValue()));
  assertThat(taskMock.getPercentComplete(), IsInstanceOf.instanceOf(Double.class));
  assertThat(taskMock.getPercentComplete(), IsEqual.equalTo(targetValue));
}
项目:spring-data-keyvalue    文件:KeyValuePartTreeQueryUnitTests.java   
@Test // DATAKV-142
@SuppressWarnings({ "unchecked", "rawtypes" })
public void shouldApplyDerivedMaxResultsToQueryWithParameters() throws SecurityException, NoSuchMethodException {

    when(metadataMock.getDomainType()).thenReturn((Class) Person.class);
    when(metadataMock.getReturnedDomainClass(any(Method.class))).thenReturn((Class) Person.class);

    QueryMethod qm = new QueryMethod(Repo.class.getMethod("findTop3ByFirstname", String.class), metadataMock,
            projectionFactoryMock);

    KeyValuePartTreeQuery partTreeQuery = new KeyValuePartTreeQuery(qm, DefaultEvaluationContextProvider.INSTANCE,
            kvOpsMock, SpelQueryCreator.class);

    KeyValueQuery<?> query = partTreeQuery.prepareQuery(new Object[] { "firstname" });

    assertThat(query.getCriteria(), is(notNullValue()));
    assertThat(query.getCriteria(), IsInstanceOf.instanceOf(SpelCriteria.class));
    assertThat(((SpelCriteria) query.getCriteria()).getExpression().getExpressionString(),
            is("#it?.firstname?.equals([0])"));
    assertThat(query.getRows(), is(3));
}
项目:spliceengine    文件:SITransactorInMemTest.java   
@Test//(expected = CannotCommitException.class)
public void writeWriteOverlap() throws IOException {
    Txn t1 = control.beginTransaction();
    Assert.assertEquals("joe012 absent", testUtility.read(t1, "joe012"));
    t1 = t1.elevateToWritable(DESTINATION_TABLE);
    testUtility.insertAge(t1, "joe012", 20);
    Assert.assertEquals("joe012 age=20 job=null", testUtility.read(t1, "joe012"));

    Txn t2 = control.beginTransaction();
    Assert.assertEquals("joe012 age=20 job=null", testUtility.read(t1, "joe012"));
    Assert.assertEquals("joe012 absent", testUtility.read(t2, "joe012"));
    t2 = t2.elevateToWritable(DESTINATION_TABLE);
    try {
        testUtility.insertAge(t2, "joe012", 30);
        Assert.fail("was able to insert age");
    } catch (IOException e) {
        testUtility.assertWriteConflict(e);
    } finally {
        t2.rollback();
    }
    Assert.assertEquals("joe012 age=20 job=null", testUtility.read(t1, "joe012"));
    t1.commit();
    error.expect(IsInstanceOf.instanceOf(CannotCommitException.class));
    t2.commit(); //should not work, probably need to change assertion
    Assert.fail("Was able to commit a rolled back transaction");
}
项目:spliceengine    文件:SITransactorInMemTest.java   
@Test
public void writeDeleteOverlap() throws IOException {
    Txn t1 = control.beginTransaction();
    t1 = t1.elevateToWritable(DESTINATION_TABLE);
    testUtility.insertAge(t1, "joe2", 20);

    Txn t2 = control.beginTransaction(DESTINATION_TABLE);
    try {
        testUtility.deleteRow(t2, "joe2");
        Assert.fail("No Write conflict was detected!");
    } catch (IOException e) {
        testUtility.assertWriteConflict(e);
    } finally {
        t2.rollback();
    }
    Assert.assertEquals("joe2 age=20 job=null", testUtility.read(t1, "joe2"));
    t1.commit();
    error.expect(IsInstanceOf.instanceOf(CannotCommitException.class));
    error.expectMessage(String.format("[%1$d]Transaction %1$d cannot be committed--it is in the %2$s state",t2.getTxnId(),Txn.State.ROLLEDBACK));
    t2.commit();
    Assert.fail("Did not throw CannotCommit exception!");
}
项目:spliceengine    文件:SITransactorInMemTest.java   
@Test
public void writeAllNullsWriteOverlap() throws IOException {
    Txn t1 = control.beginTransaction();
    Assert.assertEquals("joe116 absent", testUtility.read(t1, "joe116"));
    t1 = t1.elevateToWritable(DESTINATION_TABLE);
    testUtility.insertAge(t1, "joe116", null);
    Assert.assertEquals("joe116 age=null job=null", testUtility.read(t1, "joe116"));

    Txn t2 = control.beginTransaction();
    Assert.assertEquals("joe116 age=null job=null", testUtility.read(t1, "joe116"));
    Assert.assertEquals("joe116 absent", testUtility.read(t2, "joe116"));
    t2 = t2.elevateToWritable(DESTINATION_TABLE);
    try {
        testUtility.insertAge(t2, "joe116", 30);
        Assert.fail("Allowed insertion");
    } catch (IOException e) {
        testUtility.assertWriteConflict(e);
    } finally {
        t2.rollback();
    }
    Assert.assertEquals("joe116 age=null job=null", testUtility.read(t1, "joe116"));
    t1.commit();
    error.expect(IsInstanceOf.instanceOf(CannotCommitException.class));
    t2.commit();
    Assert.fail("Was able to comit a rolled back transaction");
}
项目:spliceengine    文件:SITransactorTest.java   
@Test//(expected = CannotCommitException.class)
public void writeWriteOverlap() throws IOException {
    Txn t1 = control.beginTransaction();
    Assert.assertEquals("joe012 absent", testUtility.read(t1, "joe012"));
    t1 = t1.elevateToWritable(DESTINATION_TABLE);
    testUtility.insertAge(t1, "joe012", 20);
    Assert.assertEquals("joe012 age=20 job=null", testUtility.read(t1, "joe012"));

    Txn t2 = control.beginTransaction();
    Assert.assertEquals("joe012 age=20 job=null", testUtility.read(t1, "joe012"));
    Assert.assertEquals("joe012 absent", testUtility.read(t2, "joe012"));
    t2 = t2.elevateToWritable(DESTINATION_TABLE);
    try {
        testUtility.insertAge(t2, "joe012", 30);
        Assert.fail("was able to insert age");
    } catch (IOException e) {
        testUtility.assertWriteConflict(e);
    } finally {
        t2.rollback();
    }
    Assert.assertEquals("joe012 age=20 job=null", testUtility.read(t1, "joe012"));
    t1.commit();
    error.expect(IsInstanceOf.instanceOf(CannotCommitException.class));
    t2.commit(); //should not work, probably need to change assertion
    Assert.fail("Was able to commit a rolled back transaction");
}
项目:spliceengine    文件:SITransactorTest.java   
@Test
public void writeDeleteOverlap() throws IOException {
    Txn t1 = control.beginTransaction();
    t1 = t1.elevateToWritable(DESTINATION_TABLE);
    testUtility.insertAge(t1, "joe2", 20);

    Txn t2 = control.beginTransaction(DESTINATION_TABLE);
    try {
        testUtility.deleteRow(t2, "joe2");
        Assert.fail("No Write conflict was detected!");
    } catch (IOException e) {
        testUtility.assertWriteConflict(e);
    } finally {
        t2.rollback();
    }
    Assert.assertEquals("joe2 age=20 job=null", testUtility.read(t1, "joe2"));
    t1.commit();
    error.expect(IsInstanceOf.instanceOf(CannotCommitException.class));
    error.expectMessage(String.format("[%1$d]Transaction %1$d cannot be committed--it is in the %2$s state",t2.getTxnId(),Txn.State.ROLLEDBACK));
    t2.commit();
    Assert.fail("Did not throw CannotCommit exception!");
}
项目:spliceengine    文件:SITransactorTest.java   
@Test
public void writeAllNullsWriteOverlap() throws IOException {
    Txn t1 = control.beginTransaction();
    Assert.assertEquals("joe116 absent", testUtility.read(t1, "joe116"));
    t1 = t1.elevateToWritable(DESTINATION_TABLE);
    testUtility.insertAge(t1, "joe116", null);
    Assert.assertEquals("joe116 age=null job=null", testUtility.read(t1, "joe116"));

    Txn t2 = control.beginTransaction();
    Assert.assertEquals("joe116 age=null job=null", testUtility.read(t1, "joe116"));
    Assert.assertEquals("joe116 absent", testUtility.read(t2, "joe116"));
    t2 = t2.elevateToWritable(DESTINATION_TABLE);
    try {
        testUtility.insertAge(t2, "joe116", 30);
        Assert.fail("Allowed insertion");
    } catch (IOException e) {
        testUtility.assertWriteConflict(e);
    } finally {
        t2.rollback();
    }
    Assert.assertEquals("joe116 age=null job=null", testUtility.read(t1, "joe116"));
    t1.commit();
    error.expect(IsInstanceOf.instanceOf(CannotCommitException.class));
    t2.commit();
    Assert.fail("Was able to comit a rolled back transaction");
}
项目:GitHub    文件:EnumIT.java   
@Test
@SuppressWarnings("unchecked")
public void intEnumIsDeserializedCorrectly() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, JsonParseException, JsonMappingException, IOException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/integerEnumToSerialize.json", "com.example");

    // the schema for a valid instance
    Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize");
    Class<Enum> enumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize$TestEnum");

    // read the instance into the type
    ObjectMapper objectMapper = new ObjectMapper();
    Object valueWithEnumProperty = objectMapper.readValue("{\"testEnum\" : 2}", typeWithEnumProperty);

    Method getEnumMethod = typeWithEnumProperty.getDeclaredMethod("getTestEnum");
    Method getValueMethod = enumClass.getDeclaredMethod("value");

    // call getTestEnum on the value
    assertThat(getEnumMethod, is(notNullValue()));
    Object enumObject = getEnumMethod.invoke(valueWithEnumProperty);

    // assert that the object returned is a) a TestEnum, and b) calling .value() on it returns 2
    // as per the json snippet above
    assertThat(enumObject, IsInstanceOf.instanceOf(enumClass));
    assertThat(getValueMethod, is(notNullValue()));
    assertThat((Integer)getValueMethod.invoke(enumObject), is(2));
}
项目:orizuru-java    文件:MessageTest.java   
@Test
public void decode_shouldThrowADecodeMessageContentExceptionIfTheSchemaIsNull() throws Exception {

    // expect
    exception.expect(DecodeMessageContentException.class);
    exception.expectMessage("Failed to consume message: Failed to decode message content");
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));

    // given
    Message message = new Message();

    // when
    message.decode();

}
项目:orizuru-java    文件:MessageTest.java   
@Test
public void decodeFromTransport_shouldThrowADecodeMessageExceptionIfTheTransportIsNull() throws Exception {

    // expect
    exception.expect(DecodeMessageException.class);
    exception.expectMessage("Failed to consume message: Failed to decode message");
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));

    // given
    Message message = new Message();

    // when
    message.decodeFromTransport(null);

}
项目:orizuru-java    文件:MessageTest.java   
@Test
public void encode_shouldThrowAnEncodeMessageContentExceptionIfTheMessageDataIsNull() throws Exception {

    // expect
    exception.expect(EncodeMessageContentException.class);
    exception.expectMessage("Failed to publish message: Failed to encode message content");
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));

    // given
    Message message = new Message();

    // when
    message.encode(null);

}
项目:orizuru-java    文件:ContextTest.java   
@Test
public void decodeFromTransport_shouldThrowADecodeContextExceptionsIfTheTransportIsNull() throws Exception {

    // expect
    exception.expect(DecodeContextException.class);
    exception.expectMessage("Failed to consume message: Failed to decode context");
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));

    // given
    Context context = new Context();

    // when
    context.decodeFromTransport(null);

}
项目:orizuru-java    文件:AbstractConsumerTest.java   
@Test
public void consume_throwsDecodeTransportExceptionForNullBody() throws OrizuruException {

    // expect
    exception.expect(DecodeTransportException.class);
    exception.expectMessage("Failed to consume message: Failed to decode transport");
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));

    // given
    IConsumer consumer = new Consumer(QUEUE_NAME);

    // when
    consumer.consume(null);

}
项目:orizuru-java    文件:AbstractPublisherTest.java   
@Test
public void publish_shouldThrowAnOrizuruPublisherExceptionForANullMessage() throws Exception {

    // expect
    exception.expect(OrizuruPublisherException.class);
    exception.expectCause(IsInstanceOf.<Throwable>instanceOf(NullPointerException.class));
    exception.expectMessage("Failed to publish message");

    // when
    publisher.publish(null, null);

}
项目:polymorphia    文件:SpecialFieldsMapCodecTest.java   
@Test
public void test() {
    MongoCollection<RichTextData> mongoCollection = mongoClient.getDatabase("test")
            .getCollection("documents")
            .withDocumentClass(RichTextData.class);

    RichTextData richText = new RichTextData();
    RichTextData.EntityMapEntry<Date> entityMapEntry = new RichTextData.EntityMapEntry<>();
    entityMapEntry.put("date", new Date());
    RichTextData.EntityMapEntry<Date> entityMapEntry1 = new RichTextData.EntityMapEntry<>();
    entityMapEntry1.put("date", new Date());
    entityMapEntry1.put("someDocumentProperty", new Document("propA", "String"));
    Map<String, RichTextData.EntityMapEntry<Date>> entityMap = new LinkedHashMap<>();
    entityMap.put("0", entityMapEntry);
    entityMap.put("1", entityMapEntry1);
    richText.put("entityMap", entityMap);
    richText.put("someOtherProperty", 11);
    richText.put("document", new Document("p1", new Date()));

    mongoCollection.insertOne(richText);


    RichTextData richTextRead = mongoCollection.find().first();
    assertNotNull(richTextRead);
    assertThat(richTextRead.getEntityMap(), IsInstanceOf.instanceOf(Map.class));
    assertThat(richTextRead.getEntityMap().get("0"), IsInstanceOf.instanceOf(RichTextData.EntityMapEntry.class));


}
项目:TurboChat    文件:MainActivityLoadDataTest.java   
@Test
public void mainActivityLoadDataTest() {
    ViewInteraction textView = onView(
            allOf(withText("Teams"),
                    childAtPosition(
                            allOf(withId(R.id.toolbar),
                                    childAtPosition(
                                            IsInstanceOf.<View>instanceOf(android.widget.LinearLayout.class),
                                            0)),
                            1),
                    isDisplayed()));
    textView.check(matches(withText("Teams")));

    ViewInteraction textView2 = onView(
            allOf(withText("Turbo Chat"),
                    childAtPosition(
                            allOf(withId(R.id.toolbar),
                                    childAtPosition(
                                            IsInstanceOf.<View>instanceOf(android.widget.LinearLayout.class),
                                            0)),
                            0),
                    isDisplayed()));
    textView2.check(matches(withText("Turbo Chat")));

    ViewInteraction textView3 = onView(
            allOf(withId(R.id.txt_team_name), withText("Java developer team"),
                    childAtPosition(
                            childAtPosition(
                                    withId(R.id.card_view),
                                    0),
                            1),
                    isDisplayed()));
    textView3.check(matches(withText("Java developer team")));

}
项目:TurboChat    文件:MainActivityMessageViewNavigationTest.java   
@Test
public void mainActivityMessageViewNavigationTest() {
    ViewInteraction textView = onView(
            allOf(withId(R.id.txt_team_name), withText("Java developer team"),
                    childAtPosition(
                            childAtPosition(
                                    withId(R.id.card_view),
                                    0),
                            1),
                    isDisplayed()));
    textView.check(matches(withText("Java developer team")));

    ViewInteraction recyclerView = onView(
            allOf(withId(R.id.recycler_teams), isDisplayed()));
    recyclerView.perform(actionOnItemAtPosition(0, click()));


    EspressoTestUtils.matchToolbarTitle("Java developer team");

    ViewInteraction appCompatImageButton = onView(
            allOf(withContentDescription("Navigate up"),
                    withParent(withId(R.id.toolbar)),
                    isDisplayed()));
    appCompatImageButton.perform(click());

    ViewInteraction textView4 = onView(
            allOf(withText("Turbo Chat"),
                    childAtPosition(
                            allOf(withId(R.id.toolbar),
                                    childAtPosition(
                                            IsInstanceOf.<View>instanceOf(android.widget.LinearLayout.class),
                                            0)),
                            0),
                    isDisplayed()));
    textView4.check(matches(withText("Turbo Chat")));

}
项目:Karaf-Vertx    文件:MicroservicesTest.java   
@Test
public void readDataPerBus() throws Exception {

    eventBus.send("de.nierbeck.vertx.jdbc.read", new Book(1l, null, null), message -> {
        assertThat(message.result().body(), IsInstanceOf.instanceOf(Book.class));
        Book book = (Book) message.result().body();
        assertThat(book.getId(), is(1l));
        assertThat(book.getIsbn(), containsString("1234-56789"));
        assertThat(book.getName(), containsString("Java Cookbook"));
    });
}