Java Code Examples for org.springframework.mock.web.MockHttpServletRequest#addParameter()

The following examples show how to use org.springframework.mock.web.MockHttpServletRequest#addParameter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticationViaFormActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
    public void testSuccessfulAuthenticationWithServiceAndWarn()
        throws Exception {
        final MockHttpServletRequest request = new MockHttpServletRequest();
        final MockHttpServletResponse response = new MockHttpServletResponse();
        final MockRequestContext context = new MockRequestContext();

        request.addParameter("username", "test");
        request.addParameter("password", "test");
        request.addParameter("warn", "true");
        request.addParameter("service", "test");

        context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, response));
        context.getRequestScope().put("credentials",
            TestUtils.getCredentialsWithSameUsernameAndPassword());
 //       this.action.bind(context);
 //       assertEquals("success", this.action.submit(context).getId());
//        assertNotNull(response.getCookie(this.warnCookieGenerator
//            .getCookieName()));
    }
 
Example 2
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@Test
public void testGetMethod_badRequest_corruptParams() throws Exception {
	EasyMock.expect(mockService.testMethod("Whirinaki")).andReturn("Forest");
	EasyMock.replay(mockService);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-get");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.addParameter("id", Integer.toString(123));
	request.addParameter("method", "testMethod");
	request.addParameter("params", "{BROKEN}");

	jsonRpcServer.handle(request, response);

	assertTrue(MockHttpServletResponse.SC_BAD_REQUEST == response.getStatus());

	JsonNode errorNode = error(toByteArrayOutputStream(response.getContentAsByteArray()));

	assertNotNull(errorNode);
	assertEquals(errorCode(errorNode).asLong(), (long) ErrorResolver.JsonError.PARSE_ERROR.code);
}
 
Example 3
Source File: StylesJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test of doCreateStyle method, of fr.paris.lutece.portal.web.style.StylesJspBean.
 * 
 * @throws AccessDeniedException
 */
public void testDoCreateStyle( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    int nId = StyleHome.getStylesList( ).stream( ).map( Style::getId ).max( Integer::compare ).get( ) + 1;
    request.addParameter( Parameters.STYLE_ID, Integer.toString( nId ) );
    String name = getRandomName( );
    request.addParameter( Parameters.STYLE_NAME, name );
    String portalComponantId = "1";
    request.addParameter( Parameters.PORTAL_COMPONENT, portalComponantId );
    request.addParameter( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, "admin/style/create_style.html" ) );
    try
    {
        instance.doCreateStyle( request );
        AdminMessage message = AdminMessageService.getMessage( request );
        assertNull( message );
        Style stored = StyleHome.findByPrimaryKey( nId );
        assertNotNull( stored );
        assertEquals( nId, stored.getId( ) );
    }
    finally
    {
        StyleHome.remove( nId );
    }
}
 
Example 4
Source File: CrnkServletRejectJsonTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Option to reject plain JSON GET requests is enabled explicitly.
 */
@Test
public void testRejectPlainJson() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo("/tasks");
    request.setRequestURI("/api/tasks");
    request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
    request.addHeader("Accept", "application/json");
    request.addParameter("filter[Task][name]", "John");
    request.setQueryString(URLEncoder.encode("filter[Task][name]", StandardCharsets.UTF_8.name()) + "=John");

    MockHttpServletResponse response = new MockHttpServletResponse();

    servlet.service(request, response);

    assertEquals(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, response.getStatus());
    String responseContent = response.getContentAsString();
    assertTrue(responseContent == null || "".equals(responseContent.trim()));
}
 
Example 5
Source File: TestAddCobar.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
public void testAddCobar() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    MockHttpSession session = new MockHttpSession();
    UserDO user = new UserDO();
    user.setStatus(ConstantDefine.NORMAL);
    user.setUser_role(ConstantDefine.CLUSTER_ADMIN);
    session.setAttribute("user", user);
    request.setSession(session);
    request.addParameter("clusterId", "1");
    request.addParameter("host", "1.2.4.3");
    request.addParameter("cobarName", "test");
    request.addParameter("port", "8066");
    request.addParameter("userName", "test");
    request.addParameter("password", "TTT");
    request.addParameter("status", "ACTIVE");

    ModelAndView mav = addcobar.handleRequest(request, new MockHttpServletResponse());
    Assert.assertEquals("add cobar success", String.valueOf(mav.getModel().get("info")));
}
 
