Ejemplo n.º 1
0
  /**
   * Validates that the stage properly identifies when a message should be restored
   *
   * @throws Exception on error
   */
  @Test
  public void testRestoreMissingMessage() throws Exception {
    List<IMessageContext> msgs = new ArrayList<IMessageContext>();
    IMessageContext msg = EasyMock.createStrictMock(IMessageContext.class);
    msgs.add(msg);

    // isUpdate & does not need restorage == don't store!
    EasyMock.expect(msg.shouldReplaceStorage()).andReturn(false);
    EasyMock.expect(msg.isUpdate()).andReturn(true);
    EasyMock.replay(msg);
    List<IMessageContext> needsStorage = Itertools.filter(PartitionStoreStage.NEEDS_STORAGE, msgs);
    assertTrue(needsStorage.isEmpty());
    EasyMock.verify(msg);
    EasyMock.reset(msg);

    // should replace storage will bypass the other tests
    EasyMock.expect(msg.shouldReplaceStorage()).andReturn(true);
    EasyMock.replay(msg);
    needsStorage = Itertools.filter(PartitionStoreStage.NEEDS_STORAGE, msgs);
    assertEquals(1, needsStorage.size());
    EasyMock.verify(msg);
    EasyMock.reset(msg);

    // !isUpdate & no filepath & does not need restorage == store!
    EasyMock.expect(msg.shouldReplaceStorage()).andReturn(false);
    EasyMock.expect(msg.isUpdate()).andReturn(false);
    EasyMock.expect(msg.getStoreFileSubPath()).andReturn(null);
    EasyMock.replay(msg);
    needsStorage = Itertools.filter(PartitionStoreStage.NEEDS_STORAGE, msgs);
    assertEquals(1, needsStorage.size());
    EasyMock.verify(msg);
    EasyMock.reset(msg);
  }
Ejemplo n.º 2
0
  protected void assertGetIfNewerTest(
      ProgressAnswer progressAnswer, boolean expectedResult, int expectedSize) throws IOException {
    if (expectedResult) {
      verifyMock(progressAnswer, expectedSize);

      assertNotNull("check checksum is not null", checksumObserver.getActualChecksum());

      assertEquals(
          "compare checksums",
          "6b144b7285ffd6b0bc8300da162120b9",
          checksumObserver.getActualChecksum());

      // Now compare the contents of the artifact that was placed in
      // the repository with the contents of the artifact that was
      // retrieved from the repository.

      String sourceContent = FileUtils.fileRead(sourceFile);
      String destContent = FileUtils.fileRead(destFile);
      assertEquals(sourceContent, destContent);
    } else {
      verify(mockTransferListener);

      reset(mockTransferListener);

      assertNull("check checksum is null", checksumObserver.getActualChecksum());

      assertFalse(destFile.exists());
    }
  }
Ejemplo n.º 3
0
  @Test
  public final void testCreateOrUpdateDevice() throws IOException {
    DeviceDescription description =
        new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, HW, SW1, SN, CID);
    Capture<InternalDeviceEvent> message = new Capture<>();
    Capture<MessageSubject> subject = new Capture<>();
    Capture<Function<InternalDeviceEvent, byte[]>> encoder = new Capture<>();

    resetCommunicatorExpectingSingleBroadcast(message, subject, encoder);
    DeviceEvent event = deviceStore.createOrUpdateDevice(PID, DID1, description);
    assertEquals(DEVICE_ADDED, event.type());
    assertDevice(DID1, SW1, event.subject());
    verify(clusterCommunicator);
    assertInternalDeviceEvent(NID1, DID1, PID, description, message, subject, encoder);

    DeviceDescription description2 =
        new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, HW, SW2, SN, CID);
    resetCommunicatorExpectingSingleBroadcast(message, subject, encoder);
    DeviceEvent event2 = deviceStore.createOrUpdateDevice(PID, DID1, description2);
    assertEquals(DEVICE_UPDATED, event2.type());
    assertDevice(DID1, SW2, event2.subject());

    verify(clusterCommunicator);
    assertInternalDeviceEvent(NID1, DID1, PID, description2, message, subject, encoder);
    reset(clusterCommunicator);

    assertNull("No change expected", deviceStore.createOrUpdateDevice(PID, DID1, description2));
  }
  /** Test renaming of Players including checking events are raised */
  public void testPlayerNaming() throws RulesBrokenException {
    PlayerColor blue = new PlayerColor("Blue", Color.blue, 'b');
    Player p = new Player(blue, changeNo, mockConstraints);

    mockListener.playerRenamed(new PlayerEvent(p));
    mockListener.playerRenamed(new PlayerEvent(p));
    replay(mockListener);

    p.addPlayerListener(mockListener);

    // Check the default name works
    assertEquals(p.getName(), blue.toString());

    // Can we change it (and does the right event fire?)
    p.setName("BLAH");

    assertEquals(p.getName(), "BLAH");

    // Back to where we started (along with another event)
    p.resetName();

    assertEquals(p.getName(), blue.toString());

    // Check the remove works (the next setName shouldn't send an event)
    p.removePlayerListener(mockListener);

    p.setName("MORE BLAHS");

    verify(mockListener);
  }
