Exemplo n.º 1
0
  public void getDiscoveryServices(
      DiscoveryServiceComponent component,
      TestStub dsTestStub,
      List<ServiceID> dsList,
      boolean modified) {
    DiscoveryService discoveryService = (DiscoveryService) getDiscoveryServiceProxy();
    ObjectDeployment dsOD = getDiscoveryServiceControlDeployment(component);

    DiscoveryService ds = (DiscoveryService) dsTestStub.getObject();

    AcceptanceTestUtil.publishTestObject(
        component, dsTestStub.getDeploymentID(), ds, DiscoveryService.class);

    AcceptanceTestUtil.setExecutionContext(component, dsOD, dsTestStub.getDeploymentID());

    CommuneLogger logger = component.getLogger();

    logger.debug(
        "The Discovery Service "
            + dsTestStub.getDeploymentID().getServiceID()
            + " requested my network list");
    EasyMock.replay(logger);

    ds.hereAreDiscoveryServices(DiscoveryServicesServiceIDListMatcher.eqMatcher(dsList));
    EasyMock.replay(ds);

    discoveryService.getDiscoveryServices(ds);

    EasyMock.verify(logger);
    EasyMock.verify(ds);
    EasyMock.reset(logger);
    EasyMock.reset(ds);
  }
  @Test
  public void test302DoesNotRetryAfterLimit() {

    HttpCommand command = createMock(HttpCommand.class);
    HttpResponse response =
        new HttpResponse(
            302,
            "HTTP/1.1 302 Found",
            null,
            ImmutableMultimap.of(
                HttpHeaders.LOCATION,
                "/api/v0.8b-ext2.5/Error.aspx?aspxerrorpath=/api/v0.8b-ext2.5/org.svc/1906645"));

    expect(command.incrementRedirectCount()).andReturn(5);

    replay(command);

    RedirectionRetryHandler retry =
        Guice.createInjector(new MockModule(), new RestModule())
            .getInstance(RedirectionRetryHandler.class);

    assert !retry.shouldRetryRequest(command, response);

    verify(command);
  }
 private void verifyMocks() {
   verify(
       mockExternalLinkUtil,
       mockBuildUtilsInfo,
       mockLicenseStringFactory,
       mockJiraLicenseService,
       mockValidationResult,
       mockIndexManager,
       mockAttachmentPathManager,
       mockIndexPathManager,
       mockUpgradeManager,
       mockConsistencyChecker,
       mockMailQueue,
       mockScheduler,
       mockBeanFactory,
       mockI18nHelper,
       mockPermissionManager,
       mockJiraHome,
       mockTaskManager,
       mockOfBizDelegator,
       mockModelReader,
       mockPluginEventManager,
       mockFactory,
       mockBarrier,
       backup);
 }
  /** tests {@link MostSimilarItemPairsMapper} */
  public void testMostSimilarItemsPairsMapper() throws Exception {

    OpenIntLongHashMap indexItemIDMap = new OpenIntLongHashMap();
    indexItemIDMap.put(12, 12L);
    indexItemIDMap.put(34, 34L);
    indexItemIDMap.put(56, 56L);

    Mapper<IntWritable, VectorWritable, EntityEntityWritable, DoubleWritable>.Context context =
        EasyMock.createMock(Mapper.Context.class);

    context.write(new EntityEntityWritable(34L, 56L), new DoubleWritable(0.9));

    EasyMock.replay(context);

    Vector vector = new RandomAccessSparseVector(Integer.MAX_VALUE);
    vector.set(12, 0.2);
    vector.set(34, 1.0);
    vector.set(56, 0.9);

    MostSimilarItemPairsMapper mapper = new MostSimilarItemPairsMapper();
    setField(mapper, "indexItemIDMap", indexItemIDMap);
    setField(mapper, "maxSimilarItemsPerItem", 1);

    mapper.map(new IntWritable(34), new VectorWritable(vector), context);

    EasyMock.verify(context);
  }
