コード例 #1
1
  @Test
  public void testExceptionWhenIOExceptionOn200()
      throws ExecutionException, InterruptedException, TimeoutException, IOException {
    Function<HttpResponse, URI> function =
        new ParseURIFromListOrLocationHeaderIf20x(uriBuilderProvider);
    HttpResponse response = createMock(HttpResponse.class);
    Payload payload = createMock(Payload.class);

    expect(response.getStatusCode()).andReturn(200).atLeastOnce();
    expect(response.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE)).andReturn("text/uri-list");
    RuntimeException exception = new RuntimeException("bad");
    expect(response.getPayload()).andReturn(payload).atLeastOnce();
    expect(payload.getInput()).andThrow(exception);
    payload.release();

    replay(payload);
    replay(response);
    try {
      function.apply(response);
    } catch (Exception e) {
      assert e.equals(exception);
    }
    verify(payload);
    verify(response);
  }
コード例 #2
0
 public static EdmEntityType mockSourceEdmEntityType() {
   EdmEntityType entityType = EasyMock.createMock(EdmEntityType.class);
   EdmMapping mapping = EasyMock.createMock(EdmMapping.class);
   List<String> navigationPropertyNames = new ArrayList<String>();
   List<String> propertyNames = new ArrayList<String>();
   propertyNames.add("id");
   propertyNames.add("description");
   navigationPropertyNames.add("SalesOrderLineItemDetails");
   try {
     EasyMock.expect(mapping.getInternalName()).andStubReturn("SalesOrderHeader");
     EasyMock.replay(mapping);
     EasyMock.expect(entityType.getName()).andStubReturn("SalesOrderHeader");
     EasyMock.expect(entityType.getMapping()).andStubReturn(mapping);
     EasyMock.expect(entityType.getNavigationPropertyNames())
         .andStubReturn(navigationPropertyNames);
     EasyMock.expect(entityType.getProperty("SalesOrderLineItemDetails"))
         .andStubReturn(mockNavigationProperty());
     EdmProperty property1 = mockEdmPropertyOfSource1();
     EasyMock.expect(entityType.getProperty("id")).andStubReturn(property1);
     EasyMock.expect(entityType.getProperty("description"))
         .andStubReturn(mockEdmPropertyOfSource2());
     EasyMock.expect(entityType.getPropertyNames()).andStubReturn(propertyNames);
     List<EdmProperty> keyProperties = new ArrayList<EdmProperty>();
     keyProperties.add(property1);
     EasyMock.expect(entityType.getKeyProperties()).andStubReturn(keyProperties);
   } catch (EdmException e) {
     fail(
         ODataJPATestConstants.EXCEPTION_MSG_PART_1
             + e.getMessage()
             + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
   }
   EasyMock.replay(entityType);
   return entityType;
 }
コード例 #3
0
  /**
   * Verify that when adding a second player to a game, the correct information for that player is
   * set and it does not conflict with the first player
   */
  @Test
  public void addSecondPlayerTest() {
    // setup dummy entityfactory
    EntityFactory dummyEntityFactory = EasyMock.createMock(EntityFactory.class);
    SnowmanFlag dummyFlag = EasyMock.createNiceMock(SnowmanFlag.class);
    EasyMock.expect(dummyFlag.getID()).andStubReturn(new Integer(0));
    EasyMock.replay(dummyFlag);
    EasyMock.expect(
            dummyEntityFactory.createSnowmanFlag(
                EasyMock.isA(SnowmanGame.class),
                EasyMock.isA(ETeamColor.class),
                EasyMock.isA(Coordinate.class),
                EasyMock.isA(Coordinate.class)))
        .andStubReturn(dummyFlag);
    EasyMock.replay(dummyEntityFactory);

    // create the player
    ClientSession session = EasyMock.createNiceMock(ClientSession.class);
    SnowmanPlayer dummyPlayer = EasyMock.createMock(SnowmanPlayer.class);
    ETeamColor color = ETeamColor.Red;

    // create the second player
    ClientSession session2 = EasyMock.createNiceMock(ClientSession.class);
    SnowmanPlayer dummyPlayer2 = EasyMock.createMock(SnowmanPlayer.class);
    ETeamColor color2 = ETeamColor.Blue;

    // create the game
    SnowmanGame game = new SnowmanGameImpl(gameName, 4, dummyEntityFactory);

    // record information that should be set on the player1
    dummyPlayer.setID(1);
    dummyPlayer.setLocation(EasyMock.anyFloat(), EasyMock.anyFloat());
    dummyPlayer.setTeamColor(color);
    dummyPlayer.setGame(game);
    EasyMock.expect(dummyPlayer.getSession()).andStubReturn(session);
    EasyMock.replay(dummyPlayer);

    // record information that should be set on the player2
    dummyPlayer2.setID(2);
    dummyPlayer2.setLocation(EasyMock.anyFloat(), EasyMock.anyFloat());
    dummyPlayer2.setTeamColor(color2);
    dummyPlayer2.setGame(game);
    EasyMock.expect(dummyPlayer2.getSession()).andStubReturn(session2);
    EasyMock.replay(dummyPlayer2);

    // record that the players should be added to the channel
    EasyMock.resetToDefault(gameChannel);
    EasyMock.expect(gameChannel.join(session)).andReturn(gameChannel);
    EasyMock.expect(gameChannel.join(session2)).andReturn(gameChannel);
    EasyMock.replay(gameChannel);

    // add the player
    game.addPlayer(dummyPlayer, color);
    game.addPlayer(dummyPlayer2, color2);

    // verify the calls
    EasyMock.verify(dummyPlayer);
    EasyMock.verify(dummyPlayer2);
    EasyMock.verify(gameChannel);
  }
コード例 #4
0
ファイル: RetryOnRenewTest.java プロジェクト: kwart/jclouds
  @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);
  }