Example 6
Source File: ServiceValidateControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidServiceTicket() throws Exception {
    final String tId = getCentralAuthenticationService()
            .createTicketGrantingTicket(TestUtils.getCredentialsWithSameUsernameAndPassword());
    final String sId = getCentralAuthenticationService().grantServiceTicket(tId, TestUtils.getService());

    getCentralAuthenticationService().destroyTicketGrantingTicket(tId);

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", TestUtils.getService().getId());
    request.addParameter("ticket", sId);

    assertEquals(ServiceValidateController.DEFAULT_SERVICE_FAILURE_VIEW_NAME,
            this.serviceValidateController.handleRequestInternal(request,
                    new MockHttpServletResponse()).getViewName());
}
 
Example 7
Source File: ServiceValidateControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidServiceTicketWithInvalidPgt() throws Exception {
    this.serviceValidateController.setProxyHandler(new Cas10ProxyHandler());
    final String tId = getCentralAuthenticationService()
            .createTicketGrantingTicket(TestUtils.getCredentialsWithSameUsernameAndPassword());
    final String sId = getCentralAuthenticationService().grantServiceTicket(tId, TestUtils.getService());

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", TestUtils.getService().getId());
    request.addParameter("ticket", sId);
    request.addParameter("pgtUrl", "duh");

    final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse());
    assertEquals(ServiceValidateController.DEFAULT_SERVICE_SUCCESS_VIEW_NAME, modelAndView.getViewName());
    assertNull(modelAndView.getModel().get("pgtIou"));
}
 
Example 8
Source File: PageListControllerTest.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * The mockWebResourceDataService contains only 2 WebResource. One has 
 * Id=1 and is a Page instance, the second has Id=2 and is a Site instance.
 * If a webresource with an id different from 1 or 2 is requested, the
 * ForbiddenPageException is caught
 * 
 * @throws Exception 
 */
public void testDisplayPageListWithUnknownAuditId() throws Exception {
    System.out.println("testDisplayPageListWithUnknownAuditId");
    
    setUpMockAuditDataService(UNKNOWN_AUDIT_ID);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(TgolKeyStore.AUDIT_ID_KEY, String.valueOf(UNKNOWN_AUDIT_ID));
    try {
        instance.displayPageList(
                request, 
                new MockHttpServletResponse(), 
                new ExtendedModelMap());
        assertTrue(false);
    } catch (ForbiddenPageException fbe) {
        // The auditDataService catch the NoResultException and return null.
        // Then if the audit is null, a ForbiddenPageException is caught
        assertTrue(true);
    }
}
 
Example 9
Source File: AdminPageJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testDoRemovePageInvalidToken( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( Parameters.PAGE_ID, Integer.toString( _page.getId( ) ) );
    request.addParameter( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/site/DoRemovePage.jsp" )
            + "b" );
    try
    {
        _bean.doRemovePage( request );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertTrue( PageHome.checkPageExist( _page.getId( ) ) );
    }
}
 
Example 10
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@Test
public void testGetMethod_badRequest_noMethod() throws Exception {
	EasyMock.expect(mockService.testMethod("Whirinaki")).andReturn("Forest");
	EasyMock.replay(mockService);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-get");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.addParameter("id", Integer.toString(123));
	// no method!
	request.addParameter("params", net.iharder.Base64.encodeBytes("[\"Whirinaki\"]".getBytes(StandardCharsets.UTF_8)));

	jsonRpcServer.handle(request, response);

	assertTrue(MockHttpServletResponse.SC_NOT_FOUND == response.getStatus());

	JsonNode errorNode = error(toByteArrayOutputStream(response.getContentAsByteArray()));

	assertNotNull(errorNode);
	assertEquals(errorCode(errorNode).asLong(), (long) ErrorResolver.JsonError.METHOD_NOT_FOUND.code);
}
 
