java类org.hamcrest.CoreMatchers的实例源码

UIAnimatorTest.java 文件源码 项目:Expert-Android-Programming 阅读 33 收藏 0 点赞 0 评论 0
@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);
}
TestContainerLaunch.java 文件源码 项目:hadoop 阅读 30 收藏 0 点赞 0 评论 0
@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));
  }
}
InputTypeFinderTest.java 文件源码 项目:incap 阅读 25 收藏 0 点赞 0 评论 0
@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"));
}
OFSwitchHandlerTestBase.java 文件源码 项目:iTAP-controller 阅读 35 收藏 0 点赞 0 评论 0
/**
 * 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));
}
InputTypeFinderTest.java 文件源码 项目:incap 阅读 27 收藏 0 点赞 0 评论 0
@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"));
}
SyncedRealmTests.java 文件源码 项目:GitHub 阅读 32 收藏 0 点赞 0 评论 0
@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();
        }
    }
}
RealmMigrationTests.java 文件源码 项目:GitHub 阅读 26 收藏 0 点赞 0 评论 0
@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>'"));
    }
}
RealmObjectSchemaTests.java 文件源码 项目:GitHub 阅读 25 收藏 0 点赞 0 评论 0
@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);
    }
}
OFChannelHandlerVer13Test.java 文件源码 项目:iTAP-controller 阅读 30 收藏 0 点赞 0 评论 0
@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);
}
RtUsersTest.java 文件源码 项目:jb-hub-client 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 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
        )
    );
}
MainActivityTest.java 文件源码 项目:android-architecture-components 阅读 40 收藏 0 点赞 0 评论 0
@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));
}
RtUserTest.java 文件源码 项目:jb-hub-client 阅读 30 收藏 0 点赞 0 评论 0
/**
 * 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
        )
    );
}
JSONLDTestUtil.java 文件源码 项目:com-liferay-apio-architect 阅读 30 收藏 0 点赞 0 评论 0
/**
 * 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)));
}
OFChannelHandlerVer13Test.java 文件源码 项目:iTAP-controller 阅读 48 收藏 0 点赞 0 评论 0
/** 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));
}
BlobPullerIntegrationTest.java 文件源码 项目:minikube-build-tools-for-java 阅读 27 收藏 0 点赞 0 评论 0
@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));
  }
}
AuthenticationMethodRetrieverTest.java 文件源码 项目:minikube-build-tools-for-java 阅读 24 收藏 0 点赞 0 评论 0
@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"));
  }
}
DmBuildInfoTest.java 文件源码 项目:document-management-store-app 阅读 29 收藏 0 点赞 0 评论 0
@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));
}
GeoPointFieldMapperTests.java 文件源码 项目:elasticsearch_my 阅读 30 收藏 0 点赞 0 评论 0
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));
}
TypeCreatorServiceTest.java 文件源码 项目:randomito-all 阅读 20 收藏 0 点赞 0 评论 0
@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);
}
QueueRunnerFactoryTest.java 文件源码 项目:db-queue 阅读 34 收藏 0 点赞 0 评论 0
@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));
}
PixelChannelTest.java 文件源码 项目:word-clock-raspberry-pi-zero-neopixels 阅读 33 收藏 0 点赞 0 评论 0
@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));
}
AnnotationUtilTest.java 文件源码 项目:vind 阅读 39 收藏 0 点赞 0 评论 0
@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));
}
RtUsersTest.java 文件源码 项目:jb-hub-client 阅读 24 收藏 0 点赞 0 评论 0
/**
 * 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"
            )
        )
    );
}
OFChannelHandlerVer10Test.java 文件源码 项目:fresco_floodlight 阅读 34 收藏 0 点赞 0 评论 0
/** 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));
}
OFSwitchHandlerTestBase.java 文件源码 项目:iTAP-controller 阅读 44 收藏 0 点赞 0 评论 0
/** 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());
}
TestHarnessTest.java 文件源码 项目:ysoserial-plus 阅读 32 收藏 0 点赞 0 评论 0
@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"));
    }
}
OFSwitchHandlerTestBase.java 文件源码 项目:fresco_floodlight 阅读 41 收藏 0 点赞 0 评论 0
/**
 * 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);
}
TestContainerLaunch.java 文件源码 项目:hadoop 阅读 52 收藏 0 点赞 0 评论 0
@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));
  }
}
OFSwitchHandlerTestBase.java 文件源码 项目:fresco_floodlight 阅读 37 收藏 0 点赞 0 评论 0
/** 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));
}
OFSwitchHandshakeHandlerVer13Test.java 文件源码 项目:fresco_floodlight 阅读 33 收藏 0 点赞 0 评论 0
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);
}


问题


面经


文章

微信
公众号

扫码关注公众号