Example usage for org.springframework.mock.web MockHttpServletResponse getStatus

List of usage examples for org.springframework.mock.web MockHttpServletResponse getStatus

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletResponse getStatus.

Prototype

@Override
    public int getStatus() 

Source Link

Usage

From source file:com.liferay.trash.service.webserver.test.WebServerTrashTest.java

@Test
public void testRequestFileInTrash() throws Exception {
    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId(),
            TestPropsValues.getUserId());

    FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(TestPropsValues.getUserId(), group.getGroupId(),
            parentFolder.getFolderId(), "Test Trash.txt", ContentTypes.TEXT_PLAIN,
            RandomTestUtil.randomBytes(TikaSafeRandomizerBumper.INSTANCE), serviceContext);

    MockHttpServletResponse mockHttpServletResponse = testRequestFile(fileEntry, _user, false);

    Assert.assertEquals(MockHttpServletResponse.SC_OK, mockHttpServletResponse.getStatus());

    DLTrashServiceUtil.moveFileEntryToTrash(fileEntry.getFileEntryId());

    mockHttpServletResponse = testRequestFile(fileEntry, _user, false);

    Assert.assertEquals(MockHttpServletResponse.SC_NOT_FOUND, mockHttpServletResponse.getStatus());

    mockHttpServletResponse = testRequestFile(fileEntry, _user, true);

    Assert.assertEquals(MockHttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus());

    RoleLocalServiceUtil.addUserRoles(_user.getUserId(), new long[] { _role.getRoleId() });

    mockHttpServletResponse = testRequestFile(fileEntry, _user, true);

    Assert.assertEquals(MockHttpServletResponse.SC_OK, mockHttpServletResponse.getStatus());
}

From source file:com.google.api.server.spi.handlers.ExplorerHandlerTest.java

private void testHandle(String scheme, int port, String expectedLocation) throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme(scheme);/*from  www .  jav a 2  s  . c  om*/
    request.setServerName("localhost");
    request.setServerPort(port);
    request.setRequestURI("/_ah/api/explorer/");
    MockHttpServletResponse response = new MockHttpServletResponse();
    ExplorerHandler handler = new ExplorerHandler();
    EndpointsContext context = new EndpointsContext("GET", "explorer", request, response);
    handler.handle(context);

    assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FOUND);
    assertThat(response.getHeader("Location")).isEqualTo(expectedLocation);
}

From source file:org.craftercms.security.authentication.impl.LoginFailureHandlerImplTest.java

@Test
public void testSendError() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);

    handler.handle(context, new AuthenticationException());

    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertTrue(response.isCommitted());/*from w w  w  . j av a  2 s.  c  o  m*/
}

From source file:org.craftercms.security.authentication.impl.RestAuthenticationRequiredHandlerTest.java

@Test
public void testHandle() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/profile.json");
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);

    handler.handle(context, new AuthenticationRequiredException(ERROR_MESSAGE));

    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals(EXPECTED_RESPONSE_CONTENT, response.getContentAsString());
}

From source file:it.geosolutions.httpproxy.service.BaseProxyServiceTest.java

/**
 * Test IProxyService execute as HTTP GET
 *///from  w w  w .jav a2  s.  c o  m
public void executeGet() {
    try {
        // Generate mocked request and response
        MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "/proxy/");
        mockRequest.addParameter("url", testUrl);
        MockHttpServletResponse mockResponse = new MockHttpServletResponse();

        // Call proxy execute
        proxy.execute(mockRequest, mockResponse);

        // Assert the response
        assertNotNull(mockResponse);
        assertEquals(mockResponse.getStatus(), HttpStatus.SC_OK);
        assertNotNull(mockResponse.getOutputStream());
        assertNotNull(mockResponse.getContentType());
        assertTrue(mockResponse.getContentType().contains("text/xml"));

        LOGGER.info("Success proxy GET in '" + testUrl + "'");
        LOGGER.info("************************ Response ************************");
        LOGGER.info(mockResponse.getContentAsString());
        LOGGER.info("********************** EoF Response **********************");

    } catch (Exception e) {
        fail("Exception executing proxy");
    }
}

