コード例 #1
0
  @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);
  }
コード例 #2
0
  public void testHeadingMarkupForResolutionGV() {

    final IssueConstant issueConstant = createMock(IssueConstant.class);

    expect(issueConstant.getNameTranslation()).andStubReturn("theNameTranslated");
    expect(issueConstant.getDescTranslation()).andStubReturn("theDescTranslated");
    expect(issueConstant.getIconUrl()).andStubReturn("http://jira/icon.gif");

    replay(issueConstant);

    expect(constantsManager.getIssueConstant((GenericValue) anyObject())).andReturn(issueConstant);

    replay(constantsManager);

    String s =
        ObjectToFieldValueMapper.transform(
                "resolution", new MockGenericValue("foo"), FULL_URL, transformer)
            .getHtml();

    assertEquals(
        "<img src=\"http://jira/icon.gif\" height=\"16\" width=\"16\" alt=\"theNameTranslated\" title=\"theNameTranslated - theDescTranslated\"/><a href='"
            + FULL_URL
            + "' title='theDescTranslated'>theNameTranslated</a>",
        s);
  }
コード例 #3
0
ファイル: Req_511_Util.java プロジェクト: OurGrid/OurGrid
  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);
  }
コード例 #4
0
  @Test
  public void accepts() throws DatabaseException {
    ArrayList<RanChangeSet> ranChanges = new ArrayList<RanChangeSet>();
    ranChanges.add(
        new RanChangeSet(
            "path/changelog", "1", "testAuthor", CheckSum.parse("12345"), new Date(), null, null));
    ranChanges.add(
        new RanChangeSet(
            "path/changelog", "2", "testAuthor", CheckSum.parse("12345"), new Date(), null, null));

    Database database = createMock(Database.class);
    expect(database.getRanChangeSetList()).andReturn(ranChanges);
    expect(database.getDatabaseChangeLogTableName()).andReturn("DATABASECHANGELOG").anyTimes();
    expect(database.getDefaultSchemaName()).andReturn(null).anyTimes();

    Executor template = createMock(Executor.class);
    expect(template.update(isA(UpdateStatement.class))).andReturn(1).anyTimes();
    //        template.comment("Lock Database");
    //        expectLastCall();

    replay(database);
    replay(template);
    ExecutorService.getInstance().setExecutor(database, template);

    ShouldRunChangeSetFilter filter = new ShouldRunChangeSetFilter(database);

    // everything same
    assertFalse(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, false, "path/changelog", null, null)));

    // alwaysRun
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", true, false, "path/changelog", null, null)));

    // run on change
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, true, "path/changelog", null, null)));

    // different id
    assertTrue(
        filter.accepts(
            new ChangeSet("3", "testAuthor", false, false, "path/changelog", null, null)));

    // different author
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "otherAuthor", false, false, "path/changelog", null, null)));

    // different path
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, false, "other/changelog", null, null)));
  }
コード例 #5
0
  public void testHeadingMarkupForNoCustomFields() {

    expect(cfm.getCustomFieldObject("customfield_nick")).andReturn(null);
    replay(cfm);

    expect(i18n.getText("common.words.none")).andReturn("none");

    replay(i18n);

    final StatsMarkup statsMarkup =
        ObjectToFieldValueMapper.transform("customfield_nick", "nick", FULL_URL, transformer);

    assertEquals("<a href='" + FULL_URL + "'>none</a>", statsMarkup.getHtml());
  }
コード例 #6
0
  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);
  }