Ejemplo n.º 5
0
  protected void fileRoundTripTesting() throws Exception {
    message("File round trip testing ...");

    int expectedSize = putFile();

    assertNotNull("check checksum is not null", checksumObserver.getActualChecksum());

    assertEquals(
        "compare checksums",
        "6b144b7285ffd6b0bc8300da162120b9",
        checksumObserver.getActualChecksum());

    checksumObserver = new ChecksumObserver();

    getFile(expectedSize);

    assertNotNull("check checksum is not null", checksumObserver.getActualChecksum());

    assertEquals(
        "compare checksums",
        "6b144b7285ffd6b0bc8300da162120b9",
        checksumObserver.getActualChecksum());

    // Now compare the conents of the artifact that was placed in
    // the repository with the contents of the artifact that was
    // retrieved from the repository.

    String sourceContent = FileUtils.fileRead(sourceFile);

    String destContent = FileUtils.fileRead(destFile);

    assertEquals(sourceContent, destContent);
  }
Ejemplo n.º 6
0
  @Test
  public void test_processGameFinished_haveTiles() throws Exception {
    final Dictionary dictionary = createDictionary();
    final TilesBank tilesBank = new TilesBank(editor.createTilesBankInfo());

    final ScribbleBoard board =
        new ScribbleBoard(
            settings, Arrays.asList(player1, player2, player3), tilesBank, dictionary);
    h1 = board.getPlayerHand(player1);
    h2 = board.getPlayerHand(player2);
    h3 = board.getPlayerHand(player3);

    h1.setTiles(tilesBank.getTiles(0, 3, 6, 9)); // abcd: 10 points - should be winner
    h2.setTiles(tilesBank.getTiles(9, 12, 15, 18)); // defg: 22 points
    h3.setTiles(tilesBank.getTiles(16, 17, 19, 20)); // ffgg: 26 points

    // we need increate player points to make it winner.
    final Method method =
        h3.getClass().getSuperclass().getDeclaredMethod("increasePoints", short.class);
    method.setAccessible(true);
    method.invoke(h3, (short) 1); // Player h3 has 1 points and other have 0 points.

    short[] ints = board.processGameFinished();
    assertEquals(3, ints.length);

    assertEquals(-10, ints[0]); // final points for h1: looser
    assertEquals(-22, ints[1]); // final points for h2: looser
    assertEquals(-26, ints[2]); // final points for h3: winned
  }
