Java 类org.hamcrest.CoreMatchers 实例源码

项目:Expert-Android-Programming    文件:UIAnimatorTest.java   
@Before
public void startMainActivityFromHomeScreen() {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

    // Start from the home screen
    mDevice.pressHome();

    // Wait for launcher
    final String launcherPackage = mDevice.getLauncherPackageName();
    Assert.assertThat(launcherPackage, CoreMatchers.notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
            LAUNCH_TIMEOUT);

    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
    // Clear out any previous instances
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
            LAUNCH_TIMEOUT);
}
项目:hadoop    文件:TestContainerLaunch.java   
@Test (timeout = 10000)
public void testWindowsShellScriptBuilderEnv() throws IOException {
  // Test is only relevant on Windows
  Assume.assumeTrue(Shell.WINDOWS);

  // The tests are built on assuming 8191 max command line length
  assertEquals(8191, Shell.WINDOWS_MAX_SHELL_LENGHT);

  ShellScriptBuilder builder = ShellScriptBuilder.create();

  // test env
  builder.env("somekey", org.apache.commons.lang.StringUtils.repeat("A", 1024));
  builder.env("somekey", org.apache.commons.lang.StringUtils.repeat(
      "A", Shell.WINDOWS_MAX_SHELL_LENGHT - ("@set somekey=").length()));
  try {
    builder.env("somekey", org.apache.commons.lang.StringUtils.repeat(
        "A", Shell.WINDOWS_MAX_SHELL_LENGHT - ("@set somekey=").length()) + 1);
    fail("long env was expected to throw");
  } catch(IOException e) {
    assertThat(e.getMessage(), CoreMatchers.containsString(expectedMessage));
  }
}
项目:incap    文件:InputTypeFinderTest.java   
@Test
public void inputTypeFinder_should_returnClassItself() {
  //GIVEN
  source =
      forSourceString(
          "test.Test",
          "" //
              + "package test;\n" //
              + "import org.gradle.incap.Annotation1;\n" //
              + "@Annotation1\n" //
              + "public class Test {\n" //
              + "}");

  //WHEN
  InputType inputType = findInputTypeSuccessFully(source);

  //THEN
  assertThat(inputType, CoreMatchers.notNullValue());
  assertThat(inputType.getName(), CoreMatchers.is("test.Test"));
}
项目:iTAP-controller    文件:OFSwitchHandlerTestBase.java   
/**
 * Verify that the given exception event capture (as returned by
 * getAndInitExceptionCapture) has thrown an exception of the given
 * expectedExceptionClass.
 * Resets the capture
 * @param err
 */