コード例 #7
0
    private void installSourceHelper(WMSLayer tl) throws Exception {
      // WMSSourceHelper that on makeRequest() returns always the same fake image
      WMSSourceHelper mockSourceHelper = EasyMock.createMock(WMSSourceHelper.class);

      Capture<WMSMetaTile> wmsRequestsCapturer =
          new Capture<WMSMetaTile>() {

            @Override
            public void setValue(WMSMetaTile o) {
              wmsMetaRequestCounter.incrementAndGet();
            }
          };
      Capture<Resource> resourceCapturer =
          new Capture<Resource>() {

            @Override
            public void setValue(Resource target) {
              try {
                target.transferFrom(Channels.newChannel(new ByteArrayInputStream(fakeWMSResponse)));
                tileTransferCounter.incrementAndGet();
              } catch (IOException e) {
                throw new RuntimeException(e);
              }
            }
          };
      mockSourceHelper.makeRequest(capture(wmsRequestsCapturer), capture(resourceCapturer));
      expectLastCall().anyTimes().asStub();
      mockSourceHelper.setConcurrency(32);
      mockSourceHelper.setBackendTimeout(120);
      replay(mockSourceHelper);

      tl.setSourceHelper(mockSourceHelper);
    }
コード例 #8
0
  public void testLocalDeadlock() throws Exception {
    final DldGlobalTransaction ddgt = (DldGlobalTransaction) gtf.newGlobalTransaction();

    InvocationContext localTxContext = buildLocalTxIc(ddgt);

    ddgt.setCoinToss(0);
    lockOwner.setCoinToss(1);
    assert ddgt.wouldLose(lockOwner);

    // this makes sure that we cannot acquire lock from the first try
    expect(lc.acquireLock("k", SPIN_DURATION, TimeUnit.MILLISECONDS)).andReturn(null);
    Lock mockLock = createNiceMock(Lock.class);
    expect(lc.acquireLock("k", SPIN_DURATION, TimeUnit.MILLISECONDS)).andReturn(mockLock);
    lockOwner.setRemote(false);
    lockOwner.setLockIntention("k");
    lockManager.setOwner(lockOwner);
    lockManager.setOwnsLock(true);
    replay(lc);
    try {
      lockManager.lockAndRecord("k", localTxContext);
      assert false;
    } catch (DeadlockDetectedException e) {
      // expected
    }
    assertEquals(1l, lockManager.getDetectedLocalDeadlocks());
  }
コード例 #9
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);
  }
コード例 #10
0
  @Test(expected = Exception.class)
  public void testResolveDirectoryBeforeTimeout() throws LBInvocationException {
    LexBIGService lbs = EasyMock.createMock(LexBIGService.class);

    CodingSchemeRenderingList csrl = new CodingSchemeRenderingList();
    CodingSchemeRendering csr = new TimeoutCodingSchemeRendering();

    csrl.addCodingSchemeRendering(csr);

    EasyMock.expect(lbs.getSupportedCodingSchemes()).andReturn(csrl).anyTimes();
    EasyMock.replay(lbs);

    lexEvsCodeSystemVersionQuery.setLexBigService(lbs);
    codeSystemVersonDirectoryURIFactory.setLexBigService(lbs);

    CodeSystemVersionDirectoryURI directoryUri =
        lexEvsCodeSystemVersionQuery.getCodeSystemVersions();

    QueryControl queryControl = new QueryControl();
    queryControl.setTimeLimit(600l);

    CodeSystemVersionDirectory directory =
        lexEvsCodeSystemVersionQuery.resolve(directoryUri, queryControl, null);

    assertNotNull(directory);
  }
コード例 #11
0
  @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);
  }
コード例 #12
0
  @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);
  }
コード例 #13
0
ファイル: FlickrFacadeTest.java プロジェクト: cliffano/bloojm
  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});
  }