Exemplo n.º 5
0
  /**
   * Closing a connection handle should release that connection back in the pool and mark it as
   * closed.
   *
   * @throws SecurityException
   * @throws NoSuchFieldException
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   * @throws NoSuchMethodException
   * @throws SQLException
   */
  @SuppressWarnings("unchecked")
  @Test
  public void testInternalClose()
      throws SecurityException, NoSuchFieldException, IllegalArgumentException,
          IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException {
    ConcurrentLinkedQueue<Statement> mockStatementHandles =
        createNiceMock(ConcurrentLinkedQueue.class);
    StatementHandle mockStatement = createNiceMock(StatementHandle.class);

    mockConnection.close();
    expectLastCall().once().andThrow(new SQLException()).once();

    Map<Connection, Reference<ConnectionHandle>> refs =
        new HashMap<Connection, Reference<ConnectionHandle>>();
    expect(mockPool.getFinalizableRefs()).andReturn(refs).anyTimes();
    FinalizableReferenceQueue finalizableRefQueue = new FinalizableReferenceQueue();

    expect(mockPool.getFinalizableRefQueue()).andReturn(finalizableRefQueue).anyTimes();
    expect(mockConnection.getPool()).andReturn(mockPool).anyTimes();

    replay(mockStatement, mockConnection, mockStatementHandles, mockPool);
    testClass.internalClose();
    try {
      testClass.internalClose(); // 2nd time should throw exception
      fail("Should have thrown an exception");
    } catch (Throwable t) {
      // do nothing.
    }

    verify(mockStatement, mockConnection, mockStatementHandles);
  }
  @Test
  public void test() {
    ChefClient chef = createMock(ChefClient.class);

    Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall>of();

    Node node = new Node("name", ImmutableSet.<String>of());

    Supplier<Map<String, JsonBall>> automaticSupplier =
        Suppliers.<Map<String, JsonBall>>ofInstance(automatic);

    Node nodeWithAutomatic =
        new Node(
            "name",
            ImmutableMap.<String, JsonBall>of(),
            ImmutableMap.<String, JsonBall>of(),
            ImmutableMap.<String, JsonBall>of(),
            automatic,
            ImmutableSet.<String>of());

    expect(chef.getNode("name")).andReturn(node);
    node.getAutomatic().putAll(automaticSupplier.get());
    expect(chef.updateNode(nodeWithAutomatic)).andReturn(null);

    replay(chef);

    UpdateAutomaticAttributesOnNodeImpl updater =
        new UpdateAutomaticAttributesOnNodeImpl(chef, automaticSupplier);

    updater.execute("name");
    verify(chef);
  }
Exemplo n.º 7
0
  /** tests {@link PartialMultiplyMapper} */
  @Test
  public void testPartialMultiplyMapper() throws Exception {

    Vector similarityColumn = new RandomAccessSparseVector(Integer.MAX_VALUE, 100);
    similarityColumn.set(3, 0.5);
    similarityColumn.set(7, 0.8);

    Mapper<VarIntWritable, VectorAndPrefsWritable, VarLongWritable, PrefAndSimilarityColumnWritable>
            .Context
        context = EasyMock.createMock(Mapper.Context.class);

    PrefAndSimilarityColumnWritable one = new PrefAndSimilarityColumnWritable();
    PrefAndSimilarityColumnWritable two = new PrefAndSimilarityColumnWritable();
    one.set(1.0f, similarityColumn);
    two.set(3.0f, similarityColumn);

    context.write(EasyMock.eq(new VarLongWritable(123L)), EasyMock.eq(one));
    context.write(EasyMock.eq(new VarLongWritable(456L)), EasyMock.eq(two));

    EasyMock.replay(context);

    VectorAndPrefsWritable vectorAndPrefs =
        new VectorAndPrefsWritable(
            similarityColumn, Arrays.asList(123L, 456L), Arrays.asList(1.0f, 3.0f));

    new PartialMultiplyMapper().map(new VarIntWritable(1), vectorAndPrefs, context);

    EasyMock.verify(context);
  }
  @Before
  public void setUp() throws Exception {
    props = EasyMock.createStrictMock(Props.class);
    mockFlow1 = EasyMock.createMock(ExecutableFlow.class);
    mockFlow2 = EasyMock.createMock(ExecutableFlow.class);

    EasyMock.expect(mockFlow1.getName()).andReturn("a").once();
    EasyMock.expect(mockFlow2.getName()).andReturn("b").once();

    EasyMock.expect(mockFlow1.getStatus()).andReturn(Status.READY).times(3);
    EasyMock.expect(mockFlow2.getStatus()).andReturn(Status.READY).times(3);

    EasyMock.expect(mockFlow1.getStartTime()).andReturn(null).once();
    EasyMock.expect(mockFlow2.getStartTime()).andReturn(null).once();

    EasyMock.expect(mockFlow1.getName()).andReturn("1").once();
    EasyMock.expect(mockFlow2.getName()).andReturn("2").once();
    EasyMock.replay(mockFlow1, mockFlow2, props);

    flow = new GroupedExecutableFlow("blah", mockFlow1, mockFlow2);
    Assert.assertEquals("1 + 2", flow.getName());

    EasyMock.verify(mockFlow1, mockFlow2, props);
    EasyMock.reset(mockFlow1, mockFlow2, props);
  }
  @Test
  public void testBasic() throws Exception {
    ServiceHandler handler = new ServiceHandler();
    Service service = new Service();
    handler.registerWebService(service);

    Request baseRequest = org.easymock.classextension.EasyMock.createMock(Request.class);
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);

    expect(baseRequest.isHandled()).andReturn(false);
    expect(request.getMethod()).andReturn("GET");
    expect(request.getPathInfo()).andReturn("/");
    expect(request.getParameter("bar")).andReturn("bar2");
    expect(request.getParameter("baz")).andReturn(null);
    expect(request.getHeader("Content-Length")).andReturn("103");
    expect(response.isCommitted()).andReturn(false).anyTimes();
    baseRequest.setHandled(true);

    org.easymock.classextension.EasyMock.replay(baseRequest);
    replay(request, response);
    handler.handle(null, baseRequest, request, response);
    org.easymock.classextension.EasyMock.verify(baseRequest);
    verify(request, response);
  }