コード例 #5
0
  @Test
  public void answer() throws ObjectNotFoundException {
    UUID selfHelpGuideResponseId = UUID.randomUUID();
    UUID selfHelpGuideQuestionId = UUID.randomUUID();
    Boolean answerResponse = true;
    SelfHelpGuideResponse selfHelpGuideResponse = new SelfHelpGuideResponse();
    SelfHelpGuideQuestion selfHelpGuideQuestion = new SelfHelpGuideQuestion();

    expect(service.get(selfHelpGuideResponseId)).andReturn(selfHelpGuideResponse);
    expect(selfHelpGuideQuestionService.get(selfHelpGuideQuestionId))
        .andReturn(selfHelpGuideQuestion);
    expect(
            service.answerSelfHelpGuideQuestion(
                selfHelpGuideResponse, selfHelpGuideQuestion, answerResponse))
        .andReturn(false);

    replay(service);
    replay(selfHelpGuideQuestionService);

    try {
      Boolean response =
          controller.answer(selfHelpGuideResponseId, selfHelpGuideQuestionId, answerResponse);

      verify(service);
      verify(selfHelpGuideQuestionService);
      assertFalse(response);
    } catch (Exception e) {
      fail("controller error");
    }
  }
コード例 #6
0
  public void simpleRootTestWithSudoPassword() {
    node = createMock(NodeMetadata.class);
    expect(node.getCredentials())
        .andReturn(new LoginCredentials("tester", "testpassword!", null, true))
        .atLeastOnce();
    replay(node);
    RunScriptOnNodeUsingSsh testMe =
        new RunScriptOnNodeUsingSsh(
            sshFactory,
            eventBus,
            node,
            exec("echo $USER\necho $USER"),
            wrapInInitScript(false).runAsRoot(true));
    testMe.init();

    sshClient.connect();
    expect(sshClient.getUsername()).andReturn("tester");
    expect(sshClient.getHostAddress()).andReturn("somewhere.example.com");
    expect(
            sshClient.exec(
                "sudo -S sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n"
                    + "testpassword!\n"
                    + "echo $USER\n"
                    + "echo $USER\n"
                    + "RUN_SCRIPT_AS_ROOT_SSH\n"))
        .andReturn(new ExecResponse("root\nroot\n", null, 0));
    sshClient.disconnect();
    replay(sshClient);

    testMe.call();
  }
