private void doRequestWithoutDocs(String url) throws Exception {
    ApiRequestParams params =
        ApiRequestParams.builder()
            .apiNs("Ext.ns")
            .actionNs("actionns")
            .group("doc")
            .configuration(configurationService.getConfiguration())
            .build();
    MockHttpServletRequestBuilder request =
        get(url).accept(MediaType.ALL).characterEncoding("UTF-8");
    request.param("apiNs", params.getApiNs());
    request.param("actionNs", params.getActionNs());
    request.param("group", params.getGroup());

    MvcResult result =
        mockMvc
            .perform(request)
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/javascript"))
            .andReturn();

    ApiControllerTest.compare(result, ApiControllerTest.groupApisWithDoc("actionns"), params);
    Assert.doesNotContain(
        "/**",
        result.getResponse().getContentAsString(),
        "generation of api.js should not contain method documentation");
  }
  private ActionDoc callApi(String method) throws Exception {
    ApiRequestParams params =
        ApiRequestParams.builder()
            .apiNs("Ext.ns")
            .actionNs("actionns")
            .group("doc")
            .configuration(configurationService.getConfiguration())
            .build();
    MockHttpServletRequestBuilder request =
        get("/api-debug-doc.js").accept(MediaType.ALL).characterEncoding("UTF-8");
    request.param("apiNs", params.getApiNs());
    request.param("actionNs", params.getActionNs());
    request.param("group", params.getGroup());

    MvcResult result =
        mockMvc
            .perform(request)
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/javascript"))
            .andReturn();

    ApiControllerTest.compare(result, ApiControllerTest.groupApisWithDoc("actionns"), params);
    ActionDoc doc = getCommentForMethod(result.getResponse().getContentAsString(), method);
    return doc;
  }
  private void saveProfile(String editTeamUri) throws Exception {
    MockHttpServletRequestBuilder requestBuilder = put(editTeamUri).principal(principal);
    requestBuilder.param("name", "Some_ Guy_");
    requestBuilder.param("jobTitle", "Rock Star");
    requestBuilder.param("location", "London_");
    requestBuilder.param("bio", "I am just a guy_");
    requestBuilder.param("twitterUsername", "tw_some-guy_");
    requestBuilder.param("speakerdeckUsername", "sd_some-guy_");
    requestBuilder.param("lanyrdUsername", "ly_some-guy_");
    requestBuilder.param("geoLocation", "-12.5,45.3");
    requestBuilder.param(
        "videoEmbeds",
        "<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/J---aiyznGQ\" frameborder=\"0\" allowfullscreen></iframe>");

    performRequestAndExpectRedirect(requestBuilder, editTeamUri);

    MemberProfile profile = teamRepository.findByUsername("some-guy");
    assertThat(profile, not(nullValue()));
    assertEquals("some-guy", profile.getUsername());
    assertEquals("gh-some-guy", profile.getGithubUsername());
    assertEquals("Some_ Guy_", profile.getName());
    assertEquals("Rock Star", profile.getJobTitle());
    assertEquals("London_", profile.getLocation());
    assertEquals("I am just a guy_", profile.getBio());
    assertEquals("tw_some-guy_", profile.getTwitterUsername());
    assertEquals("sd_some-guy_", profile.getSpeakerdeckUsername());
    assertEquals("ly_some-guy_", profile.getLanyrdUsername());
    assertEquals(
        "<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/J---aiyznGQ\" frameborder=\"0\" allowfullscreen></iframe>",
        profile.getVideoEmbeds());

    assertThat(profile.getGeoLocation(), not(nullValue()));
    assertThat((double) profile.getGeoLocation().getLatitude(), closeTo(-12.5, 0.1));
    assertThat((double) profile.getGeoLocation().getLongitude(), closeTo(45.3, 0.1));
  }
