/**
  * Run the following test case.
  *
  * <ol>
  *   <li>Run a multiple search query, with only multiple requests, with *win* / *lin* as the
  *       parameter, searching for VMs
  *   <li>Force a failure with an HTTP status code = 404
  *   <li>Check to make sure the appropriate query start and query complete events are fired
  * </ol>
  */
 @Test
 public void testRunMultipleQueries_404_failure() {
   // Don't immediately call process until both queries are in the queue.
   fakeScheduler.setThreshold(2);
   when(mockConstants.requestToServerFailedWithCode())
       .thenReturn("A Request to the Server failed with the following Status Code"); // $NON-NLS-1$
   ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>();
   queryTypeList.add(VdcQueryType.Search);
   queryTypeList.add(VdcQueryType.Search);
   ArrayList<VdcQueryParametersBase> queryParamsList = new ArrayList<VdcQueryParametersBase>();
   queryParamsList.add(new SearchParameters("*win*", SearchType.VM)); // $NON-NLS-1$
   queryParamsList.add(new SearchParameters("*lin*", SearchType.VM)); // $NON-NLS-1$
   frontend.runMultipleQueries(
       queryTypeList, queryParamsList, mockMultipleQueryCallback, "test"); // $NON-NLS-1$
   StatusCodeException exception =
       new StatusCodeException(HttpServletResponse.SC_NOT_FOUND, "404 status code"); // $NON-NLS-1$
   // Repeat 4 times, because of retries.
   for (int i = 1; i < RETRY_COUNT; i++) {
     // Reset the count so we can re-add both entries again.
     fakeScheduler.resetCount();
     verify(mockService, times(i))
         .RunMultipleQueries(
             eq(queryTypeList), eq(queryParamsList), callbackMultipleQueries.capture());
     // Call the failure handler.
     callbackMultipleQueries.getValue().onFailure(exception);
   }
   ArgumentCaptor<FrontendFailureEventArgs> eventArgs =
       ArgumentCaptor.forClass(FrontendFailureEventArgs.class);
   verify(mockFrontendFailureEvent).raise(eq(Frontend.class), eventArgs.capture());
   assertEquals(
       "Message text didn't match", //$NON-NLS-1$
       "A Request to the Server failed with the following Status Code: 404", //$NON-NLS-1$
       eventArgs.getValue().getMessage().getText());
 }
  @Test
  public void testProcessRequest_DefaultFanartMissing() {
    AdvancedFanartMediaRequestHandler handler = spy(new AdvancedFanartMediaRequestHandler());
    doNothing().when(handler).sendFile(any(File.class), any(HttpServletResponse.class));
    doNothing()
        .when(handler)
        .error(
            anyInt(), anyString(), any(HttpServletRequest.class), any(HttpServletResponse.class));
    HttpServletRequest req = mock(HttpServletRequest.class);
    HttpServletResponse resp = mock(HttpServletResponse.class);

    doReturn("true").when(req).getParameter(AdvancedFanartMediaRequestHandler.PARAM_USE_DEFAULT);
    doReturn("movie").when(req).getParameter(AdvancedFanartMediaRequestHandler.PARAM_MEDIATYPE);
    doReturn("banner").when(req).getParameter(AdvancedFanartMediaRequestHandler.PARAM_ARTIFACTTYPE);
    doReturn("1").when(req).getParameter(AdvancedFanartMediaRequestHandler.PARAM_MEDIAFILE);
    handler.processRequest(req, resp);

    ArgumentCaptor<Integer> capture = ArgumentCaptor.forClass(Integer.class);
    verify(handler)
        .error(
            capture.capture(),
            anyString(),
            any(HttpServletRequest.class),
            any(HttpServletResponse.class));
    assertEquals(HttpServletResponse.SC_NOT_FOUND, capture.getValue().intValue());
  }
  @Test
  public void testLocksAreReleasedOnLogout() throws Exception {
    // Capture the event listener.
    ObservationManager observationManager = getMocker().getInstance(ObservationManager.class);
    ArgumentCaptor<EventListener> eventListenerCaptor =
        ArgumentCaptor.forClass(EventListener.class);
    verify(observationManager).addListener(eventListenerCaptor.capture());
    assertEquals("deleteLocksOnLogoutListener", eventListenerCaptor.getValue().getName());

    Query query = mock(Query.class);
    when(session.createQuery("delete from XWikiLock as lock where lock.userName=:userName"))
        .thenReturn(query);
    when(context.getUserReference())
        .thenReturn(new DocumentReference("xwiki", "XWiki", "LoggerOutter"));
    when(context.getUser()).thenReturn("XWiki.LoggerOutter");

    // Fire the logout event.
    eventListenerCaptor.getValue().onEvent(new ActionExecutingEvent("logout"), null, context);

    verify(session, times(2)).setFlushMode(FlushMode.COMMIT);
    verify(query).setString("userName", "XWiki.LoggerOutter");
    verify(query).executeUpdate();
    verify(transaction).commit();
    verify(session).close();

    // setDatabase() is called for each transaction and that calls checkDatabase().
    DataMigrationManager dataMigrationManager =
        mocker.getInstance(DataMigrationManager.class, "hibernate");
    verify(dataMigrationManager).checkDatabase();
  }