コード例 #7
0
  private ComponentExecutionRelatedInstances createComponentExecutionRelatedInstances(
      Capture<ConsoleRow> consoleRowCapture) {
    ComponentExecutionStorageBridge compExeStorageBridgeMock =
        EasyMock.createStrictMock(ComponentExecutionStorageBridge.class);
    EasyMock.expect(compExeStorageBridgeMock.getComponentExecutionDataManagementId())
        .andStubReturn(DM_ID);
    EasyMock.replay(compExeStorageBridgeMock);

    ComponentExecutionRelatedStates compExeRelatedStates = new ComponentExecutionRelatedStates();
    compExeRelatedStates.executionCount.set(EXE_COUNT);
    compExeRelatedStates.consoleRowSequenceNumber.set(CONSOLE_ROW_SEQ_NUMBER);
    compExeRelatedStates.compHasSentConsoleRowLogMessages.set(true);

    batchingConsoleRowForwarderMock = EasyMock.createStrictMock(BatchingConsoleRowsForwarder.class);
    batchingConsoleRowForwarderMock.onConsoleRow(EasyMock.capture(consoleRowCapture));
    EasyMock.replay(batchingConsoleRowForwarderMock);

    ComponentExecutionRelatedInstances compExeRelatedInstances =
        new ComponentExecutionRelatedInstances();
    compExeRelatedInstances.compExeStorageBridge = compExeStorageBridgeMock;
    compExeRelatedInstances.compExeCtx = new ComponentExecutionContextDefaultStub();
    compExeRelatedInstances.compExeRelatedStates = compExeRelatedStates;
    compExeRelatedInstances.batchingConsoleRowsForwarder = batchingConsoleRowForwarderMock;

    return compExeRelatedInstances;
  }
コード例 #8
0
  @Test
  public void testConfigurationEventAdded() throws Exception {
    String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "test123";
    Configuration conf = EasyMock.createMock(Configuration.class);
    EasyMock.expect(conf.getPid()).andReturn(testPid).anyTimes();
    EasyMock.replay(conf);

    ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class);
    EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes();
    EasyMock.expect(cm.getConfiguration(testPid)).andReturn(conf).anyTimes();
    EasyMock.replay(cm);

    final List<String> generateCalled = new ArrayList<String>();
    SecuredCommandConfigTransformer scct =
        new SecuredCommandConfigTransformer() {
          @Override
          void generateServiceGuardConfig(Configuration config) throws IOException {
            generateCalled.add(config.getPid());
          }
        };
    scct.setConfigAdmin(cm);
    scct.init();

    @SuppressWarnings("unchecked")
    ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(cmRef);

    ConfigurationEvent event =
        new ConfigurationEvent(cmRef, ConfigurationEvent.CM_UPDATED, null, testPid);

    assertEquals("Precondition", 0, generateCalled.size());
    scct.configurationEvent(event);
    assertEquals(1, generateCalled.size());
    assertEquals(testPid, generateCalled.iterator().next());
  }
コード例 #9
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testStartMonitoringWithTimeout() {
    ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class);
    ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class);
    expect(
            schedulerMock.scheduleWithFixedDelay(
                anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class)))
        .andReturn(mockFuture);

    replay(mockFuture);
    replay(schedulerMock);

    AsyncMonitor<Object> monitor =
        mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), new EventBus());

    assertNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.startMonitoring(100L);

    assertNotNull(monitor.getFuture());
    assertNotNull(monitor.getTimeout());
    assertTrue(monitor.getTimeout() > 100L);

    verify(mockFuture);
    verify(schedulerMock);
  }