Ejemplo n.º 7
0
  @Test
  public void test_checkMove_pass() throws GameMoveException {
    final Dictionary dictionary = createDictionary("abcd", "def", "fefgabcd");
    final TilesBank tilesBank = new TilesBank(editor.createTilesBankInfo());
    final ScribbleBoard board =
        new ScribbleBoard(
            settings, Arrays.asList(player1, player2, player3), tilesBank, dictionary);
    h1 = board.getPlayerHand(player1);
    h2 = board.getPlayerHand(player2);
    h3 = board.getPlayerHand(player3);

    h1.setTiles(tilesBank.getTiles(0, 3, 6, 9, 12, 15, 18)); // abcdefg
    h2.setTiles(tilesBank.getTiles(1, 4, 7, 10, 13, 16, 19)); // abcdefg
    h3.setTiles(tilesBank.getTiles(2, 5, 8, 11, 14, 17, 20)); // abcdefg

    final Personality person = board.getPlayerTurn();
    final ScribblePlayerHand hand = board.getPlayerHand(person);
    board.passTurn(person);

    assertEquals(7, hand.getTiles().length);
    assertEquals(1, board.getGameMoves().size());
    assertEquals(PassTurn.class, board.getGameMoves().get(0).getClass());
    assertEquals(13, tilesBank.getTilesLimit());

    assertNotSame(hand, board.getPlayerTurn());
  }
  @Test
  public void testCompatibleExtensionTogetherSuccess() {
    // initialize
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("main")))
        .andReturn(mainExtensionMock)
        .anyTimes();
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("fallback")))
        .andReturn(null)
        .anyTimes();
    replay(mainHandshakerMock);

    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("fallback")))
        .andReturn(fallbackExtensionMock)
        .anyTimes();
    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("main")))
        .andReturn(null)
        .anyTimes();
    replay(fallbackHandshakerMock);

    expect(mainExtensionMock.rsv()).andReturn(WebSocketExtension.RSV1).anyTimes();
    expect(mainExtensionMock.newReponseData())
        .andReturn(new WebSocketExtensionData("main", Collections.<String, String>emptyMap()))
        .once();
    expect(mainExtensionMock.newExtensionEncoder()).andReturn(new DummyEncoder()).once();
    expect(mainExtensionMock.newExtensionDecoder()).andReturn(new DummyDecoder()).once();
    replay(mainExtensionMock);

    expect(fallbackExtensionMock.rsv()).andReturn(WebSocketExtension.RSV2).anyTimes();
    expect(fallbackExtensionMock.newReponseData())
        .andReturn(new WebSocketExtensionData("fallback", Collections.<String, String>emptyMap()))
        .once();
    expect(fallbackExtensionMock.newExtensionEncoder()).andReturn(new Dummy2Encoder()).once();
    expect(fallbackExtensionMock.newExtensionDecoder()).andReturn(new Dummy2Decoder()).once();
    replay(fallbackExtensionMock);

    // execute
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new WebSocketServerExtensionHandler(mainHandshakerMock, fallbackHandshakerMock));

    HttpRequest req = newUpgradeRequest("main, fallback");
    ch.writeInbound(req);

    HttpResponse res = newUpgradeResponse(null);
    ch.writeOutbound(res);

    HttpResponse res2 = ch.readOutbound();
    List<WebSocketExtensionData> resExts =
        WebSocketExtensionUtil.extractExtensions(
            res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));

    // test
    assertEquals(2, resExts.size());
    assertEquals("main", resExts.get(0).name());
    assertEquals("fallback", resExts.get(1).name());
    assertNotNull(ch.pipeline().get(DummyDecoder.class));
    assertNotNull(ch.pipeline().get(DummyEncoder.class));
    assertNotNull(ch.pipeline().get(Dummy2Decoder.class));
    assertNotNull(ch.pipeline().get(Dummy2Encoder.class));
  }
Ejemplo n.º 9
0
  @Test
  public void testConstructor() {
    int tickLengthUnit = Calendar.DAY_OF_MONTH;
    int tickLength = 1;

    IMocksControl control = createControl();

    GregorianCalendar startDateMock = control.createMock(GregorianCalendar.class);
    GregorianCalendar startDateCloneMock = control.createMock(GregorianCalendar.class);
    expect(startDateMock.clone()).andReturn(startDateCloneMock).once();

    EventBus eventBusMock = control.createMock(EventBus.class);

    control.replay();

    TimeManagerImpl manager =
        new TimeManagerImpl(startDateMock, tickLengthUnit, tickLength, eventBusMock);

    assertSame(startDateMock, manager.getStartDate());
    assertEquals(tickLengthUnit, manager.getTickLengthUnit());
    assertEquals(tickLength, manager.getTickLength());
    assertNotSame(startDateMock, manager.getCurrentDate());
    assertSame(startDateCloneMock, manager.getCurrentDate());

    control.verify();
  }