void verifyExceptionCaptured(
        OFMessage err, Class<? extends Throwable> expectedExceptionClass) {

    Throwable caughtEx = null;
    // This should purposely cause an exception
    try{
        switchHandler.processOFMessage(err);
    }
    catch(Exception e){
        // Capture the exception
        caughtEx = e;
    }

    assertThat(caughtEx, CoreMatchers.instanceOf(expectedExceptionClass));
}
项目:incap    文件:InputTypeFinderTest.java   
@Test
public void inputTypeFinder_should_returnClassContainingField() {
  //GIVEN
  source =
      forSourceString(
          "test.Test",
          "" //
              + "package test;\n" //
              + "import org.gradle.incap.Annotation1;\n" //
              + "public class Test {\n" //
              + "  @Annotation1 String foo;\n" //
              + "}");

  //WHEN
  InputType inputType = findInputTypeSuccessFully(source);

  //THEN
  assertThat(inputType, CoreMatchers.notNullValue());
  assertThat(inputType.getName(), CoreMatchers.is("test.Test"));
}
项目:GitHub    文件:SyncedRealmTests.java   
@Test
@UiThreadTest
public void waitForInitialRemoteData_mainThreadThrows() {
    final SyncUser user = SyncTestUtils.createTestUser(Constants.AUTH_URL);
    SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM)
            .waitForInitialRemoteData()
            .build();

    Realm realm = null;
    try {
        realm = Realm.getInstance(config);
        fail();
    } catch (IllegalStateException expected) {
        assertThat(expected.getMessage(), CoreMatchers.containsString(
                "downloadAllServerChanges() cannot be called from the main thread."));
    } finally {
        if (realm != null) {
            realm.close();
        }
    }
}
项目:GitHub    文件:RealmMigrationTests.java   
@Test
public void migrationException_realmListChanged() throws IOException {
    RealmConfiguration config = configFactory.createConfiguration();
    // Initialize the schema with RealmList<Cat>
    Realm.getInstance(configFactory.createConfiguration()).close();

    DynamicRealm dynamicRealm = DynamicRealm.getInstance(config);
    dynamicRealm.beginTransaction();
    // Change the RealmList type to RealmList<Dog>
    RealmObjectSchema dogSchema = dynamicRealm.getSchema().get(Dog.CLASS_NAME);
    RealmObjectSchema ownerSchema = dynamicRealm.getSchema().get(CatOwner.CLASS_NAME);
    ownerSchema.removeField(CatOwner.FIELD_CATS);
    ownerSchema.addRealmListField(CatOwner.FIELD_CATS, dogSchema);
    dynamicRealm.commitTransaction();
    dynamicRealm.close();

    try {
        realm = Realm.getInstance(config);
        fail();
    } catch (RealmMigrationNeededException ignored) {
        assertThat(ignored.getMessage(),
                CoreMatchers.containsString("Property 'CatOwner.cats' has been changed from 'array<Dog>' to 'array<Cat>'"));
    }
}
项目:GitHub    文件:RealmObjectSchemaTests.java   
@Test
public void setRequired_true_onPrimaryKeyField_containsNullValues_shouldThrow() {
    if (type == ObjectSchemaType.IMMUTABLE) {
        return;
    }
    for (PrimaryKeyFieldType fieldType : PrimaryKeyFieldType.values()) {
        String className = fieldType.getType().getSimpleName() + "Class";
        String fieldName = "primaryKey";
        schema = realmSchema.create(className);
        if (!fieldType.isNullable()) {
            continue;
        }
        schema.addField(fieldName, fieldType.getType(), FieldAttribute.PRIMARY_KEY);
        DynamicRealmObject object = ((DynamicRealm)realm).createObject(schema.getClassName(), null);
        assertTrue(object.isNull(fieldName));
        try {
            schema.setRequired(fieldName, true);
            fail();
        } catch (IllegalStateException expected) {
            assertThat(expected.getMessage(),
                    CoreMatchers.containsString("The primary key field 'primaryKey' has 'null' values stored."));
        }
        realmSchema.remove(className);
    }
}
项目:iTAP-controller    文件:OFChannelHandlerVer13Test.java   
@Test
public void moveToWaitHello() throws Exception {
    resetChannel();
    channel.write(capture(writeCapture));
    expectLastCall().andReturn(null).once();
    replay(channel);
    // replay unused mocks
    replay(messageEvent);

    handler.channelConnected(ctx, channelStateEvent);

    List<OFMessage> msgs = getMessagesFromCapture();
    assertEquals(1, msgs.size());
    assertEquals(OFType.HELLO, msgs.get(0).getType());
    assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.WaitHelloState.class));
    verifyUniqueXids(msgs);
}
项目:jb-hub-client    文件:RtUsersTest.java   
/**
 * Return the same hub.
 * @throws Exception If fails
 */
@Test
public void sameHub() throws Exception {
    final Hub hub = new RtHub(
        new URI("hub.com"),
        "token"
    );
    MatcherAssert.assertThat(
        new RtUsers(
            hub
        ).hub(),
        CoreMatchers.equalTo(
            hub
        )
    );
}
项目:android-architecture-components    文件:MainActivityTest.java   
@Before
public void waitForDbCreation() throws Throwable {
    final CountDownLatch latch = new CountDownLatch(1);
    final LiveData<Boolean> databaseCreated = AppDatabase.getInstance(
            InstrumentationRegistry.getTargetContext(), new AppExecutors())
            .getDatabaseCreated();
    mActivityRule.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            databaseCreated.observeForever(new Observer<Boolean>() {
                @Override
                public void onChanged(@Nullable Boolean aBoolean) {
                    if (Boolean.TRUE.equals(aBoolean)) {
                        databaseCreated.removeObserver(this);
                        latch.countDown();
                    }
                }
            });
        }
    });
    MatcherAssert.assertThat("database should've initialized",
            latch.await(1, TimeUnit.MINUTES), CoreMatchers.is(true));
}
项目:jb-hub-client    文件:RtUserTest.java   
/**
 * Return the same user.
 * @throws Exception If fails
 */
@Test
public void sameUser() throws Exception {
    final Request req = new JdkRequest("");
    final RtUsers users = new RtUsers(
        req,
        new RtHub(
            req
        )
    );
    MatcherAssert.assertThat(
        new RtUser(
            req,
            users,
            "me"
        ).users(),
        CoreMatchers.equalTo(
            users
        )
    );
}
项目:com-liferay-apio-architect    文件:JSONLDTestUtil.java   
/**
 * Returns a {@link Matcher} that checks if the field contains the provided
 * types as a JSON Array.
 *
 * @param  types the types to match
 * @return a matcher for a type JSON Array
 * @review
 */
