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

The following examples show how to use org.springframework.mock.web.MockHttpServletRequest#setMethod() . 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: SpringWebMvc_5_x_IT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequest() throws Exception {
    MockServletConfig config = new MockServletConfig();
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    config.addInitParameter("contextConfigLocation", "classpath:spring-web-test.xml");
    req.setMethod("GET");
    req.setRequestURI("/");
    req.setRemoteAddr("1.2.3.4");
    
    DispatcherServlet servlet = new DispatcherServlet();
    servlet.init(config);
    
    servlet.service(req, res);
    
    Method method = FrameworkServlet.class.getDeclaredMethod("doGet", HttpServletRequest.class, HttpServletResponse.class);
    
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    
    verifier.verifyTrace(Expectations.event(SPRING_MVC, method));
    verifier.verifyTraceCount(0);
}
 
Example 2
Source File: ServletRequestContextTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testRootPath() {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("");
	request.setPathInfo("");
	request.setRequestURI("");
	request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
	request.addHeader("Accept", "*/*");
	request.setServerName("test");
	request.setServerPort(1234);

	ServletRequestContext context = new ServletRequestContext(servletContext, request, servletResponse, null);

	Assert.assertEquals("/", context.getPath());
	Assert.assertEquals("http://test:1234", context.getBaseUrl());
}
 
Example 3
Source File: CrnkServletTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnacceptableRequestContentType() 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/xml");
    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 4
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testKatharsisIncludeWithNullIterableRelationshipCall() throws Exception {
	Node root = new Node(1L, null, null);
	// by making the setting children null and requesting them in the include statement should cause a serialization error
	Node child1 = new Node(2L, root, null);
	Node child2 = new Node(3L, root, null);
	root.setChildren(new LinkedHashSet<>(Arrays.asList(child1, child2)));
	nodeRepository.save(root);
	nodeRepository.save(child1);
	nodeRepository.save(child2);
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setServletPath("/api");
	request.setPathInfo("/nodes");
	request.setRequestURI("/api/nodes");
	request.setQueryString("include[nodes]=children");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	Map<String, String> params = new HashMap<>();
	params.put("include[nodes]", "children");
	request.setParameters(params);
	request.addHeader("Accept", "*/*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	katharsisServlet.service(request, response);
	assertEquals(500, response.getStatus());
}
 
Example 5
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void onSimpleResourceGetShouldReturnOneResource() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks/1");
	request.setRequestURI("/api/tasks/1");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "*/*");

	MockHttpServletResponse response = new MockHttpServletResponse();

	katharsisServlet.service(request, response);

	String responseContent = response.getContentAsString();

	log.debug("responseContent: {}", responseContent);
	assertNotNull(responseContent);

	assertJsonPartEquals("tasks", responseContent, "data.type");
	assertJsonPartEquals("\"1\"", responseContent, "data.id");
	assertJsonPartEquals(SOME_TASK_ATTRIBUTES, responseContent, "data.attributes");
	assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links");
	assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links");
}
 
Example 6
Source File: KatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testKatharsisMatchingException() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks-matching-exception");
	request.setRequestURI("/api/matching-exception");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "*/*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	katharsisServlet.service(request, response);

	String responseContent = response.getContentAsString();
	assertTrue("Response should not be returned for non matching resource type", StringUtils.isBlank(responseContent));
	assertEquals(404, response.getStatus());

}
 
Example 7
Source File: RegisteredServiceSimpleFormControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testEditRegisteredServiceWithValues() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();

    final RegisteredServiceImpl r = new RegisteredServiceImpl();
    r.setId(1000);
    r.setName("Test Service");
    r.setServiceId("test");
    r.setDescription("description");

    this.manager.save(r);

    request.addParameter("description", "description");
    request.addParameter("serviceId", "serviceId1");
    request.addParameter("name", "name");
    request.addParameter("theme", "theme");
    request.addParameter("allowedToProxy", "true");
    request.addParameter("enabled", "true");
    request.addParameter("ssoEnabled", "true");
    request.addParameter("anonymousAccess", "false");
    request.addParameter("evaluationOrder", "2");
    request.addParameter("id", "1000");

    request.setMethod("POST");

    this.controller.handleRequest(
            request, response);

    assertFalse(this.manager.getAllServices().isEmpty());
    final RegisteredService r2 = this.manager.findServiceBy(1000);

    assertEquals("serviceId1", r2.getServiceId());
}
 
Example 8
Source File: HttpMethodTest.java    From tus-java-server with MIT License 5 votes vote down vote up
@Test
public void getMethodNotSupported() throws Exception {
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("put");

    assertEquals(null,
            HttpMethod.getMethodIfSupported(servletRequest, EnumSet.noneOf(HttpMethod.class)));
}
 