Ejemplo n.º 10
0
 @Test
 public void testGetRoleInfoDefault() {
   RoleInfo info = controller.getRoleInfo();
   assertEquals(HARole.ACTIVE, info.getRole());
   assertNotNull(info.getRoleChangeDescription());
   assertEquals(HARole.ACTIVE, controller.getRole());
   // FIXME: RoleInfo's date. but the format is kinda broken
 }
Ejemplo n.º 11
0
 private static void assertDevice(DeviceId id, String swVersion, Device device) {
   assertNotNull(device);
   assertEquals(id, device.id());
   assertEquals(MFR, device.manufacturer());
   assertEquals(HW, device.hwVersion());
   assertEquals(swVersion, device.swVersion());
   assertEquals(SN, device.serialNumber());
 }
Ejemplo n.º 12
0
 @Test
 public void testNewCalendar() {
   DocumentReference calDocRef =
       new DocumentReference(context.getDatabase(), "mySpace", "myCalDoc");
   cal = new Calendar(calDocRef, isArchiv);
   assertEquals(calDocRef, cal.getDocumentReference());
   assertEquals(isArchiv, cal.isArchive());
 }
Ejemplo n.º 13
0
  @Test
  public void get() {
    assertEquals(111, context.get("pull1"));
    assertEquals(222, context.get("pull2"));
    assertEquals(333, context.get("parent"));
    assertEquals(444, context.get("child"));

    assertEquals(null, context.get("other"));
  }
Ejemplo n.º 14
0
 @Test
 public void testProjectData() {
   ProjectTO projTO = new ProjectTO(project);
   projectAction.setProjectId(project.getId());
   expect(projectBusiness.getProjectData(project.getId())).andReturn(projTO);
   replayAll();
   assertEquals(Action.SUCCESS, projectAction.projectData());
   assertEquals(projTO, projectAction.getProject());
   verifyAll();
 }
Ejemplo n.º 15
0
  @Test
  public final void testGetDeviceCount() {
    assertEquals("initialy empty", 0, deviceStore.getDeviceCount());

    putDevice(DID1, SW1);
    putDevice(DID2, SW2);
    putDevice(DID1, SW1);

    assertEquals("expect 2 uniq devices", 2, deviceStore.getDeviceCount());
  }
Ejemplo n.º 16
0
 /**
  * Verifies that Annotations created by merging {@code annotations} is equal to actual
  * Annotations.
  *
  * @param actual Annotations to check
  * @param annotations
  */
 private static void assertAnnotationsEquals(
     Annotations actual, SparseAnnotations... annotations) {
   SparseAnnotations expected = DefaultAnnotations.builder().build();
   for (SparseAnnotations a : annotations) {
     expected = DefaultAnnotations.union(expected, a);
   }
   assertEquals(expected.keys(), actual.keys());
   for (String key : expected.keys()) {
     assertEquals(expected.value(key), actual.value(key));
   }
 }
 @Test
 public void testGetFieldInheritor() {
   String className = "TestClassName";
   List<String> docList = new ArrayList<String>();
   docList.add("my.Doc");
   docList.add("my.Doc2");
   FieldInheritor inheritor = _factory.getFieldInheritor(className, docList, _context);
   XObjectIterator iterator = inheritor.getIteratorFactory().createIterator();
   assertEquals(className, iterator.getClassName());
   assertEquals(docList, iterator.getDocListCopy());
 }
 private void verifyActions(OFFlowMod testFlowMod, OFFlowMod goodFlowMod) {
   List<OFAction> goodActions = goodFlowMod.getActions();
   List<OFAction> testActions = testFlowMod.getActions();
   assertNotNull(goodActions);
   assertNotNull(testActions);
   assertEquals(goodActions.size(), testActions.size());
   // assumes actions are marshalled in same order; should be safe
   for (int i = 0; i < goodActions.size(); i++) {
     assertEquals(goodActions.get(i), testActions.get(i));
   }
 }