public static Matcher<? extends JsonElement> containsTheTypes(
    String... types) {

    Stream<String> stream = Arrays.stream(types);

    List<Matcher<? super JsonElement>> matchers = stream.map(
        CoreMatchers::equalTo
    ).map(
        JsonMatchers::aJsonString
    ).collect(
        Collectors.toList()
    );

    return is(aJsonArrayThat(contains(matchers)));
}
项目:iTAP-controller    文件:OFChannelHandlerVer13Test.java   
/** Move the channel from scratch to WAIT_FEATURES_REPLY state
 * Builds on moveToWaitHello()
 * adds testing for WAIT_HELLO state
 */
@Test
public void moveToWaitFeaturesReply() throws Exception {
    moveToWaitHello();
    resetChannel();
    channel.write(capture(writeCapture));
    expectLastCall().andReturn(null).atLeastOnce();
    replay(channel);

    OFMessage hello = factory.buildHello().build();
    sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(hello));

    List<OFMessage> msgs = getMessagesFromCapture();
    assertEquals(1, msgs.size());
    assertEquals(OFType.FEATURES_REQUEST, msgs.get(0).getType());
    verifyUniqueXids(msgs);

    assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.WaitFeaturesReplyState.class));
}
项目:minikube-build-tools-for-java    文件:BlobPullerIntegrationTest.java   
@Test
public void testPull_unknownBlob() throws RegistryException, IOException, DigestException {
  DescriptorDigest nonexistentDigest =
      DescriptorDigest.fromHash(
          "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

  try {
    RegistryClient registryClient = new RegistryClient(null, "localhost:5000", "busybox");
    registryClient.pullBlob(nonexistentDigest, Mockito.mock(Path.class));
    Assert.fail("Trying to pull nonexistent blob should have errored");

  } catch (RegistryErrorException ex) {
    Assert.assertThat(
        ex.getMessage(),
        CoreMatchers.containsString(
            "pull BLOB for localhost:5000/busybox with digest " + nonexistentDigest));
  }
}
项目:minikube-build-tools-for-java    文件:AuthenticationMethodRetrieverTest.java   
@Test
public void testHandleHttpResponseException_badAuthenticationMethod()
    throws HttpResponseException {
  String authenticationMethod = "bad authentication method";

  Mockito.when(mockHttpResponseException.getStatusCode())
      .thenReturn(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
  Mockito.when(mockHttpResponseException.getHeaders()).thenReturn(mockHeaders);
  Mockito.when(mockHeaders.getAuthenticate()).thenReturn(authenticationMethod);

  try {
    testAuthenticationMethodRetriever.handleHttpResponseException(mockHttpResponseException);
    Assert.fail(
        "Authentication method retriever should fail if 'WWW-Authenticate' header failed to parse");

  } catch (RegistryErrorException ex) {
    Assert.assertThat(
        ex.getMessage(),
        CoreMatchers.containsString(
            "Failed get authentication method from 'WWW-Authenticate' header"));
  }
}
项目:document-management-store-app    文件:DmBuildInfoTest.java   
@Test
public void shouldAddBuildInfoToBuilder() throws Exception {
    DmBuildInfo dmBuildInfo = new DmBuildInfo("name","env","project");

    Info.Builder builder = new Info.Builder();
    dmBuildInfo.contribute(builder);


    Map<String,Object> buildInfo = new HashMap<>();
    buildInfo.put("environment", "env");
    buildInfo.put("project", "project");
    buildInfo.put("name", "name");
    buildInfo.put("version", "unknown");
    buildInfo.put("date", "unknown");
    buildInfo.put("commit", "unknown");
    buildInfo.put("extra", Collections.EMPTY_MAP);

    Map<String,Object> map = new HashMap<>();
    map.put("buildInfo",buildInfo);

    Info info = builder.build();

    assertThat(info.getDetails(), CoreMatchers.equalTo(map));
}
项目:elasticsearch_my    文件:GeoPointFieldMapperTests.java   
public void testLonLatArrayArrayStored() throws Exception {
    XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
        .startObject("properties").startObject("point").field("type", "geo_point");
    String mapping = xContentBuilder.field("store", true).field("doc_values", false).endObject().endObject()
        .endObject().endObject().string();
    DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));

    ParsedDocument doc = defaultMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
            .startObject()
            .startArray("point")
            .startArray().value(1.3).value(1.2).endArray()
            .startArray().value(1.5).value(1.4).endArray()
            .endArray()
            .endObject()
            .bytes());

    assertThat(doc.rootDoc().getFields("point"), notNullValue());
    assertThat(doc.rootDoc().getFields("point").length, CoreMatchers.equalTo(4));
}
项目:randomito-all    文件:TypeCreatorServiceTest.java   
@Test
public void testRegisterAndCreateForType() {
    // given
    Class<TypeCreatorServiceTest> type = TypeCreatorServiceTest.class;
    TypeCreator creator = new TypeCreator() {
        @Override
        public Object newInstance() {
            return new TypeCreatorServiceTest();
        }
    };

    // when
    service.register(type, creator);
    Object forType = service.createForType(this, type);

    // then
    Assert.assertThat(forType, CoreMatchers.is(CoreMatchers.notNullValue()));
    Assert.assertTrue(forType.getClass() == type);
}
项目:db-queue    文件:QueueRunnerFactoryTest.java   
@Test
public void should_return_wrap_in_transaction_runner() throws Exception {
    QueueConsumer queueConsumer = mock(QueueConsumer.class);
    QueueSettings settings = QueueSettings.builder().withBetweenTaskTimeout(Duration.ZERO).withNoTaskTimeout(Duration.ZERO)
            .withProcessingMode(ProcessingMode.WRAP_IN_TRANSACTION).build();
    QueueLocation location = QueueLocation.builder().withTableName("testTable")
            .withQueueId(new QueueId("testQueue")).build();
    when(queueConsumer.getQueueConfig()).thenReturn(new QueueConfig(location, settings));

    QueueRunner queueRunner = QueueRunner.Factory.createQueueRunner(queueConsumer,
            new QueueDao(new QueueShardId("s1"), mock(JdbcOperations.class), mock(TransactionOperations.class)),
            mock(TaskLifecycleListener.class),
            null);

    assertThat(queueRunner, CoreMatchers.instanceOf(QueueRunnerInTransaction.class));
}
项目:word-clock-raspberry-pi-zero-neopixels    文件:PixelChannelTest.java   
@Test
public void setPixel() throws Exception {
    PixelHandler pixelHandler = PixelHandler.getBuilder()
        .buildChannel0().setDimention(10,10).add()
        .buildChannel1().add()
        .instance();

    PixelChannel pixelChannel = pixelHandler.getPixelChannel(0);

    assertThat("Should have 100 pixels",pixelChannel.getLedCount(), CoreMatchers.equalTo(100));

    for (float i = 0; i < 10; i++) {
        int value = (int)(255 - (i*25.5F));
        pixelChannel.setPixel((int)i,0,Pixel.fromColor(value,value,value,value));
    }

    assertThat("Should have 255 at pixels 0",pixelChannel.getPixel(0,0).rawColor, CoreMatchers.equalTo(0xFFFFFFFF));
    assertThat("Should have 255 at pixels 0",pixelChannel.getPixel(9,0).rawColor, CoreMatchers.equalTo(0x19191919));

    pixelChannel.rightShiftPixelsRow(0);

    assertThat("Should have 255 at pixels 0",pixelChannel.getPixel(0,0).rawColor, CoreMatchers.equalTo(0x19191919));
    assertThat("Should have 255 at pixels 0",pixelChannel.getPixel(9,0).rawColor, CoreMatchers.equalTo(0x33333333));
}
项目:vind    文件:AnnotationUtilTest.java   
@Test
public void testCreateDocument1() throws Exception {
    Pojo1 p = new Pojo1();
    p.id = "foo";
    p.title = "title";
    p.content = "content";
    p.someInternalData = UUID.randomUUID().toString();
    p.categories = new HashSet<>(Arrays.asList("cat1", "cat2", "cat3"));
    p.tax = new Taxonomy("id-1","term 1", Arrays.asList("first Term","term 1", "term one"));

    final Document doc = AnnotationUtil.createDocument(p);
    assertThat("id", doc.getId(), equalTo(p.id));
    assertThat("type", doc.getType(), equalTo("Pojo"));

    assertThat("title", doc.getValue("title"), allOf(instanceOf(String.class), CoreMatchers.<Object>equalTo(p.title)));
    assertThat("content", doc.getValue("data"), allOf(instanceOf(String.class), equalTo(p.content)));
    assertFalse("someInternalData", doc.hasValue("someInternalData"));

    assertThat("categories", doc.getValue("cats"), instanceOf(Collection.class));
}
项目:jb-hub-client    文件:RtUsersTest.java   
/**
 * Self get return correct user.
 * @throws Exception If fails
 */