Exemplo n.º 10
0
  /**
   * Closing a connection handle should release that connection back in the pool and mark it as
   * closed.
   *
   * @throws SecurityException
   * @throws NoSuchFieldException
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   * @throws NoSuchMethodException
   * @throws SQLException
   */
  @Test
  public void testClose()
      throws SecurityException, NoSuchFieldException, IllegalArgumentException,
          IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException {

    Field field = testClass.getClass().getDeclaredField("doubleCloseCheck");
    field.setAccessible(true);
    field.set(testClass, true);

    testClass.renewConnection();
    mockPool.releaseConnection((Connection) anyObject());
    expectLastCall().once().andThrow(new SQLException()).once();
    replay(mockPool);

    testClass.close();

    // logically mark the connection as closed
    field = testClass.getClass().getDeclaredField("logicallyClosed");

    field.setAccessible(true);
    Assert.assertTrue(field.getBoolean(testClass));
    assertTrue(testClass.isClosed());

    testClass.renewConnection();
    try {
      testClass.close(); // 2nd time should throw an exception
      fail("Should have thrown an exception");
    } catch (Throwable t) {
      // do nothing.
    }

    verify(mockPool);
  }
  @Test
  public void testWriteEmptyFile() throws Exception {
    AbstractStreamWriteFilter<M> filter = createFilter();
    M message = createMessage(new byte[0]);

    WriteRequest writeRequest = new DefaultWriteRequest(message, new DummyWriteFuture());

    NextFilter nextFilter = EasyMock.createMock(NextFilter.class);
    /*
     * Record expectations
     */
    nextFilter.messageSent(session, writeRequest);

    /*
     * Replay.
     */
    EasyMock.replay(nextFilter);

    filter.filterWrite(nextFilter, session, writeRequest);

    /*
     * Verify.
     */
    EasyMock.verify(nextFilter);

    assertTrue(writeRequest.getFuture().isWritten());
  }