From source file:it.geosolutions.httpproxy.service.ProxyServiceDefaultTest.java

/**
 * Test IProxyService execute as HTTP GET
 *///from  www . ja  va 2 s .  co  m
@Test
public void testExecuteGet() {
    try {
        // Generate mocked request and response
        MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "/proxy/");
        mockRequest.addParameter("url", TEST_URL);
        MockHttpServletResponse mockResponse = new MockHttpServletResponse();

        // Call proxy execute
        proxy.execute(mockRequest, mockResponse);

        // Assert the response
        assertNotNull(mockResponse);
        assertEquals(mockResponse.getStatus(), HttpStatus.SC_OK);
        assertNotNull(mockResponse.getOutputStream());
        assertNotNull(mockResponse.getContentType());
        assertTrue(mockResponse.getContentType().contains("application/vnd.ogc.wms_xml"));

        LOGGER.info("Success proxy GET in '" + TEST_URL + "'");
        LOGGER.info("************************ Response ************************");
        LOGGER.info(mockResponse.getContentAsString());
        LOGGER.info("********************** EoF Response **********************");

    } catch (Exception e) {
        fail("Exception executing proxy-->\t" + e.getLocalizedMessage());
    }
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_8.ChangePasswordController1_8Test.java

@Test
public void testUserChangeOtherUsersPassword() throws Exception {
    User authenticatedUser = setUpUser("daemon");

    Role role = new Role("Privileged Role");
    role.addPrivilege(new Privilege(PrivilegeConstants.EDIT_USER_PASSWORDS));
    authenticatedUser.addRole(role);//w w w  . ja  v a 2  s.c o  m

    String newPassword = "newPassword9";

    MockHttpServletResponse response = handle(newPostRequest(
            PASSWORD_URI + "/" + RestTestConstants1_8.USER_UUID, "{\"password\":\"" + newPassword + "\"}"));

    assertEquals(200, response.getStatus());
}

From source file:at.molindo.notify.servlet.NotifyFilterTest.java