@Test
public void selfGet() throws Exception {
    final Request req = new JdkRequest("");
    final RtUsers users = new RtUsers(
        req,
        new RtHub(
            req
        )
    );
    MatcherAssert.assertThat(
        users.self(),
        CoreMatchers.equalTo(
            new RtUser(
                req.uri().path("/users").back(),
                users,
                "me"
            )
        )
    );
}
项目:fresco_floodlight    文件:OFChannelHandlerVer10Test.java   
/** Move the channel from scratch to WAIT_FEATURES_REPLY state
 * Builds on moveToWaitHello()
 * adds testing for WAIT_HELLO state
 */
@Test
public void moveToWaitFeaturesReply() throws Exception {

    moveToWaitHello();

    resetChannel();
    expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).atLeastOnce();
    replay(channel);

    OFMessage hello = factory.buildHello().build();
    sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(hello));

    List<OFMessage> msgs = getMessagesFromCapture();
    assertEquals(1, msgs.size());
    assertEquals(OFType.FEATURES_REQUEST, msgs.get(0).getType());
    verifyUniqueXids(msgs);

    assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.WaitFeaturesReplyState.class));
}
项目:iTAP-controller    文件:OFSwitchHandlerTestBase.java   
/** Move channel from scratch to WAIT_INITIAL_STATE, then MASTER,
 * then SLAVE for cases where the switch does not support roles.
 * I.e., the final SLAVE transition should disconnect the switch.
 */