Example #4
0
  /*
   * Test POST or PUT to /restAPI/items/{id}, to update a new document
   * But the request body is not valid
   */
  public void testUpdateDocNotValid(boolean isPost) throws Exception {

    ModelMap newDoc = createDoc("Bach", "unknonwn", "Wonderful");

    String jsonNewDoc = objectToJson(newDoc);

    String id = this.preAddedDocs.get(0).getId();

    // Manipulate the json string to be a wrong input
    jsonNewDoc = jsonNewDoc.substring(0, jsonNewDoc.lastIndexOf("}"));

    MockHttpServletRequestBuilder builder;

    if (isPost) builder = post("/restAPI/items/" + id);
    else builder = put("/restAPI/items/" + id);

    this.mockMvc
        .perform(builder.contentType(contentType).content(jsonNewDoc))
        .andExpect(status().isBadRequest());

    // Number of document not changed
    assertEquals(2, docRepository.count());

    // Original document not changed
    StoredDocument retrievedDoc = docRepository.findOne(id);

    assertEquals(preAddedDocs.get(0).getDocument(), retrievedDoc.getDocument());
  }
  @Test
  public void createUserInOtherZoneWithUaaAdminTokenFromNonDefaultZone() throws Exception {
    IdentityZone identityZone = getIdentityZone();

    String authorities = "uaa.admin";
    clientDetails =
        utils()
            .createClient(
                this.getMockMvc(),
                uaaAdminToken,
                "testClientId",
                "testClientSecret",
                null,
                null,
                Collections.singletonList("client_credentials"),
                authorities,
                null,
                identityZone);
    String uaaAdminTokenFromOtherZone =
        testClient.getClientCredentialsOAuthAccessToken(
            "testClientId", "testClientSecret", "uaa.admin", identityZone.getSubdomain());

    byte[] requestBody = JsonUtils.writeValueAsBytes(getScimUser());
    MockHttpServletRequestBuilder post =
        post("/Users")
            .header("Authorization", "Bearer " + uaaAdminTokenFromOtherZone)
            .contentType(APPLICATION_JSON)
            .content(requestBody);
    post.with(new SetServerNameRequestPostProcessor(identityZone.getSubdomain() + ".localhost"));
    post.header(IdentityZoneSwitchingFilter.HEADER, IdentityZone.getUaa().getId());

    getMockMvc().perform(post).andExpect(status().isForbidden());
  }
Example #6
0
  /*
   * Test POST or PUT to /restAPI/items/{id}, to update a new document
   * But the specified document is not found
   */
  public void testUpdateDocNotFound(boolean isPost) throws Exception {

    ModelMap newDoc = createDoc("Bach", "unknonwn", "Wonderful");

    String jsonNewDoc = objectToJson(newDoc);

    String id = this.preAddedDocs.get(0).getId();

    // Fake ID which does not exist
    String fakeId = id.substring(0, id.length() - 1);

    MockHttpServletRequestBuilder builder;

    if (isPost) builder = post("/restAPI/items/" + fakeId);
    else builder = put("/restAPI/items/" + fakeId);

    this.mockMvc
        .perform(builder.contentType(contentType).content(jsonNewDoc))
        .andExpect(status().isNotFound());

    // Number of document not changed
    assertEquals(2, docRepository.count());

    // Original document not changed
    StoredDocument retrievedDoc = docRepository.findOne(id);

    assertEquals(preAddedDocs.get(0).getDocument(), retrievedDoc.getDocument());
  }
Example #7
0
  /*
   * Test POST or PUT to /restAPI/items/{id}, to update a new document
   */
  public void testUpdateDoc(boolean isPost) throws Exception {

    ModelMap newDoc = createDoc("Bach", "unknonwn", "Wonderful");

    String jsonNewDoc = objectToJson(newDoc);

    // get an existing id
    String id = this.preAddedDocs.get(0).getId();

    MockHttpServletRequestBuilder builder;

    if (isPost) builder = post("/restAPI/items/" + id);
    else builder = put("/restAPI/items/" + id);

    this.mockMvc
        .perform(builder.contentType(contentType).content(jsonNewDoc))
        .andExpect(status().isOk());

    // the number of document not changed
    assertEquals(2, docRepository.count());

    // Verify the original document is updated
    StoredDocument retrievedDoc = docRepository.findOne(id);

    assertEquals(newDoc, retrievedDoc.getDocument());
  }
