@BeforeMethod
 public void initMethod() {
   machine = new Machine(ID_MACHINE, mockXmlReader, mockDBReader, mockPropertyReader);
   reset(mockXmlReader);
   reset(mockDBReader);
   reset(mockPropertyReader);
 }
  @Test
  public void testExpandMailbox() throws Exception {
    int customerID = m_user.getCustomerID();
    int userID = m_user.getUserID();
    String maildir = m_user.getMailDir();
    long messageId = 7890;

    EasyMock.reset(m_mockStoreManager);
    executeRequest(
        500, "uid", -1, "pid", 1, "cid", customerID, "mid", messageId, "private", "true");

    EasyMock.reset(m_mockStoreManager);
    EasyMock.expect(m_mockStoreManager.expandMessageToMeta(customerID, maildir, messageId, 1, true))
        .andReturn(true);
    executeRequest(200, "pid", 1, "uid", userID, "mid", messageId, "sender", "true");

    EasyMock.reset(m_mockStoreManager);
    EasyMock.expect(
            m_mockStoreManager.expandMessageToMeta(customerID, maildir, messageId, 1, false))
        .andReturn(true);
    executeRequest(
        200, "pid", 1, "cid", customerID, "uid", userID, "mid", messageId, "sender", "false");

    EasyMock.reset(m_mockStoreManager);
    EasyMock.expect(
            m_mockStoreManager.expandMessageToMeta(customerID, maildir, messageId, 1, false))
        .andReturn(false);
    executeRequest(
        500, "pid", 1, "cid", customerID, "uid", userID, "mid", messageId, "sender", "false");
  }
  /**
   * 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);
  }
 @Before
 public void initBeforeEachTest() {
   reset(mockPool);
   reset(securityClientMock);
   reset(insClientMock);
   reset(regClientMock);
   reset(ezTokenMock);
 }
  /** test getAuthorizationHeader */
  @Test
  public void testGetAuthorizationHeader() throws Exception {
    final TreeMap<String, Set<CharSequence>> params = new TreeMap<String, Set<CharSequence>>();
    CoreOAuthConsumerSupport support =
        new CoreOAuthConsumerSupport() {
          @Override
          protected Map<String, Set<CharSequence>> loadOAuthParameters(
              ProtectedResourceDetails details,
              URL requestURL,
              OAuthConsumerToken requestToken,
              String httpMethod,
              Map<String, String> additionalParameters) {
            return params;
          }
        };
    URL url = new URL("https://myhost.com/somepath?with=some&query=params&too");
    OAuthConsumerToken token = new OAuthConsumerToken();
    ProtectedResourceDetails details = createMock(ProtectedResourceDetails.class);

    expect(details.isAcceptsAuthorizationHeader()).andReturn(false);
    replay(details);
    assertNull(support.getAuthorizationHeader(details, token, url, "POST", null));
    verify(details);
    reset(details);

    params.put("with", Collections.singleton((CharSequence) "some"));
    params.put("query", Collections.singleton((CharSequence) "params"));
    params.put("too", null);
    expect(details.isAcceptsAuthorizationHeader()).andReturn(true);
    expect(details.getAuthorizationHeaderRealm()).andReturn("myrealm");
    replay(details);
    assertEquals(
        "OAuth realm=\"myrealm\", query=\"params\", with=\"some\"",
        support.getAuthorizationHeader(details, token, url, "POST", null));
    verify(details);
    reset(details);

    params.put(
        OAuthConsumerParameter.oauth_consumer_key.toString(),
        Collections.singleton((CharSequence) "mykey"));
    params.put(
        OAuthConsumerParameter.oauth_nonce.toString(),
        Collections.singleton((CharSequence) "mynonce"));
    params.put(
        OAuthConsumerParameter.oauth_timestamp.toString(),
        Collections.singleton((CharSequence) "myts"));
    expect(details.isAcceptsAuthorizationHeader()).andReturn(true);
    expect(details.getAuthorizationHeaderRealm()).andReturn("myrealm");
    replay(details);
    assertEquals(
        "OAuth realm=\"myrealm\", oauth_consumer_key=\"mykey\", oauth_nonce=\"mynonce\", oauth_timestamp=\"myts\", query=\"params\", with=\"some\"",
        support.getAuthorizationHeader(details, token, url, "POST", null));
    verify(details);
    reset(details);
  }
 @Before
 public void setUp() throws Exception {
   super.setUp();
   queue.clear();
   reset(workQueueMock);
   reset(runningMapMock);
   reset(completedMapMock);
   reset(failureMapMock);
   reset(shardHandlerFactoryMock);
   reset(shardHandlerMock);
   reset(zkStateReaderMock);
   reset(clusterStateMock);
   reset(solrZkClientMock);
   underTest =
       new OverseerCollectionProcessorToBeTested(
           zkStateReaderMock,
           "1234",
           shardHandlerFactoryMock,
           ADMIN_PATH,
           workQueueMock,
           runningMapMock,
           completedMapMock,
           failureMapMock);
   zkMap.clear();
   collectionsSet.clear();
 }
  /** Tests a corner case, when there is no BGP speakers in the configuration. */
  @Test
  public void testNullBgpSpeakers() {
    reset(bgpConfig);
    expect(bgpConfig.bgpSpeakers()).andReturn(Collections.emptySet()).anyTimes();
    replay(bgpConfig);

    // We don't expect any intents in this case
    reset(intentSynchronizer);
    replay(intentSynchronizer);
    peerConnectivityManager.start();
    verify(intentSynchronizer);
  }
 @After
 public void tearDown() {
   EasyMock.reset(privateEntityRepository);
   EasyMock.reset(privateSegmentRepository);
   EasyMock.reset(privateEntityKeyRepository);
   EasyMock.reset(partnerRepository);
   EasyMock.reset(cityRepository);
   EasyMock.reset(partnerKeyRepository);
   EasyMock.reset(partnerPhoneRepository);
   EasyMock.reset(partnerCategoryRepository);
   EasyMock.reset(contactGroupRepository);
   EasyMock.reset(sequenceMgr);
 }
  /** Tests a corner case, when there are no interfaces in the configuration. */
  @Test
  public void testNullInterfaces() {
    reset(interfaceService);
    interfaceService.addListener(anyObject(InterfaceListener.class));
    expectLastCall().anyTimes();

    expect(interfaceService.getInterfaces()).andReturn(Sets.newHashSet()).anyTimes();
    expect(interfaceService.getInterfacesByPort(s2Eth1))
        .andReturn(Collections.emptySet())
        .anyTimes();
    expect(interfaceService.getInterfacesByPort(s1Eth1))
        .andReturn(Collections.emptySet())
        .anyTimes();
    expect(interfaceService.getInterfacesByIp(IpAddress.valueOf("192.168.10.101")))
        .andReturn(Collections.emptySet())
        .anyTimes();
    expect(interfaceService.getMatchingInterface(IpAddress.valueOf("192.168.10.1")))
        .andReturn(null)
        .anyTimes();
    expect(interfaceService.getInterfacesByIp(IpAddress.valueOf("192.168.20.101")))
        .andReturn(Collections.emptySet())
        .anyTimes();
    expect(interfaceService.getMatchingInterface(IpAddress.valueOf("192.168.20.1")))
        .andReturn(null)
        .anyTimes();
    expect(interfaceService.getInterfacesByIp(IpAddress.valueOf("192.168.30.101")))
        .andReturn(Collections.emptySet())
        .anyTimes();
    expect(interfaceService.getMatchingInterface(IpAddress.valueOf("192.168.30.1")))
        .andReturn(null)
        .anyTimes();
    expect(interfaceService.getInterfacesByIp(IpAddress.valueOf("192.168.40.101")))
        .andReturn(Collections.emptySet())
        .anyTimes();
    expect(interfaceService.getMatchingInterface(IpAddress.valueOf("192.168.40.1")))
        .andReturn(null)
        .anyTimes();
    expect(interfaceService.getInterfacesByIp(IpAddress.valueOf("192.168.50.101")))
        .andReturn(Collections.emptySet())
        .anyTimes();
    expect(interfaceService.getMatchingInterface(IpAddress.valueOf("192.168.50.1")))
        .andReturn(null)
        .anyTimes();

    replay(interfaceService);

    reset(intentSynchronizer);
    replay(intentSynchronizer);
    peerConnectivityManager.start();
    verify(intentSynchronizer);
  }
  @Test
  public void testSessionLifecycle() throws Exception {
    IoServiceListenerSupport support = new IoServiceListenerSupport(mockService);

    DummySession session = new DummySession();
    session.setService(mockService);
    session.setLocalAddress(ADDRESS);

    IoHandler handler = EasyMock.createStrictMock(IoHandler.class);
    session.setHandler(handler);

    IoServiceListener listener = EasyMock.createStrictMock(IoServiceListener.class);

    // Test creation
    listener.sessionCreated(session);
    handler.sessionCreated(session);
    handler.sessionOpened(session);

    EasyMock.replay(listener);
    EasyMock.replay(handler);

    support.add(listener);
    support.fireSessionCreated(session);

    EasyMock.verify(listener);
    EasyMock.verify(handler);

    assertEquals(1, support.getManagedSessions().size());
    assertSame(session, support.getManagedSessions().get(session.getId()));

    // Test destruction & other side effects
    EasyMock.reset(listener);
    EasyMock.reset(handler);
    handler.sessionClosed(session);
    listener.sessionDestroyed(session);

    EasyMock.replay(listener);
    //// Activate more than once
    support.fireSessionCreated(session);
    //// Deactivate
    support.fireSessionDestroyed(session);
    //// Deactivate more than once
    support.fireSessionDestroyed(session);

    EasyMock.verify(listener);

    assertTrue(session.isClosing());
    assertEquals(0, support.getManagedSessions().size());
    assertNull(support.getManagedSessions().get(session.getId()));
  }
  /** configureURLForProtectedAccess */
  @Test
  public void testConfigureURLForProtectedAccess() throws Exception {
    CoreOAuthConsumerSupport support =
        new CoreOAuthConsumerSupport() {
          // Inherited.
          @Override
          public String getOAuthQueryString(
              ProtectedResourceDetails details,
              OAuthConsumerToken accessToken,
              URL url,
              String httpMethod,
              Map<String, String> additionalParameters) {
            return "myquerystring";
          }
        };
    support.setStreamHandlerFactory(new DefaultOAuthURLStreamHandlerFactory());
    ProtectedResourceDetails details = createMock(ProtectedResourceDetails.class);
    OAuthConsumerToken token = new OAuthConsumerToken();
    URL url = new URL("https://myhost.com/somepath?with=some&query=params&too");

    expect(details.isAcceptsAuthorizationHeader()).andReturn(true);
    replay(details);
    assertEquals(
        "https://myhost.com/somepath?with=some&query=params&too",
        support.configureURLForProtectedAccess(url, token, details, "GET", null).toString());
    verify(details);
    reset(details);

    expect(details.isAcceptsAuthorizationHeader()).andReturn(false);
    replay(details);
    assertEquals(
        "https://myhost.com/somepath?myquerystring",
        support.configureURLForProtectedAccess(url, token, details, "GET", null).toString());
    verify(details);
    reset(details);

    replay(details);
    assertEquals(
        "https://myhost.com/somepath?with=some&query=params&too",
        support.configureURLForProtectedAccess(url, token, details, "POST", null).toString());
    verify(details);
    reset(details);

    replay(details);
    assertEquals(
        "https://myhost.com/somepath?with=some&query=params&too",
        support.configureURLForProtectedAccess(url, token, details, "PUT", null).toString());
    verify(details);
    reset(details);
  }
  @Test
  public void testConnectorActivation() throws Exception {
    IoConnector connector = EasyMock.createStrictMock(IoConnector.class);

    IoServiceListenerSupport support = new IoServiceListenerSupport(connector);

    final DummySession session = new DummySession();
    session.setService(connector);
    session.setRemoteAddress(ADDRESS);

    IoHandler handler = EasyMock.createStrictMock(IoHandler.class);
    session.setHandler(handler);

    IoServiceListener listener = EasyMock.createStrictMock(IoServiceListener.class);

    // Creating a session should activate a service automatically.
    listener.serviceActivated(connector);
    listener.sessionCreated(session);
    handler.sessionCreated(session);
    handler.sessionOpened(session);

    EasyMock.replay(listener);
    EasyMock.replay(handler);

    support.add(listener);
    support.fireSessionCreated(session);

    EasyMock.verify(listener);
    EasyMock.verify(handler);

    // Destroying a session should deactivate a service automatically.
    EasyMock.reset(listener);
    EasyMock.reset(handler);
    listener.sessionDestroyed(session);
    handler.sessionClosed(session);
    listener.serviceDeactivated(connector);

    EasyMock.replay(listener);
    EasyMock.replay(handler);

    support.fireSessionDestroyed(session);

    EasyMock.verify(listener);
    EasyMock.verify(handler);

    assertEquals(0, support.getManagedSessions().size());
    assertNull(support.getManagedSessions().get(session.getId()));
  }
  @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);
  }
  @Test
  public void testResolveJmsEndpoint() throws Exception {
    reset(applicationContext);

    expect(applicationContext.getBeansOfType(EndpointComponent.class))
        .andReturn(Collections.<String, EndpointComponent>emptyMap())
        .once();
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(EasyMock.createMock(ConnectionFactory.class))
        .once();

    replay(applicationContext);

    TestContext context = new TestContext();
    context.setApplicationContext(applicationContext);

    DefaultEndpointFactory factory = new DefaultEndpointFactory();
    Endpoint endpoint = factory.create("jms:Sample.Queue.Name", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(),
        "Sample.Queue.Name");

    verify(applicationContext);
  }
  @Test
  public void testCreateQueueEndpoint() throws Exception {
    JmsEndpointComponent component = new JmsEndpointComponent();

    reset(applicationContext);
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(connectionFactory)
        .once();
    replay(applicationContext);

    Endpoint endpoint = component.createEndpoint("jms:queuename", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);

    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(), "queuename");
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().isPubSubDomain(), false);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getConnectionFactory(),
        connectionFactory);
    Assert.assertNull(((JmsEndpoint) endpoint).getEndpointConfiguration().getDestination());
    Assert.assertEquals(((JmsEndpoint) endpoint).getEndpointConfiguration().getTimeout(), 5000L);

    verify(applicationContext);
  }
  /** 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;
  }
Example #17
0
  @Test
  public void testJoinsAndWatchesSurviveExpiredSession() throws Exception {
    onLoseMembership.execute();
    replay(onLoseMembership);

    assertEmptyMembershipObserved();

    Membership membership = joinGroup.join(onLoseMembership);
    String originalMemberId = membership.getMemberId();
    assertMembershipObserved(originalMemberId);

    expireSession(zkClient);

    // We should have lost our group membership and then re-gained it with a new ephemeral node.
    // We may or may-not see the intermediate state change but we must see the final state
    Iterable<String> members = listener.take();
    if (Iterables.isEmpty(members)) {
      members = listener.take();
    }
    assertEquals(1, Iterables.size(members));
    assertNotEqual(originalMemberId, Iterables.getOnlyElement(members));
    assertNotEqual(originalMemberId, membership.getMemberId());

    listener.assertEmpty();

    verify(onLoseMembership);
    reset(onLoseMembership); // Turn off expectations during ZK server shutdown.
  }
  public static ZkStateReader getMockZkStateReader(final Set<String> collections) {
    ZkStateReader mock = createMock(ZkStateReader.class);
    EasyMock.reset(mock);
    EasyMock.replay(mock);

    return mock;
  }
  @Test
  public void testConfigureHandlerInterceptor() throws Exception {
    List<Object> interceptors = new ArrayList<Object>();
    interceptors.add(new LoggingHandlerInterceptor());

    reset(httpServer);

    expect(httpServer.getInterceptors()).andReturn(interceptors).once();
    expect(httpServer.getEndpointAdapter()).andReturn(null).once();
    expect(httpServer.getMessageConverter()).andReturn(new HttpMessageConverter()).once();
    expect(httpServer.getWebSockets()).andReturn(new ArrayList<WebSocketEndpoint>()).once();

    replay(httpServer);

    servlet.initStrategies(applicationContext);

    Assert.assertEquals(handlerInterceptor.getInterceptors().size(), 1L);
    Assert.assertEquals(handlerInterceptor.getInterceptors().get(0), interceptors.get(0));
    Assert.assertNotNull(httpMessageController.getEndpointConfiguration().getMessageConverter());

    Assert.assertEquals(
        httpMessageController.getEndpointAdapter().getClass(), EmptyResponseEndpointAdapter.class);

    verify(httpServer);
  }
  @Test
  public void testServiceLifecycle() throws Exception {
    IoServiceListenerSupport support = new IoServiceListenerSupport(mockService);

    IoServiceListener listener = EasyMock.createStrictMock(IoServiceListener.class);

    // Test activation
    listener.serviceActivated(mockService);

    EasyMock.replay(listener);

    support.add(listener);
    support.fireServiceActivated();

    EasyMock.verify(listener);

    // Test deactivation & other side effects
    EasyMock.reset(listener);
    listener.serviceDeactivated(mockService);

    EasyMock.replay(listener);
    //// Activate more than once
    support.fireServiceActivated();
    //// Deactivate
    support.fireServiceDeactivated();
    //// Deactivate more than once
    support.fireServiceDeactivated();

    EasyMock.verify(listener);
  }
Example #21
0
  protected void verifyMock(ProgressAnswer progressAnswer, int length) {
    verify(mockTransferListener);

    assertEquals(length, progressAnswer.getSize());

    reset(mockTransferListener);
  }
Example #22
0
  protected void assertGetIfNewerTest(
      ProgressAnswer progressAnswer, boolean expectedResult, int expectedSize) throws IOException {
    if (expectedResult) {
      verifyMock(progressAnswer, expectedSize);

      assertNotNull("check checksum is not null", checksumObserver.getActualChecksum());

      assertEquals(
          "compare checksums",
          "6b144b7285ffd6b0bc8300da162120b9",
          checksumObserver.getActualChecksum());

      // Now compare the contents of the artifact that was placed in
      // the repository with the contents of the artifact that was
      // retrieved from the repository.

      String sourceContent = FileUtils.fileRead(sourceFile);
      String destContent = FileUtils.fileRead(destFile);
      assertEquals(sourceContent, destContent);
    } else {
      verify(mockTransferListener);

      reset(mockTransferListener);

      assertNull("check checksum is null", checksumObserver.getActualChecksum());

      assertFalse(destFile.exists());
    }
  }
  @Test
  public void testRunnableWrappsRunnable() throws Exception {
    final Object mockChannel = createMock("mockChannel", AbstractAioChannel.class);
    replay(mockChannel);

    final Runnable r =
        new Runnable() {

          @SuppressWarnings("unused")
          @Override
          public void run() {
            Object channel = mockChannel;
            // Noop
          }
        };
    Runnable r2 =
        new Runnable() {

          @SuppressWarnings("unused")
          @Override
          public void run() {
            Runnable runnable = r;
            // Noop
          }
        };
    AioChannelFinder finder = create();
    AbstractAioChannel channel = finder.findChannel(r2);
    assertNotNull(channel);

    AbstractAioChannel channel2 = finder.findChannel(r2);
    assertNotNull(channel2);
    assertSame(channel2, channel);
    verify(mockChannel);
    reset(mockChannel);
  }
  @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);
  }
  @SuppressWarnings("unchecked")
  @Before
  public void setUp() throws Exception {
    messageConverter = createMock(HttpMessageConverter.class);
    expect(messageConverter.getSupportedMediaTypes())
        .andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
    replay(messageConverter);

    processor =
        new RequestResponseBodyMethodProcessor(
            Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
    reset(messageConverter);

    Method handle = getClass().getMethod("handle1", String.class, Integer.TYPE);
    paramRequestBodyString = new MethodParameter(handle, 0);
    paramInt = new MethodParameter(handle, 1);
    returnTypeString = new MethodParameter(handle, -1);
    returnTypeInt = new MethodParameter(getClass().getMethod("handle2"), -1);
    returnTypeStringProduces = new MethodParameter(getClass().getMethod("handle3"), -1);
    paramValidBean = new MethodParameter(getClass().getMethod("handle4", SimpleBean.class), 0);

    mavContainer = new ModelAndViewContainer();

    servletRequest = new MockHttpServletRequest();
    servletResponse = new MockHttpServletResponse();
    webRequest = new ServletWebRequest(servletRequest, servletResponse);
  }
  @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);
  }
  @Test
  public void testExecutePLSQLBuilderWithSQLResource() throws IOException {
    MockBuilder builder =
        new MockBuilder() {
          @Override
          public void configure() {
            plsql(dataSource).sqlResource(sqlResource);
          }
        };

    reset(sqlResource);
    expect(sqlResource.getInputStream())
        .andReturn(new ByteArrayInputStream("testScript".getBytes()))
        .once();
    replay(sqlResource);

    builder.run(null, null);

    Assert.assertEquals(builder.testCase().getActions().size(), 1);
    Assert.assertEquals(
        builder.testCase().getActions().get(0).getClass(), ExecutePLSQLAction.class);

    ExecutePLSQLAction action = (ExecutePLSQLAction) builder.testCase().getActions().get(0);
    Assert.assertEquals(action.getName(), ExecutePLSQLAction.class.getSimpleName());
    Assert.assertEquals(action.isIgnoreErrors(), false);
    Assert.assertEquals(action.getStatements().size(), 0L);
    Assert.assertEquals(action.getScript(), "testScript");
    Assert.assertEquals(action.getDataSource(), dataSource);
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    NMR nmr = OsgiSupport.getReference(bundleContext, NMR.class);
    assertNotNull(nmr);

    endpointService1 = ServiceMixSupport.createAndRegisterEndpoint(nmr, service1, null);
    endpointService2 =
        ServiceMixSupport.createAndRegisterEndpoint(
            nmr, service2, new ExchangeProcessorImpl(service2.toString()));

    mockInterceptor = new MockInterceptor();

    Dictionary<String, String> interceptorProps = new Hashtable<String, String>();
    interceptorProps.put("role", "consumer,provider");
    interceptorProps.put("scope", "request,response");

    addRegistrationToCancel(
        bundleContext.registerService(
            Interceptor.class.getCanonicalName(), mockInterceptor, interceptorProps));
    Thread.sleep(500);

    reset(resolverMock);
  }
  @Test
  public void testCanParseBoxServerError()
      throws BoxRestException, IllegalStateException, IOException, BoxJSONException {
    BoxJSONParser jsonParser = new BoxJSONParser(new BoxResourceHub());
    EasyMock.reset(boxResponse, response, entity);
    inputStream =
        new ByteArrayInputStream(jsonParser.convertBoxObjectToJSONString(error).getBytes());
    EasyMock.expect(boxResponse.getHttpResponse()).andStubReturn(response);
    EasyMock.expect(response.getEntity()).andStubReturn(entity);
    EasyMock.expect(entity.getContent()).andStubReturn(inputStream);
    EasyMock.expect(entity.isStreaming()).andStubReturn(false);

    EasyMock.expect(boxResponse.getHttpResponse()).andStubReturn(response);
    EasyMock.expect(response.getStatusLine()).andStubReturn(statusLine);
    EasyMock.expect(statusLine.getStatusCode()).andStubReturn(statusCode);

    EasyMock.replay(boxResponse, response, entity, statusLine);
    ErrorResponseParser parser = new ErrorResponseParser(jsonParser);
    Object object = parser.parse(boxResponse);
    Assert.assertEquals(BoxServerError.class, object.getClass());

    Assert.assertEquals(
        jsonParser.convertBoxObjectToJSONString(error),
        jsonParser.convertBoxObjectToJSONString(object));
    EasyMock.verify(boxResponse, response, entity, statusLine);
  }
Example #30
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;
  }