コード例 #10
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testMonitorAndContinueWithoutTimeout() {
    ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class);
    ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class);
    expect(
            schedulerMock.scheduleWithFixedDelay(
                anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class)))
        .andReturn(mockFuture);

    replay(mockFuture);
    replay(schedulerMock);

    CoutingEventHandler handler = new CoutingEventHandler();
    EventBus eventBus = new EventBus();
    eventBus.register(handler);

    AsyncMonitor<Object> monitor =
        mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.CONTINUE), eventBus);

    assertNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.startMonitoring(null);
    assertNotNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.run();
    assertEquals(handler.numCompletes, 0);
    assertEquals(handler.numFailures, 0);
    assertEquals(handler.numTimeouts, 0);

    verify(mockFuture);
    verify(schedulerMock);
  }
コード例 #11
0
  private void doGet(Map<String, String> parameters, boolean checkResultContent)
      throws IOException, ServletException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    expect(request.getRequestURI()).andReturn("/test/monitoring").anyTimes();
    expect(request.getRequestURL()).andReturn(new StringBuffer("/test/monitoring")).anyTimes();
    expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    expect(request.getRemoteAddr()).andReturn("here").anyTimes();
    for (final Map.Entry<String, String> entry : parameters.entrySet()) {
      if (REQUEST_PARAMETER.equals(entry.getKey())) {
        expect(request.getHeader(entry.getKey())).andReturn(entry.getValue()).anyTimes();
      } else {
        expect(request.getParameter(entry.getKey())).andReturn(entry.getValue()).anyTimes();
      }
    }
    expect(request.getHeaders("Accept-Encoding"))
        .andReturn(Collections.enumeration(Arrays.asList("application/gzip")))
        .anyTimes();
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    expect(response.getOutputStream()).andReturn(new FilterServletOutputStream(output)).anyTimes();
    final StringWriter stringWriter = new StringWriter();
    expect(response.getWriter()).andReturn(new PrintWriter(stringWriter)).anyTimes();

    replay(request);
    replay(response);
    reportServlet.doGet(request, response);
    verify(request);
    verify(response);

    if (checkResultContent) {
      assertTrue("result", output.size() != 0 || stringWriter.getBuffer().length() != 0);
    }
  }
コード例 #12
0
  public void testExceptionIfNot5xx() {
    FalseOn5xx function = new FalseOn5xx();
    HttpResponse response = EasyMock.createMock(HttpResponse.class);
    HttpResponseException exception = EasyMock.createMock(HttpResponseException.class);

    // Status code is called twice
    expect(response.getStatusCode()).andReturn(600);
    expect(response.getStatusCode()).andReturn(600);
    // Get response gets called twice
    expect(exception.getResponse()).andReturn(response);
    expect(exception.getResponse()).andReturn(response);
    // Get cause is called to determine the root cause
    expect(exception.getCause()).andReturn(null);

    replay(response);
    replay(exception);

    try {
      function.createOrPropagate(exception);
    } catch (Exception ex) {
      assertEquals(ex, exception);
    }

    verify(response);
    verify(exception);
  }
コード例 #13
0
ファイル: LatesterTest.java プロジェクト: txdv/sockso
  public void testGetLatestAlbums() throws SQLException {

    final Properties p = createMock(Properties.class);
    expect(p.get(Constants.WWW_BROWSE_LATEST_ALBUMS_COUNT, 10)).andReturn(10l);
    replay(p);

    final ResultSet rs = createNiceMock(ResultSet.class);
    expect(rs.next()).andReturn(true);
    expect(rs.next()).andReturn(true);
    expect(rs.next()).andReturn(false);
    replay(rs);

    final PreparedStatement st = createMock(PreparedStatement.class);
    st.setInt(1, 10);
    expect(st.executeQuery()).andReturn(rs).times(1);
    replay(st);

    final Database db = createMock(Database.class);
    expect(db.prepare((String) anyObject())).andReturn(st).times(1);
    replay(db);

    final Latester b = new Latester();
    b.setProperties(p);
    b.setDatabase(db);

    final Vector<Album> albums = b.getLatestAlbums();

    assertNotNull(albums);
    assertEquals(2, albums.size());

    verify(db);
    verify(st);
    verify(rs);
    verify(p);
  }