Example #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());
  }
  @Test
  public void testProcessRequest_DefaultFanartFromUserData() throws IOException {
    // but we want to test that it reads from the userdata area.
    File file =
        new File(
            Phoenix.getInstance().getUserPath(AdvancedFanartMediaRequestHandler.DEFAULT_FANART),
            "default_movie_poster.jpg");
    FileUtils.touch(file);

    AdvancedFanartMediaRequestHandler handler = spy(new AdvancedFanartMediaRequestHandler());
    doNothing().when(handler).sendFile(any(File.class), any(HttpServletResponse.class));
    doNothing()
        .when(handler)
        .error(
            anyInt(), anyString(), any(HttpServletRequest.class), any(HttpServletResponse.class));
    HttpServletRequest req = mock(HttpServletRequest.class);
    HttpServletResponse resp = mock(HttpServletResponse.class);

    doReturn("true").when(req).getParameter(AdvancedFanartMediaRequestHandler.PARAM_USE_DEFAULT);
    doReturn("movie").when(req).getParameter(AdvancedFanartMediaRequestHandler.PARAM_MEDIATYPE);
    doReturn("poster").when(req).getParameter(AdvancedFanartMediaRequestHandler.PARAM_ARTIFACTTYPE);
    doReturn("1").when(req).getParameter(AdvancedFanartMediaRequestHandler.PARAM_MEDIAFILE);
    handler.processRequest(req, resp);

    ArgumentCaptor<File> capture = ArgumentCaptor.forClass(File.class);
    verify(handler).sendFile(capture.capture(), any(HttpServletResponse.class));
    assertEquals("default_movie_poster.jpg", capture.getValue().getName());
    assertEquals("Should be 0 byte file, since we just created it", 0, capture.getValue().length());
  }
  private static void assertThemeUsed(ActionBarIconGenerator.Theme theme, @Nullable Color color)
      throws Exception {
    ArgumentCaptor<ActionBarIconGenerator.ActionBarOptions> argument =
        ArgumentCaptor.forClass(ActionBarIconGenerator.ActionBarOptions.class);

    ActionBarIconGenerator generator = mock(ActionBarIconGenerator.class);

    TemplateWizardState state = new TemplateWizardState();
    AssetStudioAssetGenerator studioGenerator =
        new AssetStudioAssetGenerator(
            new TemplateWizardContextAdapter(state), generator, null, null);
    pickImage(state);
    state.put(ATTR_ASSET_TYPE, AssetType.ACTIONBAR.name());
    state.put(ATTR_ASSET_THEME, theme.name());
    state.put(ATTR_FOREGROUND_COLOR, color);
    studioGenerator.generateImages(true);

    verify(generator, times(1))
        .generate(
            isNull(String.class),
            any(Map.class),
            eq(studioGenerator),
            argument.capture(),
            anyString());

    assertEquals(theme, argument.getValue().theme);

    if (color != null && theme.equals(ActionBarIconGenerator.Theme.CUSTOM)) {
      assertEquals(color.getRGB(), argument.getValue().customThemeColor);
    }
  }
