@SuppressWarnings({"resource", "unchecked", "rawtypes"})
  @Test
  public void updateStreamWithSomeListeners() {
    Repository<Entity> decoratedRepository = Mockito.mock(Repository.class);
    Mockito.when(decoratedRepository.getName()).thenReturn("entityFullName");
    EntityListenerRepositoryDecorator entityListenerRepositoryDecorator =
        new EntityListenerRepositoryDecorator(decoratedRepository, entityListenersService);
    EntityListener entityListener1 =
        Mockito.when(Mockito.mock(EntityListener.class).getEntityId())
            .thenReturn(Integer.valueOf(2))
            .getMock();
    entityListenersService.addEntityListener("entityFullName", entityListener1);

    Entity entity0 =
        Mockito.when(Mockito.mock(Entity.class).getIdValue())
            .thenReturn(Integer.valueOf(1))
            .getMock();
    Entity entity1 =
        Mockito.when(Mockito.mock(Entity.class).getIdValue())
            .thenReturn(Integer.valueOf(2))
            .getMock();
    Stream<Entity> entities = Stream.of(entity0, entity1);
    entityListenerRepositoryDecorator.update(entities);

    ArgumentCaptor<Stream<Entity>> captor = ArgumentCaptor.forClass((Class) Stream.class);
    Mockito.verify(decoratedRepository).update(captor.capture());
    Assert.assertEquals(
        captor.getValue().collect(Collectors.toList()), Arrays.asList(entity0, entity1));
    Mockito.verify(entityListener1, Mockito.times(1)).postUpdate(entity1);
  }
  @Test
  public void testPreferencesWithModeEditGuestInPublicLayoutWithPermission() throws Exception {

    _layout.setPrivateLayout(false);

    PowerMockito.mockStatic(PortletLocalServiceUtil.class);

    Mockito.when(PortletLocalServiceUtil.getPortletById(_layout.getCompanyId(), _PORTLET_ID))
        .thenReturn(getGroupPortlet());

    PowerMockito.mockStatic(LayoutPermissionUtil.class);

    Mockito.when(
            LayoutPermissionUtil.contains(
                Mockito.any(PermissionChecker.class),
                Mockito.eq(_layout),
                Mockito.eq(ActionKeys.UPDATE)))
        .thenReturn(true);

    long siteGroupId = _layout.getGroupId();
    boolean modeEditGuest = true;

    PortletPreferencesFactoryUtil.getPortletPreferencesIds(
        siteGroupId, _USER_ID, _layout, _PORTLET_ID, modeEditGuest);
  }
예제 #3
0
  @Test
  public void getContentShortcut() throws Exception {
    final PropertyTree rootDataSet = new PropertyTree();
    rootDataSet.addReference("target", Reference.from("ref"));

    final Content content =
        Content.create()
            .id(ContentId.from("id"))
            .path(ContentPath.from("site/somepath/shortcut"))
            .owner(PrincipalKey.from("user:myStore:me"))
            .displayName("My Content")
            .modifier(PrincipalKey.from("user:system:admin"))
            .type(ContentTypeName.shortcut())
            .data(rootDataSet)
            .build();

    Mockito.when(this.contentService.getByPath(content.getPath().asAbsolute())).thenReturn(content);
    Mockito.when(this.portalUrlService.pageUrl(Mockito.any(PageUrlParams.class)))
        .thenReturn("/master/site/otherpath");

    this.request.setContentPath(ContentPath.from("/site/somepath/shortcut"));

    final PortalResponse res = this.handler.handle(this.request);
    assertNotNull(res);
    assertEquals(HttpStatus.TEMPORARY_REDIRECT, res.getStatus());
    assertEquals("/master/site/otherpath", res.getHeaders().get("Location"));
  }
