public void testPlayerComparing() throws RulesBrokenException {
    PlayerColor blue = new PlayerColor("Blue", Color.blue, 'b');
    PlayerColor green = new PlayerColor("Green", Color.green, 'g');

    Player pB = new Player(blue, changeNo, mockConstraints);
    Player pG = new Player(green, changeNo, mockConstraints);

    // sanity check
    assertTrue(pB.compareTo(pB) == 0);
    assertTrue(pG.compareTo(pG) == 0);
    assertTrue(pB.compareTo(pG) != 0);
    assertTrue(pG.compareTo(pB) != 0);

    // Give Blue some points
    pB.setVP(3);

    // Now Green should be less than Blue
    assertTrue(pB.compareTo(pG) < 0);
    assertTrue(pG.compareTo(pB) > 0);

    // Put Green ahead;
    pG.setVP(4);

    // Now Green should be more than Blue
    assertTrue(pB.compareTo(pG) > 0);
    assertTrue(pG.compareTo(pB) < 0);

    // Catch Blue up:
    pB.setVP(4);

    // Green should still be ahead (as they got there first);
    assertTrue(pB.compareTo(pG) > 0);
    assertTrue(pG.compareTo(pB) < 0);
  }
  public void testConnectionFailure() throws Exception {
    // create mock objects that will simulate a connection failure
    GSSClient client = createMock(GSSClient.class);
    expect(client.getCentralRevision((QName) anyObject()))
        .andThrow(new IOException("Host unreachable"));
    replay(client);
    GSSClientFactory factory = createMock(GSSClientFactory.class);
    expect(factory.createClient(new URL("http://localhost:8081/geoserver/ows"), null, null))
        .andReturn(client);
    replay(factory);

    synch.clientFactory = factory;

    // perform synch
    Date start = new Date();
    synch.synchronizeOustandlingLayers();
    Date end = new Date();

    // check we stored the last failure marker
    SimpleFeature f =
        getSingleFeature(fsUnitTables, ff.equal(ff.property("table_id"), ff.literal(1), false));
    Date lastFailure = (Date) f.getAttribute("last_failure");
    assertNotNull(lastFailure);
    assertTrue(lastFailure.compareTo(start) >= 0 && lastFailure.compareTo(end) <= 0);

    // check we marked the unit as failed
    f = getSingleFeature(fsUnits, ff.equal(ff.property("unit_name"), ff.literal("unit1"), false));
    assertTrue((Boolean) f.getAttribute("errors"));
  }
Esempio n. 3
0
  @Test
  public final void testMarkOffline() {

    putDevice(DID1, SW1);
    assertTrue(deviceStore.isAvailable(DID1));

    Capture<InternalDeviceEvent> message = new Capture<>();
    Capture<MessageSubject> subject = new Capture<>();
    Capture<Function<InternalDeviceEvent, byte[]>> encoder = new Capture<>();

    resetCommunicatorExpectingSingleBroadcast(message, subject, encoder);
    DeviceEvent event = deviceStore.markOffline(DID1);
    assertEquals(DEVICE_AVAILABILITY_CHANGED, event.type());
    assertDevice(DID1, SW1, event.subject());
    assertFalse(deviceStore.isAvailable(DID1));
    verify(clusterCommunicator);
    // TODO: verify broadcast message
    assertTrue(message.hasCaptured());

    resetCommunicatorExpectingNoBroadcast(message, subject, encoder);
    DeviceEvent event2 = deviceStore.markOffline(DID1);
    assertNull("No change, no event", event2);
    verify(clusterCommunicator);
    assertFalse(message.hasCaptured());
  }