Exemplo n.º 12
0
  public void getPeerStatusChangeHistory(
      DiscoveryServiceComponent component, List<DS_PeerStatusChange> historyList) {

    CommunityStatusProvider communityStatusProvider = getCommunityStatusProviders(component);
    ObjectDeployment cspObjectDeployment = getCommunityStatusProvidersObjectDeployment(component);

    CommunityStatusProviderClient cspClientMock =
        EasyMock.createMock(CommunityStatusProviderClient.class);

    // adding behavior
    cspClientMock.hereIsPeerStatusChangeHistory(
        DS_PeerStatusChangeHistoryMatcher.eqMatcher((historyList)), EasyMock.gt(0L));

    EasyMock.replay(cspClientMock);

    DeploymentID deploymentID =
        new DeploymentID(new ContainerID("dsClient", "dsServer", "peer", "dsClientPK"), "peer");
    AcceptanceTestUtil.publishTestObject(
        component, deploymentID, cspClientMock, CommunityStatusProviderClient.class);

    AcceptanceTestUtil.setExecutionContext(component, cspObjectDeployment, deploymentID);

    communityStatusProvider.getPeerStatusChangeHistory(cspClientMock, 0L);

    EasyMock.verify(cspClientMock);
  }
  @Test
  public void testWriteWhileWriteInProgress() throws Exception {
    AbstractStreamWriteFilter<M> filter = createFilter();
    M message = createMessage(new byte[5]);

    Queue<WriteRequest> queue = new LinkedList<WriteRequest>();

    /*
     * Make up the situation.
     */
    session.setAttribute(filter.CURRENT_STREAM, message);
    session.setAttribute(filter.WRITE_REQUEST_QUEUE, queue);

    NextFilter nextFilter = EasyMock.createMock(NextFilter.class);
    /*
     * Replay.  (We recorded *nothing* because nothing should occur.)
     */
    EasyMock.replay(nextFilter);

    WriteRequest wr = new DefaultWriteRequest(new Object(), new DummyWriteFuture());
    filter.filterWrite(nextFilter, session, wr);
    assertEquals(1, queue.size());
    assertSame(wr, queue.poll());

    /*
     * Verify.
     */
    EasyMock.verify(nextFilter);

    session.removeAttribute(filter.CURRENT_STREAM);
    session.removeAttribute(filter.WRITE_REQUEST_QUEUE);
  }
  /**
   * Tests when the contents of the file fits into one write buffer.
   *
   * @throws Exception when something goes wrong
   */
  @Test
  public void testWriteSingleBufferFile() throws Exception {
    byte[] data = new byte[] {1, 2, 3, 4};

    AbstractStreamWriteFilter<M> filter = createFilter();
    M message = createMessage(data);

    WriteRequest writeRequest = new DefaultWriteRequest(message, new DummyWriteFuture());

    NextFilter nextFilter = EasyMock.createMock(NextFilter.class);
    /*
     * Record expectations
     */
    nextFilter.filterWrite(
        EasyMock.eq(session), eqWriteRequest(new DefaultWriteRequest(IoBuffer.wrap(data))));
    nextFilter.messageSent(session, writeRequest);

    /*
     * Replay.
     */
    EasyMock.replay(nextFilter);

    filter.filterWrite(nextFilter, session, writeRequest);
    filter.messageSent(nextFilter, session, writeRequest);

    /*
     * Verify.
     */
    EasyMock.verify(nextFilter);

    assertTrue(writeRequest.getFuture().isWritten());
  }
  /**
   * Tests that the filter just passes objects which aren't FileRegion's through to the next filter.
   *
   * @throws Exception when something goes wrong
   */
  @Test
  public void testWriteNonFileRegionMessage() throws Exception {
    AbstractStreamWriteFilter<M> filter = createFilter();

    Object message = new Object();
    WriteRequest writeRequest = new DefaultWriteRequest(message, new DummyWriteFuture());

    NextFilter nextFilter = EasyMock.createMock(NextFilter.class);
    /*
     * Record expectations
     */
    nextFilter.filterWrite(session, writeRequest);
    nextFilter.messageSent(session, writeRequest);

    /*
     * Replay.
     */
    EasyMock.replay(nextFilter);

    filter.filterWrite(nextFilter, session, writeRequest);
    filter.messageSent(nextFilter, session, writeRequest);

    /*
     * Verify.
     */
    EasyMock.verify(nextFilter);
  }
  @Test
  public void testAllBaseJobsCompleted() throws Exception {
    EasyMock.replay(mockFlow1, mockFlow2, props);

    final JobManager factory = EasyMock.createStrictMock(JobManager.class);
    EasyMock.replay(factory);

    final IndividualJobExecutableFlow completedJob1 =
        new IndividualJobExecutableFlow("blah", "blah", factory);
    final IndividualJobExecutableFlow completedJob2 =
        new IndividualJobExecutableFlow("blah", "blah", factory);

    flow = new GroupedExecutableFlow("blah", completedJob1, completedJob2);

    completedJob1.markCompleted();
    completedJob2.markCompleted();

    AtomicBoolean callbackWasCalled = new AtomicBoolean(false);
    flow.execute(
        props,
        new OneCallFlowCallback(callbackWasCalled) {
          @Override
          public void theCallback(Status status) {
            Assert.assertEquals(Status.SUCCEEDED, status);
          }
        });

    Assert.assertTrue("Callback wasn't called!?", callbackWasCalled.get());
    EasyMock.verify(factory);
  }