Ejemplo n.º 19
0
  private void assertPortDescriptionEquals(
      PortDescription expectedDesc,
      List<SparseAnnotations> expectedAnnotations,
      PortDescription actual) {

    assertEquals(expectedDesc.portNumber(), actual.portNumber());
    assertEquals(expectedDesc.isEnabled(), actual.isEnabled());

    assertAnnotationsEquals(
        actual.annotations(), expectedAnnotations.toArray(new SparseAnnotations[0]));
  }
 @Test
 public void testGetPageLayoutInheritor() {
   String className = "Celements2.PageType";
   String fullName = "mySpace.myDoc";
   List<String> docList = new ArrayList<String>();
   docList.add(fullName);
   docList.add("mySpace.WebPreferences");
   docList.add("XWiki.XWikiPreferences");
   FieldInheritor inheritor = _factory.getPageLayoutInheritor(fullName, _context);
   XObjectIterator iterator = inheritor.getIteratorFactory().createIterator();
   assertEquals(className, iterator.getClassName());
   assertEquals(docList, iterator.getDocListCopy());
 }
Ejemplo n.º 21
0
  private static void assertDeviceDescriptionEquals(
      DeviceDescription expected, DeviceDescription actual) {
    if (expected == actual) {
      return;
    }
    assertEquals(expected.deviceURI(), actual.deviceURI());
    assertEquals(expected.hwVersion(), actual.hwVersion());
    assertEquals(expected.manufacturer(), actual.manufacturer());
    assertEquals(expected.serialNumber(), actual.serialNumber());
    assertEquals(expected.swVersion(), actual.swVersion());

    assertAnnotationsEquals(actual.annotations(), expected.annotations());
  }
Ejemplo n.º 22
0
  @Test
  /* This test tests internal working of the class alone */
  public void testCreateInterface() {
    vr.createInterface("if1", "netVirt1", null, true);
    assertNotNull(vr.getInterfaceMap().get("if1"));
    assertEquals(true, vr.getInterfaceMap().get("if1").isNetVirt());

    vr.createInterface("if2", null, "rtr1", true);
    assertNotNull(vr.getInterfaceMap().get("if2"));
    assertEquals(false, vr.getInterfaceMap().get("if2").isNetVirt());

    assertEquals(2, vr.getInterfaceMap().size());
  }
Ejemplo n.º 23
0
  @Test
  public void testProjectMetrics() {
    ProjectMetrics metrics = new ProjectMetrics();
    projectAction.setProjectId(project.getId());
    expect(projectBusiness.retrieve(project.getId())).andReturn(project);
    expect(projectBusiness.getProjectMetrics(project)).andReturn(metrics);
    replayAll();

    assertEquals(Action.SUCCESS, projectAction.projectMetrics());
    assertEquals(metrics, projectAction.getProjectMetrics());

    verifyAll();
  }