예제 #4
0
  @Test
  public void testGetUsersWithAuthority() throws SQLException {

    String expectedQuery =
        "select \"public\".\"users\".\"username\", \"public\".\"users\".\"locked\", \"public\".\"authorities\".\"authority\", count(\"public\".\"users\".\"username\") over () as \"count\" from \"public\".\"users\" join \"public\".\"authorities\" on \"public\".\"users\".\"username\" = \"public\".\"authorities\".\"username\" where \"public\".\"authorities\".\"authority\" = 'ROLE_ADMIN' order by \"public\".\"users\".\"username\" asc limit 5 offset 0";
    Pageable pageable = Mockito.mock(Pageable.class);

    ResultSet resultSet = Mockito.mock(ResultSet.class);

    Mockito.when(pageable.getPageNumber()).thenReturn(0);
    Mockito.when(pageable.getPageSize()).thenReturn(5);

    Mockito.when(resultSet.getInt(PagingConstants.COUNT)).thenReturn(1);
    Mockito.when(resultSet.getString("username")).thenReturn("admin");

    RESTPage<UserDTO> page = userDao.getUsersWithAuthority("ROLE_ADMIN", pageable);

    ArgumentCaptor<PagingRowCallbackHandler> pagingRowCallbackHandlerCaptor =
        ArgumentCaptor.forClass(PagingRowCallbackHandler.class);

    Mockito.verify(jdbcTemplate)
        .query(Matchers.eq(expectedQuery), pagingRowCallbackHandlerCaptor.capture());

    PagingRowCallbackHandler pagingRowCallbackHandler = pagingRowCallbackHandlerCaptor.getValue();

    pagingRowCallbackHandler.processRow(resultSet);

    Mockito.verify(resultSet).getInt(PagingConstants.COUNT);

    Mockito.verify(resultSet).getString("username");

    Assert.assertEquals(1, page.getContentSize());
    Assert.assertEquals("admin", page.getContent().get(0).getUsername());
  }
 @Before
 public void prepare() {
   Mockito.when(systemStatus.isNexusStarted()).thenReturn(true);
   Mockito.when(applicationStatusSource.getSystemStatus()).thenReturn(systemStatus);
   Mockito.when(mavenProxyRepository.getId()).thenReturn("central");
   Mockito.when(mavenProxyRepository.getName()).thenReturn("Central Repository");
 }
