@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();
 }
  @Test
  public void testStop() throws Exception {
    RoundRobinSchedulerStats stats =
        EasyMock.createMockBuilder(RoundRobinSchedulerStats.class)
            .withConstructor()
            .addMockedMethod("unregisterMBean")
            .createStrictMock();

    MovingAverage mavg = EasyMock.createStrictMock(MovingAverage.class);
    stats.m_addMavg = mavg;
    stats.m_addMavg.stopTimer();
    EasyMock.expectLastCall();
    stats.unregisterMBean();
    EasyMock.expectLastCall();

    EasyMock.replay(stats, mavg);
    stats.stop();
    EasyMock.verify(stats, mavg);
    assertNull("Mavg should be null.", stats.m_addMavg);

    // with no avg
    EasyMock.reset(stats);
    EasyMock.replay(stats);
    stats.stop();
    EasyMock.verify(stats);
  }
 // 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(timeout = 4000L)
  public void testRealtimeIndexTaskFailure() throws Exception {
    setUpAndStartTaskQueue(
        new DataSegmentPusher() {
          @Override
          public String getPathForHadoop(String s) {
            throw new UnsupportedOperationException();
          }

          @Override
          public DataSegment push(File file, DataSegment dataSegment) throws IOException {
            throw new RuntimeException("FAILURE");
          }
        });
    monitorScheduler.addMonitor(EasyMock.anyObject(Monitor.class));
    EasyMock.expectLastCall().atLeastOnce();
    monitorScheduler.removeMonitor(EasyMock.anyObject(Monitor.class));
    EasyMock.expectLastCall().anyTimes();
    EasyMock.replay(monitorScheduler, queryRunnerFactoryConglomerate);

    RealtimeIndexTask realtimeIndexTask = giveMeARealtimeIndexTask();
    final String taskId = realtimeIndexTask.getId();
    tq.add(realtimeIndexTask);

    // Wait for realtime index task to fail
    while (tsqa.getStatus(taskId).get().isRunnable()) {
      Thread.sleep(10);
    }

    Assert.assertTrue("Task should be in Failure state", tsqa.getStatus(taskId).get().isFailure());

    EasyMock.verify(monitorScheduler, queryRunnerFactoryConglomerate);
  }