Esempio n. 4
0
 /**
  * Test that point features are rendered at the expected image coordinates when the map is
  * rotated. StreamingRenderer
  *
  * @throws Exception
  */
 @Test
 public void testRotatedTransform() throws Exception {
   // If we rotate the world rectangle + 90 degrees around (0,0), we get the screen rectangle
   final Rectangle screen = new Rectangle(0, 0, 100, 50);
   final Envelope world = new Envelope(0, 50, 0, -100);
   final AffineTransform worldToScreen =
       AffineTransform.getRotateInstance(Math.toRadians(90), 0, 0);
   DefaultFeatureCollection fc = new DefaultFeatureCollection();
   fc.add(createPoint(0, 0));
   fc.add(createPoint(world.getMaxX(), world.getMinY()));
   MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
   mapContext.addLayer((FeatureCollection) fc, createPointStyle());
   BufferedImage image =
       new BufferedImage(screen.width, screen.height, BufferedImage.TYPE_4BYTE_ABGR);
   final StreamingRenderer sr = new StreamingRenderer();
   sr.setContext(mapContext);
   sr.paint(image.createGraphics(), screen, worldToScreen);
   assertTrue("Pixel should be drawn at 0,0 ", image.getRGB(0, 0) != 0);
   assertTrue(
       "Pixel should not be drawn in image centre ",
       image.getRGB(screen.width / 2, screen.height / 2) == 0);
   assertTrue(
       "Pixel should be drawn at image max corner ",
       image.getRGB(screen.width - 1, screen.height - 1) != 0);
 }