Example #7
0
  @Test
  public void testPrintGotoFormWritesValidXML()
      throws IOException, ParserConfigurationException, SAXException {
    JspWriter mockJspWriter = mock(JspWriter.class);
    ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
    doAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(InvocationOnMock invok) {
                Object[] args = invok.getArguments();
                jspWriterOutput += (String) args[0];
                return null;
              }
            })
        .when(mockJspWriter)
        .print(arg.capture());

    jspWriterOutput = "";

    JspHelper.printGotoForm(mockJspWriter, 424242, "a token string", "foobar/file", "0.0.0.0");

    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(jspWriterOutput));
    parser.parse(is);
  }
  @Test
  public void shouldSaveNewConfig() {
    when(settingsFacade.asProperties()).thenReturn(new Properties());

    MetricsConfig config = ConfigUtil.getDefaultConfig();
    metricsConfigFacade.saveMetricsConfig(config);

    verify(settingsFacade).saveConfigProperties(any(), propertiesCaptor.capture());

    Properties properties = propertiesCaptor.getValue();

    assertNotNull(properties);

    assertEquals(properties.getProperty(METRICS_ENABLED), "true");

    assertEquals(properties.getProperty(CONSOLE_REPORTER_ENABLED), "true");
    assertEquals(properties.getProperty(CONSOLE_REPORTER_REPORTING_FREQUENCY_VALUE), "1");
    assertEquals(properties.getProperty(CONSOLE_REPORTER_REPORTING_FREQUENCY_UNIT), "SECONDS");
    assertEquals(properties.getProperty(CONSOLE_REPORTER_CONVERT_RATES_UNIT), "MILLISECONDS");
    assertEquals(properties.getProperty(CONSOLE_REPORTER_CONVERT_DURATIONS_UNIT), "SECONDS");

    assertEquals(properties.getProperty(GRAPHITE_REPORTER_ENABLED), "true");
    assertEquals(
        properties.getProperty(GRAPHITE_REPORTER_GRAPHITE_SERVER_URI), "http://foo.com/graphite");
    assertEquals(properties.getProperty(GRAPHITE_REPORTER_GRAPHITE_SERVER_PORT), "2003");
    assertEquals(properties.getProperty(GRAPHITE_REPORTER_REPORTING_FREQUENCY_VALUE), "1");
    assertEquals(properties.getProperty(GRAPHITE_REPORTER_REPORTING_FREQUENCY_UNIT), "SECONDS");
    assertEquals(properties.getProperty(GRAPHITE_REPORTER_CONVERT_RATES_UNIT), "MILLISECONDS");
    assertEquals(properties.getProperty(GRAPHITE_REPORTER_CONVERT_DURATIONS_UNIT), "SECONDS");
  }
  @Test
  public void testGroupCollapseFilterFieldAllFiltered() throws IOException {
    mockResponse(true);
    when(rb.grouping()).thenReturn(true);
    when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(true);
    when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FL))
        .thenReturn("price,discount,isCloseout,color,colorFamily");
    when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FF)).thenReturn(FIELD_CLOSEOUT);
    component.process(rb);
    verify(rb).grouping();
    verify(rb).getGroupingSpec();
    verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false);
    verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FL);
    verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FF);
    verify(params).getParams(GroupCollapseParams.GROUP_COLLAPSE_FQ);
    verifyNoMoreInteractions(rb);
    verifyNoMoreInteractions(params);

    ArgumentCaptor<NamedList> namedListArgument = ArgumentCaptor.forClass(NamedList.class);
    verify(rsp).add(eq("groups_summary"), namedListArgument.capture());

    NamedList groupsSummary = namedListArgument.getValue();
    NamedList productId = (NamedList) groupsSummary.get("productId");
    assertNotNull(productId);
    Set<String> colorFamilies = new HashSet<String>();
    colorFamilies.add("RedColorFamily");
    colorFamilies.add("BlackColorFamily");
    verifyProductSummary(
        (NamedList) productId.get("product1"), 80.0f, 100.0f, 0.0f, 20.0f, 2, colorFamilies);
    colorFamilies = new HashSet<String>();
    colorFamilies.add("OrangeColorFamily");
    colorFamilies.add("BrownColorFamily");
    verifyProductSummary(
        (NamedList) productId.get("product2"), 60.0f, 80.0f, 20.0f, 40.0f, 2, colorFamilies);
  }
  @Test
  public void testExtractHeadersAllCommonHeaders() throws Exception {

    final RequestType request1 = m_httpRecording.addRequest(m_connectionDetails1, "GET", "/path");

    request1.setHeaders(
        createHeaders(
            new NVPair("foo", "bah"), new NVPair("User-Agent", "blah"), new NVPair("Accept", "x")));
    request1.addNewResponse();

    final RequestType request2 = m_httpRecording.addRequest(m_connectionDetails1, "GET", "/path");

    request2.setHeaders(
        createHeaders(
            new NVPair("foo", "bah"), new NVPair("User-Agent", "blah"), new NVPair("Accept", "x")));
    request2.addNewResponse();

    m_httpRecording.dispose();

    verify(m_resultProcessor).process(m_recordingCaptor.capture());

    final HTTPRecordingType recording = m_recordingCaptor.getValue().getHttpRecording();

    assertEquals(1, recording.getCommonHeadersArray().length);

    final RequestType request = recording.getPageArray(0).getRequestArray(0);
    final HeadersType headers = request.getHeaders();
    assertEquals("headers0", headers.getExtends());
    assertEquals(1, headers.sizeOfHeaderArray());
  }
 /**
  * Run the following test case.
  *
  * <ol>
  *   <li>Run a multiple search query, with multiple requests, with *win* or *lin* as the
  *       parameter, searching for VMs
  *   <li>Return success, the success status is succeeded, with a failure in the result set
  *   <li>Check to make sure the appropriate query start and query complete events are fired
  * </ol>
  */
 @Test
 public void testRunMultipleQueries_multiple_success_and_failure() {
   // Don't immediately call process until both queries are in the queue.
   fakeScheduler.setThreshold(2);
   ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>();
   queryTypeList.add(VdcQueryType.Search);
   queryTypeList.add(VdcQueryType.Search);
   ArrayList<VdcQueryParametersBase> queryParamsList = new ArrayList<VdcQueryParametersBase>();
   queryParamsList.add(new SearchParameters("*win*", SearchType.VM)); // $NON-NLS-1$
   queryParamsList.add(new SearchParameters("*lin*", SearchType.VM)); // $NON-NLS-1$
   frontend.runMultipleQueries(
       queryTypeList, queryParamsList, mockMultipleQueryCallback, "test"); // $NON-NLS-1$
   verify(mockService)
       .RunMultipleQueries(
           eq(queryTypeList), eq(queryParamsList), callbackMultipleQueries.capture());
   // Call the failure handler.
   List<VdcQueryReturnValue> result = new ArrayList<VdcQueryReturnValue>();
   result.add(new VdcQueryReturnValue());
   result.get(0).setSucceeded(false);
   result.add(new VdcQueryReturnValue());
   result.get(1).setSucceeded(true);
   ArgumentCaptor<FrontendMultipleQueryAsyncResult> multipleResultCaptor =
       ArgumentCaptor.forClass(FrontendMultipleQueryAsyncResult.class);
   callbackMultipleQueries.getValue().onSuccess((ArrayList<VdcQueryReturnValue>) result);
   verify(mockMultipleQueryCallback).executed(multipleResultCaptor.capture());
   assertEquals(
       "callback result much match",
       result, //$NON-NLS-1$
       multipleResultCaptor.getValue().getReturnValues());
 }
  @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());
    }
  }
  private void checkRenderedSelectedCells(
      final int selectionRowIndex,
      final int selectionColumnIndex,
      final int selectionColumnCount,
      final int selectionRowCount,
      final int minVisibleRowIndex,
      final int maxVisibleRowIndex) {
    this.model.selectCells(
        selectionRowIndex, selectionColumnIndex, selectionColumnCount, selectionRowCount);
    when(context.getMinVisibleRowIndex()).thenReturn(minVisibleRowIndex);
    when(context.getMaxVisibleRowIndex()).thenReturn(maxVisibleRowIndex);

    renderer.renderSelectedCells(model, context, rendererHelper);

    verify(renderer, times(1))
        .renderSelectedRange(
            eq(model),
            columnsCaptor.capture(),
            eq(selectionColumnIndex),
            selectedRangeCaptor.capture());

    final List<GridColumn<?>> columns = columnsCaptor.getValue();
    assertNotNull(columns);
    assertEquals(1, columns.size());
    assertEquals(column, columns.get(0));

    final SelectedRange selectedRange = selectedRangeCaptor.getValue();
    assertNotNull(selectedRange);
    assertEquals(selectionColumnIndex, selectedRange.getUiColumnIndex());
    assertEquals(minVisibleRowIndex, selectedRange.getUiRowIndex());
    assertEquals(selectionColumnCount, selectedRange.getWidth());
    assertEquals(maxVisibleRowIndex - minVisibleRowIndex + 1, selectedRange.getHeight());
  }
  @Test
  public void shouldQueryResourceSetToken() throws Exception {

    // Given
    Map<String, Object> queryParameters = new HashMap<String, Object>();
    queryParameters.put(ResourceSetTokenField.CLIENT_ID, "CLIENT_ID");
    ResourceSetDescription resourceSet1 =
        new ResourceSetDescription(
            "123", "CLIENT_ID", "RESOURCE_OWNER_ID", Collections.<String, Object>emptyMap());
    ResourceSetDescription resourceSet2 =
        new ResourceSetDescription(
            "456", "CLIENT_ID", "RESOURCE_OWNER_ID", Collections.<String, Object>emptyMap());

    given(dataStore.query(Matchers.<QueryFilter<String>>anyObject()))
        .willReturn(asSet(resourceSet1, resourceSet2));
    resourceSet1.setRealm("REALM");
    resourceSet2.setRealm("REALM");

    // When
    QueryFilter<String> query = QueryFilter.alwaysTrue();
    Set<ResourceSetDescription> resourceSetDescriptions = store.query(query);

    // Then
    assertThat(resourceSetDescriptions).contains(resourceSet1, resourceSet2);
    ArgumentCaptor<QueryFilter> tokenFilterCaptor = ArgumentCaptor.forClass(QueryFilter.class);
    verify(dataStore).query(tokenFilterCaptor.capture());
    assertThat(tokenFilterCaptor.getValue())
        .isEqualTo(
            QueryFilter.and(query, QueryFilter.equalTo(ResourceSetTokenField.REALM, "REALM")));
  }
 @Test
 public void clientRequestMultipleEmptyDataFrames() throws Exception {
   final String text = "";
   final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/path/resource2", content, true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, text.length());
     final Http2Headers http2Headers =
         new DefaultHttp2Headers().method(as("GET")).path(as("/some/path/resource2"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> requestCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener).messageReceived(requestCaptor.capture());
     capturedRequests = requestCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
   } finally {
     request.release();
   }
 }
  @Test
  public void testServerReturnsAnHttp401() throws Exception {
    ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);

    when(myHttpResponse.getStatusLine())
        .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 401, "Unauthorized"));
    when(myHttpResponse.getEntity().getContentType())
        .thenReturn(new BasicHeader("content-type", Constants.CT_TEXT));
    when(myHttpResponse.getEntity().getContent())
        .thenAnswer(
            new Answer<InputStream>() {
              @Override
              public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
                return new ReaderInputStream(
                    new StringReader("Unauthorized"), Charset.forName("UTF-8"));
              }
            });
    when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);

    IGenericClient client = myCtx.newRestfulGenericClient("http://foo");
    try {
      client.read().resource(Patient.class).withId("123").execute();
      fail();
    } catch (AuthenticationException e) {
      // good
    }
  }
  @Test
  public void testServerReturnsWrongVersionForDstu2() throws Exception {
    Conformance conf = new Conformance();
    conf.setFhirVersion("0.80");
    String msg = myCtx.newXmlParser().encodeResourceToString(conf);

    ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);

    when(myHttpResponse.getStatusLine())
        .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    when(myHttpResponse.getEntity().getContentType())
        .thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
    when(myHttpResponse.getEntity().getContent())
        .thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")));

    when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);

    myCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE);
    try {
      myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123"));
      fail();
    } catch (FhirClientInappropriateForServerException e) {
      String out = e.toString();
      String want =
          "The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.80\" which corresponds to DSTU1, but this client is configured to use DSTU2 (via the FhirContext)";
      ourLog.info(out);
      ourLog.info(want);
      assertThat(out, containsString(want));
    }
  }
  @Test
  public void deveGerarPagamentoParaUmLeilaoEncerrado() {
    RepositorioDeLeiloes leiloes = mock(RepositorioDeLeiloes.class);
    RepositorioDePagamentos pagamentos = mock(RepositorioDePagamentos.class);
    // Avaliador avaliador = mock(Avaliador.class);
    Avaliador avaliador = new Avaliador();

    Leilao leilao =
        new CriadorDeLeilao()
            .para("TV")
            .lance(new Usuario("Fritz"), 2000.0)
            .lance(new Usuario("Frida"), 2500.0)
            .constroi();

    when(leiloes.encerrados()).thenReturn(Arrays.asList(leilao));
    // when(avaliador.getMaiorLance()).thenReturn(2500.0);

    GeradorDePagamento gerador = new GeradorDePagamento(leiloes, pagamentos, avaliador);
    gerador.gera();

    ArgumentCaptor<Pagamento> argumento = ArgumentCaptor.forClass(Pagamento.class);

    verify(pagamentos).salvar(argumento.capture());
    Pagamento pagamentoGerado = argumento.getValue();

    assertEquals(2500.0, pagamentoGerado.getValor(), 0.2);
  }
  @Ignore
  public void testMarshalRecordCollectionById() throws UnsupportedEncodingException, JAXBException {
    final int totalResults = 2;

    XStream xstream = createXStream(CswConstants.GET_RECORD_BY_ID_RESPONSE);
    CswRecordCollection collection = createCswRecordCollection(null, totalResults);
    collection.setById(true);

    ArgumentCaptor<MarshallingContext> captor = ArgumentCaptor.forClass(MarshallingContext.class);

    String xml = xstream.toXML(collection);

    // Verify the context arguments were set correctly
    verify(mockProvider, times(totalResults))
        .marshal(any(Object.class), any(HierarchicalStreamWriter.class), captor.capture());

    MarshallingContext context = captor.getValue();
    assertThat(context, not(nullValue()));
    assertThat(
        (String) context.get(CswConstants.OUTPUT_SCHEMA_PARAMETER),
        is(CswConstants.CSW_OUTPUT_SCHEMA));
    assertThat((ElementSetType) context.get(CswConstants.ELEMENT_SET_TYPE), is(nullValue()));
    assertThat(context.get(CswConstants.ELEMENT_NAMES), is(nullValue()));

    JAXBElement<GetRecordByIdResponseType> jaxb =
        (JAXBElement<GetRecordByIdResponseType>)
            getJaxBContext()
                .createUnmarshaller()
                .unmarshal(new ByteArrayInputStream(xml.getBytes("UTF-8")));

    GetRecordByIdResponseType response = jaxb.getValue();
    // Assert the GetRecordsResponse elements and attributes
    assertThat(response, not(nullValue()));
  }