Example #5
0
  private Message mockMessage(
      String baseAddress, String pathInfo, String query, List<ClassResourceInfo> cris)
      throws Exception {
    Message m = new MessageImpl();
    Exchange e = new ExchangeImpl();
    e.put(Service.class, new JAXRSServiceImpl(cris));
    m.setExchange(e);
    control.reset();
    ServletDestination d = control.createMock(ServletDestination.class);
    EndpointInfo epr = new EndpointInfo();
    epr.setAddress(baseAddress);
    d.getEndpointInfo();
    EasyMock.expectLastCall().andReturn(epr).anyTimes();

    Endpoint endpoint = new EndpointImpl(null, null, epr);
    e.put(Endpoint.class, endpoint);
    endpoint.put(ServerProviderFactory.class.getName(), ServerProviderFactory.getInstance());
    e.setDestination(d);
    BindingInfo bi = control.createMock(BindingInfo.class);
    epr.setBinding(bi);
    bi.getProperties();
    EasyMock.expectLastCall().andReturn(Collections.emptyMap()).anyTimes();
    m.put(Message.REQUEST_URI, pathInfo);
    m.put(Message.QUERY_STRING, query);
    m.put(Message.HTTP_REQUEST_METHOD, "GET");
    control.replay();
    return m;
  }
  public void testRetriesLoggedAtInfoWithCount() throws Exception {
    SSHClientConnection mockConnection = createMock(SSHClientConnection.class);
    net.schmizz.sshj.SSHClient mockClient = createMock(net.schmizz.sshj.SSHClient.class);

    mockConnection.clear();
    expectLastCall();
    mockConnection.create();
    expectLastCall().andThrow(new ConnectionException("test1"));
    mockConnection.clear();
    expectLastCall();
    // currently does two clears, one on failure (above) and one on next iteration (below)
    mockConnection.clear();
    expectLastCall();
    mockConnection.create();
    expectLastCall().andReturn(mockClient);
    replay(mockConnection);
    replay(mockClient);

    ssh.sshClientConnection = mockConnection;
    BufferLogger logcheck = new BufferLogger(ssh.getClass().getCanonicalName());
    ssh.logger = logcheck;
    logcheck.setLevel(Level.INFO);

    ssh.connect();

    Assert.assertEquals(ssh.sshClientConnection, mockConnection);
    verify(mockConnection);
    verify(mockClient);
    Record r = logcheck.assertLogContains("attempt 1 of 5");
    logcheck.assertLogDoesntContain("attempt 2 of 5");
    Assert.assertEquals(Level.INFO, r.getLevel());
  }
 private void prepareServiceWithMultipleJobExecutions() throws Exception {
   jobService.listJobExecutionsForJob("job", 0, 100);
   EasyMock.expectLastCall().andReturn(Arrays.asList(jobExecution, earlierExecution));
   jobService.listJobExecutionsForJob("job", 100, 100);
   EasyMock.expectLastCall().andReturn(Arrays.asList());
   EasyMock.replay(jobService);
 }
  @Test
  public void testStart() throws Exception {
    RoundRobinSchedulerStats stats =
        EasyMock.createMockBuilder(RoundRobinSchedulerStats.class)
            .withConstructor()
            .addMockedMethod("registerMBean")
            .addMockedMethod("createMovingAverage")
            .createStrictMock();

    MovingAverage mavg = EasyMock.createStrictMock(MovingAverage.class);
    EasyMock.expect(stats.createMovingAverage()).andReturn(mavg);
    mavg.startTimer("RoundRobinAddMavg", stats.getAddMavgPeriod(), TimeUnit.MILLISECONDS);
    EasyMock.expectLastCall();

    stats.registerMBean();
    EasyMock.expectLastCall();

    EasyMock.replay(stats, mavg);
    stats.start();
    EasyMock.verify(stats, mavg);
    assertEquals("Mavg not set.", mavg, stats.m_addMavg);

    // with already called
    EasyMock.reset(stats, mavg);
    EasyMock.replay(stats, mavg);
    stats.start();
    EasyMock.verify(stats, mavg);
  }
  @Test
  public void testHandleFire() throws Exception {
    expect(rootJobSettings.getJobClass()).andReturn(TestRootJob.class.getName());

    Capture<String> capturedPath = newCapture();
    Capture<Msg> capturedMsg = newCapture();
    Capture<ActorRef> capturedSrcRef = newCapture();
    workerMock.sendMsg(
        EasyMock.capture(capturedPath),
        EasyMock.capture(capturedMsg),
        EasyMock.capture(capturedSrcRef));
    expectLastCall();

    workerMock.doSnapshot();
    expectLastCall();

    replayAll();

    RootJobFireHandler handler = new RootJobFireHandler(workerMock);

    handler.handleFire();

    verifyAll();

    assertThat(capturedPath.getValue(), is("/user/supervisor"));
    assertEquals(
        ((NewMsg) capturedMsg.getValue()).getJob().getJobProducerClass(),
        TestRootJobProducer.class);
    assertThat(capturedSrcRef.getValue(), is(self));
  }
  @Test
  public void testTrackClusterNewUser() throws Exception {
    // activate
    String serverId = getServerId();
    Capture<String> serverIdCapture = new Capture<String>();
    Capture<ClusterServerImpl> clusterServerCapture = new Capture<ClusterServerImpl>();
    expect(serverTrackingCache.list()).andReturn(new ArrayList<Object>()).times(2);
    expect(serverTrackingCache.put(capture(serverIdCapture), capture(clusterServerCapture)))
        .andReturn(new Object());

    // trackClusterUser
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);

    Cookie cookieA = new Cookie("something", "someValue");
    Cookie cookieB = new Cookie("somethingElse", "someOtherValue");

    Cookie[] cookies = new Cookie[] {cookieA, cookieB};

    expect(request.getCookies()).andReturn(cookies);
    expect(request.getRemoteUser()).andReturn("userid");

    expect(response.isCommitted()).andReturn(false);
    Capture<Cookie> captureCookie = new Capture<Cookie>();
    response.addCookie(capture(captureCookie));
    expectLastCall();

    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    // deactivate
    serverTrackingCache.remove(serverId);

    replay();
    clusterTrackingServiceImpl.activate(componentContext);

    clusterTrackingServiceImpl.trackClusterUser(request, response);

    clusterTrackingServiceImpl.deactivate(componentContext);
    assertTrue(serverIdCapture.hasCaptured());
    assertEquals(serverId, serverIdCapture.getValue());
    assertTrue(clusterServerCapture.hasCaptured());
    ClusterServerImpl clusterServerImpl = clusterServerCapture.getValue();
    assertEquals(serverId, clusterServerImpl.getServerId());
    assertTrue(System.currentTimeMillis() >= clusterServerImpl.getLastModified());

    // check the cookie
    assertTrue(captureCookie.hasCaptured());
    Cookie cookie = captureCookie.getValue();
    assertEquals("SAKAI-TRACKING", cookie.getName());
    assertEquals("/", cookie.getPath());
    assertEquals(-1, cookie.getMaxAge());
    assertNotNull(cookie.getValue());
    assertTrue(cookie.getValue().startsWith(serverId));
    verify();
  }
 private void expectInitialListCreation() {
   listener.onContactChange(
       eq(ContactListListener.LIST_CREATED), anyObject(ContactList.class), eq((Contact) null));
   expectLastCall();
   listener.onContactsPresenceUpdate(anyObject(Contact[].class));
   expectLastCall();
   listener.onAllContactListsLoaded();
   expectLastCall();
 }
 protected final BaseProcessor setupOutputMock(CDXLine[] cdxlines, int... expected) {
   BaseProcessor output = EasyMock.createStrictMock(BaseProcessor.class);
   output.begin();
   EasyMock.expectLastCall().once();
   for (int i : expected) {
     EasyMock.expect(output.writeLine(cdxlines[i])).andReturn(1);
   }
   output.end();
   EasyMock.expectLastCall().once();
   return output;
 }
 private ComponentExecutionStatsService createComponentExecutionStatsServiceMock(
     ComponentExecutionRelatedInstances compExeRelatedInstancesStub) {
   ComponentExecutionStatsService compExeStatsServiceMock =
       EasyMock.createStrictMock(ComponentExecutionStatsService.class);
   compExeStatsServiceMock.addStatsAtComponentRunStart(compExeRelatedInstancesStub.compExeCtx);
   EasyMock.expectLastCall();
   compExeStatsServiceMock.addStatsAtComponentRunTermination(
       compExeRelatedInstancesStub.compExeCtx);
   EasyMock.expectLastCall();
   EasyMock.replay(compExeStatsServiceMock);
   return compExeStatsServiceMock;
 }
  @Test
  public void buildByJpql() {
    final Query query = EasyMock.createMock(Query.class);
    namedQueryBuilder.build(null, null);
    EasyMock.expectLastCall().andReturn(null);
    jpqlQueryBuilder.build(null, null, null);
    EasyMock.expectLastCall().andReturn(query);
    EasyMock.replay(namedQueryBuilder, jpqlQueryBuilder);

    Assert.assertSame(query, prioritizedQueryBuilder.build(null, null, null));
    EasyMock.verify(namedQueryBuilder, jpqlQueryBuilder);
  }
  @Test
  @Ignore
  public void hasBuckCompilerErrorOccurredThenEventsCalled()
      throws IOException, InterruptedException {
    final ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "buck_events/compiler_error", tmp);
    workspace.setUp();

    WebServerBuckEventListener webServerBuckEventListener =
        createMock(WebServerBuckEventListener.class);

    // Build started
    webServerBuckEventListener.buildStarted(anyObject(BuildEvent.Started.class));
    EasyMock.expectLastCall().times(1);

    // Build progress Event
    webServerBuckEventListener.buildProgressUpdated(
        anyObject(ProgressEvent.BuildProgressUpdated.class));
    EasyMock.expectLastCall().atLeastOnce();

    // Build finished
    webServerBuckEventListener.buildFinished(anyObject(BuildEvent.Finished.class));
    EasyMock.expectLastCall().times(1);

    // Parse started
    webServerBuckEventListener.parseStarted(anyObject(ParseEvent.Started.class));
    EasyMock.expectLastCall().times(1);

    // Parse progress Event
    webServerBuckEventListener.parsingProgressUpdated(
        anyObject(ProgressEvent.ParsingProgressUpdated.class));
    EasyMock.expectLastCall().atLeastOnce();

    // Parse finished
    webServerBuckEventListener.parseFinished(anyObject(ParseEvent.Finished.class));
    EasyMock.expectLastCall().times(1);

    // Compiler error
    webServerBuckEventListener.compilerErrorEvent(anyObject(CompilerErrorEvent.class));
    EasyMock.expectLastCall().times(1);

    // Console event
    webServerBuckEventListener.consoleEvent(anyObject(ConsoleEvent.class));
    EasyMock.expectLastCall().times(1);

    // Output trace
    webServerBuckEventListener.outputTrace(anyObject(BuildId.class));
    EasyMock.expectLastCall().times(1);

    EasyMock.replay(webServerBuckEventListener);

    ProjectWorkspace.ProcessResult build =
        workspace.runBuckdCommand(new TestContext(), "build", "//:broken");
    build.assertFailure();

    verify(webServerBuckEventListener);
  }
  @Test
  @DirtiesContext
  public void testMoveStoryAndChildren() {
    Story parent = new Story();
    Story child1 = new Story();
    Story child2 = new Story();

    parent.getChildren().add(story);

    story.setParent(parent);
    story.getChildren().add(child1);

    child1.setParent(story);
    child1.getChildren().add(child2);

    child2.setParent(child1);

    parent.setBacklog(firstProject);
    story.setBacklog(firstProject);
    child1.setBacklog(firstProject);
    child2.setBacklog(firstIteration);

    firstIteration.setParent(firstProduct);

    expect(storyTreeIntegrityBusiness.hasParentStoryConflict(story, secondProject)).andReturn(true);
    storyHierarchyBusiness.updateChildrenTreeRanks(parent);

    expect(backlogBusiness.getParentProduct(firstProject)).andReturn(firstProduct).anyTimes();
    expect(backlogBusiness.getParentProduct(secondProject)).andReturn(firstProduct).anyTimes();

    storyDAO.store(child2);

    storyRankBusiness.removeRank(child2, firstIteration);
    storyRankBusiness.removeRank(child2, firstIteration.getParent());

    storyRankBusiness.rankToBottom(child2, secondProject);

    storyDAO.store(child1);
    storyDAO.store(story);

    backlogHistoryEntryBusiness.updateHistory(firstIteration.getId());
    backlogHistoryEntryBusiness.updateHistory(secondProject.getId());
    iterationHistoryBusiness.updateIterationHistory(firstIteration.getId());
    backlogHistoryEntryBusiness.updateHistory(firstProject.getId());
    EasyMock.expectLastCall().times(2);
    backlogHistoryEntryBusiness.updateHistory(secondProject.getId());
    EasyMock.expectLastCall().times(2);

    replayAll();
    storyBusiness.moveStoryAndChildren(story, secondProject);
    verifyAll();
  }
  @Test
  public void testCreateWithConnection() throws Exception {
    PreparedStatement preparedStatement = EasyMock.createStrictMock(PreparedStatement.class);
    ResultSet resultSet = EasyMock.createStrictMock(ResultSet.class);
    Connection connection = EasyMock.createStrictMock(Connection.class);
    SavedReviewerSearch search = new SavedReviewerSearch();
    Date date = new Date();

    SavedReviewerSearchDAO dao =
        EasyMock.createMockBuilder(SavedReviewerSearchDAO.class)
            .withConstructor()
            .addMockedMethod("updatePreparedStatementForCreate")
            .createStrictMock();

    EasyMock.expect(connection.prepareStatement(SavedReviewerSearchDAO.CREATE_SQL))
        .andReturn(preparedStatement);
    dao.updatePreparedStatementForCreate(preparedStatement, search);
    EasyMock.expectLastCall();
    EasyMock.expect(preparedStatement.executeQuery()).andReturn(resultSet);
    EasyMock.expect(resultSet.next()).andReturn(true);
    EasyMock.expect(resultSet.getTimestamp(1)).andReturn(new Timestamp(date.getTime()));
    resultSet.close();
    EasyMock.expectLastCall();
    preparedStatement.close();
    EasyMock.replay(preparedStatement, resultSet, connection, dao);
    SavedReviewerSearch result = dao.create(connection, search);
    EasyMock.verify(preparedStatement, resultSet, connection, dao);
    assertEquals("Wrong created date.", date, result.getCreatedDate());

    // failure case
    EasyMock.reset(preparedStatement, resultSet, connection, dao);
    EasyMock.expect(connection.prepareStatement(SavedReviewerSearchDAO.CREATE_SQL))
        .andReturn(preparedStatement);
    dao.updatePreparedStatementForCreate(preparedStatement, search);
    EasyMock.expectLastCall();
    EasyMock.expect(preparedStatement.executeQuery()).andReturn(resultSet);
    EasyMock.expect(resultSet.next()).andReturn(false);
    resultSet.close();
    EasyMock.expectLastCall();
    preparedStatement.close();
    EasyMock.replay(preparedStatement, resultSet, connection, dao);
    try {
      dao.create(connection, search);
      fail("Should have thrown a sql exception.");
    } catch (SQLException ex) {
      // expected
    }
    EasyMock.verify(preparedStatement, resultSet, connection, dao);
  }
 private ComponentExecutionStorageBridge createComponentExecutionStorageBridgeNonRunFailure(
     ComponentExecutionRelatedInstances compExeRelatedInstancesStub, Integer exeCount)
     throws ComponentExecutionException {
   ComponentExecutionStorageBridge compExeStorageBridgeMock =
       EasyMock.createStrictMock(ComponentExecutionStorageBridge.class);
   EasyMock.expect(compExeStorageBridgeMock.hasUnfinishedComponentExecution()).andReturn(false);
   compExeStorageBridgeMock.addComponentExecution(
       compExeRelatedInstancesStub.compExeCtx, exeCount);
   EasyMock.expectLastCall();
   Capture<FinalComponentRunState> finalStateCapture = new Capture<>();
   compExeStorageBridgeMock.setComponentExecutionFinished(EasyMock.capture(finalStateCapture));
   EasyMock.expectLastCall();
   EasyMock.replay(compExeStorageBridgeMock);
   return compExeStorageBridgeMock;
 }
 private ComponentExecutionStorageBridge createComponentExecutionStorageBridgeRunSuccess(
     ComponentExecutionRelatedInstances compExeRelatedInstancesStub,
     FinalComponentRunState finalState)
     throws ComponentExecutionException {
   ComponentExecutionStorageBridge compExeStorageBridgeMock =
       EasyMock.createStrictMock(ComponentExecutionStorageBridge.class);
   compExeStorageBridgeMock.addComponentExecution(
       compExeRelatedInstancesStub.compExeCtx,
       compExeRelatedInstancesStub.compExeRelatedStates.executionCount.get());
   EasyMock.expectLastCall();
   compExeStorageBridgeMock.setComponentExecutionFinished(finalState);
   EasyMock.expectLastCall();
   EasyMock.replay(compExeStorageBridgeMock);
   return compExeStorageBridgeMock;
 }
 private ConsoleRowsSender createConsoleRowsSenderMock(
     Capture<ConsoleRow.Type> consoleRowTypeCapture, Capture<String> logMessageCapture) {
   ConsoleRowsSender consoleRowsSenderMock = EasyMock.createStrictMock(ConsoleRowsSender.class);
   if (consoleRowTypeCapture != null) {
     consoleRowsSenderMock.sendLogMessageAsConsoleRow(
         EasyMock.capture(consoleRowTypeCapture),
         EasyMock.capture(logMessageCapture),
         EasyMock.anyInt());
     EasyMock.expectLastCall();
   }
   consoleRowsSenderMock.sendLogFileWriteTriggerAsConsoleRow();
   EasyMock.expectLastCall();
   EasyMock.replay(consoleRowsSenderMock);
   return consoleRowsSenderMock;
 }