Esempio n. 5
0
  public void testReportExporting() {
    String siteId = null;
    Report r = null;
    ReportParams rp = null;
    List<String> totalsBy = null;

    siteId = FakeData.SITE_A_ID;
    ReportDef rd = new ReportDef();
    rd.setId(0);
    rd.setSiteId(siteId);
    rd.setCreatedBy(FakeData.USER_A_ID);
    rd.setModifiedBy(FakeData.USER_A_ID);
    rd.setTitle("Title 1");
    rp = new ReportParams(siteId);
    rp.setWhat(ReportManager.WHAT_RESOURCES);
    rp.setWhen(ReportManager.WHEN_ALL);
    rp.setWho(ReportManager.WHO_ALL);
    totalsBy = new ArrayList<String>();
    totalsBy.add(StatsManager.T_SITE);
    totalsBy.add(StatsManager.T_USER);
    rp.setHowTotalsBy(totalsBy);
    rp.setHowSort(false);
    rp.setHowPresentationMode(ReportManager.HOW_PRESENTATION_TABLE);
    rd.setReportParams(rp);
    Report report = M_rm.getReport(rd, false);
    assertNotNull(report);

    // CSV
    String csv = M_rm.getReportAsCsv(report);
    assertNotNull(csv);
    assertTrue(csv.length() > 0);

    // EXCEL
    byte[] excel = M_rm.getReportAsExcel(report, "sheetname");
    assertNotNull(excel);
    assertTrue(excel.length > 0);
    // To verify locally...
    //		File file = new File("d:/sitestats-test.xls");
    //		if(file.exists()) {file.delete();}
    //		FileOutputStream out = null;
    //		try{
    //			out = new FileOutputStream(file);
    //			out.write(excel);
    //			out.flush();
    //		}catch(FileNotFoundException e){
    //			e.printStackTrace();
    //		}catch(IOException e){
    //			e.printStackTrace();
    //		}finally{
    //			if(out != null) {
    //				try{ out.close(); }catch(IOException e){ /* IGNORE */}
    //			}
    //		}

    // PDF: currently disabled due to classloading trouble
    //		byte[] pdf = M_rm.getReportAsPDF(report);
    //		assertNotNull(pdf);
    //		assertTrue(pdf.length > 0);
  }
 @Test
 public void testGetStartDate() {
   Date startDateBefore = new Date();
   cal = new Calendar(calDocRef, isArchiv);
   Date startDateAfter = new Date();
   assertTrue(startDateBefore.compareTo(cal.getStartDate()) <= 0);
   assertTrue(startDateAfter.compareTo(cal.getStartDate()) >= 0);
 }
 @Test
 public void shouldReturnReadOnlyDerivedBuffer() {
   ByteBuf buf = Unpooled.unmodifiableBuffer(Unpooled.buffer(1));
   assertTrue(buf.duplicate() instanceof ReadOnlyByteBuf);
   assertTrue(buf.slice() instanceof ReadOnlyByteBuf);
   assertTrue(buf.slice(0, 1) instanceof ReadOnlyByteBuf);
   assertTrue(buf.duplicate() instanceof ReadOnlyByteBuf);
 }
 @Test
 public void shouldReturnReadOnlyDerivedBuffer() {
   ChannelBuffer buf = ChannelBuffers.unmodifiableBuffer(ChannelBuffers.buffer(1));
   assertTrue(buf.duplicate() instanceof ReadOnlyChannelBuffer);
   assertTrue(buf.slice() instanceof ReadOnlyChannelBuffer);
   assertTrue(buf.slice(0, 1) instanceof ReadOnlyChannelBuffer);
   assertTrue(buf.duplicate() instanceof ReadOnlyChannelBuffer);
 }
  @Test
  public void containsKey() {
    assertTrue(context.containsKey("pull1"));
    assertTrue(context.containsKey("pull2"));
    assertTrue(context.containsKey("parent"));
    assertTrue(context.containsKey("child"));

    assertFalse(context.containsKey("other"));
  }
  @Test
  public void supportedParameters() throws Exception {
    // Only @ModelAttribute arguments
    assertTrue(processor.supportsParameter(paramNamedValidModelAttr));
    assertTrue(processor.supportsParameter(paramModelAttr));

    assertFalse(processor.supportsParameter(paramErrors));
    assertFalse(processor.supportsParameter(paramInt));
    assertFalse(processor.supportsParameter(paramNonSimpleType));
  }
  @Test
  public void shouldForwardReadCallsBlindly() throws Exception {
    ChannelBuffer buf = createStrictMock(ChannelBuffer.class);
    expect(buf.readerIndex()).andReturn(0).anyTimes();
    expect(buf.writerIndex()).andReturn(0).anyTimes();
    expect(buf.capacity()).andReturn(0).anyTimes();

    expect(buf.getBytes(1, (GatheringByteChannel) null, 2)).andReturn(3);
    buf.getBytes(4, (OutputStream) null, 5);
    buf.getBytes(6, (byte[]) null, 7, 8);
    buf.getBytes(9, (ChannelBuffer) null, 10, 11);
    buf.getBytes(12, (ByteBuffer) null);
    expect(buf.getByte(13)).andReturn(Byte.valueOf((byte) 14));
    expect(buf.getShort(15)).andReturn(Short.valueOf((short) 16));
    expect(buf.getUnsignedMedium(17)).andReturn(18);
    expect(buf.getInt(19)).andReturn(20);
    expect(buf.getLong(21)).andReturn(22L);

    ByteBuffer bb = ByteBuffer.allocate(100);
    ByteBuffer[] bbs = {ByteBuffer.allocate(101), ByteBuffer.allocate(102)};

    expect(buf.toByteBuffer(23, 24)).andReturn(bb);
    expect(buf.toByteBuffers(25, 26)).andReturn(bbs);
    expect(buf.capacity()).andReturn(27);

    replay(buf);

    ChannelBuffer roBuf = unmodifiableBuffer(buf);
    assertEquals(3, roBuf.getBytes(1, (GatheringByteChannel) null, 2));
    roBuf.getBytes(4, (OutputStream) null, 5);
    roBuf.getBytes(6, (byte[]) null, 7, 8);
    roBuf.getBytes(9, (ChannelBuffer) null, 10, 11);
    roBuf.getBytes(12, (ByteBuffer) null);
    assertEquals((byte) 14, roBuf.getByte(13));
    assertEquals((short) 16, roBuf.getShort(15));
    assertEquals(18, roBuf.getUnsignedMedium(17));
    assertEquals(20, roBuf.getInt(19));
    assertEquals(22L, roBuf.getLong(21));

    ByteBuffer roBB = roBuf.toByteBuffer(23, 24);
    assertEquals(100, roBB.capacity());
    assertTrue(roBB.isReadOnly());

    ByteBuffer[] roBBs = roBuf.toByteBuffers(25, 26);
    assertEquals(2, roBBs.length);
    assertEquals(101, roBBs[0].capacity());
    assertTrue(roBBs[0].isReadOnly());
    assertEquals(102, roBBs[1].capacity());
    assertTrue(roBBs[1].isReadOnly());
    assertEquals(27, roBuf.capacity());

    verify(buf);
  }
  @Test
  public void supportedParametersInDefaultResolutionMode() throws Exception {
    processor = new ModelAttributeMethodProcessor(true);

    // Only non-simple types, even if not annotated
    assertTrue(processor.supportsParameter(paramNamedValidModelAttr));
    assertTrue(processor.supportsParameter(paramErrors));
    assertTrue(processor.supportsParameter(paramModelAttr));
    assertTrue(processor.supportsParameter(paramNonSimpleType));

    assertFalse(processor.supportsParameter(paramInt));
  }
 @Test
 public void shouldFindChangedFiles() throws IOException {
   Set<File> files = detector.findChangedFiles();
   assertTrue("Should have found changed files on first run", files.size() > 0);
   assertThat(
       "TestFakeProduct should be in changed list",
       files,
       hasItem(getFileForClass(TestFakeProduct.class)));
   assertTrue(
       "FakeProduct should be in changed list",
       files.contains(getFileForClass(FakeProduct.class)));
   assertTrue("Should have no changed files now", detector.findChangedFiles().isEmpty());
 }