@Test
public void pull() throws Exception {
    new MockTest() {

        NotifyFilterBean filter;//w w  w . j  av a  2  s.  co m
        FilterChain mockFilterChain;
        MockFilterConfig config;

        @Override
        @SuppressWarnings(value = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS", justification = "mocks accept null")
        protected void setup(EasyMockContext context) throws Exception {
            filter = new NotifyFilterBean();
            mockFilterChain = new MockFilterChain();
            config = new MockFilterConfig();
            config.addInitParameter(NotifyFilterBean.PARAMTER_BASE_URL, "http://www.example.com/");

            context.create(IPullChannel.class);

            expect(context.get(IPullChannel.class).getId()).andReturn(CHANNELID).anyTimes();
            expect(context.get(IPullChannel.class).getNotificationTypes()).andReturn(Type.TYPES_ALL).anyTimes();
            expect(context.get(IPullChannel.class).pull(eq(USERID),
                    anyObject(ConfigurableChannelPreferences.class))).andReturn(BODY);
            expect(context.get(IPullChannel.class).newDefaultPreferences())
                    .andReturn(new ConfigurableChannelPreferences());

            eq(USERID);
            reportMatcher(new IArgumentMatcher() {

                @Override
                public boolean matches(Object argument) {
                    ConfigurableChannelPreferences cPrefs = (ConfigurableChannelPreferences) argument;
                    return SECRET.equals(cPrefs.getParams().get(AbstractPullChannel.SECRET));
                }

                @Override
                public void appendTo(StringBuffer buffer) {
                    buffer.append("secret not included");
                }
            });
            expect(context.get(IPullChannel.class).isAuthorized(null, null)).andReturn(true);

            expect(context.get(IPullChannel.class).isConfigured(anyObject(Params.class))).andReturn(true);

            // toPullPath
            expect(context.get(IPullChannel.class).newDefaultPreferences())
                    .andReturn(new PushChannelPreferences());
        }

        @Override
        protected void test(EasyMockContext context) throws Exception {
            filter.setChannels(CollectionUtils.set(context.get(IPullChannel.class)));
            filter.init(config);

            MockHttpServletRequest request = new MockHttpServletRequest("GET",
                    "/notify/" + NotifyFilterBean.DEFAULT_PULL_PREFIX + "/" + CHANNELID + "/" + USERID);

            request.setServletPath("/notify");
            request.setParameter(AbstractPullChannel.SECRET.getName(), SECRET);

            MockHttpServletResponse response = new MockHttpServletResponse();

            filter.doFilter(request, response, mockFilterChain);

            assertEquals(200, response.getStatus());
            assertEquals(BODY, response.getContentAsString());

            Confirmation confirmation = new Confirmation(new Notification());
            assertEquals("http://www.example.com/notify/confirm/" + confirmation.getKey(),
                    filter.toConfirmPath(confirmation));

            assertEquals("http://www.example.com/notify/pull/test-channel/test-user",
                    filter.toPullPath(CHANNELID, USERID, new Params()));
        }

    }.run();
}

From source file:ch.ralscha.extdirectspring.util.ExtDirectSpringUtilTest.java

@Test
public void testHandleCacheableResponseWithIfNoneMatch() throws IOException {
    byte[] data = "the response data".getBytes();
    String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + '"';
    String contentType = "application/javascript;charset=UTF-8";

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader("If-None-Match", etag);
    MockHttpServletResponse response = new MockHttpServletResponse();

    ExtDirectSpringUtil.handleCacheableResponse(request, response, data, contentType);
    assertThat(response.getStatus()).isEqualTo(304);

    request = new MockHttpServletRequest();
    request.addHeader("If-None-Match", etag);
    response = new MockHttpServletResponse();
    data = "new response data".getBytes();
    etag = "\"0" + DigestUtils.md5DigestAsHex(data) + '"';
    ExtDirectSpringUtil.handleCacheableResponse(request, response, data, contentType);
    assertThat(response.getStatus()).isEqualTo(200);
    assertResponse(response, 5, etag, 6);
    assertThat(response.getContentLength()).isEqualTo(data.length);
    assertThat(response.getContentType()).isEqualTo(contentType);
    assertThat(response.getContentAsByteArray()).isEqualTo(data);
}

From source file:com.liferay.document.library.webserver.test.WebServerRangeTest.java

protected MockHttpServletResponse testRange(String rangeHeader) throws Exception {

    String fileName = "Test Range.txt";

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId(),
            TestPropsValues.getUserId());

    FileEntry fileEntry = _dlAppLocalService.addFileEntry(TestPropsValues.getUserId(), group.getGroupId(),
            parentFolder.getFolderId(), fileName, ContentTypes.TEXT_PLAIN, _SAMPLE_DATA.getBytes(),
            serviceContext);//from   w w  w. jav a2  s  . c o  m

    String path = fileEntry.getGroupId() + "/" + fileEntry.getFolderId() + "/" + fileEntry.getTitle();

    Map<String, String> headers = new HashMap<>();

    if (Validator.isNotNull(rangeHeader)) {
        headers.put(HttpHeaders.RANGE, rangeHeader);
    }

    MockHttpServletResponse mockHttpServletResponse = service(Method.GET, path, headers, null, null, null);

    int status = mockHttpServletResponse.getStatus();

    Assert.assertTrue(mockHttpServletResponse.containsHeader(HttpHeaders.ACCEPT_RANGES));

    if (Validator.isNotNull(rangeHeader)) {
        Assert.assertEquals(HttpServletResponse.SC_PARTIAL_CONTENT, status);
    } else {
        Assert.assertEquals(HttpServletResponse.SC_OK, status);
    }

    String contentType = mockHttpServletResponse.getContentType();

    if (Validator.isNotNull(rangeHeader) && rangeHeader.contains(StringPool.COMMA)) {

        Assert.assertTrue(contentType.startsWith("multipart/byteranges"));
    } else {
        Assert.assertEquals(ContentTypes.TEXT_PLAIN, contentType);
    }

    return mockHttpServletResponse;
}