Example #21
0
 void setUpPhaseInterceptorInvocations(
     PhaseInterceptorSupport<Message> p, boolean fail, boolean expectFault) {
   p.handleMessage(message);
   if (fail) {
     EasyMock.expectLastCall().andThrow(new RuntimeException());
     message.setContent(EasyMock.eq(Exception.class), EasyMock.isA(Exception.class));
     EasyMock.expectLastCall();
   } else {
     EasyMock.expectLastCall();
   }
   if (expectFault) {
     p.handleFault(message);
     EasyMock.expectLastCall();
   }
 }
  @Test
  public void testForLifeCycle() {
    BusLifeCycleListener bl = EasyMock.createMock(BusLifeCycleListener.class);
    Bus bus = new SpringBusFactory().createBus();
    BusLifeCycleManager lifeCycleManager = bus.getExtension(BusLifeCycleManager.class);
    lifeCycleManager.registerLifeCycleListener(bl);

    bl.preShutdown();
    EasyMock.expectLastCall();
    bl.postShutdown();
    EasyMock.expectLastCall();
    EasyMock.replay(bl);
    bus.shutdown(true);
    EasyMock.verify(bl);
  }
  /**
   * Starting from a node 1, traverse the graph. Node 1 discovers two extra nodes, 1 and 2, of which
   * only 2 should be called.
   *
   * <p>Ensures that any state maintained during traversal is cleared.
   */
  @Test
  public void traverseFrom_node() throws IllegalAccessException {
    traverser.addNodeVisitor(visitor1);

    // initially, node 1 will be queued
    traverser.enqueueNodes(colEq(Arrays.<Object>asList(1)));
    expectLastCall();

    traverser.hasNext();
    expectLastCall().andReturn(true);
    traverser.next();
    expectLastCall().andReturn(1);

    StringBuilder traversalState = new StringBuilder();
    visitor1.visitNode(1, traverser, traversalState);
    expectLastCall()
        .andAnswer(new NodeVisitorAction(traverser, Arrays.<Object>asList(1, 2), "James", true));

    // the second node 1 should not be enqueued
    traverser.enqueueNodes(colEq(Arrays.<Object>asList(2)));
    expectLastCall();

    traverser.hasNext();
    expectLastCall().andReturn(true);
    traverser.next();
    expectLastCall().andReturn(2);

    // the visitor should *not* be called again for node 1
    visitor1.visitNode(2, traverser, traversalState);
    expectLastCall().andAnswer(new NodeVisitorAction(traverser, null, " Bond", true));

    // all nodes have been visited
    traverser.hasNext();
    expectLastCall().andReturn(false);

    replay(traverser, visitor1);

    // none of the visitors returned "false", so the traversal should succeed
    assertTrue(traverser.traverseFrom(1, traversalState));

    verify(traverser, visitor1);

    // check that the state object was correctly updated
    assertEquals("James Bond", traversalState.toString());

    // check that any internal state maintained during the cloning has been cleaned up
    assertTrue(ReflectionUtils.<Set<?>>getValue(traverser, "visitedOrQueuedNodes").isEmpty());
  }
  @Test
  public void testGetQueryNoCache() throws Exception {
    final PermissionsFilterCache cache = mockController.getMock(PermissionsFilterCache.class);
    final BooleanQuery generatedQuery = new BooleanQuery();

    org.easymock.EasyMock.expect(cache.getQuery(theUser)).andReturn(null);

    cache.storeQuery(generatedQuery, theUser);
    org.easymock.EasyMock.expectLastCall();

    replay();
    final PermissionQueryFactory permissionQueryFactory =
        new PermissionQueryFactory() {
          public Query getQuery(com.atlassian.crowd.embedded.api.User searcher, int permissionId) {
            assertSame(theUser, searcher);
            assertEquals(Permissions.BROWSE, permissionId);
            return generatedQuery;
          }
        };

    final PermissionsFilterGeneratorImpl generator =
        new PermissionsFilterGeneratorImpl(permissionQueryFactory) {
          @Override
          PermissionsFilterCache getCache() {
            return cache;
          }
        };

    final Query result = generator.getQuery(theUser);

    assertSame(generatedQuery, result);
  }
  @Test
  public void inloggenJuist() {
    Medewerker medewerker = new Medewerker();
    medewerker.setIdentificatie("emailadres");
    medewerker.setHashWachtwoord("wachtwoord");

    try {
      EasyMock.expect(gebruikerRepository.zoek("emailadres")).andReturn(medewerker);
    } catch (NietGevondenException e1) {
      fail();
    }

    HttpSession httpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(servletRequest.getSession()).andReturn(httpSession);
    EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("1234").times(2);
    EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent");

    EasyMock.expect(httpSession.getId()).andReturn("234");

    gebruikerRepository.opslaan(medewerker);
    EasyMock.expectLastCall();

    replayAll();

    try {
      gebruikerService.inloggen("emailadres", "wachtwoord", "false", servletRequest);
    } catch (LeegVeldException | NietGevondenException | OnjuistWachtwoordException e) {
      fail(e.getMessage());
    }

    verifyAll();
  }
  @Test
  public void uitloggen() {
    HttpSession httpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(servletRequest.getSession()).andReturn(httpSession).times(2);
    EasyMock.expect(httpSession.getId()).andReturn("a").times(2);
    EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("adr").times(2);
    EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent");

    Medewerker medewerker = new Medewerker();
    medewerker.setId(46L);

    Sessie sessie = new Sessie();
    sessie.setGebruiker(medewerker);
    sessie.setIpadres("adr");
    sessie.setSessie("a");
    medewerker.getSessies().add(sessie);

    try {
      EasyMock.expect(gebruikerRepository.zoekOpSessieEnIpadres("a", "adr")).andReturn(medewerker);
    } catch (NietGevondenException e1) {
    }

    gebruikerRepository.opslaan(medewerker);
    EasyMock.expectLastCall();

    replayAll();
    EasyMock.replay(httpSession);

    gebruikerService.uitloggen(servletRequest);

    verifyAll();
    EasyMock.verify(httpSession);
  }