예제 #6
0
 protected void mockUserDatabase(String userId, UaaUser user) {
   userDatabase = Mockito.mock(UaaUserDatabase.class);
   Mockito.when(userDatabase.retrieveUserById(Matchers.eq(userId))).thenReturn(user);
   Mockito.when(userDatabase.retrieveUserById(AdditionalMatchers.not(Matchers.eq(userId))))
       .thenThrow(new UsernameNotFoundException("mock"));
   tokenServices.setUserDatabase(userDatabase);
 }
  @Test
  public void methodToMethod() throws Exception {

    ShapeHelperWrapper shapeHelperWrapper = Mockito.mock(ShapeHelperWrapper.class);
    UnoRuntimeWrapper unoRuntimeWrapper = Mockito.mock(UnoRuntimeWrapper.class);

    XShape method1 = Mockito.mock(XShape.class);

    XShape method2 = Mockito.mock(XShape.class);
    Mockito.when(shapeHelperWrapper.getNodeType(method2)).thenReturn(Node.NodeType.MethodOfProcess);

    XConnectorShape link = Mockito.mock(XConnectorShape.class);
    XPropertySet linkPropertySet = Mockito.mock(XPropertySet.class);

    Mockito.when(shapeHelperWrapper.isConnectorShape(link)).thenReturn(true);

    Mockito.when(linkPropertySet.getPropertyValue(ConnectedShapes.START_SHAPE)).thenReturn(method2);
    Mockito.when(linkPropertySet.getPropertyValue(ConnectedShapes.END_SHAPE)).thenReturn(method1);

    Mockito.when(unoRuntimeWrapper.queryInterface(XPropertySet.class, link))
        .thenReturn(linkPropertySet);

    Injector injector = Guice.createInjector(new TestModule(shapeHelperWrapper, unoRuntimeWrapper));

    DiagramWalker diagramWalker = injector.getInstance(DiagramWalker.class);

    //        diagramWalker.walk(Sets.newHashSet());
  }
 @Test
 public void noNullPointerWhenWeReturnNull() throws Exception {
   AbstractPrintFileProcessor processor = createNewPrintFileProcessor();
   PrintJob printJob = createTestPrintJob(processor);
   Mockito.when(
           printJob
               .getPrinter()
               .getConfiguration()
               .getSlicingProfile()
               .getzLiftDistanceCalculator())
       .thenReturn(";");
   Mockito.when(printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class)))
       .thenReturn(null);
   DataAid aid = processor.initializeJobCacheWithDataAid(printJob);
   try {
     aid.customizer.setNextStep(PrinterStep.PerformExposure);
     processor.printImageAndPerformPostProcessing(aid, image);
     Mockito.verify(printJob.getPrinter().getGCodeControl(), Mockito.times(1))
         .executeGCodeWithTemplating(Mockito.any(PrintJob.class), Mockito.anyString());
   } catch (IllegalArgumentException e) {
     Assert.assertEquals(
         "The result of your lift distance script needs to evaluate to an instance of java.lang.Number",
         e.getMessage());
   }
 }
 @Test
 public void usingUnsupportedBuildAreaWithLiftDistance() throws Exception {
   AbstractPrintFileProcessor processor = createNewPrintFileProcessor();
   Graphics2D graphics = Mockito.mock(Graphics2D.class);
   PrintJob printJob = createTestPrintJob(processor);
   Mockito.when(
           printJob.getPrinter().getConfiguration().getSlicingProfile().getZLiftDistanceGCode())
       .thenReturn("G99 ${1 + UnknownVariable * 2} ;dependent on buildArea");
   Double whenBuilAreaMMCalled =
       printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class));
   Mockito.when(whenBuilAreaMMCalled).thenReturn(null);
   DataAid aid = processor.initializeJobCacheWithDataAid(printJob);
   try {
     aid.customizer.setNextStep(PrinterStep.PerformExposure);
     processor.printImageAndPerformPostProcessing(aid, image);
     Assert.fail("Must throw InappropriateDeviceException");
   } catch (InappropriateDeviceException e) {
     Mockito.verify(printJob.getPrintFileProcessor(), Mockito.times(2))
         .getBuildAreaMM(Mockito.any(PrintJob.class));
   }
   Mockito.when(
           printJob.getPrinter().getConfiguration().getSlicingProfile().getZLiftDistanceGCode())
       .thenReturn("G99 ${1 + buildAreaMM * 2} ;dependent on buildArea");
   try {
     aid.customizer.setNextStep(PrinterStep.PerformExposure);
     processor.printImageAndPerformPostProcessing(aid, image);
     Mockito.verify(printJob.getPrintFileProcessor(), Mockito.times(5))
         .getBuildAreaMM(Mockito.any(PrintJob.class));
   } catch (InappropriateDeviceException e) {
     Assert.fail("Should not throw InappropriateDeviceException");
   }
 }
  @Before
  public void setup() throws Exception {
    TEST_UTIL = new HBaseTestingUtility();
    TEST_UTIL.startMiniZKCluster();
    conf = TEST_UTIL.getConfiguration();
    // Use a different ZK wrapper instance for each tests.
    zkw =
        new ZooKeeperWatcher(conf, "split-log-manager-tests" + UUID.randomUUID().toString(), null);
    ZKUtil.deleteChildrenRecursively(zkw, zkw.baseZNode);
    ZKUtil.createAndFailSilent(zkw, zkw.baseZNode);
    assertTrue(ZKUtil.checkExists(zkw, zkw.baseZNode) != -1);
    LOG.debug(zkw.baseZNode + " created");
    ZKUtil.createAndFailSilent(zkw, zkw.splitLogZNode);
    assertTrue(ZKUtil.checkExists(zkw, zkw.splitLogZNode) != -1);
    LOG.debug(zkw.splitLogZNode + " created");

    stopped = false;
    resetCounters();

    // By default, we let the test manage the error as before, so the server
    //  does not appear as dead from the master point of view, only from the split log pov.
    Mockito.when(sm.isServerOnline(Mockito.any(ServerName.class))).thenReturn(true);
    Mockito.when(master.getServerManager()).thenReturn(sm);

    to = 4000;
    conf.setInt("hbase.splitlog.manager.timeout", to);
    conf.setInt("hbase.splitlog.manager.unassigned.timeout", 2 * to);
    conf.setInt("hbase.splitlog.manager.timeoutmonitor.period", 100);
    to = to + 4 * 100;
  }
  @Test
  public void testDoFilterForClientBackwardsCompatibility() throws Exception {
    Filter filter = new FalconAuthenticationFilter();

    final String userName = System.getProperty("user.name");
    final String httpAuthType =
        StartupProperties.get().getProperty("falcon.http.authentication.type", "simple");
    try {
      System.setProperty("user.name", "");
      StartupProperties.get()
          .setProperty(
              "falcon.http.authentication.type",
              "org.apache.falcon.security.RemoteUserInHeaderBasedAuthenticationHandler");

      synchronized (StartupProperties.get()) {
        filter.init(mockConfig);
      }

      Mockito.when(mockRequest.getMethod()).thenReturn("POST");
      Mockito.when(mockRequest.getQueryString()).thenReturn("");
      Mockito.when(mockRequest.getRemoteUser()).thenReturn(null);
      Mockito.when(mockRequest.getHeader("Remote-User")).thenReturn("remote-user");

      filter.doFilter(mockRequest, mockResponse, mockChain);

      Assert.assertEquals(CurrentUser.getUser(), "remote-user");

    } finally {
      System.setProperty("user.name", userName);
      StartupProperties.get().setProperty("falcon.http.authentication.type", httpAuthType);
    }
  }
  @Test
  public void testFindByFilter() {
    // arrange
    Map<String, List<String>> multiValue = new HashMap<>();
    multiValue.put("title", Arrays.asList("Home"));
    MultivaluedMap<String, String> queryParameters = new MultivaluedMapImpl<>(multiValue);
    List<UserRole> userRoles = new ArrayList<>();
    UserRole userRole = this.buildUserRole();
    userRoles.add(userRole);
    List<User> users = new ArrayList<User>();
    users.add(userRole.getUser());

    Mockito.when(userRoleDao.findByFilter(queryParameters)).thenReturn(userRoles);
    Mockito.when(userRoleDao.count(queryParameters)).thenReturn(10L);
    Mockito.when(userService.fetchUsers(Matchers.anyList())).thenReturn(users);

    // act
    Map<String, Object> result = this.userRoleServiceImpl.findByFilter(queryParameters);

    // assert
    assertTrue(result.containsKey("count"));
    assertTrue(result.containsValue(10L));
    assertTrue(result.containsKey("data"));
    assertTrue(result.containsValue(userRoles));
    Mockito.verify(userRoleDao).count(queryParameters);
    Mockito.verify(userRoleDao).findByFilter(queryParameters);
  }
  @Test
  public void testOnBreakpointListChanged() throws InterruptedException {
    CloudDebugHistoricalSnapshots snapshots = new CloudDebugHistoricalSnapshots(handler);

    Breakpoint bp1 = new Breakpoint();
    bp1.setId("an ID");
    bp1.setFinalTime("2015-08-22T05:23:34.123Z");
    bp1.setIsFinalState(true);
    SourceLocation location = new SourceLocation();
    location.setPath("foo/bar/baz");
    location.setLine(12);
    bp1.setLocation(location);

    List<Breakpoint> breakpoints = new ArrayList<Breakpoint>();
    breakpoints.add(bp1);

    Mockito.when(mockProcess.getCurrentBreakpointList()).thenReturn(breakpoints);
    Mockito.when(mockProcess.getCurrentSnapshot()).thenReturn(bp1);
    CloudBreakpointHandler breakpointHandler = Mockito.mock(CloudBreakpointHandler.class);
    Mockito.when(mockProcess.getBreakpointHandler()).thenReturn(breakpointHandler);

    runModelSetter(snapshots);

    Assert.assertEquals(0, snapshots.myTable.getSelectedRow());
  }
  @SuppressWarnings("resource")
  @Test
  public void updateEntityWithListeners() {
    @SuppressWarnings("unchecked")
    Repository<Entity> decoratedRepository = Mockito.mock(Repository.class);
    Mockito.when(decoratedRepository.getName()).thenReturn("entityFullName");
    EntityListenerRepositoryDecorator entityListenerRepositoryDecorator =
        new EntityListenerRepositoryDecorator(decoratedRepository, entityListenersService);
    EntityListener entityListener0 =
        Mockito.when(Mockito.mock(EntityListener.class).getEntityId())
            .thenReturn(Integer.valueOf(1))
            .getMock();
    EntityListener entityListener1 =
        Mockito.when(Mockito.mock(EntityListener.class).getEntityId())
            .thenReturn(Integer.valueOf(1))
            .getMock();
    entityListenersService.addEntityListener("entityFullName", entityListener0);
    entityListenersService.addEntityListener("entityFullName", entityListener1);

    Entity entity =
        Mockito.when(Mockito.mock(Entity.class).getIdValue())
            .thenReturn(Integer.valueOf(1))
            .getMock();
    entityListenerRepositoryDecorator.update(entity);

    Mockito.verify(decoratedRepository).update(entity);
    Mockito.verify(entityListener0, Mockito.times(1)).postUpdate(entity);
    Mockito.verify(entityListener1, Mockito.times(1)).postUpdate(entity);
  }