Example 9
Source File: CrnkFilterTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void onSimpleResourceGetShouldReturnOneResource() throws Exception {
    MockFilterChain filterChain = new MockFilterChain();

    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo(null);
    request.setRequestURI("/api/tasks/1");
    request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
    request.addHeader("Accept", "*/*");

    MockHttpServletResponse response = new MockHttpServletResponse();

    filter.doFilter(request, response, filterChain);

    String responseContent = response.getContentAsString();

    log.debug("responseContent: {}", responseContent);
    assertNotNull(responseContent);

    assertJsonPartEquals("tasks", responseContent, "data.type");
    assertJsonPartEquals("\"1\"", responseContent, "data.id");
    assertJsonPartEquals(FIRST_TASK_ATTRIBUTES, responseContent, "data.attributes");
    assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links");
    assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links");
}
 
Example 10
Source File: AdminLoginJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoResetPasswordChangedPassword( )
{
    AdminLoginJspBean bean = new AdminLoginJspBean( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setMethod( "POST" );
    request.setParameter( Parameters.USER_ID, Integer.toString( user.getUserId( ) ) );
    Date timestamp = new Date( );
    String token = AdminUserService.getUserPasswordResetToken( user, timestamp, request );
    request.setParameter( "ts", Long.toString( timestamp.getTime( ) ) );
    request.setParameter( "token", token );
    request.setParameter( Parameters.NEW_PASSWORD, NEW_PASSWORD );
    request.setParameter( Parameters.CONFIRM_NEW_PASSWORD, NEW_PASSWORD );

    IPasswordFactory passwordFactory = SpringContextService.getBean( IPasswordFactory.BEAN_NAME );
    final String changedPassword = PASSWORD + "_changed";
    assertFalse( PASSWORD.equals( changedPassword ) );
    assertFalse( NEW_PASSWORD.equals( changedPassword ) );
    user.setPassword( passwordFactory.getPasswordFromCleartext( changedPassword ) );
    getAdminUserDAO( ).store( user, PasswordUpdateMode.UPDATE );

    String res = bean.doResetPassword( request );
    assertNotNull( res );
    AdminMessage message = AdminMessageService.getMessage( request );
    assertNotNull( message );
    assertEquals( AdminMessage.TYPE_STOP, message.getType( ) );
    LuteceDefaultAdminUser storedUser = getAdminUserDAO( ).loadDefaultAdminUser( user.getUserId( ) );
    assertNotNull( storedUser );
    assertTrue( storedUser.getPassword( ).check( changedPassword ) );
}
 
Example 11
Source File: DomainValidateFilterTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
private MockHttpServletRequest getMockedRequest(String host) throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/api/meta/getactivekeeper/cluster1/shard1");
    request.setMethod("GET");
    request.addHeader("host", host);

    return request;

}
 
Example 12
Source File: CrnkFilterTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void onCollectionRequestWithParamsGetShouldReturnCollection() throws Exception {
    MockFilterChain filterChain = new MockFilterChain();

    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo(null);
    request.setRequestURI("/api/tasks");
    request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
    request.addHeader("Accept", "*/*");
    request.addParameter("filter[name]", "First task");
    request.setQueryString(URLEncoder.encode("filter[name]", StandardCharsets.UTF_8.name()) + "=First task");

    MockHttpServletResponse response = new MockHttpServletResponse();

    filter.doFilter(request, response, filterChain);

    String responseContent = response.getContentAsString();

    log.debug("responseContent: {}", responseContent);
    assertNotNull(responseContent);

    assertJsonPartEquals("tasks", responseContent, "data[0].type");
    assertJsonPartEquals("\"1\"", responseContent, "data[0].id");
    assertJsonPartEquals(FIRST_TASK_ATTRIBUTES, responseContent, "data[0].attributes");
    assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data[0].links");
    assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data[0].relationships.project.links");
}
 
Example 13
Source File: UifViewBeanWrapperTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    TestForm model = new TestForm();
    model.setMethodToCall("field7TestMethodToCall");

    UifBeanPropertyBindingResult bindingResult = new UifBeanPropertyBindingResult(model, "model", true, 100);

    beanWrapper = new UifViewBeanWrapper(model, bindingResult);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.addParameter(UifConstants.CONTROLLER_METHOD_DISPATCH_PARAMETER_NAME, "field7TestMethodToCall");

    RequestContextHolder.setRequestAttributes(new ServletWebRequest(request));
}
 