Esempio n. 14
0
  /**
   * Test {@link Wagon#getFileList(String)}.
   *
   * @throws Exception
   * @since 1.0-beta-2
   */
  public void testWagonGetFileList() throws Exception {
    setupRepositories();

    setupWagonTestingFixtures();

    String dirName = "file-list";

    String filenames[] =
        new String[] {
          "test-resource.txt",
          "test-resource.pom",
          "test-resource b.txt",
          "more-resources.dat",
          ".index.txt"
        };

    for (String filename : filenames) {
      putFile(dirName + "/" + filename, dirName + "/" + filename, filename + "\n");
    }

    Wagon wagon = getWagon();

    wagon.connect(testRepository, getAuthInfo());

    List<String> list = wagon.getFileList(dirName);
    assertNotNull("file list should not be null.", list);
    assertTrue(
        "file list should contain more items (actually contains '" + list + "').",
        list.size() >= filenames.length);

    for (String filename : filenames) {
      assertTrue("Filename '" + filename + "' should be in list.", list.contains(filename));
    }

    // WAGON-250
    list = wagon.getFileList("");
    assertNotNull("file list should not be null.", list);
    assertTrue(
        "file list should contain items (actually contains '" + list + "').", !list.isEmpty());
    assertTrue(list.contains("file-list/"));
    assertFalse(list.contains("file-list"));
    assertFalse(list.contains("."));
    assertFalse(list.contains(".."));
    assertFalse(list.contains("./"));
    assertFalse(list.contains("../"));

    wagon.disconnect();

    tearDownWagonTestingFixtures();
  }
 @Test
 public void testGetEvents() {
   Set<Class<? extends Event>> eventClasses = new HashSet<Class<? extends Event>>();
   for (Event theEvent : listener.getEvents()) {
     eventClasses.add(theEvent.getClass());
   }
   assertEquals(2, eventClasses.size());
   assertTrue(
       "Expecting registration for DocumentUpdatingEvent",
       eventClasses.contains(DocumentUpdatingEvent.class));
   assertTrue(
       "Expecting registration for DocumentUpdatedEvent events",
       eventClasses.contains(DocumentUpdatedEvent.class));
 }