예제 #15
0
  @Test
  public void testExecRequestPersistentStatefulConnection() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.same(request),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response);
    Mockito.when(reuseStrategy.keepAlive(Mockito.same(response), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);
    Mockito.when(userTokenHandler.getUserToken(Mockito.<HttpClientContext>any()))
        .thenReturn("this and that");

    mainClientExec.execute(route, request, context, execAware);
    Mockito.verify(connManager).requestConnection(route, null);
    Mockito.verify(connRequest).get(0, TimeUnit.MILLISECONDS);
    Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context);
    Mockito.verify(connManager)
        .releaseConnection(managedConn, "this and that", 0, TimeUnit.MILLISECONDS);
    Mockito.verify(managedConn, Mockito.never()).close();

    Assert.assertEquals("this and that", context.getUserToken());
  }
예제 #16
0
  @Test
  public void testExecRequestPersistentConnection() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.same(request),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response);
    Mockito.when(reuseStrategy.keepAlive(Mockito.same(response), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);
    Mockito.when(
            keepAliveStrategy.getKeepAliveDuration(
                Mockito.same(response), Mockito.<HttpClientContext>any()))
        .thenReturn(678L);

    final CloseableHttpResponse finalResponse =
        mainClientExec.execute(route, request, context, execAware);
    Mockito.verify(connManager).requestConnection(route, null);
    Mockito.verify(connRequest).get(0, TimeUnit.MILLISECONDS);
    Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context);
    Mockito.verify(connManager).releaseConnection(managedConn, null, 678L, TimeUnit.MILLISECONDS);
    Mockito.verify(managedConn, Mockito.never()).close();

    Assert.assertNotNull(finalResponse);
    Assert.assertTrue(finalResponse instanceof HttpResponseProxy);
  }