Example #8
0
  // Test POST or PUT on /restAPI/items, to add a document
  private void testAddOneNewDoc(boolean isPost) throws Exception {
    ModelMap newDoc = createDoc("Bach", "unknonwn", "Wonderful");

    String jsonNewDoc = objectToJson(newDoc);

    MockHttpServletRequestBuilder builder;

    if (isPost) builder = post("/restAPI/items/");
    else builder = put("/restAPI/items");

    MvcResult result =
        mockMvc
            .perform(builder.contentType(contentType).content(jsonNewDoc))
            .andExpect(status().isCreated())
            .andReturn();

    // Get the response body
    String resultJson = result.getResponse().getContentAsString();

    // Get the document ID returned
    DocIDReturn idRet = mapper.readValue(resultJson, DocIDReturn.class);

    // Now in the database there shall be 3 documents
    assertEquals(3, docRepository.count());

    // Get the document just added, and verify
    StoredDocument retrievedDoc = docRepository.findOne(idRet.getId());

    assertEquals(newDoc, retrievedDoc.getDocument());
  }
  @Test
  public void testMockGetUserByUsernameAndPassword1() throws Exception {
    MockHttpServletRequestBuilder requestBuilder =
        MockMvcRequestBuilders.get("/login/user/{username}/pwd/{password}");

    requestBuilder.param("username", "tholmes");
    requestBuilder.param("password", "pass1");

    this.mockMvc.perform(requestBuilder).andDo(print());
  }
 private MvcResult sendPingWithTraceId(String headerName, Long correlationId, boolean sampling)
     throws Exception {
   MockHttpServletRequestBuilder request =
       MockMvcRequestBuilders.get("/ping")
           .accept(MediaType.TEXT_PLAIN)
           .header(headerName, Span.toHex(correlationId))
           .header(Span.SPAN_ID_NAME, Span.toHex(new Random().nextLong()));
   if (!sampling) {
     request.header(Span.NOT_SAMPLED_NAME, "true");
   }
   return this.mockMvc.perform(request).andReturn();
 }
  private ResultActions createUserAndReturnResult(
      ScimUser user, String token, String subdomain, String switchZone) throws Exception {
    byte[] requestBody = JsonUtils.writeValueAsBytes(user);
    MockHttpServletRequestBuilder post =
        post("/Users")
            .header("Authorization", "Bearer " + token)
            .contentType(APPLICATION_JSON)
            .content(requestBody);
    if (subdomain != null && !subdomain.equals(""))
      post.with(new SetServerNameRequestPostProcessor(subdomain + ".localhost"));
    if (switchZone != null) post.header(IdentityZoneSwitchingFilter.HEADER, switchZone);

    return getMockMvc().perform(post);
  }
  private MockHttpServletResponse getResponse(String url, Map<String, String> params)
      throws Exception {
    MockHttpServletRequestBuilder request = get(url);
    if (params != null && params.size() > 0) {
      for (String key : params.keySet()) {
        request.param(key, params.get(key));
      }
    }
    ResultActions result = this.mockMvc.perform(request);
    result.andExpect(MockMvcResultMatchers.status().is(this.HttpStatus));
    MvcResult mvcresult = result.andReturn();
    MockHttpServletResponse mockresponse = mvcresult.getResponse();

    return mockresponse;
  }
Example #13
0
  /*
   * Test POST or PUT on /restAPI/items, but with an invalid body
   */
  public void testAddOneNewDoc_Invalid(boolean isPost) throws Exception {

    ModelMap newDoc = createDoc("Bach", "unknonwn", "Wonderful");

    String jsonNewDoc = objectToJson(newDoc);

    // Manipulate the json string to be a wrong input
    jsonNewDoc = jsonNewDoc.substring(0, jsonNewDoc.lastIndexOf("}"));

    MockHttpServletRequestBuilder builder;

    if (isPost) builder = post("/restAPI/items/");
    else builder = put("/restAPI/items/");

    mockMvc
        .perform(builder.contentType(contentType).content(jsonNewDoc))
        .andExpect(status().isBadRequest());

    // Number of document not changed
    assertEquals(2, docRepository.count());
  }
  @Test
  public void testCreateInvalidModel() throws Exception {

    Location location = new Location(null, null);
    String json = JackSONUtils.toJSON(location);
    LOG.info("location json: " + json);

    // -------- Request --------//

    MockHttpServletRequestBuilder requestBuilder = post(resourcePath).content(json);
    ResultActions resultActions =
        mockMvc.perform(
            requestBuilder
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON));

    // -------- Response --------//

    // Check: Status == 400 (bad request)
    resultActions.andExpect(status().isBadRequest());
    ResultActionsUtil.log(resultActions);
  }
  @Test
  public void testFetchAll() throws Exception {

    // Create 3
    for (int i = 0; i < 3; i++) {
      String json = JackSONUtils.toJSON(new Location(null, "karbing"));
      LOG.info("location json: " + json);
      mockMvc.perform(
          post(resourcePath)
              .content(json)
              .accept(MediaType.APPLICATION_JSON)
              .contentType(MediaType.APPLICATION_JSON));
    }
    // Fetch
    MockHttpServletRequestBuilder requestBuilder = get(resourcePath);
    ResultActions resultActions =
        mockMvc.perform(requestBuilder.accept(MediaType.APPLICATION_JSON));
    resultActions
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    // debug the result
    // ResultActionsUtil.log(resultActions);
  }