Esempio n. 16
0
  @Test
  public void test_checkMove_exchange() 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
    // roll all tiles back and request tiles from 0 to 20
    final int capacity = tilesBank.getBankCapacity();
    for (int i = 0; i < capacity; i++) {
      tilesBank.rollbackTile(i);
    }
    for (int i = 0; i < 21; i++) {
      tilesBank.requestTile(i);
    }

    assertEquals(13, tilesBank.getTilesLimit());

    final Personality person = board.getPlayerTurn();
    final ScribblePlayerHand hand = board.getPlayerHand(person);
    final Tile[] tiles = hand.getTiles().clone();
    board.exchangeTiles(
        person, new int[] {tiles[0].getNumber(), tiles[1].getNumber(), tiles[2].getNumber()});

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

    // Check that tiles was rolled back to bank
    assertFalse(tilesBank.isTileInUse(tiles[0].getNumber()));
    assertFalse(tilesBank.isTileInUse(tiles[1].getNumber()));
    assertFalse(tilesBank.isTileInUse(tiles[2].getNumber()));

    // Check that tiles with number > 20 is taken
    assertTrue(hand.getTiles()[0].getNumber() > 20);
    assertTrue(hand.getTiles()[1].getNumber() > 20);
    assertTrue(hand.getTiles()[2].getNumber() > 20);

    // Check no points
    assertEquals(0, hand.getPoints());
  }
  @Test
  public void testStore_updateBacklogAndClearResponsibles() {
    this.store_createMockStoryBusiness();
    Backlog newBacklog = new Project();
    newBacklog.setId(123);
    Set<User> users = new HashSet<User>(Arrays.asList(new User(), new User()));
    storyInIteration.setResponsibles(users);

    expect(storyDAO.get(storyInIteration.getId())).andReturn(storyInIteration);
    expect(backlogBusiness.retrieve(newBacklog.getId())).andReturn(newBacklog);

    storyDAO.store(EasyMock.isA(Story.class));

    blheBusiness.updateHistory(storyInIteration.getBacklog().getId());

    replayAll();
    Story actual =
        storyBusiness.store(
            storyInIteration.getId(),
            new Story(),
            newBacklog.getId(),
            new HashSet<Integer>(),
            false);
    verifyAll();

    assertEquals(0, actual.getResponsibles().size());

    assertTrue(storyBacklogUpdated);
  }
Esempio n. 18
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);
  }
  @Test
  @DirtiesContext
  public void testHasParentStoryConflict_differentProduct() {
    Product product = new Product();
    Product targetProduct = new Product();
    Project project = new Project();
    Project targetProject = new Project();

    Story parentStory = new Story();
    Story story = new Story();

    targetProject.setParent(targetProduct);
    project.setParent(product);

    parentStory.setBacklog(project);
    story.setBacklog(project);
    story.setParent(parentStory);

    expect(this.backlogBusiness.getParentProduct(targetProject)).andReturn(targetProduct);
    expect(this.backlogBusiness.getParentProduct(project)).andReturn(product);

    replayAll();
    assertTrue(this.testable.hasParentStoryConflict(story, targetProject));
    verifyAll();
  }