@Test
public void testNoRoleInitialToMasterToSlave() throws Exception {
    int xid = 46;
    // First, lets move the state to MASTER without role support
    testInitialMoveToMasterNoRole();
    assertThat(switchHandler.getStateForTesting(),
            CoreMatchers.instanceOf(OFSwitchHandshakeHandler.MasterState.class));

    assertThat("Unexpected messages have been captured",
            connection.getMessages(),
             Matchers.empty());

    // try to set master role again. should be a no-op
    setupSwitchRoleChangeUnsupported(xid, OFControllerRole.ROLE_MASTER);
    assertThat(switchHandler.getStateForTesting(), CoreMatchers.instanceOf(OFSwitchHandshakeHandler.MasterState.class));

    assertThat("Unexpected messages have been captured",
            connection.getMessages(),
             Matchers.empty());

    setupSwitchRoleChangeUnsupported(xid, OFControllerRole.ROLE_SLAVE);
    assertThat(connection.isConnected(), equalTo(false));

    assertThat("Unexpected messages have been captured",
            connection.getMessages(),
             Matchers.empty());
}
项目:ysoserial-plus    文件:TestHarnessTest.java   
@Test
public void testHarnessClassLoaderFail() throws Exception {
    try {
        PayloadsTest.testPayload(ExecMockPayload.class, new Class[0]);
        Assert.fail("should have failed");
    } catch (AssertionError e) {
        Assert.assertThat(e.getMessage(), CoreMatchers.containsString("ClassNotFoundException"));
    }
}
项目:fresco_floodlight    文件:OFSwitchHandlerTestBase.java   
/**
 * Move the channel from scratch to WAIT_INITIAL_ROLE state via
 * WAIT_SWITCH_DRIVER_SUB_HANDSHAKE
 * Does extensive testing for the WAIT_SWITCH_DRIVER_SUB_HANDSHAKE state
 *
 */