예제 #17
0
  /** 用Mockito快速創建一個已認證的用户. */
  public static void mockSubject(Object principal) {
    Subject subject = Mockito.mock(Subject.class);
    Mockito.when(subject.isAuthenticated()).thenReturn(true);
    Mockito.when(subject.getPrincipal()).thenReturn(principal);

    bindSubject(subject);
  }
  @Test
  public void testRemoveAttachment() throws Exception {

    // CREATING ATTACHMENT FOR REMOVE
    List<MultipartFile> files = new ArrayList<>();
    files.add(multipartFile);

    Mockito.when(attachmentFactory.newAttachment()).thenReturn(null);

    attachmentService.setAttachment(new Attachment());
    attachmentService.setMessageResponse(new MessageResponse());

    MessageResponse messageResponse1 = attachmentService.createAttachment(files);

    Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture());

    Attachment attachment = argumentCaptor.getValue().get(0);

    // REMOVE ATTACHMENT
    Mockito.when(attachmentDao.removeAttachment(attachment.getAttachmentId()))
        .thenReturn(attachment);

    MessageResponse messageResponse =
        attachmentService.removeAttachment(attachment.getAttachmentId());

    boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath()));
    boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Assert.assertTrue(!isExistPreview && !isExistImage && messageResponse.getCode() == 1);
  }
  @Before
  public void setup() {

    service = new SentenceServiceImpl();

    //	Establish Mock Dependencies:
    SubjectClient subject = Mockito.mock(SubjectClient.class);
    VerbClient verb = Mockito.mock(VerbClient.class);
    ArticleClient article = Mockito.mock(ArticleClient.class);
    AdjectiveClient adjective = Mockito.mock(AdjectiveClient.class);
    NounClient noun = Mockito.mock(NounClient.class);

    service.setSubjectService(subject);
    service.setVerbService(verb);
    service.setArticleService(article);
    service.setAdjectiveService(adjective);
    service.setNounService(noun);

    //	Describe Mock Behaviors:
    Mockito.when(subject.getWord()).thenReturn(new Word("1"));
    Mockito.when(verb.getWord()).thenReturn(new Word("2"));
    Mockito.when(article.getWord()).thenReturn(new Word("3"));
    Mockito.when(adjective.getWord()).thenReturn(new Word("4"));
    Mockito.when(noun.getWord()).thenReturn(new Word("5"));
  }