Example #20
0
  @Test
  public void mockUpgradeLevels() throws Exception {
    UserServiceImpl userServiceImpl = new UserServiceImpl();

    UserDao mockUserDao = mock(UserDao.class);
    when(mockUserDao.getAll()).thenReturn(this.users);
    userServiceImpl.setUserDao(mockUserDao);

    MailSender mockMailSender = mock(MailSender.class);
    userServiceImpl.setMailSender(mockMailSender);

    userServiceImpl.upgradeLevels();

    verify(mockUserDao, times(2)).update(any(User.class));
    verify(mockUserDao, times(2)).update(any(User.class));
    verify(mockUserDao).update(users.get(1));
    assertThat(users.get(1).getLevel(), is(Level.SILVER));
    verify(mockUserDao).update(users.get(3));
    assertThat(users.get(3).getLevel(), is(Level.GOLD));

    ArgumentCaptor<SimpleMailMessage> mailMessageArg =
        ArgumentCaptor.forClass(SimpleMailMessage.class);
    verify(mockMailSender, times(2)).send(mailMessageArg.capture());
    List<SimpleMailMessage> mailMessages = mailMessageArg.getAllValues();
    assertThat(mailMessages.get(0).getTo()[0], is(users.get(1).getEmail()));
    assertThat(mailMessages.get(1).getTo()[0], is(users.get(3).getEmail()));
  }