Esempio n. 20
0
 @After
 public void tearDown() {
   tp.getScheduledExecutor().shutdownNow();
   // Make sure thare are not left over updates in the queue
   assertTrue(
       "Updates left in controller update queue", controller.isUpdateQueueEmptyForTesting());
 }
  // Call when not tracking state
  @Test
  public void testRunNotTracking() {
    sLogger.setWriter(new StringWriter());
    sLogger.start();
    assertTrue(sLogger.isRunning());
    ArrayList<StateGroup> grouplist = new ArrayList<>();
    grouplist.add(group);

    resetAll();
    expect(mockTracker.isTrackingState()).andReturn(false).anyTimes();
    expect(mockTracker.getIoSet()).andReturn(ioSet).anyTimes();
    expect(mockTracker.getStateList()).andReturn(grouplist).anyTimes();
    replayAll();

    Thread t =
        new Thread(
            new Runnable() {

              @Override
              public void run() {
                try {
                  Thread.sleep(2500);
                } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }

                sLogger.stop();
              }
            });
    t.start();
    sLogger.run();
  }
 @Test
 public void testApproveSubscription() throws Exception {
   expectInitialListCreation();
   Capture<RosterListener> listenerCapture = new Capture<RosterListener>();
   roster.addRosterListener(capture(listenerCapture));
   expectLastCall();
   subscriptionRequestListener.onSubscriptionApproved(TEST_CONTACT);
   expectLastCall().times(2);
   smackCon.sendPacket(anyObject(Packet.class));
   expectLastCall().times(2);
   expect(roster.getGroups()).andReturn(new ArrayList<RosterGroup>());
   expect(roster.getUnfiledEntryCount()).andStubReturn(0);
   roster.createEntry(
       eq(TEST_CONTACT), eq(TEST_CONTACT_NAME), aryEq(new String[] {DEFAULT_GROUP_NAME}));
   expectLastCall().times(2);
   listener.onContactChange(
       eq(ContactListListener.LIST_CONTACT_ADDED),
       anyObject(ContactList.class),
       anyObject(Contact.class));
   expectLastCall();
   replayAll();
   contactListManager.listenToRoster(roster);
   contactListManager.loadContactLists();
   contactListManager.approveSubscriptionRequest(TEST_CONTACT);
   // Second time should not call notifyContactListUpdated, since contact
   // already exists
   contactListManager.approveSubscriptionRequest(TEST_CONTACT);
   assertEquals(1, contactListManager.getContactLists().size());
   assertNotNull(contactListManager.getContactList(DEFAULT_GROUP_NAME));
   assertTrue(con.joinGracefully());
   verifyAll();
 }
 // Approve a subscription while the server already has a Buddies group
 @Test
 public void testApproveSubscription_serverBuddies() throws Exception {
   expectInitialListCreation();
   Capture<RosterListener> listenerCapture = new Capture<RosterListener>();
   roster.addRosterListener(capture(listenerCapture));
   expectLastCall();
   subscriptionRequestListener.onSubscriptionApproved(TEST_CONTACT);
   expectLastCall();
   smackCon.sendPacket(anyObject(Packet.class));
   expectLastCall();
   final ArrayList<RosterGroup> groups = new ArrayList<RosterGroup>();
   RosterGroup buddiesGroup = createNiceMock(RosterGroup.class);
   expect(buddiesGroup.getName()).andStubReturn(DEFAULT_GROUP_NAME);
   expect(buddiesGroup.getEntries()).andStubReturn(new ArrayList<RosterEntry>());
   groups.add(buddiesGroup);
   expect(roster.getGroups()).andReturn(groups);
   expect(roster.getUnfiledEntryCount()).andStubReturn(0);
   roster.createEntry(
       eq(TEST_CONTACT), eq(TEST_CONTACT_NAME), aryEq(new String[] {DEFAULT_GROUP_NAME}));
   expectLastCall();
   listener.onContactChange(
       eq(ContactListListener.LIST_CONTACT_ADDED),
       anyObject(ContactList.class),
       anyObject(Contact.class));
   expectLastCall();
   replayAll();
   contactListManager.listenToRoster(roster);
   contactListManager.loadContactLists();
   contactListManager.approveSubscriptionRequest(TEST_CONTACT);
   assertEquals(1, contactListManager.getContactLists().size());
   assertNotNull(contactListManager.getContactList(DEFAULT_GROUP_NAME));
   assertTrue(con.joinGracefully());
   verifyAll();
 }
  /** Test of add/remove AuditServiceListener method of class AuditServiceImpl. */
  public void testAddAndRemove() {

    Audit audit = createMock(Audit.class);

    AuditServiceThreadImpl instance = initialiseAuditServiceThread(audit);

    AuditServiceThreadListener mockAuditServiceThreadListener =
        createMock(AuditServiceThreadListener.class);
    // when try to remove a listener not recorded, nothing happened
    instance.remove(mockAuditServiceThreadListener);

    instance.add(mockAuditServiceThreadListener);
    assertTrue(instance.getListeners().contains(mockAuditServiceThreadListener));
    instance.remove(mockAuditServiceThreadListener);
    assertTrue(instance.getListeners().isEmpty());
  }
Esempio n. 25
0
  public void testFailedGetIfNewer() throws Exception {
    if (supportsGetIfNewer()) {
      setupRepositories();
      setupWagonTestingFixtures();
      message("Getting test artifact from test repository " + testRepository);
      Wagon wagon = getWagon();
      wagon.addTransferListener(checksumObserver);
      wagon.connect(testRepository, getAuthInfo());
      destFile = FileTestUtils.createUniqueFile(getName(), getName());
      destFile.deleteOnExit();
      try {
        wagon.getIfNewer("fubar.txt", destFile, 0);
        fail("File was found when it shouldn't have been");
      } catch (ResourceDoesNotExistException e) {
        // expected
        assertTrue(true);
      } finally {
        wagon.removeTransferListener(checksumObserver);

        wagon.disconnect();

        tearDownWagonTestingFixtures();
      }
    }
  }