Exemplo n.º 17
0
  public void testGetPhotosetsViaMockService() throws Exception {

    Photo photo1 = (Photo) EasyMock.createStrictMock(Photo.class);
    EasyMock.expect(photo1.getId()).andReturn("dummyId1");
    Photo photo2 = (Photo) EasyMock.createStrictMock(Photo.class);
    EasyMock.expect(photo2.getId()).andReturn("dummyId2");

    List photosetsPhotos1 = new ArrayList();
    photosetsPhotos1.add(photo1);
    List photosetsPhotos2 = new ArrayList();
    photosetsPhotos2.add(photo2);

    PhotosetsInterface photosetsInterface =
        (PhotosetsInterface) EasyMock.createStrictMock(PhotosetsInterface.class);
    EasyMock.expect(photosetsInterface.getPhotos("711101")).andReturn(photosetsPhotos1);
    EasyMock.expect(photosetsInterface.getPhotos("711155")).andReturn(photosetsPhotos2);

    PhotosInterface photosInterface =
        (PhotosInterface) EasyMock.createStrictMock(PhotosInterface.class);
    EasyMock.expect(photosInterface.getSizes("dummyId1")).andReturn(new ArrayList());
    EasyMock.expect(photosInterface.getSizes("dummyId2")).andReturn(new ArrayList());

    Flickr flickr = (Flickr) EasyMock.createStrictMock(Flickr.class);
    EasyMock.expect(flickr.getPhotosetsInterface()).andReturn(photosetsInterface);
    EasyMock.expect(flickr.getPhotosInterface()).andReturn(photosInterface);

    EasyMock.replay(new Object[] {flickr, photosetsInterface, photosInterface, photo1, photo2});

    FlickrFacade flickrFacade = new FlickrFacade(flickr);
    List photos = flickrFacade.getPhotosFromPhotosets(PHOTOSET_IDS_CSV);
    assertNotNull(photos);
    assertTrue(photos.size() == 2);

    EasyMock.verify(new Object[] {flickr, photosetsInterface, photosInterface, photo1, photo2});
  }
Exemplo n.º 18
0
  /**
   * Proper closure test
   *
   * @throws SecurityException
   * @throws NoSuchFieldException
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws SQLException
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Test
  public void testStatementCacheCheckForProperClosure()
      throws SecurityException, NoSuchFieldException, IllegalArgumentException,
          IllegalAccessException, SQLException {

    ConcurrentMap mockCache = createNiceMock(ConcurrentMap.class);
    List<StatementHandle> mockStatementCollections = createNiceMock(List.class);
    StatementCache testClass = new StatementCache(1, false, null);
    Field field = testClass.getClass().getDeclaredField("cache");
    field.setAccessible(true);
    field.set(testClass, mockCache);

    field = testClass.getClass().getDeclaredField("logger");
    field.setAccessible(true);
    field.set(null, mockLogger);

    Iterator<StatementHandle> mockIterator = createNiceMock(Iterator.class);
    StatementHandle mockStatement = createNiceMock(StatementHandle.class);

    expect(mockCache.values()).andReturn(mockStatementCollections).anyTimes();
    expect(mockStatementCollections.iterator()).andReturn(mockIterator).anyTimes();
    expect(mockIterator.hasNext()).andReturn(true).once().andReturn(false).once();
    expect(mockIterator.next()).andReturn(mockStatement).anyTimes();
    expect(mockStatement.isClosed()).andReturn(false).once();
    mockLogger.error((String) anyObject());
    expectLastCall().once();
    replay(mockCache, mockStatementCollections, mockIterator, mockStatement, mockLogger);

    testClass.checkForProperClosure();
    verify(mockCache, mockStatement, mockLogger);
  }
Exemplo n.º 19
0
  /**
   * tests {@link UserVectorSplitterMapper} in the special case that some userIDs shall be excluded
   */
  @Test
  public void testUserVectorSplitterMapperUserExclusion() throws Exception {
    Mapper<VarLongWritable, VectorWritable, VarIntWritable, VectorOrPrefWritable>.Context context =
        EasyMock.createMock(Mapper.Context.class);

    context.write(
        EasyMock.eq(new VarIntWritable(34)), prefOfVectorOrPrefWritableMatches(123L, 0.5f));
    context.write(
        EasyMock.eq(new VarIntWritable(56)), prefOfVectorOrPrefWritableMatches(123L, 0.7f));

    EasyMock.replay(context);

    FastIDSet usersToRecommendFor = new FastIDSet();
    usersToRecommendFor.add(123L);

    UserVectorSplitterMapper mapper = new UserVectorSplitterMapper();
    setField(mapper, "maxPrefsPerUserConsidered", 10);
    setField(mapper, "usersToRecommendFor", usersToRecommendFor);

    RandomAccessSparseVector vector = new RandomAccessSparseVector(Integer.MAX_VALUE, 100);
    vector.set(34, 0.5);
    vector.set(56, 0.7);

    mapper.map(new VarLongWritable(123L), new VectorWritable(vector), context);
    mapper.map(new VarLongWritable(456L), new VectorWritable(vector), context);

    EasyMock.verify(context);
  }