Example 14
Source File: AdminLoginJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void doResetPasswordTest( )
{
    AdminLoginJspBean bean = new AdminLoginJspBean( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setMethod( "POST" );
    request.setParameter( Parameters.USER_ID, Integer.toString( user.getUserId( ) ) );
    Date timestamp = new Date( );
    String token = AdminUserService.getUserPasswordResetToken( user, timestamp, request );
    request.setParameter( "ts", Long.toString( timestamp.getTime( ) ) );
    request.setParameter( "token", token );
    request.setParameter( Parameters.NEW_PASSWORD, NEW_PASSWORD );
    request.setParameter( Parameters.CONFIRM_NEW_PASSWORD, NEW_PASSWORD );

    String res = bean.doResetPassword( request );
    assertNotNull( res );
    AdminMessage message = AdminMessageService.getMessage( request );
    assertNotNull( message );
    assertEquals( AdminMessage.TYPE_INFO, message.getType( ) );
    LuteceDefaultAdminUser storedUser = getAdminUserDAO( ).loadDefaultAdminUser( user.getUserId( ) );
    assertNotNull( storedUser );
    assertFalse( storedUser.getPassword( ).check( PASSWORD ) );
    assertTrue( storedUser.getPassword( ).check( NEW_PASSWORD ) );
    List<IPassword> passwordHistory = AdminUserHome.selectUserPasswordHistory( user.getUserId( ) );
    boolean found = false;
    for ( IPassword password : passwordHistory )
    {
        if ( password.check( NEW_PASSWORD ) )
        {
            found = true;
            break;
        }
    }
    assertTrue( found );
}
 
Example 15
Source File: QueryFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCallAuthenticationManagerAuthenticate() {
    httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod(HttpMethod.GET.name());
    httpServletResponse = new MockHttpServletResponse();
    queryFilter.setAuthenticationManager(authenticationManager);
    when(authenticationService.getJwtTokenFromRequest(any())).thenReturn(
        Optional.of(VALID_TOKEN)
    );

    queryFilter.attemptAuthentication(httpServletRequest, httpServletResponse);

    verify(authenticationManager).authenticate(any());
}
 
Example 16
Source File: KatharsisServletTest.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testKatharsisIncludeNestedWithDefault() throws Exception {
	Node root = new Node(1L, null, null);
	Locale engLocale = new Locale(1L, java.util.Locale.ENGLISH);
	Node child1 = new Node(2L, root, Collections.<Node>emptySet());
	NodeComment child1Comment = new NodeComment(1L, "Child 1", child1, engLocale);
	child1.setNodeComments(new LinkedHashSet<>(Collections.singleton(child1Comment)));
	Node child2 = new Node(3L, root, Collections.<Node>emptySet(), Collections.<NodeComment>emptySet());
	root.setChildren(new LinkedHashSet<>(Arrays.asList(child1, child2)));
	nodeRepository.save(root);
	nodeRepository.save(child1);
	nodeRepository.save(child2);

	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setServletPath("/api");
	request.setPathInfo("/nodes/1");
	request.setRequestURI("/api/nodes/1");
	request.setQueryString("include[nodes]=children.nodeComments");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	Map<String, String> params = new HashMap<>();
	params.put("include[nodes]", "children.nodeComments.langLocale");
	request.setParameters(params);
	request.addHeader("Accept", "*/*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	katharsisServlet.service(request, response);
	String responseContent = response.getContentAsString();
	assertTopLevelNodesCorrectWithChildren(responseContent);
}
 
Example 17
Source File: HttpMethodTest.java    From tus-java-server with MIT License 5 votes vote down vote up
@Test
public void getMethodOverridden() throws Exception {
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("post");
    servletRequest.addHeader(HttpHeader.METHOD_OVERRIDE, "patch");

    assertEquals(HttpMethod.PATCH,
            HttpMethod.getMethodIfSupported(servletRequest, EnumSet.allOf(HttpMethod.class)));
}
 
Example 18
Source File: RepositoryServletSecurityTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
public void testPutWithValidUserWithNoWriteAccess()
    throws Exception
{
    
    servlet.setDavSessionProvider( davSessionProvider );

    ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
    archivaDavResourceFactory.setHttpAuth( httpAuth );
    archivaDavResourceFactory.setServletAuth( servletAuth );
    servlet.setResourceFactory( archivaDavResourceFactory );

    AuthenticationResult result = new AuthenticationResult();

    EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
                                                       anyObject( HttpServletResponse.class ) ) ).andReturn(
        result );

    EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
                                                  anyObject( AuthenticationResult.class ) ) ).andReturn( true );

    // ArchivaDavResourceFactory#isAuthorized()
    SecuritySession session = new DefaultSecuritySession();

    EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
                                                       anyObject( HttpServletResponse.class ) ) ).andReturn(
        result );

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    EasyMock.expect( httpAuth.getSecuritySession( mockHttpServletRequest.getSession( true ) ) ).andReturn(
        session );

    EasyMock.expect( httpAuth.getSessionUser( mockHttpServletRequest.getSession() ) ).andReturn( new SimpleUser() );

    EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
        true );

    EasyMock.expect(
        servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
                                  eq( ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ) ).andThrow(
        new UnauthorizedException( "User not authorized" ) );
    httpAuthControl.replay();
    servletAuthControl.replay();

    InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
    assertNotNull( "artifact.jar inputstream", is );

    mockHttpServletRequest.addHeader( "User-Agent", "foo" );
    mockHttpServletRequest.setMethod( "PUT" );
    mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
    mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
    mockHttpServletRequest.setContentType( "application/octet-stream" );

    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    servlet.service( mockHttpServletRequest, mockHttpServletResponse );

    httpAuthControl.verify();
    servletAuthControl.verify();

    assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
}
 