Example 11
Source File: PluginJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoInstallPluginNoToken( ) throws AccessDeniedException
{
    assertFalse( PluginService.isPluginEnable( PLUGIN_NAME ) );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( "plugin_name", PLUGIN_NAME );
    try
    {
        instance.doInstallPlugin( request, request.getServletContext( ) );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertFalse( PluginService.isPluginEnable( PLUGIN_NAME ) );
    }
}
 
Example 12
Source File: InsertServiceSelectorJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test of getServicesListPage method, of class
 * fr.paris.lutece.portal.web.insertservice.InsertServiceSelectorJspBean.
 */
public void testGetServicesListPage( )
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( "input", "text" );
    request.addParameter( "selected_text", "selected_text" );

    InsertServiceSelectorJspBean instance = new InsertServiceSelectorJspBean( );

    assertTrue( StringUtils.isNotEmpty( instance.getServicesListPage( request ) ) );
}
 
Example 13
Source File: PluginJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoUninstallPlugin( ) throws AccessDeniedException
{
    PluginService.getPlugin( PLUGIN_NAME ).install( );
    assertTrue( PluginService.isPluginEnable( PLUGIN_NAME ) );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( "plugin_name", PLUGIN_NAME );
    request.addParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/system/DoUninstallPlugin.jsp" ) );
    instance.doUninstallPlugin( request, request.getServletContext( ) );
    assertFalse( PluginService.isPluginEnable( PLUGIN_NAME ) );
}
 
Example 14
Source File: AdminPagePortletJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test when no parameter given
 * 
 * @throws AccessDeniedException
 *             should not happen
 */
public void testDoModifyPortletStatusNoParam( ) throws AccessDeniedException
{
    AdminPagePortletJspBean bean = new AdminPagePortletJspBean( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/site/DoModifyPortletStatus.jsp" ) );
    String url = bean.doModifyPortletStatus( request );
    assertNotNull( url );
    AdminMessage message = AdminMessageService.getMessage( request );
    assertNotNull( message );
    assertEquals( message.getType( ), AdminMessage.TYPE_ERROR );
}
 
Example 15
Source File: AdminPageJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testGetAdminPageBlockChildPage( ) throws PasswordResetException, AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    Utils.registerAdminUserWithRigth( request, _adminUser, AdminPageJspBean.RIGHT_MANAGE_ADMIN_SITE );
    _bean.init( request, AdminPageJspBean.RIGHT_MANAGE_ADMIN_SITE );
    request.addParameter( "param_block", "5" );
    String html = _bean.getAdminPage( request );
    assertNotNull( html );
}
 
Example 16
Source File: AuthenticationViaFormActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
    public void testSuccessfulAuthenticationWithNoService() throws Exception {
        final MockHttpServletRequest request = new MockHttpServletRequest();
        final MockRequestContext context = new MockRequestContext();

        request.addParameter("username", "test");
        request.addParameter("password", "test");

        context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
        context.getRequestScope().put("credentials",
            TestUtils.getCredentialsWithSameUsernameAndPassword());
//        this.action.bind(context);
//        assertEquals("success", this.action.submit(context).getId());
    }
 
Example 17
Source File: AdminLoginJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoForgotPasswordDoesNotExist( ) throws Exception
{
    AdminLoginJspBean bean = new AdminLoginJspBean( );

    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( Parameters.ACCESS_CODE, "DOES_NOT_EXIST" );
    String url = bean.doForgotPassword( request );
    assertEquals( "AdminFormContact.jsp", url );
}
 