Exemplo n.º 20
0
  /** tests {@link ToVectorAndPrefReducer} */
  @Test
  public void testToVectorAndPrefReducer() throws Exception {
    Reducer<VarIntWritable, VectorOrPrefWritable, VarIntWritable, VectorAndPrefsWritable>.Context
        context = EasyMock.createMock(Reducer.Context.class);

    context.write(
        EasyMock.eq(new VarIntWritable(1)),
        vectorAndPrefsWritableMatches(
            Arrays.asList(123L, 456L),
            Arrays.asList(1.0f, 2.0f),
            MathHelper.elem(3, 0.5),
            MathHelper.elem(7, 0.8)));

    EasyMock.replay(context);

    Vector similarityColumn = new RandomAccessSparseVector(Integer.MAX_VALUE, 100);
    similarityColumn.set(3, 0.5);
    similarityColumn.set(7, 0.8);

    VectorOrPrefWritable itemPref1 = new VectorOrPrefWritable(123L, 1.0f);
    VectorOrPrefWritable itemPref2 = new VectorOrPrefWritable(456L, 2.0f);
    VectorOrPrefWritable similarities = new VectorOrPrefWritable(similarityColumn);

    new ToVectorAndPrefReducer()
        .reduce(new VarIntWritable(1), Arrays.asList(itemPref1, itemPref2, similarities), context);

    EasyMock.verify(context);
  }
  @Test
  public void launchRemoteSession_generatesSslCertsIfBrowserSideLogEnabled() throws Exception {
    String location = null;

    generator = createStrictMock(SslCertificateGenerator.class);
    generator.generateSSLCertsForLoggingHosts();
    expectLastCall().once();

    remoteConfiguration.setSeleniumServer(generator);
    ((DesiredCapabilities) browserOptions).setCapability("browserSideLog", true);

    launcher =
        new SafariCustomProfileLauncher(browserOptions, remoteConfiguration, "session", location) {
          @Override
          protected void launch(String url) {}

          @Override
          protected BrowserInstallation locateSafari(String location) {
            return new BrowserInstallation("", "");
          }
        };

    replay(generator);
    launcher.launchRemoteSession("http://url");
    verify(generator);
  }
  private void assertCodeMakes(
      String method,
      URI uri,
      int statusCode,
      String message,
      String contentType,
      String content,
      Class<? extends Exception> expected) {

    ElasticStackErrorHandler function =
        Guice.createInjector().getInstance(ElasticStackErrorHandler.class);

    HttpCommand command = createMock(HttpCommand.class);
    HttpRequest request = new HttpRequest(method, uri);
    HttpResponse response =
        new HttpResponse(
            statusCode, message, Payloads.newInputStreamPayload(Strings2.toInputStream(content)));
    response.getPayload().getContentMetadata().setContentType(contentType);

    expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();
    command.setException(classEq(expected));

    replay(command);

    function.handleError(command, response);

    verify(command);
  }