コード例 #14
0
  private ValuesIndexManager setupMockObjects(
      String dsName, String table, String indexName, String variableName, Variable variable) {
    ValuesIndexManager indexManager = createMock(ValuesIndexManager.class);
    Datasource datasource = createMockDatasource(dsName, table);

    ValueTable mockTable = datasource.getValueTable(table);
    reset(mockTable);
    ValueTableValuesIndex mockTableIndex = createMock(ValueTableValuesIndex.class);
    expect(mockTableIndex.getIndexName()).andReturn(indexName).anyTimes();
    expect(mockTableIndex.getFieldName("LAST_MEAL_WHEN"))
        .andReturn(indexName + "-LAST_MEAL_WHEN")
        .anyTimes();
    expect(mockTableIndex.getFieldName("RES_FIRST_HEIGHT"))
        .andReturn(indexName + "-RES_FIRST_HEIGHT")
        .anyTimes();
    replay(mockTableIndex);

    expect(mockTable.getVariable(variableName)).andReturn(variable).anyTimes();
    expect(indexManager.getIndex(mockTable)).andReturn(mockTableIndex).anyTimes();
    replay(indexManager);
    replay(mockTable);

    MagmaEngine.get().addDatasource(datasource);

    return indexManager;
  }
コード例 #15
0
  public static EdmEntityType mockTargetEdmEntityType() {
    EdmEntityType entityType = EasyMock.createMock(EdmEntityType.class);
    EdmMapping mapping = EasyMock.createMock(EdmMapping.class);

    List<String> propertyNames = new ArrayList<String>();
    propertyNames.add("price");
    try {
      EasyMock.expect(mapping.getInternalName()).andStubReturn("SalesOrderLineItem");
      EasyMock.replay(mapping);
      EasyMock.expect(entityType.getName()).andStubReturn("SalesOrderLineItem");
      EasyMock.expect(entityType.getMapping()).andStubReturn(mapping);
      EdmProperty property = mockEdmPropertyOfTarget();
      EasyMock.expect(entityType.getProperty("price")).andStubReturn(property);
      EasyMock.expect(entityType.getPropertyNames()).andStubReturn(propertyNames);

      List<EdmProperty> keyProperties = new ArrayList<EdmProperty>();
      keyProperties.add(property);
      EasyMock.expect(entityType.getKeyProperties()).andStubReturn(keyProperties);

    } catch (EdmException e) {
      fail(
          ODataJPATestConstants.EXCEPTION_MSG_PART_1
              + e.getMessage()
              + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
    }
    EasyMock.replay(entityType);
    return entityType;
  }
コード例 #16
0
  @Before
  public void setUp() {
    logger = new ByteArrayOutputStream();

    kpPairs = new ArrayList<GlobalKeepassPair>();
    URL url = getClass().getResource("/TestDB.kdbx");
    kpPairs.add(new GlobalKeepassPair(url.getPath(), MASTER_PASS));

    vpList = new ArrayList<VarPasswordPair>();

    config =
        EasyMock.createMockBuilder(MaskPasswordsConfig.class)
            .addMockedMethod("getGlobalVarPasswordPairs")
            .addMockedMethod("getGlobalKeepassLocations")
            .addMockedMethod("isMasked")
            .createMock();
    wrapper =
        EasyMock.createMockBuilder(MaskPasswordsBuildWrapper.class)
            .addMockedMethod("getConfig")
            .createMock();

    EasyMock.expect(config.getGlobalKeepassLocations()).andReturn(kpPairs);
    EasyMock.expect(config.getGlobalVarPasswordPairs()).andReturn(vpList);
    EasyMock.expect(config.isMasked(EasyMock.anyString())).andReturn(true).anyTimes();
    EasyMock.replay(config);
    EasyMock.expect(wrapper.getConfig()).andReturn(config).anyTimes();
    EasyMock.replay(wrapper);

    build = EasyMock.createMock(AbstractBuild.class);
    EasyMock.expect(build.getAction(ParametersAction.class)).andReturn(null);
    EasyMock.replay(build);
  }
コード例 #17
0
  // TODO(oana): Added a task in tracker for fixing these dependencies and
  // making the mocking of objects easier.
  public void testEnterArgumentNode() {
    CssDefinitionNode def = new CssDefinitionNode(new CssLiteralNode("COLOR"));

    MutatingVisitController visitController = createMock(MutatingVisitController.class);
    CssTree tree = createMock(CssTree.class);
    expect(tree.getMutatingVisitController()).andReturn(visitController).anyTimes();
    ConstantDefinitions definitions = EasyMock.createMock(ConstantDefinitions.class);
    expect(definitions.getConstantDefinition("COLOR")).andReturn(def).anyTimes();
    replay(definitions);
    replay(tree);

    ReplaceConstantReferences pass =
        new ReplaceConstantReferences(
            tree,
            definitions,
            true /* removeDefs */,
            new DummyErrorManager(),
            true /* allowUndefinedConstants */);

    Capture<List<CssNode>> tempList = new Capture<List<CssNode>>();
    visitController.replaceCurrentBlockChildWith(capture(tempList), eq(true));
    replay(visitController);

    CssConstantReferenceNode node = new CssConstantReferenceNode("COLOR", null);
    pass.enterArgumentNode(node);
    verify(visitController);
    assertEquals(1, tempList.getValue().size());
    assertEquals(CssCompositeValueNode.class, tempList.getValue().get(0).getClass());
  }
コード例 #18
0
  @Test
  public void testNext() {
    boolean expected = true;
    EasyMock.expect(peekIterator.hasNext()).andReturn(expected).times(4);
    String defaultString = "S1";
    String resString = "S2";
    EasyMock.expect(peekIterator.next()).andReturn(defaultString);
    EasyMock.expect(binaryFn.apply(EasyMock.eq(defaultString), EasyMock.isNull()))
        .andReturn(resString);
    EasyMock.expect(peekIterator.next()).andReturn(defaultString);
    EasyMock.expect(comparator.compare(EasyMock.eq(resString), EasyMock.eq(defaultString)))
        .andReturn(0);
    EasyMock.expect(peekIterator.next()).andReturn(defaultString);
    EasyMock.expect(binaryFn.apply(EasyMock.eq(resString), EasyMock.eq(defaultString)))
        .andReturn(resString);
    EasyMock.expect(comparator.compare(EasyMock.eq(resString), EasyMock.eq(defaultString)))
        .andReturn(1);

    EasyMock.replay(peekIterator);
    EasyMock.replay(binaryFn);
    EasyMock.replay(comparator);

    String actual = testingIterator.next();
    Assert.assertEquals(resString, actual);

    EasyMock.verify(peekIterator);
    EasyMock.verify(comparator);
    EasyMock.verify(binaryFn);
  }
コード例 #19
0
  @Test
  public void testConfigurationEventDeletedNonScope() throws Exception {
    String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "abc.def";

    ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class);
    EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes();
    EasyMock.replay(cm);

    SecuredCommandConfigTransformer scct = new SecuredCommandConfigTransformer();
    scct.setConfigAdmin(cm);
    scct.init();

    @SuppressWarnings("unchecked")
    ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(cmRef);
    ConfigurationEvent event =
        new ConfigurationEvent(cmRef, ConfigurationEvent.CM_DELETED, null, testPid);

    EasyMock.reset(cm);
    // Do not expect any further calls to cm...
    EasyMock.replay(cm);

    scct.configurationEvent(event);
    EasyMock.verify(cm);
  }