コード例 #14
0
  @Test
  public void testInitializationSecondFailed() throws Exception {
    DateTime expectedStartTime = new DateTime(0);
    DateTime falseStartTime = new DateTime(1);
    DateTime expectedEndTime = new DateTime(100);
    DateTime falseEndTime = new DateTime(99);

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

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

    EasyMock.expect(mockFlow1.getStartTime()).andReturn(expectedStartTime).once();
    EasyMock.expect(mockFlow1.getEndTime()).andReturn(falseEndTime).once();
    EasyMock.expect(mockFlow2.getStartTime()).andReturn(falseStartTime).once();
    EasyMock.expect(mockFlow2.getEndTime()).andReturn(expectedEndTime).once();

    EasyMock.expect(mockFlow2.getParentProps()).andReturn(props).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(Status.FAILED, flow.getStatus());
    Assert.assertEquals(expectedStartTime, flow.getStartTime());
    Assert.assertEquals(expectedEndTime, flow.getEndTime());
    Assert.assertEquals(emptyExceptions, flow.getExceptions());
    Assert.assertEquals(props, flow.getParentProps());
  }
コード例 #15
0
  @Test
  public void testInitializationSecondSucceeded() throws Exception {
    DateTime expectedStartTime = new DateTime(0);

    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.SUCCEEDED).times(3);

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

    EasyMock.expect(mockFlow2.getParentProps()).andReturn(props).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(Status.READY, flow.getStatus());
    Assert.assertEquals(expectedStartTime, flow.getStartTime());
    Assert.assertEquals(null, flow.getEndTime());
    // <<<<<<< HEAD:azkaban/src/unit/azkaban/flow/GroupedExecutableFlowTest.java
    Assert.assertEquals(emptyExceptions, flow.getExceptions());
    Assert.assertEquals(props, flow.getParentProps());
  }
コード例 #16
0
  @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());
  }
コード例 #17
0
  @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);
  }
コード例 #18
0
  @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);
  }
コード例 #19
0
  @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);
  }
コード例 #20
0
  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);
  }
コード例 #21
0
ファイル: TestSystemTests.java プロジェクト: PaloAlto/bonecp
  @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);
  }
コード例 #22
0
  public MockCatalogBuilder layerGroup(
      String name, List<String> layerNames, List<String> styleNames) {

    final LayerGroupInfo lg = createMock(LayerGroupInfo.class);
    layerGroups.add(lg);

    expect(lg.getId()).andReturn(newId()).anyTimes();
    expect(lg.getName()).andReturn(name).anyTimes();

    List<PublishedInfo> grpLayers = new ArrayList<PublishedInfo>();
    List<StyleInfo> grpStyles = new ArrayList<StyleInfo>();
    for (int i = 0; i < layerNames.size(); i++) {
      String layerName = layerNames.get(i);
      LayerInfo l = null;
      for (LayerInfo layer : layers) {
        if (layerName.equals(layer.getName())) {
          l = layer;
          break;
        }
      }

      if (l == null) {
        throw new RuntimeException("No such layer: " + layerName);
      }

      grpLayers.add(l);

      StyleInfo s = null;
      if (styleNames != null) {
        String styleName = styleNames.get(i);
        for (StyleInfo style : styles) {
          if (styleName.equals(style.getName())) {
            s = style;
            break;
          }
        }
      }

      grpStyles.add(s);
    }
    expect(lg.getLayers()).andReturn(grpLayers).anyTimes();
    expect(lg.getStyles()).andReturn(grpStyles).anyTimes();

    lg.accept((CatalogVisitor) anyObject());
    expectLastCall()
        .andAnswer(
            new VisitAnswer() {
              @Override
              protected void doVisit(CatalogVisitor visitor) {
                visitor.visit(lg);
              }
            })
        .anyTimes();

    expect(catalog.getLayerGroupByName(name)).andReturn(lg).anyTimes();

    callback.onLayerGroup(name, lg, this);
    replay(lg);
    return this;
  }
コード例 #23
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);
  }
コード例 #24
0
  /**
   * 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());
  }
コード例 #25
0
ファイル: FlickrFacadeTest.java プロジェクト: cliffano/bloojm
  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});
  }
コード例 #26
0
ファイル: Req_510_Util.java プロジェクト: OurGrid/OurGrid
  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);
  }
コード例 #27
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);
  }
コード例 #28
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);
  }
コード例 #29
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);
  }
コード例 #30
0
  /**
   * 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);
  }