예제 #20
0
  /** Make sure we can get a valid SAMLContextProvider. */
  @Test
  public void canGetContextProvider() {
    final SAMLProperties properties = Mockito.mock(SAMLProperties.class);

    Mockito.when(properties.getLoadBalancer()).thenReturn(null);

    SAMLContextProvider provider = this.config.contextProvider(properties);
    Assert.assertNotNull(provider);
    Assert.assertFalse(provider instanceof SAMLContextProviderLB);

    final SAMLProperties.LoadBalancer loadBalancer = new SAMLProperties.LoadBalancer();
    final String scheme = UUID.randomUUID().toString();
    loadBalancer.setScheme(scheme);
    final String serverName = UUID.randomUUID().toString();
    loadBalancer.setServerName(serverName);
    final int port = 443;
    loadBalancer.setServerPort(port);
    final String contextPath = UUID.randomUUID().toString();
    loadBalancer.setContextPath(contextPath);

    Mockito.when(properties.getLoadBalancer()).thenReturn(loadBalancer);
    provider = this.config.contextProvider(properties);
    Assert.assertNotNull(provider);
    Assert.assertTrue(provider instanceof SAMLContextProviderLB);
  }
 public void testJobDispatcher() {
   final MultipleNodeExecutorFactory factory = Mockito.mock(MultipleNodeExecutorFactory.class);
   final MultipleNodeExecutorTuner tuner = new MultipleNodeExecutorTuner(factory);
   final JobDispatcher dispatcher = Mockito.mock(JobDispatcher.class);
   final Map<String, Collection<Capability>> capabilities =
       new HashMap<String, Collection<Capability>>();
   Mockito.when(dispatcher.getAllCapabilities()).thenReturn(capabilities);
   tuner.setJobDispatcher(dispatcher);
   tuner.run();
   Mockito.verifyZeroInteractions(factory);
   capabilities.put("A", Arrays.asList(Capability.instanceOf("Foo")));
   capabilities.put("B", Arrays.asList(Capability.instanceOf("Bar")));
   tuner.run();
   Mockito.verifyZeroInteractions(factory);
   capabilities.put(
       "A",
       Arrays.asList(
           Capability.instanceOf("Foo"),
           Capability.parameterInstanceOf(PlatformCapabilities.NODE_COUNT, 10d)));
   capabilities.put(
       "B",
       Arrays.asList(
           Capability.instanceOf("Bar"),
           Capability.parameterInstanceOf(PlatformCapabilities.NODE_COUNT, 4d)));
   tuner.run();
   Mockito.verify(factory, Mockito.times(1)).setMaximumConcurrency(7);
   Mockito.verify(factory, Mockito.times(1)).invalidateCache();
   Mockito.when(factory.getMaximumConcurrency()).thenReturn(7);
   tuner.run();
   Mockito.verify(factory, Mockito.times(1)).setMaximumConcurrency(7);
   Mockito.verify(factory, Mockito.times(1)).invalidateCache();
 }
  @Test
  @Transactional
  @Rollback(value = true)
  @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL)
  public void test_Pageable_GetAllRecentUpdate() throws Exception {
    final int count = 10;

    Map<NEntityReference, Persistable<Long>> persistableMap = Maps.newHashMap();
    for (int it = 0; it < count; it++) {
      final Persistable<Long> persistable = this.getSpiedPersistableFromSupported(it);
      Mockito.when(persistable.getId()).thenReturn((long) (it + 1));
      final NEntityReference ref =
          (NEntityReference) this.entityReferenceHelper.toReference(persistable);
      this.recentlyUpdatedService.newRecentUpdate(persistable);

      persistableMap.put(ref, persistable);
    }

    final EntityReferenceHelper spy = Mockito.spy(this.entityReferenceHelper);
    for (final NEntityReference ref : persistableMap.keySet()) {
      Mockito.when(spy.fromReference(ref)).thenReturn(persistableMap.get(ref));
    }

    ReflectionTestUtils.setField(this.recentlyUpdatedService, "entityReferenceHelper", spy);

    final Page<RecentUpdateBean> recentlyUpdated =
        this.recentlyUpdatedService.getRecentlyUpdated(new PageRequest(0, 50));

    Assert.assertNotNull(recentlyUpdated);
    Assert.assertTrue(recentlyUpdated.getNumberOfElements() > 0);
    Assert.assertEquals(count, recentlyUpdated.getNumberOfElements());
  }
  @Test
  public void testRemoveArticle() throws Exception {

    MessageResponseServiceImpl mrs = new MessageResponseServiceImpl();

    // Successful case
    mrs.setMessageResponse(new MessageResponse());
    articleService.setMessageResponseService(mrs);

    Article articleSuccess = new Article();
    articleSuccess.setTitle("test success");
    articleSuccess.setDeleted(true);

    Mockito.when(articleDao.removeArticle(articleSuccess)).thenReturn(articleSuccess);

    MessageResponse messageSuccess = articleService.removeArticle(articleSuccess);

    // Fail case
    mrs.setMessageResponse(new MessageResponse());
    articleService.setMessageResponseService(mrs);

    Article articleFail = new Article();
    articleFail.setTitle("test fail");
    articleFail.setDeleted(false);

    Mockito.when(articleDao.removeArticle(articleFail)).thenReturn(articleFail);

    MessageResponse messageFail = articleService.removeArticle(articleFail);

    Assert.assertTrue(messageSuccess.getCode() == 1 && messageFail.getCode() == 0);
  }