コード例 #20
0
  @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);
  }
コード例 #21
0
  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());
  }
コード例 #22
0
  @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);
  }
コード例 #23
0
  @Test
  public void initiate() throws Exception {
    Person bob = new Person(UUID.randomUUID());
    String sessionId = (new Date()).toString();
    securityService.setCurrent(bob);

    UUID selfHelpGuideId = UUID.randomUUID();

    SelfHelpGuide selfHelpGuide = new SelfHelpGuide();
    SelfHelpGuideResponse selfHelpGuideResponse = new SelfHelpGuideResponse();

    expect(selfHelpGuideService.get(selfHelpGuideId)).andReturn(selfHelpGuide);

    expect(service.initiateSelfHelpGuideResponse(selfHelpGuide, bob, sessionId))
        .andReturn(selfHelpGuideResponse);

    replay(service);
    replay(selfHelpGuideService);

    String response = controller.initiate(selfHelpGuideId);

    verify(service);
    verify(selfHelpGuideService);
    assertEquals(selfHelpGuideResponse.toString(), response);
  }
コード例 #24
0
  /** Tests {@link ControllerImpl#saveOrUpdate(Object)}. */
  @Test
  public void saveOrUpdate() {

    final String OTHER_OBJECT = "kkkkk";

    // at first, we test with a persistent object
    EasyMock.expect(dao.isPersistent(OBJECT)).andReturn(true);
    EasyMock.expect(dao.update(OBJECT)).andReturn(OTHER_OBJECT);
    EasyMock.replay(dao);

    String returned = controller.saveOrUpdate(OBJECT);
    EasyMock.verify(dao);

    assert returned == OTHER_OBJECT;

    // at last, we test with a non-persistent object
    EasyMock.reset(dao);

    EasyMock.expect(dao.isPersistent(OBJECT)).andReturn(false);
    dao.save(OBJECT);
    EasyMock.replay(dao);

    returned = controller.saveOrUpdate(OBJECT);
    EasyMock.verify(dao);

    assert returned == OBJECT;
  }