Example #27
0
  @Test
  public void test401ShouldRetry() {
    HttpCommand command = createMock(HttpCommand.class);
    HttpRequest request = createMock(HttpRequest.class);
    HttpResponse response = createMock(HttpResponse.class);
    @SuppressWarnings("unchecked")
    LoadingCache<Credentials, Access> cache = createMock(LoadingCache.class);
    BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);

    expect(command.getCurrentRequest()).andReturn(request);

    cache.invalidateAll();
    expectLastCall();

    expect(response.getPayload()).andReturn(Payloads.newStringPayload("")).anyTimes();
    expect(response.getStatusCode()).andReturn(401).atLeastOnce();

    replay(command);
    replay(response);
    replay(cache);
    replay(backoffHandler);

    RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);

    assertTrue(retry.shouldRetryRequest(command, response));

    verify(command);
    verify(response);
    verify(cache);
  }
Example #28
0
  @SuppressWarnings("unchecked")
  @Test
  public void testFindCustomersWithConnection() throws Exception {
    CustomerDAO dao =
        EasyMock.createMockBuilder(CustomerDAO.class)
            .addMockedMethod("readNextCustomer")
            .addMockedMethod("getCustomerQuery")
            .createStrictMock();
    ResultSet resultSet = EasyMock.createStrictMock(ResultSet.class);
    Connection connection = EasyMock.createStrictMock(Connection.class);
    Statement statement = EasyMock.createStrictMock(Statement.class);
    List<SearchConstraint> constraints = new LinkedList<SearchConstraint>();

    EasyMock.expect(dao.getCustomerQuery(constraints)).andReturn("aQuery");
    EasyMock.expect(connection.createStatement()).andReturn(statement);
    EasyMock.expect(statement.executeQuery("aQuery")).andReturn(resultSet);

    EasyMock.expect(resultSet.next()).andReturn(true);
    EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class)))
        .andReturn(true);
    EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class)))
        .andReturn(true);
    EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class)))
        .andReturn(false);
    resultSet.close();
    EasyMock.expectLastCall();
    statement.close();
  }
 /** Test {@link DeviceSetup#setUp(ITestDevice, IBuildInfo)} when build does not boot */
 public void testSetup_buildError() throws Exception {
   mMockDevice.setRecoveryMode(RecoveryMode.ONLINE);
   mMockFlasher.overrideDeviceOptions(mMockDevice);
   mMockFlasher.setForceSystemFlash(false);
   mMockFlasher.setDataWipeSkipList(Arrays.asList(new String[] {}));
   mMockFlasher.flash(mMockDevice, mMockBuildInfo);
   mMockDevice.waitForDeviceOnline();
   EasyMock.expect(mMockDevice.enableAdbRoot()).andStubReturn(Boolean.TRUE);
   mMockDevice.setDate(null);
   EasyMock.expect(mMockDevice.getBuildId()).andReturn(mMockBuildInfo.getBuildId());
   EasyMock.expect(mMockDevice.getBuildFlavor()).andReturn(mMockBuildInfo.getBuildFlavor());
   EasyMock.expect(mMockDevice.isEncryptionSupported()).andStubReturn(Boolean.TRUE);
   EasyMock.expect(mMockDevice.isDeviceEncrypted()).andStubReturn(Boolean.FALSE);
   mMockDevice.clearLogcat();
   mMockDevice.waitForDeviceAvailable(EasyMock.anyLong());
   EasyMock.expectLastCall().andThrow(new DeviceUnresponsiveException("foo"));
   mMockDevice.setRecoveryMode(RecoveryMode.AVAILABLE);
   EasyMock.replay(mMockFlasher, mMockDevice);
   try {
     mDeviceFlashPreparer.setUp(mMockDevice, mMockBuildInfo);
     fail("DeviceFlashPreparerTest not thrown");
   } catch (BuildError e) {
     // expected; use the general version to make absolutely sure that
     // DeviceFailedToBootError properly masquerades as a BuildError.
     assertTrue(e instanceof DeviceFailedToBootError);
   }
   EasyMock.verify(mMockFlasher, mMockDevice);
 }
  @Test
  public void protected_asset_client_URL() {
    ResourceCache cache = mockResourceCache();
    ClasspathAssetAliasManager aliasManager = mockClasspathAssetAliasManager();

    Resource r = new ClasspathResource("foo/Bar.txt");

    train_requiresDigest(cache, r, true);

    expect(cache.getDigest(r)).andReturn("ABC123");

    String expectedClientURL = "/context/asset/foo/Bar.ABC123.txt";

    train_toClientURL(aliasManager, "foo/Bar.ABC123.txt", expectedClientURL);

    EasyMock.expectLastCall().times(2); // 2nd time is the toString() call

    replay();

    AssetFactory factory = new ClasspathAssetFactory(cache, aliasManager);

    Asset asset = factory.createAsset(r);

    assertSame(asset.getResource(), r);
    assertEquals(asset.toClientURL(), expectedClientURL);
    assertEquals(asset.toString(), expectedClientURL);

    verify();
  }