예제 #24
0
  /** Tests that in DEPLOYMENT mode the API is NOT exposed. */
  @Test
  public void apiCallInDeploymentMode() throws Exception {
    final Properties props = new Properties();
    // init WroConfig properties
    props.setProperty(ConfigConstants.debug.name(), Boolean.FALSE.toString());
    final WroFilter theFilter =
        new WroFilter() {
          @Override
          protected ObjectFactory<WroConfiguration> newWroConfigurationFactory() {
            final PropertyWroConfigurationFactory factory = new PropertyWroConfigurationFactory();
            factory.setProperties(props);
            return factory;
          }
        };
    initFilterWithValidConfig(theFilter);
    final HttpServletRequest request =
        Mockito.mock(HttpServletRequest.class, Mockito.RETURNS_DEEP_STUBS);
    Mockito.when(request.getRequestURI()).thenReturn(WroFilter.API_RELOAD_CACHE);

    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Mockito.when(response.getWriter()).thenReturn(new PrintWriter(System.out));
    final FilterChain chain = Mockito.mock(FilterChain.class);
    // by default configuration is development
    theFilter.init(config);

    theFilter.doFilter(request, response, chain);
    // No api method exposed -> proceed with chain
    verifyChainIsCalled(chain);
  }
  @Test
  public void isUserInRole() {
    AuthenticationUtilService tested = getTested();

    Mockito.when(tested.httpRequest.isUserInRole(ROLE1)).thenReturn(false);
    Mockito.when(tested.httpRequest.isUserInRole(ROLE2)).thenReturn(true);

    {
      Assert.assertFalse(tested.isUserInRole(null));
      Mockito.verifyZeroInteractions(tested.httpRequest);
    }
    {
      Assert.assertFalse(tested.isUserInRole(""));
      Mockito.verifyZeroInteractions(tested.httpRequest);
    }
    {
      Assert.assertFalse(tested.isUserInRole("  "));
      Mockito.verifyZeroInteractions(tested.httpRequest);
    }
    {
      Assert.assertFalse(tested.isUserInRole(ROLE1));
      Mockito.verify(tested.httpRequest).isUserInRole(ROLE1);
    }
    {
      Assert.assertTrue(tested.isUserInRole(ROLE2));
      Mockito.verify(tested.httpRequest).isUserInRole(ROLE2);
    }
  }