Example 18
Source File: TargetSeedsHandlerTest.java    From webcurator with Apache License 2.0 4 votes vote down vote up
@Test
public final void testProcessOtherRemoveSelected() {
	MockHttpServletRequest aReq = new MockHttpServletRequest();
	MockTargetManager targetManager = new MockTargetManager(testFile);
	
	testInstance.setTargetManager(targetManager);
	testSetBusinessObjectFactory();
	testSetValidator();
	testSetAuthorityManager();
	testSetMessageSource();
	
	Target target = targetManager.load(4000L);
	TargetEditorContext targetEditorContext = new TargetEditorContext(targetManager,target,true);
	aReq.getSession().setAttribute(TabbedTargetController.EDITOR_CONTEXT, targetEditorContext);

	HttpServletResponse aResp = new MockHttpServletResponse(); 
	SeedsCommand aCmd = new SeedsCommand();
	TabbedController tc = new TabbedTargetController();

	TabConfig tabConfig = new TabConfig();
	tabConfig.setViewName("target");
	List<Tab> tabs = getTabList(targetManager);
	tabConfig.setTabs(tabs);

	tc.setTabConfig(tabConfig);
	tc.setDefaultCommandClass(org.webcurator.ui.target.command.TargetDefaultCommand.class);
	
	Tab currentTab = tabs.get(1);
	BindException aErrors = new BindException(aCmd, "SeedsCommand");
	
	assertEquals(3, target.getSeeds().size());

	aReq.addParameter("chkSelect6000", "on");
	aReq.addParameter("chkSelect6002", "on");
	aCmd.setActionCmd(SeedsCommand.ACTION_REMOVE_SELECTED);

	ModelAndView mav = testInstance.processOther(tc, currentTab, aReq, aResp, aCmd, aErrors);
	assertNotNull(mav);
	List<Seed> seeds = (List<Seed>)mav.getModel().get("seeds");
	assertEquals(1, seeds.size());
	String jsp = ((TabStatus)mav.getModel().get("tabStatus")).getCurrentTab().getJsp();
	assertEquals("../target-seeds.jsp", jsp);
	assertEquals(1, target.getSeeds().size());
}
 
Example 19
Source File: MockHttpClient.java    From karate with MIT License 4 votes vote down vote up
@Override
protected HttpResponse makeHttpRequest(HttpBody entity, ScenarioContext context) {
    logger.info("making mock http client request: {} - {}", request.getMethod(), getRequestUri());
    MockHttpServletRequest req = requestBuilder.buildRequest(getServletContext());
    byte[] bytes;
    if (entity != null) {
        bytes = entity.getBytes();
        req.setContentType(entity.getContentType());
        if (entity.isMultiPart()) {
            for (MultiPartItem item : entity.getParts()) {
                MockMultiPart part = new MockMultiPart(item);
                req.addPart(part);
                if (!part.isFile()) {
                    req.addParameter(part.getName(), part.getValue());
                }
            }
        } else if (entity.isUrlEncoded()) {
            req.addParameters(entity.getParameters());
        } else {
            req.setContent(bytes);
        }
    } else {
        bytes = null;
    }
    MockHttpServletResponse res = new MockHttpServletResponse();
    logRequest(req, bytes);
    long startTime = System.currentTimeMillis();
    try {
        getServlet(request).service(req, res);
    } catch (Exception e) {
        String message = e.getMessage();
        if (message == null && e.getCause() != null) {
            message = e.getCause().getMessage();
        }
        logger.error("mock servlet request failed: {}", message);
        throw new RuntimeException(e);
    }
    HttpResponse response = new HttpResponse(startTime, System.currentTimeMillis());
    bytes = res.getContentAsByteArray();
    logResponse(res, bytes);
    response.setUri(getRequestUri());
    response.setBody(bytes);
    response.setStatus(res.getStatus());
    for (Cookie c : res.getCookies()) {
        com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue());
        cookie.put(DOMAIN, c.getDomain());
        cookie.put(PATH, c.getPath());
        cookie.put(SECURE, c.getSecure() + "");
        cookie.put(MAX_AGE, c.getMaxAge() + "");
        cookie.put(VERSION, c.getVersion() + "");
        response.addCookie(cookie);
    }
    for (String headerName : res.getHeaderNames()) {
        response.putHeader(headerName, res.getHeaders(headerName));
    }
    return response;
}
 
Example 20
Source File: EhCacheTicketRegistryTests.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
public static Service getService() {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", "test");
    return SimpleWebApplicationServiceImpl.createServiceFrom(request);
}