Example #21
0
  private void testUpdateCreate(boolean edit) throws ClassNotFoundException {
    final DateTime dtValue = DateUtil.now();

    mockSampleFields();
    mockDataService();
    mockEntity();
    when(motechDataService.retrieve("id", INSTANCE_ID)).thenReturn(new TestSample());

    List<FieldRecord> fieldRecords =
        asList(
            FieldTestHelper.fieldRecord("strField", String.class.getName(), "", "this is a test"),
            FieldTestHelper.fieldRecord("intField", Integer.class.getName(), "", 16),
            FieldTestHelper.fieldRecord("timeField", Time.class.getName(), "", "10:17"),
            FieldTestHelper.fieldRecord("dtField", DateTime.class.getName(), "", dtValue));

    Long id = (edit) ? INSTANCE_ID : null;
    EntityRecord record = new EntityRecord(id, ENTITY_ID, fieldRecords);

    MDSClassLoader.getInstance().loadClass(TestSample.class.getName());
    instanceService.saveInstance(record);

    ArgumentCaptor<TestSample> captor = ArgumentCaptor.forClass(TestSample.class);
    if (edit) {
      verify(motechDataService).update(captor.capture());
    } else {
      verify(motechDataService).create(captor.capture());
    }

    TestSample sample = captor.getValue();
    assertEquals("this is a test", sample.getStrField());
    assertEquals(Integer.valueOf(16), sample.getIntField());
    assertEquals(new Time(10, 17), sample.getTimeField());
    assertEquals(dtValue, sample.getDtField());
  }