Exemplo n.º 23
0
  @Test
  public void testGetObjectInstance() throws Exception {
    config.setAcquireIncrement(5);
    config.setMinConnectionsPerPartition(30);
    config.setMaxConnectionsPerPartition(100);
    config.setPartitionCount(1);

    Reference mockRef = createNiceMock(Reference.class);
    Enumeration<RefAddr> mockEnum = createNiceMock(Enumeration.class);
    RefAddr mockRefAddr = createNiceMock(RefAddr.class);
    expect(mockRef.getAll()).andReturn(mockEnum).anyTimes();
    expect(mockEnum.hasMoreElements()).andReturn(true).times(2);

    expect(mockEnum.nextElement()).andReturn(mockRefAddr).anyTimes();
    expect(mockRefAddr.getType())
        .andReturn("driverClassName")
        .once()
        .andReturn("password")
        .times(2);
    expect(mockRefAddr.getContent())
        .andReturn("com.jolbox.bonecp.MockJDBCDriver")
        .once()
        .andReturn("abcdefgh")
        .once();
    replay(mockRef, mockEnum, mockRefAddr);
    BoneCPDataSource dsb = new BoneCPDataSource();
    BoneCPDataSource result = (BoneCPDataSource) dsb.getObjectInstance(mockRef, null, null, null);
    assertEquals("abcdefgh", result.getPassword());
    verify(mockRef, mockEnum, mockRefAddr);
  }
  protected void assertCodeMakes(
      String method,
      URI uri,
      int statusCode,
      String message,
      String contentType,
      String content,
      Class<? extends Exception> expected) {

    HttpErrorHandler function =
        Guice.createInjector(new SaxParserModule()).getInstance(getHandlerClass());

    HttpCommand command = createMock(HttpCommand.class);
    HttpRequest request = new HttpRequest(method, uri);
    HttpResponse response =
        new HttpResponse(statusCode, message, Payloads.newStringPayload(content));
    if (contentType != null) response.getPayload().getContentMetadata().setContentType(contentType);

    expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();
    command.setException(classEq(expected));

    replay(command);

    function.handleError(command, response);

    verify(command);
  }
Exemplo n.º 25
0
  /**
   * Tests fake exceptions, connection should be shutdown if the scheduler was marked as going down.
   * Same test except just used to check for a spurious interrupted exception (should be logged).
   *
   * @throws SQLException
   * @throws InterruptedException
   * @throws NoSuchFieldException
   * @throws SecurityException
   * @throws IllegalAccessException
   * @throws IllegalArgumentException
   */
  @Test
  public void testExceptionOnCloseConnection()
      throws SQLException, InterruptedException, SecurityException, NoSuchFieldException,
          IllegalArgumentException, IllegalAccessException {
    ArrayBlockingQueue<ConnectionHandle> fakeFreeConnections =
        new ArrayBlockingQueue<ConnectionHandle>(1);
    fakeFreeConnections.add(mockConnection);

    config.setIdleConnectionTestPeriod(1);
    expect(mockPool.getConfig()).andReturn(config).anyTimes();
    expect(mockConnectionPartition.getFreeConnections()).andReturn(fakeFreeConnections).anyTimes();
    expect(mockConnectionPartition.getMinConnections()).andReturn(10).once();
    expect(mockConnection.isPossiblyBroken()).andReturn(false);
    expect(mockConnection.getConnectionLastUsed()).andReturn(0L);
    expect(mockPool.isConnectionHandleAlive((ConnectionHandle) anyObject()))
        .andReturn(false)
        .anyTimes();

    // connection should be closed
    mockConnection.internalClose();
    expectLastCall().andThrow(new SQLException());

    replay(mockPool, mockConnection, mockConnectionPartition, mockExecutor, mockLogger);
    this.testClass = new ConnectionTesterThread(mockConnectionPartition, mockExecutor, mockPool);
    Field loggerField = this.testClass.getClass().getDeclaredField("logger");
    loggerField.setAccessible(true);
    loggerField.set(this.testClass, mockLogger);
    this.testClass.run();
    verify(mockPool, mockConnectionPartition, mockExecutor, mockConnection, mockLogger);
  }