コード例 #25
0
ファイル: RetryOnRenewTest.java プロジェクト: kwart/jclouds
  @Test
  public void test408ShouldRetry() {
    HttpCommand command = createMock(HttpCommand.class);
    HttpResponse response = createMock(HttpResponse.class);
    @SuppressWarnings("unchecked")
    LoadingCache<Credentials, Access> cache = createMock(LoadingCache.class);
    BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);

    expect(response.getPayload())
        .andReturn(
            Payloads.newStringPayload(
                "The server has waited too long for the request to be sent by the client."))
        .times(3);
    expect(backoffHandler.shouldRetryRequest(command, response)).andReturn(true).once();
    expect(response.getStatusCode()).andReturn(408).once();

    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);
    verify(backoffHandler);
  }
コード例 #26
0
  @Test
  public void testLoadBoardImpl() throws BoardLoadingException {
    final ScribbleSettings settings = new ScribbleSettings("Mock", Language.EN, 3);

    final Dictionary dictionary = createNiceMock(Dictionary.class);
    final TilesBank tilesBank =
        new TilesBank(new TilesBankInfoEditor(Language.EN).createTilesBankInfo());

    final ScribbleBoard board = createStrictMock(ScribbleBoard.class);
    expect(board.getSettings()).andReturn(settings);
    expect(board.getPlayersCount()).andReturn(3);
    board.initGameAfterLoading(tilesBank, dictionary, personalityManager);
    replay(board);

    expect(session.get(ScribbleBoard.class, 1L)).andReturn(board);
    session.evict(board);
    replay(session);

    expect(dictionaryManager.getDictionary(Language.EN)).andReturn(dictionary);
    replay(dictionaryManager);

    expect(tilesBankingHouse.createTilesBank(Language.EN, 3, true)).andReturn(tilesBank);
    replay(tilesBankingHouse);

    final ScribbleBoard board1 = scribblePlayManager.loadBoardImpl(1L);
    assertSame(board, board1);

    verify(board);
    verify(session);
    verify(dictionaryManager);
    verify(tilesBankingHouse);
  }
コード例 #27
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);
  }