Example #22
0
  @Test
  public void testReloadAndLayerRemovedExternally() throws Exception {

    final String removedLayer = tileLayer.getName();
    final String remainingLayer = tileLayerGroup.getName();

    final Set<String> layerNames = Sets.newHashSet(removedLayer, remainingLayer);

    when(tld.getLayerNames()).thenReturn(layerNames);
    doAnswer(
            new Answer<Void>() {

              @Override
              public Void answer(InvocationOnMock invocation) throws Throwable {
                layerNames.remove(removedLayer);
                return null;
              }
            })
        .when(tld)
        .reInit();

    ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);

    mediator = spy(mediator);
    doReturn(true).when(mediator).layerRemoved(argCaptor.capture());

    mediator.reload();

    verify(tld, times(1)).reInit();
    assertEquals(1, argCaptor.getAllValues().size());
    assertEquals(removedLayer, argCaptor.getValue());
  }
  @Test
  public void changedBlock() throws IOException {
    final String fileContent =
        FileUtils.readFileToString(
            new File("src/test/resources/ajdiff/deleted/logging/Person_Logging_Deleted_Blocks.aj"));
    final String generatedFromJavaFile =
        FileUtils.readFileToString(
            new File("src/test/resources/ajdiff/deleted/logging/Person_Logging_Original.aj"));
    final String generatedFromJavaFile2 =
        FileUtils.readFileToString(
            new File("src/test/resources/ajdiff/deleted/logging/Person_Logging.aj"));

    final ArgumentCaptor<JavaClass> argument = ArgumentCaptor.forClass(JavaClass.class);
    when(generatorManager.generateContentForGenerator(argument.capture(), Matchers.anyString()))
        .thenReturn(generatedFromJavaFile, generatedFromJavaFile2);

    final AspectJDiffImpl result = aspectJDiffManager.createDiff(fileContent, "");
    assertEquals(2, result.getAspectJMethodDiffs().size());
    assertEquals(
        "method(Integer, Integer, String)",
        result.getAspectJMethodDiffs().get(0).getMethod().getMethodSignature());
    assertEquals(
        "Logging", result.getAspectJMethodDiffs().get(0).getAnnotationData().getDeleted().get(0));

    assertEquals(
        "method2(Integer, Integer, String)",
        result.getAspectJMethodDiffs().get(1).getMethod().getMethodSignature());
    assertEquals(
        "Logging2", result.getAspectJMethodDiffs().get(1).getAnnotationData().getDeleted().get(0));
  }
  @Test
  public void willSaveAndMoveToNextRow() {
    // Given: selected display and there is only one entry(no plural or last entry of plural)
    selectedTU = currentPageRows.get(0);
    when(display.getNewTargets()).thenReturn(NEW_TARGETS);
    when(display.getCachedTargets()).thenReturn(CACHED_TARGETS);
    when(display.getId()).thenReturn(selectedTU.getId());
    when(display.getEditors()).thenReturn(Lists.newArrayList(editor));
    presenter.setStatesForTesting(selectedTU.getId(), 0, display);

    // When:
    presenter.saveAsApprovedAndMoveNext(selectedTU.getId());

    // Then:
    verify(eventBus, atLeastOnce()).fireEvent(eventCaptor.capture());

    TransUnitSaveEvent saveEvent =
        TestFixture.extractFromEvents(eventCaptor.getAllValues(), TransUnitSaveEvent.class);
    assertThat(saveEvent.getTransUnitId(), equalTo(selectedTU.getId()));
    assertThat(saveEvent.getTargets(), Matchers.equalTo(NEW_TARGETS));
    assertThat(saveEvent.getStatus(), equalTo(ContentState.Translated));

    NavTransUnitEvent navEvent =
        TestFixture.extractFromEvents(eventCaptor.getAllValues(), NavTransUnitEvent.class);
    assertThat(navEvent.getRowType(), equalTo(NavTransUnitEvent.NavigationType.NextEntry));
  }
  @Test
  public void testOnInsertString() {
    // Given:
    selectedTU = currentPageRows.get(0);
    when(editor.getId()).thenReturn(selectedTU.getId());
    when(display.getId()).thenReturn(selectedTU.getId());
    when(display.getEditors()).thenReturn(Lists.newArrayList(editor));
    when(tableEditorMessages.notifyCopied()).thenReturn("copied");
    when(sourceContentPresenter.getSourceContent(selectedTU.getId()))
        .thenReturn(Optional.of("source content"));

    presenter.setStatesForTesting(selectedTU.getId(), 0, display);

    // When:
    presenter.onInsertString(new InsertStringInEditorEvent("", "suggestion"));

    // Then:
    verify(editor).insertTextInCursorPosition("suggestion");

    verify(eventBus, atLeastOnce()).fireEvent(eventCaptor.capture());
    NotificationEvent notificationEvent =
        TestFixture.extractFromEvents(eventCaptor.getAllValues(), NotificationEvent.class);
    MatcherAssert.assertThat(notificationEvent.getMessage(), Matchers.equalTo("copied"));

    RunValidationEvent runValidationEvent =
        TestFixture.extractFromEvents(eventCaptor.getAllValues(), RunValidationEvent.class);
    assertThat(runValidationEvent.getSourceContent(), equalTo("source content"));
  }
  @Test
  public void testConstructorAndDispose() throws Exception {
    verifyNoMoreInteractions(m_resultProcessor);

    assertNotNull(m_httpRecording.getParameters());
    assertSame(m_httpRecording.getParameters(), m_httpRecording.getParameters());

    m_httpRecording.dispose();
    m_httpRecording.dispose();

    verify(m_resultProcessor, times(2)).process(m_recordingCaptor.capture());

    final HttpRecordingDocument recording = m_recordingCaptor.getAllValues().get(0);
    final HttpRecordingDocument recording2 = m_recordingCaptor.getAllValues().get(1);

    XMLBeansUtilities.validate(recording);
    XMLBeansUtilities.validate(recording2);

    assertNotSame("We get a copy", recording, recording2);

    final Metadata metadata = recording.getHttpRecording().getMetadata();
    assertTrue(metadata.getVersion().length() > 0);
    assertNotNull(metadata.getTime());
    assertEquals(0, recording.getHttpRecording().getCommonHeadersArray().length);
    assertEquals(0, recording.getHttpRecording().getBaseUriArray().length);
    assertEquals(0, recording.getHttpRecording().getPageArray().length);
    verifyNoMoreInteractions(m_resultProcessor);

    final IOException exception = new IOException("Eat me");
    doThrow(exception).when(m_resultProcessor).process(isA(HttpRecordingDocument.class));

    m_httpRecording.dispose();

    verify(m_logger).error(exception.getMessage(), exception);
  }
  @Test
  public void delete_characteristic() {
    DbSession batchSession = mock(DbSession.class);
    when(dbClient.openSession(true)).thenReturn(batchSession);

    when(ruleDao.findRulesByDebtSubCharacteristicId(batchSession, subCharacteristicDto.getId()))
        .thenReturn(
            newArrayList(
                new RuleDto()
                    .setSubCharacteristicId(subCharacteristicDto.getId())
                    .setRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.toString())
                    .setRemediationCoefficient("2h")
                    .setRemediationOffset("5min")));
    when(dao.selectCharacteristicsByParentId(1, batchSession))
        .thenReturn(newArrayList(subCharacteristicDto));
    when(dao.selectById(1, batchSession)).thenReturn(characteristicDto);

    service.delete(1);

    verify(ruleDao).update(eq(batchSession), ruleCaptor.capture());

    verify(dao, times(2)).update(characteristicCaptor.capture(), eq(batchSession));
    CharacteristicDto subCharacteristicDto = characteristicCaptor.getAllValues().get(0);
    CharacteristicDto characteristicDto = characteristicCaptor.getAllValues().get(1);

    // Sub characteristic is disable
    assertThat(subCharacteristicDto.getId()).isEqualTo(2);
    assertThat(subCharacteristicDto.isEnabled()).isFalse();
    assertThat(subCharacteristicDto.getUpdatedAt()).isEqualTo(now);

    // Characteristic is disable
    assertThat(characteristicDto.getId()).isEqualTo(1);
    assertThat(characteristicDto.isEnabled()).isFalse();
    assertThat(characteristicDto.getUpdatedAt()).isEqualTo(now);
  }
  /**
   * Simple test.
   *
   * @author nschuste
   * @version 1.0.0
   * @throws InterruptedException
   * @since Feb 23, 2016
   */
  @Test(timeout = 10000)
  public void test() throws InterruptedException {
    final Map<String, Object> mp = new HashMap<>();
    mp.put("abc", new TextDispatcher());
    Mockito.when(this.context.getBeansWithAnnotation(Matchers.any())).thenReturn(mp);
    final JFrame frame = new JFrame();
    final JTextField b = new JTextField();
    b.setName("xyz");
    final JButton c = new JButton();
    c.setName("cc");
    frame.getContentPane().add(b);
    frame.getContentPane().add(c);
    frame.pack();
    frame.setVisible(true);
    final JTextComponentFixture fix = new JTextComponentFixture(this.r, "xyz");
    final JButtonFixture fix2 = new JButtonFixture(this.r, "cc");
    this.dispatcher.initialize(this.lstr);
    final ArgumentCaptor<TestCaseStep> captor = ArgumentCaptor.forClass(TestCaseStep.class);
    fix.enterText("hello");
    fix2.focus();
    try {
      SwingUtilities.invokeAndWait(() -> {});

    } catch (final InvocationTargetException e) {
      e.printStackTrace();
    }
    Mockito.verify(this.lstr, Mockito.times(1)).event(captor.capture());
    final TestCaseStep capt = captor.getValue();
    Assert.assertEquals(capt.getMethodName(), "text.enter");
    Assert.assertEquals(capt.getArgs().length, 2);
    Assert.assertEquals(capt.getArgs()[0], "xyz");
    Assert.assertEquals(capt.getArgs()[1], "hello");
  }
  @Test
  public void testShouldRaiseExceptionEventWhenCaseNameIsMissing()
      throws FileNotFoundException, CaseParserException {

    CaseTask task = new CaseTask();

    CreateTask createTask = new CreateTask();

    createTask.setOwnerId("OWNER_ID");

    createTask.setCaseType("CASE_TYPE");

    task.setCreateTask(createTask);

    ArgumentCaptor<MotechEvent> motechEventCaptor = ArgumentCaptor.forClass(MotechEvent.class);

    String xml = caseConverter.convertToCaseXml(task);

    verify(eventRelay).sendEventMessage(motechEventCaptor.capture());

    MotechEvent motechEvent = motechEventCaptor.getValue();

    Assert.assertEquals(motechEvent.getSubject(), EventSubjects.MALFORMED_CASE_EXCEPTION);

    Assert.assertNull(xml);
  }
  @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());
  }