@Test
public void testSwitchDriverSubHandshake()
        throws Exception {
    moveToWaitSwitchDriverSubHandshake();

    //-------------------------------------------------
    //-------------------------------------------------
    // Send a message to the handler, it should be passed to the
    // switch's sub-handshake handling. After this message the
    // sub-handshake will be complete
    // FIXME:LOJI: With Andi's fix for a default Match object we won't
    // need to build/set this match object

    Match match = factory.buildMatch().build();
    OFMessage m = factory.buildFlowRemoved().setMatch(match).build();
    resetToStrict(sw);
    sw.processDriverHandshakeMessage(m);
    expectLastCall().once();
    expect(sw.isDriverHandshakeComplete()).andReturn(true).once();
    replay(sw);

    switchHandler.processOFMessage(m);

    assertThat(switchHandler.getStateForTesting(),
            CoreMatchers.instanceOf(OFSwitchHandshakeHandler.WaitAppHandshakeState.class));
    assertThat("Unexpected message captured", connection.getMessages(), Matchers.empty());
    verify(sw);
}
项目:hadoop    文件:TestContainerLaunch.java   
@Test (timeout = 10000)
public void testWindowsShellScriptBuilderLink() throws IOException {
  // Test is only relevant on Windows
  Assume.assumeTrue(Shell.WINDOWS);

  String linkCmd = "@" +Shell.WINUTILS + " symlink \"\" \"\"";

  // The tests are built on assuming 8191 max command line length
  assertEquals(8191, Shell.WINDOWS_MAX_SHELL_LENGHT);

  ShellScriptBuilder builder = ShellScriptBuilder.create();

  // test link
  builder.link(new Path(org.apache.commons.lang.StringUtils.repeat("A", 1024)),
      new Path(org.apache.commons.lang.StringUtils.repeat("B", 1024)));
  builder.link(
      new Path(org.apache.commons.lang.StringUtils.repeat(
          "E", (Shell.WINDOWS_MAX_SHELL_LENGHT - linkCmd.length())/2)),
      new Path(org.apache.commons.lang.StringUtils.repeat(
          "F", (Shell.WINDOWS_MAX_SHELL_LENGHT - linkCmd.length())/2)));
  try {
    builder.link(
        new Path(org.apache.commons.lang.StringUtils.repeat(
            "X", (Shell.WINDOWS_MAX_SHELL_LENGHT - linkCmd.length())/2 + 1)),
        new Path(org.apache.commons.lang.StringUtils.repeat(
            "Y", (Shell.WINDOWS_MAX_SHELL_LENGHT - linkCmd.length())/2) + 1));
    fail("long link was expected to throw");
  } catch(IOException e) {
    assertThat(e.getMessage(), CoreMatchers.containsString(expectedMessage));
  }
}
项目:fresco_floodlight    文件:OFSwitchHandlerTestBase.java   
/** Move the channel to MASTER state
 * Expects that the channel is in MASTER or SLAVE state.
 *
 */
@SuppressWarnings("unchecked")
public void changeRoleToMasterWithRequest() throws Exception {
    assertTrue("This method can only be called when handler is in " +
            "MASTER or SLAVE role", switchHandler.isHandshakeComplete());

    // Set the role
    long xid = setupSwitchSendRoleRequestAndVerify(true, OFControllerRole.ROLE_MASTER);

    // prepare mocks and inject the role reply message
    reset(sw);
    expect(sw.getOFFactory()).andReturn(factory).anyTimes();
    expect(sw.write(anyObject(OFMessage.class))).andReturn(true).anyTimes();
    expect(sw.write(anyObject(Iterable.class))).andReturn(Collections.EMPTY_LIST).anyTimes();
    expect(sw.getNumTables()).andStubReturn((short)0);
    sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, true);
    expectLastCall().once();
    sw.setControllerRole(OFControllerRole.ROLE_MASTER);
    expectLastCall().once();
    expect(sw.getStatus()).andReturn(SwitchStatus.HANDSHAKE).once();
    sw.setStatus(SwitchStatus.MASTER);
    expectLastCall().once();
    expect(sw.getTables()).andReturn(Collections.EMPTY_LIST).once();
    replay(sw);

    reset(switchManager);
    switchManager.switchStatusChanged(sw, SwitchStatus.HANDSHAKE, SwitchStatus.MASTER);
    expectLastCall().once();
    replay(switchManager);

    OFMessage reply = getRoleReply(xid, OFControllerRole.ROLE_MASTER);

    switchHandler.processOFMessage(reply);

    assertThat(switchHandler.getStateForTesting(), CoreMatchers.instanceOf(OFSwitchHandshakeHandler.MasterState.class));
}
项目:fresco_floodlight    文件:OFSwitchHandshakeHandlerVer13Test.java   
public void handleDescStatsAndCreateSwitch() throws Exception {
    // build the stats reply
    OFDescStatsReply sr = createDescriptionStatsReply();

    reset(sw);
    SwitchDescription switchDescription = new SwitchDescription(sr);
    setupSwitchForInstantiationWithReset();
    sw.setPortDescStats(anyObject(OFPortDescStatsReply.class));
    expectLastCall().once();

    expect(sw.getOFFactory()).andReturn(factory).once();
    replay(sw);

    reset(switchManager);
    expect(switchManager.getHandshakePlugins()).andReturn(plugins).anyTimes();
    expect(
           switchManager.getOFSwitchInstance(anyObject(OFConnection.class),
                                          eq(switchDescription),
                                          anyObject(OFFactory.class),
                                          anyObject(DatapathId.class))).andReturn(sw).once();
    expect(switchManager.getNumRequiredConnections()).andReturn(1).anyTimes(); 
    switchManager.switchAdded(sw);
    expectLastCall().once();
    replay(switchManager);

    // send the description stats reply
    switchHandler.processOFMessage(sr);

    OFMessage msg = connection.retrieveMessage();
    assertThat(msg, CoreMatchers.instanceOf(OFTableFeaturesStatsRequest.class));
    verifyUniqueXids(msg);

    verify(sw, switchManager);
}
项目:iTAP-controller    文件:OFSwitchHandshakeHandlerVer10Test.java   
@Test
@Override
public void moveToWaitAppHandshakeState() throws Exception {
    moveToWaitDescriptionStatReply();
    handleDescStatsAndCreateSwitch(true);
    assertThat(switchHandler.getStateForTesting(),
            CoreMatchers.instanceOf(WaitAppHandshakeState.class));
}
项目:azeroth    文件:IDBuilderTest.java   
@Test
public void buildSequenceCounterOnly() {
    final byte[] result = IDBuilder.build(new Blueprint(0, 0x22, 0, 0));
    final byte[] sixthByte = new byte[] { result[5] };
    final String expected = "22";
    assertThat(Hex.encodeHexString(sixthByte), CoreMatchers.is(expected));
}
项目:jb-hub-client    文件:RtUserTest.java   
/**
 * RtUser return Request with path.
 * @throws Exception If fails
 */