Esempio n. 26
0
  @Test
  public void test_isGameFinished() {
    final Dictionary dictionary = createDictionary();
    final TilesBank tilesBank = createTilesBank("abcdefgabcdefgabcdefg", 19);

    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);

    // not finished
    assertFalse(board.isGameFinished());

    h2.setTiles(new Tile[0]);
    assertFalse(board.isGameFinished());

    tilesBank.requestTiles(tilesBank.getTilesLimit()); // now bank is empty

    // Players have a letters
    h2.setTiles(tilesBank.getTiles(0, 1, 2));
    assertFalse(board.isGameFinished());

    h2.setTiles(new Tile[0]);
    assertTrue(board.isGameFinished());
  }
  @Test
  public void testDelete_deleteChoices_withChildren_deleteChildren() {
    Story child = new Story();
    child.setBacklog(storyInIteration.getBacklog());
    child.setIteration(iteration);
    child.setId(2333);
    child.setParent(storyInIteration);
    storyInIteration.getChildren().add(child);
    storyInIteration.setIteration(null);

    blheBusiness.updateHistory(child.getBacklog().getId());
    iheBusiness.updateIterationHistory(iteration.getId());

    hourEntryBusiness.deleteAll(child.getHourEntries());
    hourEntryBusiness.deleteAll(storyInIteration.getHourEntries());

    //        storyRankBusiness.removeStoryRanks(child);
    //        storyRankBusiness.removeStoryRanks(storyInIteration);

    //        expect(storyDAO.get(2333)).andReturn(child);

    storyDAO.remove(child.getId());
    storyDAO.remove(storyInIteration);

    replayAll();
    storyBusiness.delete(
        storyInIteration,
        TaskHandlingChoice.DELETE,
        HourEntryHandlingChoice.DELETE,
        HourEntryHandlingChoice.DELETE,
        ChildHandlingChoice.DELETE);
    //        assertNull(child.getParent());
    assertTrue(storyInIteration.getChildren().isEmpty());
    verifyAll();
  }
  @Test
  public void resovleArgumentValidation() throws Exception {
    String name = "attrName";
    Object target = new TestBean();
    mavContainer.addAttribute(name, target);

    StubRequestDataBinder dataBinder = new StubRequestDataBinder(target, name);
    WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class);
    expect(binderFactory.createBinder(webRequest, target, name)).andReturn(dataBinder);
    replay(binderFactory);

    processor.resolveArgument(paramNamedValidModelAttr, mavContainer, webRequest, binderFactory);

    assertTrue(dataBinder.isBindInvoked());
    assertTrue(dataBinder.isValidateInvoked());
  }
  @Test
  public void testStart() {
    assertFalse(sLogger.isRunning());

    sLogger.start();
    assertTrue(sLogger.isRunning());
  }
  @Test
  public void springSupport() {

    // TODOJ7: change try
    ClassPathXmlApplicationContext context = null;
    // try (ClosableClassPathXmlApplicationContext context = new
    // ClosableClassPathXmlApplicationContext("org/filterinterceptor/proxy/spring/spring-config.xml");) {
    try {
      context =
          new ClassPathXmlApplicationContext(
              "org/filterinterceptor/proxy/spring/spring-config.xml");

      IService service = (IService) context.getBean("service");
      IService realService = (IService) context.getBean("realService");
      FilterService filterService = (FilterService) context.getBean("filterService");

      String paramValue = "correctParam";
      DtoSample2 param = new DtoSample2(0, null, paramValue, null);

      // test controle
      DtoSample2 ret = realService.test2(param);
      // check
      assertTrue("References must be equals", param == ret);
      assertSame("C property must be unchanged: real service called", paramValue, ret.getC());

      // test on proxy
      ret = service.test2(param);
      // check
      assertTrue("References must be equals", param == ret);
      assertNotSame(
          "C property must be reassigned to a new value: filter called", paramValue, ret.getC());

      // unactivate the filter
      Filter<?> filter = filterService.getActiveFilter(ServiceImpl.class, "test2");
      filterService.setFilterActiveStatus(filter, false);

      // test on proxy
      param.setC(paramValue);
      ret = service.test2(param);
      // check
      assertTrue("References must be equals", param == ret);
      assertSame("C property must be unchanged: filter is unactivate", paramValue, ret.getC());
    } finally { // TODOJ7: remove
      if (context != null) context.close();
    }
  }