コード例 #28
0
  @Test
  public void testCreateBoardImpl() throws BoardCreationException {
    final ScribbleSettings settings = new ScribbleSettings("Mock", Language.EN, 3);

    final Dictionary dictionary = createNiceMock(Dictionary.class);
    replay(dictionary);

    final TilesBankInfoEditor editor = new TilesBankInfoEditor(Language.EN);
    final TilesBank tilesBank = new TilesBank(editor.add('A', 100, 1).createTilesBankInfo());

    expect(dictionaryManager.getDictionary(Language.EN)).andReturn(dictionary);
    replay(dictionaryManager);

    expect(tilesBankingHouse.createTilesBank(Language.EN, 2, true)).andReturn(tilesBank);
    replay(tilesBankingHouse);

    scribblePlayManager.setDictionaryManager(dictionaryManager);
    scribblePlayManager.setTilesBankingHouse(tilesBankingHouse);

    final ScribbleBoard board1 =
        scribblePlayManager.createBoardImpl(settings, Arrays.asList(player1, player2), null);
    assertNotNull(board1);

    verify(dictionaryManager);
    verify(tilesBankingHouse);
  }
コード例 #29
0
  /** Verify that when adding a second player to a full game, an exception is thrown */
  @Test(expected = SnowmanFullException.class)
  public void addPlayerFullTest() {
    // setup dummy entityfactory
    EntityFactory dummyEntityFactory = EasyMock.createMock(EntityFactory.class);
    SnowmanFlag dummyFlag = EasyMock.createNiceMock(SnowmanFlag.class);
    EasyMock.expect(dummyFlag.getID()).andStubReturn(new Integer(0));
    EasyMock.replay(dummyFlag);
    EasyMock.expect(
            dummyEntityFactory.createSnowmanFlag(
                EasyMock.isA(SnowmanGame.class),
                EasyMock.isA(ETeamColor.class),
                EasyMock.isA(Coordinate.class),
                EasyMock.isA(Coordinate.class)))
        .andStubReturn(dummyFlag);
    EasyMock.replay(dummyEntityFactory);

    // create the players
    SnowmanPlayer dummyPlayer = EasyMock.createMock(SnowmanPlayer.class);
    SnowmanPlayer dummyPlayer2 = EasyMock.createMock(SnowmanPlayer.class);
    SnowmanPlayer dummyPlayer3 = EasyMock.createMock(SnowmanPlayer.class);
    ETeamColor color = ETeamColor.Red;

    // create the game
    SnowmanGame game = new SnowmanGameImpl(gameName, 4, dummyEntityFactory);

    // add the players
    game.addPlayer(dummyPlayer, color);
    game.addPlayer(dummyPlayer2, color);
    game.addPlayer(dummyPlayer3, color);
  }
コード例 #30
0
  @SuppressWarnings("unchecked")
  public void test5NoSuitableEndpointFound() throws Exception {
    ServiceResolverRegistry registry =
        OsgiSupport.getReference(bundleContext, ServiceResolverRegistry.class);
    registry.register(resolverMock, resolverProps);

    EndpointDescription endpointMock = createMock(EndpointDescription.class);
    ServiceDescription serviceMock = createMock(ServiceDescription.class);

    List<EndpointDescription> endpoints = new ArrayList<EndpointDescription>();
    endpoints.add(endpointMock);

    expect(resolverMock.getEndpointsFor(service2Interface, null)).andReturn(endpoints).once();
    expect(endpointMock.getServiceName()).andReturn(new QName("dummy", "dummy")).times(2);
    expect(endpointMock.getAddress()).andReturn("non-existing-one").once();
    expect(endpointMock.getName()).andReturn("endpoint-name").once();

    replay(resolverMock);
    replay(endpointMock);
    replay(serviceMock);

    try {
      setExchangeThroughNMR();
      fail("The routing of exchange must fail");
    } catch (RuntimeException e) {
      // expected result
    }

    verify(resolverMock);
    verify(endpointMock);
    verify(serviceMock);
  }