@Test
public void path() throws Exception {
    final MkContainer container = new MkGrizzlyContainer()
        .next(
            new MkAnswer.Simple(
                HttpURLConnection.HTTP_OK,
                "{\"body\":\"hi\"}"
            )
        ).start();
    new RtUser(
        new JdkRequest(
            container.home()
        ),
        new RtUsers(
            new JdkRequest(
                container.home()
            ),
            new RtHub(
                new JdkRequest(
                    container.home()
                )
            )
        ),
        "101"
    ).json();
    container.stop();
    MatcherAssert.assertThat(
        container.take().uri(),
        CoreMatchers.equalTo(
            new URI("/101")
        )
    );
}
项目:GitHub    文件:RealmListTests.java   
@Test
public void removeAll_outsideTransaction() {
    List<Dog> objectsToRemove = Collections.singletonList(collection.get(0));
    thrown.expect(IllegalStateException.class);
    thrown.expectMessage(CoreMatchers.containsString("Objects can only be removed from inside a write transaction"));
    collection.removeAll(objectsToRemove);
}
项目:hashsdn-controller    文件:JmxAttributeValidationExceptionTest.java   
@Test
public void testJmxAttributeValidationExceptionElement() throws Exception {
    JmxAttribute attributeName = new JmxAttribute("attr_name");
    JmxAttributeValidationException jmxAttributeValidationException = new JmxAttributeValidationException(
            attributeName);
    assertThat(jmxAttributeValidationException.getAttributeNames(), CoreMatchers.hasItem(attributeName));
}
项目:GitHub    文件:LinkingObjectsManagedTests.java   
/**
 * Schema validation should fail if the backlinked column points to a non-existent field in the source class.
 */