Ejemplo n.º 24
0
  /*
   * Note: The following tests on the gateway pool/node related APIs in
   * VirutalRouterImpl class ensure only that the IGatewayPool API usage is
   * correct. It does not cover in detail the test cases for the IGatewayPool
   * APIs. Please refer GatewayPoolTest.java for detailed tests on the
   * IGatewayPool interface.
   */
  @Test
  public void testCreateGatewayPool() {
    String gatewayPoolName1 = "testGatewayPool1";
    vr.createGatewayPool(gatewayPoolName1);
    GatewayPoolImpl gatewayPool1 = vr.getGatewayPool(gatewayPoolName1);
    assertNotNull(gatewayPool1);
    assertEquals("testGatewayPool1", gatewayPool1.getName());

    String gatewayPoolName2 = "testGatewayPool2";
    vr.createGatewayPool(gatewayPoolName2);
    GatewayPoolImpl gatewayPool2 = vr.getGatewayPool(gatewayPoolName2);
    assertNotNull(gatewayPool2);
    assertEquals("testGatewayPool2", gatewayPool2.getName());
  }
  @Test
  public void testRegisterVerify() throws Exception {
    TestUser user = new TestUser();
    user.setUsername("*****@*****.**");
    assertEquals(
        RegisterResult.PENDING,
        userService.register(user, "password", "http://www.example.com/verify-email"));
    assertFalse(user.isPartial());
    assertEquals(1, user.getRoles().size());
    assertNotNull(user.getRoles().iterator().next());

    Email email = EmailTestHelper.getEmailResults().poll();
    assertTrue(
        email.getHtml().contains("http://www.example.com/verify-email?guid=" + user.getGuid()));
  }
  /** Test of getAudit method, of class AuditServiceThreadImpl. */
  public void testGetAudit() {
    System.out.println("getAudit");

    Audit audit = createMock(Audit.class);
    Audit auditReturnedByAuditCommand = createMock(Audit.class);
    AuditCommand mockAuditCommand = createMock(AuditCommand.class);
    expect(mockAuditCommand.getAudit()).andReturn(auditReturnedByAuditCommand);
    replay(mockAuditCommand);

    AuditServiceThreadImpl instance = initialiseAuditServiceThread(audit);
    assertEquals(audit, instance.getAudit());

    instance = initialiseAuditServiceThread(mockAuditCommand);
    assertEquals(auditReturnedByAuditCommand, instance.getAudit());
  }
Ejemplo n.º 27
0
  @Test
  public void testDelete_success() {
    Project proj = new Project();
    Product parent = new Product();
    parent.setId(123);
    proj.setParent(parent);

    expect(projectBusiness.retrieve(1)).andReturn(proj);
    projectBusiness.delete(1);
    replayAll();
    projectAction.setConfirmationString("yes");
    assertEquals(Action.SUCCESS, projectAction.delete());
    assertEquals(123, projectAction.getProductId());
    verifyAll();
  }
  @Test
  public void typedCharactersAppearInResultSequence() {

    typeCharacter('a');

    assertEquals("a", recorderUnderTest.getResult().getCapturedValue());

    typeCharacter('a');

    assertEquals("aa", recorderUnderTest.getResult().getCapturedValue());

    typeCharacter('a');

    assertEquals("aaa", recorderUnderTest.getResult().getCapturedValue());
  }
  private void invoke(boolean extendToInterfaces) throws NoSuchMethodException, Throwable {
    FilterService fs = createMock(FilterService.class);
    IService service = createMock(IService.class);

    // expect
    int paramValue = 10;
    Object retValue = new Object();
    Method method = IService.class.getDeclaredMethod("test0", int.class);
    expect(fs.invoke(service, extendToInterfaces, method, paramValue)).andReturn(retValue);

    // replay
    replay(service, fs);

    // test
    FilterInterceptor fi = new FilterInterceptor();
    fi.setFilterService(fs);
    fi.setExtendToInterfaces(extendToInterfaces);
    MethodInvocation mi = new TestMethodInvocation(service, method, new Object[] {paramValue});
    Object ret = fi.invoke(mi);

    // check
    verify(service, fs);
    assertNotNull("Result must not be null", ret);
    assertEquals("FilterService must be called", retValue, ret);
  }
Ejemplo n.º 30
0
  /** TEST FORCE DELETING */
  @Test
  public void testForceDelete() {
    Story story = new Story();
    story.setId(1);

    Story child = new Story();
    child.setParent(story);
    story.setChildren(new ArrayList<Story>(Arrays.asList(child)));

    story.setTasks(new HashSet<Task>(Arrays.asList(new Task(), new Task())));
    story.setHourEntries(
        new HashSet<StoryHourEntry>(
            Arrays.asList(new StoryHourEntry(), new StoryHourEntry(), new StoryHourEntry())));

    taskBusiness.delete(EasyMock.isA(Task.class), EasyMock.same(HourEntryHandlingChoice.DELETE));
    expectLastCall().times(2);

    hourEntryBusiness.deleteAll(story.getHourEntries());

    storyDAO.remove(1);

    replayAll();
    storyBusiness.forceDelete(story);
    verifyAll();

    assertNull("Child story's parent not null", child.getParent());
    assertEquals("Parent story's children not empty", 0, story.getChildren().size());
  }