Example 19
Source File: RepositoryServletSecurityTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetWithAValidUserWithNoReadAccess()
    throws Exception
{
    String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
    String expectedArtifactContents = "dummy-commons-lang-artifact";

    Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
    Files.createDirectories(artifactFile.getParent());

    org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);

    servlet.setDavSessionProvider( davSessionProvider );

    ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
    archivaDavResourceFactory.setHttpAuth( httpAuth );
    archivaDavResourceFactory.setServletAuth( servletAuth );

    servlet.setResourceFactory( archivaDavResourceFactory );

    AuthenticationResult result = new AuthenticationResult();

    EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
                                                       anyObject( HttpServletResponse.class ) ) ).andReturn(
        result );

    EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
                                                  anyObject( AuthenticationResult.class ) ) ).andReturn( true );

    // ArchivaDavResourceFactory#isAuthorized()
    SecuritySession session = new DefaultSecuritySession();

    EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
                                                       anyObject( HttpServletResponse.class ) ) ).andReturn(
        result );

    EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );

    EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( new SimpleUser() );

    EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
        true );

    EasyMock.expect(
        servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
                                  eq( ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ) ).andThrow(
        new UnauthorizedException( "User not authorized to read repository." ) );
    httpAuthControl.replay();
    servletAuthControl.replay();

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    mockHttpServletRequest.addHeader( "User-Agent", "foo" );
    mockHttpServletRequest.setMethod( "GET" );
    mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );


    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    servlet.service( mockHttpServletRequest, mockHttpServletResponse );

    httpAuthControl.verify();
    servletAuthControl.verify();

    assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
}
 
Example 20
Source File: EntityTypeResponseMapperTest.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
void toEntityTypesResponse() throws URISyntaxException {
  MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  mockHttpServletRequest.setMethod("GET");
  mockHttpServletRequest.setRequestURI("/api/metadata");
  mockHttpServletRequest.setQueryString("page=1");
  RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(mockHttpServletRequest));

  EntityType entityType = mock(EntityType.class);
  when(entityType.getId()).thenReturn("MyEntityTypeId");

  int total = 5;
  EntityTypes entityTypes =
      EntityTypes.builder().setEntityTypes(singletonList(entityType)).setTotal(total).build();

  int size = 1;
  int number = 1;

  EntityTypeResponseData entityTypeResponseData =
      EntityTypeResponseData.builder()
          .setId("MyEntityTypeId")
          .setAttributes(
              AttributesResponse.builder()
                  .setLinks(
                      LinksResponse.create(
                          null,
                          new URI("http://localhost/api/metadata/MyEntityTypeId/attributes"),
                          null))
                  .build())
          .setAbstract(false)
          .setIndexingDepth(0)
          .build();

  EntityTypeResponse entityTypeResponse =
      EntityTypeResponse.builder()
          .setLinks(
              LinksResponse.create(
                  null, new URI("http://localhost/api/metadata/MyEntityTypeId"), null))
          .setData(entityTypeResponseData)
          .build();

  EntityTypesResponse entityTypesResponse =
      EntityTypesResponse.builder()
          .setLinks(
              LinksResponse.create(
                  new URI("http://localhost/api/metadata?page=0"),
                  new URI("http://localhost/api/metadata?page=1"),
                  new URI("http://localhost/api/metadata?page=2")))
          .setItems(singletonList(entityTypeResponse))
          .setPage(PageResponse.create(size, total, number))
          .build();
  assertEquals(
      entityTypesResponse, entityTypeV3Mapper.toEntityTypesResponse(entityTypes, size, number));
}