@Test
public void migration_backlinkedSourceFieldDoesntExist() throws ClassNotFoundException {
    final String realmName = "backlinks-missingSourceField.realm";
    RealmConfiguration realmConfig = configFactory.createConfigurationBuilder()
            .name(realmName)
            .schema(BacklinksTarget.class, BacklinksSource.class)
            .build();

    // Mock the schema info so the only difference compared with the original schema is that the LinkingObject field
    // points to BacklinksSource.childNotExist.
    OsObjectSchemaInfo targetSchemaInfo = new OsObjectSchemaInfo.Builder("BacklinksTarget", 1, 1)
            .addPersistedProperty("id", RealmFieldType.INTEGER, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED)
            .addComputedLinkProperty("parents", "BacklinksSource", "childNotExist" /*"child" is the original value*/)
            .build();
    OsObjectSchemaInfo sourceSchemaInfo = new OsObjectSchemaInfo.Builder("BacklinksSource", 2, 0)
            .addPersistedProperty("name", RealmFieldType.STRING, !Property.PRIMARY_KEY, !Property.INDEXED, !Property.REQUIRED)
            .addPersistedLinkProperty("child", RealmFieldType.OBJECT, "BacklinksTarget")
            .build();
    Map<Class<? extends RealmModel>, OsObjectSchemaInfo> infoMap =
            new HashMap<Class<? extends RealmModel>, OsObjectSchemaInfo>();
    infoMap.put(BacklinksTarget.class, targetSchemaInfo);
    infoMap.put(BacklinksSource.class, sourceSchemaInfo);

    RealmProxyMediator mediator = spy(realmConfig.getSchemaMediator());
    when(mediator.getExpectedObjectSchemaInfoMap()).thenReturn(infoMap);
    RealmConfiguration spyConfig = spy(realmConfig);
    when(spyConfig.getSchemaMediator()).thenReturn(mediator);

    try {
        Realm localRealm = Realm.getInstance(spyConfig);
        localRealm.close();
        fail();
    } catch (IllegalStateException expected) {
        assertThat(expected.getMessage(), CoreMatchers.containsString(
                "Property 'BacklinksSource.childNotExist' declared as origin of linking objects property 'BacklinksTarget.parents' does not exist"
        ));
    }
}
项目:randomito-all    文件:TypeCreatorServiceTest.java   
@Test(expected = RandomitoException.class)
public void testCreateForType_exception() {
    // given
    Class<ClassWithNoDefConstructor> type = ClassWithNoDefConstructor.class;

    // when
    Object forType = service.createForType(this, type);

    // then
    Assert.assertThat(forType, CoreMatchers.is(CoreMatchers.notNullValue()));
    Assert.assertTrue(forType.getClass() == type);
}
项目:kafka-0.11.0.0-src-with-comment    文件:StoreChangelogReaderTest.java   
@Test
public void shouldIgnoreNullKeysWhenRestoring() throws Exception {
    assignPartition(3, topicPartition);
    final byte[] bytes = new byte[0];
    consumer.addRecord(new ConsumerRecord<>(topicPartition.topic(), topicPartition.partition(), 0, bytes, bytes));
    consumer.addRecord(new ConsumerRecord<>(topicPartition.topic(), topicPartition.partition(), 1, (byte[]) null, bytes));
    consumer.addRecord(new ConsumerRecord<>(topicPartition.topic(), topicPartition.partition(), 2, bytes, bytes));
    consumer.assign(Collections.singletonList(topicPartition));
    changelogReader.register(new StateRestorer(topicPartition, callback, null, Long.MAX_VALUE, false));
    changelogReader.restore();

    assertThat(callback.restored, CoreMatchers.equalTo(Utils.mkList(KeyValue.pair(bytes, bytes), KeyValue.pair(bytes, bytes))));
}
项目:word-clock-raspberry-pi-zero-neopixels    文件:WordClockTest.java   
@Test
public void testConcatMatrix() throws Exception {
    int[][] matrixA = new int[][]{
        {1,0,1},{0,1,0},{1,0,0}
    };
    int[][] matrixB = new int[][]{
        {1,1,0,0},{0,1,0,0},{1,1,1,1}
    };

    int[][]result = WordClock.concatMatrix(matrixA,matrixB);
    assertThat("Should have concatenated correctly",result.length,CoreMatchers.equalTo(3));
    assertThat("Should have concatenated correctly",result[0].length,CoreMatchers.equalTo(4));

    assertThat("Should have concatenated correctly",result[0][0],CoreMatchers.equalTo(1));
    assertThat("Should have concatenated correctly",result[0][1],CoreMatchers.equalTo(1));
    assertThat("Should have concatenated correctly",result[0][2],CoreMatchers.equalTo(1));
    assertThat("Should have concatenated correctly",result[0][3],CoreMatchers.equalTo(0));

    assertThat("Should have concatenated correctly",result[1][0],CoreMatchers.equalTo(0));
    assertThat("Should have concatenated correctly",result[1][1],CoreMatchers.equalTo(1));
    assertThat("Should have concatenated correctly",result[1][2],CoreMatchers.equalTo(0));
    assertThat("Should have concatenated correctly",result[1][3],CoreMatchers.equalTo(0));

    assertThat("Should have concatenated correctly",result[2][0],CoreMatchers.equalTo(1));
    assertThat("Should have concatenated correctly",result[2][1],CoreMatchers.equalTo(1));
    assertThat("Should have concatenated correctly",result[2][2],CoreMatchers.equalTo(1));
    assertThat("Should have concatenated correctly",result[2][3],CoreMatchers.equalTo(1));
}
项目:MathMax    文件:TokenizerTest.java   
@Test
public void testAdditionToken() {
    final String expression = "4 + 2";
    final List<Token> tokens = tokenizer.tokenize( expression );
    final List<Token> expectedTokens = ImmutableList.of(
            Token.createLiteral( 4 ),
            Token.createOperation( Operation.PLUS ),
            Token.createLiteral( 2 ) );
    Assert.assertThat( tokens, CoreMatchers.equalTo( expectedTokens ) );
}