Exemplo n.º 26
0
  /**
   * Tests fake exceptions, connection should be shutdown if the scheduler was marked as going down.
   * Mostly for code coverage.
   *
   * @throws SQLException
   * @throws InterruptedException
   */
  @Test
  public void testInterruptedException() throws SQLException, InterruptedException {
    ArrayBlockingQueue<ConnectionHandle> fakeFreeConnections =
        new ArrayBlockingQueue<ConnectionHandle>(1);
    fakeFreeConnections.add(mockConnection);

    config.setIdleConnectionTestPeriod(1);
    expect(mockPool.getConfig()).andReturn(config).anyTimes();
    expect(mockConnectionPartition.getFreeConnections()).andReturn(fakeFreeConnections).anyTimes();
    expect(mockConnectionPartition.getMinConnections()).andReturn(10).once();
    expect(mockConnection.isPossiblyBroken()).andReturn(false);
    expect(mockConnection.getConnectionLastUsed()).andReturn(0L);
    expect(mockPool.isConnectionHandleAlive((ConnectionHandle) anyObject()))
        .andReturn(true)
        .anyTimes();
    expect(mockExecutor.isShutdown()).andReturn(true);
    mockPool.releaseInAnyFreePartition(
        (ConnectionHandle) anyObject(), (ConnectionPartition) anyObject());
    expectLastCall().andThrow(new InterruptedException());
    // connection should be closed
    mockConnection.internalClose();
    mockPool.postDestroyConnection(mockConnection);
    expectLastCall().once();

    replay(mockPool, mockConnection, mockConnectionPartition, mockExecutor);
    this.testClass = new ConnectionTesterThread(mockConnectionPartition, mockExecutor, mockPool);
    this.testClass.run();
    verify(mockPool, mockConnectionPartition, mockExecutor, mockConnection);
  }
Exemplo n.º 27
0
  public void testGetPhotosViaMockServiceHandlesIOException() throws Exception {

    Photo photo = (Photo) EasyMock.createStrictMock(Photo.class);
    EasyMock.expect(photo.getId()).andReturn("dummyId1");
    EasyMock.expect(photo.getId()).andReturn("dummyId2");
    PhotosInterface photosInterface =
        (PhotosInterface) EasyMock.createStrictMock(PhotosInterface.class);
    EasyMock.expect(photosInterface.getInfo("31670708", null)).andReturn(photo);
    EasyMock.expect(photosInterface.getSizes("dummyId1")).andThrow(new IOException());
    EasyMock.expect(photosInterface.getInfo("31671077", null)).andReturn(photo);
    EasyMock.expect(photosInterface.getSizes("dummyId2")).andThrow(new IOException());
    Flickr flickr = (Flickr) EasyMock.createStrictMock(Flickr.class);
    EasyMock.expect(flickr.getPhotosInterface()).andReturn(photosInterface);

    EasyMock.replay(new Object[] {flickr, photosInterface, photo});

    FlickrFacade flickrFacade = new FlickrFacade(flickr);
    try {
      List photos = flickrFacade.getPhotos(PHOTO_IDS_CSV);
      assertNotNull(photos);
      assertTrue(photos.size() == 0);
    } catch (Exception e) {
      fail("Thrown exception should've been handled by FlickrFacade: " + e);
    }

    EasyMock.verify(new Object[] {flickr, photosInterface, photo});
  }
 /**
  * Test method for {@link
  * org.apache.tiles.request.jsp.JspPrintWriterAdapter#println(java.lang.String)}.
  *
  * @throws IOException If something goes wrong.
  */
 public void testPrintlnString() throws IOException {
   JspWriter writer = createMock(JspWriter.class);
   writer.println("this is a string");
   JspPrintWriterAdapter adapter = new JspPrintWriterAdapter(writer);
   replay(writer);
   adapter.println("this is a string");
   verify(writer);
 }
 /**
  * Test method for {@link org.apache.tiles.request.jsp.JspPrintWriterAdapter#append(char)}.
  *
  * @throws IOException If something goes wrong.
  */
 public void testAppendChar() throws IOException {
   JspWriter writer = createMock(JspWriter.class);
   expect(writer.append('c')).andReturn(writer);
   JspPrintWriterAdapter adapter = new JspPrintWriterAdapter(writer);
   replay(writer);
   assertEquals(adapter, adapter.append('c'));
   verify(writer);
 }
 /**
  * Test method for {@link org.apache.tiles.request.jsp.JspPrintWriterAdapter#flush()}.
  *
  * @throws IOException If something goes wrong.
  */
 public void testFlush() throws IOException {
   JspWriter writer = createMock(JspWriter.class);
   writer.flush();
   JspPrintWriterAdapter adapter = new JspPrintWriterAdapter(writer);
   replay(writer);
   adapter.flush();
   verify(writer);
 }