예제 #26
0
  @Test
  public void test8() throws ParseException {

    String routeInfo = "1";
    String date = "2015-12-01";
    String time = "00:00";
    Route r = new Route();
    r.setRouteId(1);
    r.setRouteName("route");
    Direction d = new Direction();
    d.setDirectionId(2);
    Shedule s = new Shedule();
    s.setDirection(d);
    s.setStep(0);
    List<Shedule> steps = new ArrayList<Shedule>();
    steps.add(s);

    List<Train> trains = new ArrayList<Train>();

    Mockito.when(dao.getRoute(Integer.parseInt(routeInfo))).thenReturn(r);
    Mockito.when(dao.getShedulesOfRoute(r.getRouteId())).thenReturn(steps);
    Mockito.when(dao.getAllTrains()).thenReturn(trains);

    NewJourneyInfo info1 = new NewJourneyInfo(routeInfo, date, time, null, null, null, false);
    NewJourneyInfo info3 = planner.plan(info1);

    Assert.assertTrue(info3.getJourneyId() == null);
    Assert.assertTrue(info3.getRouteName() == null);
    Assert.assertTrue(info3.getTrain() == null);
    Assert.assertTrue(info3.isTrainsLack());
  }
  @Test
  public void testHandleEvent_withContext_withRule_strictMaximum() throws Exception {

    Mockito.when(
            this.preferencesMngr.get(
                IPreferencesMngr.AUTONOMIC_MAX_VM_NUMBER, "" + Integer.MAX_VALUE))
        .thenReturn("4");
    Mockito.when(this.preferencesMngr.get(IPreferencesMngr.AUTONOMIC_STRICT_MAX_VM_NUMBER, "true"))
        .thenReturn("true");

    ManagedApplication ma = factorizeConfiguration();
    this.autonomicMngr.handleEvent(ma, new MsgNotifAutonomic("app", "/root", "event", null));

    Mockito.verify(this.preferencesMngr, Mockito.times(1))
        .get(IPreferencesMngr.AUTONOMIC_MAX_VM_NUMBER, "" + Integer.MAX_VALUE);
    Mockito.verify(this.preferencesMngr, Mockito.times(1))
        .get(IPreferencesMngr.AUTONOMIC_STRICT_MAX_VM_NUMBER, "true");

    ArgumentCaptor<CommandExecutionContext> execCtx =
        ArgumentCaptor.forClass(CommandExecutionContext.class);
    Mockito.verify(this.commandsMngr, Mockito.times(3))
        .execute(Mockito.any(Application.class), Mockito.anyString(), execCtx.capture());

    for (CommandExecutionContext c : execCtx.getAllValues()) {
      Assert.assertEquals(4, c.getMaxVm());
      Assert.assertTrue(c.isStrictMaxVm());
    }
  }
예제 #28
0
  @Test
  public void testEstablishRouteViaProxyTunnelRetryOnAuthChallengeNonPersistentConnection()
      throws Exception {
    final AuthState authState = new AuthState();
    final HttpRoute route = new HttpRoute(target, null, proxy, true);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
    final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
    response1.setEntity(EntityBuilder.create().setStream(instream1).build());
    final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(
            proxyAuthStrategy.isAuthenticationRequested(
                Mockito.eq(proxy), Mockito.same(response1), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);
    Mockito.when(
            reuseStrategy.keepAlive(Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.<HttpRequest>any(),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response1, response2);

    mainClientExec.establishRoute(authState, managedConn, route, request, context);

    Mockito.verify(connManager).connect(managedConn, route, 0, context);
    Mockito.verify(connManager).routeComplete(managedConn, route, context);
    Mockito.verify(instream1, Mockito.never()).close();
    Mockito.verify(managedConn).close();
  }
예제 #29
0
  @Test(expected = HttpException.class)
  public void testEstablishRouteViaProxyTunnelFailure() throws Exception {
    final AuthState authState = new AuthState();
    final HttpRoute route = new HttpRoute(target, null, proxy, true);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 500, "Boom");
    response.setEntity(new StringEntity("Ka-boom"));

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.<HttpRequest>any(),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response);

    try {
      mainClientExec.establishRoute(authState, managedConn, route, request, context);
    } catch (final TunnelRefusedException ex) {
      final HttpResponse r = ex.getResponse();
      Assert.assertEquals("Ka-boom", EntityUtils.toString(r.getEntity()));

      Mockito.verify(managedConn).close();

      throw ex;
    }
  }
예제 #30
-1
  @Test
  public void testEstablishRouteViaProxyTunnel() throws Exception {
    final AuthState authState = new AuthState();
    final HttpRoute route = new HttpRoute(target, null, proxy, true);
    final HttpClientContext context = new HttpClientContext();
    final RequestConfig config = RequestConfig.custom().setConnectTimeout(321).build();
    context.setRequestConfig(config);
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.<HttpRequest>any(),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response);

    mainClientExec.establishRoute(authState, managedConn, route, request, context);

    Mockito.verify(connManager).connect(managedConn, route, 321, context);
    Mockito.verify(connManager).routeComplete(managedConn, route, context);
    final ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
    Mockito.verify(requestExecutor)
        .execute(reqCaptor.capture(), Mockito.same(managedConn), Mockito.same(context));
    final HttpRequest connect = reqCaptor.getValue();
    Assert.assertNotNull(connect);
    Assert.assertEquals("CONNECT", connect.getRequestLine().getMethod());
    Assert.assertEquals(HttpVersion.HTTP_1_1, connect.getRequestLine().getProtocolVersion());
    Assert.assertEquals("foo:80", connect.getRequestLine().getUri());
  }