@Test public void testAddEventWithWebAuthenticationDetails() { HttpSession session = new MockHttpSession(null, "test-session-id"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); request.setRemoteAddr("1.2.3.4"); WebAuthenticationDetails details = new WebAuthenticationDetails(request); Map<String, Object> data = new HashMap<>(); data.put("test-key", details); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); }
@Test public void testLogout() throws Exception { final MockHttpSession mockHttpSession = new MockHttpSession(); testSignUp(); mockMvc .perform(post("/v1/user/signin") .session(mockHttpSession) .contentType(MediaType.APPLICATION_JSON) .content("{\"username\":\"n02\"," + "\"password\":\"soHardPassword\"}")); mockMvc .perform(post("/v1/user/logout") .session(mockHttpSession) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); }
@Test public void verifyStartAuthentication() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest(); mockRequest.setParameter(ThemeChangeInterceptor.DEFAULT_PARAM_NAME, MY_THEME); mockRequest.setParameter(LocaleChangeInterceptor.DEFAULT_PARAM_NAME, MY_LOCALE); mockRequest.setParameter(CasProtocolConstants.PARAMETER_METHOD, MY_METHOD); final MockHttpSession mockSession = new MockHttpSession(); mockRequest.setSession(mockSession); final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class); when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest); final MockRequestContext mockRequestContext = new MockRequestContext(); mockRequestContext.setExternalContext(servletExternalContext); mockRequestContext.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, org.jasig.cas.services.TestUtils.getService(MY_SERVICE)); final FacebookClient facebookClient = new FacebookClient(MY_KEY, MY_SECRET); final TwitterClient twitterClient = new TwitterClient(MY_KEY, MY_SECRET); final Clients clients = new Clients(MY_LOGIN_URL, facebookClient, twitterClient); final ClientAction action = new ClientAction(); action.setCentralAuthenticationService(mock(CentralAuthenticationService.class)); action.setClients(clients); final Event event = action.execute(mockRequestContext); assertEquals("error", event.getId()); assertEquals(MY_THEME, mockSession.getAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME)); assertEquals(MY_LOCALE, mockSession.getAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME)); assertEquals(MY_METHOD, mockSession.getAttribute(CasProtocolConstants.PARAMETER_METHOD)); final MutableAttributeMap flowScope = mockRequestContext.getFlowScope(); final Map<String, String> urls = (Map<String, String>) flowScope.get(ClientAction.PAC4J_URLS); assertTrue((urls.get("Facebook")) .startsWith("https://www.facebook.com/v2.2/dialog/oauth?client_id=my_key&redirect_uri=http%3A%2F%2Fcasserver%2Flogin%3F" + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "%3DFacebookClient&state=")); assertEquals(MY_LOGIN_URL + '?' + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "=TwitterClient&needs_client_redirection=true", urls.get("Twitter")); }
@Test public void verifyOK() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest( "GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName()); final Map<String, Object> map = modelAndView.getModel(); assertEquals(SERVICE_NAME, map.get("serviceName")); assertEquals(REDIRECT_URI + '?' + OAuthConstants.CODE + '=' + SERVICE_TICKET, map.get("callbackUrl")); }
@Test public void verifyOKWithState() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest( "GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName()); final Map<String, Object> map = modelAndView.getModel(); assertEquals(SERVICE_NAME, map.get("serviceName")); assertEquals(REDIRECT_URI + '?' + OAuthConstants.CODE + '=' + SERVICE_TICKET + '&' + OAuthConstants.STATE + '=' + STATE, map.get("callbackUrl")); }
@Test public void verifyOK() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest( "GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName()); final Map<String, Object> map = modelAndView.getModel(); assertEquals(SERVICE_NAME, map.get("serviceName")); assertEquals(REDIRECT_URI + "?" + OAuthConstants.CODE + "=" + SERVICE_TICKET, map.get("callbackUrl")); }
@Test public void verifyOKWithState() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest( "GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName()); final Map<String, Object> map = modelAndView.getModel(); assertEquals(SERVICE_NAME, map.get("serviceName")); assertEquals(REDIRECT_URI + "?" + OAuthConstants.CODE + "=" + SERVICE_TICKET + "&" + OAuthConstants.STATE + "=" + STATE, map.get("callbackUrl")); }
@Test public void verifyCodeNoProfile() throws Exception { clearAllServices(); final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.AUTHORIZE_URL); mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID); mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI); mockRequest.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.CODE.name().toLowerCase()); mockRequest.setServerName(CAS_SERVER); mockRequest.setServerPort(CAS_PORT); mockRequest.setScheme(CAS_SCHEME); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME); service.setBypassApprovalPrompt(true); this.servicesManager.save(service); final MockHttpSession session = new MockHttpSession(); mockRequest.setSession(session); final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse); assertEquals(OAuth20Constants.ERROR_VIEW, modelAndView.getViewName()); }
@Test public void testSignIn() throws Exception { testSignUp(); final MockHttpSession mockHttpSession = new MockHttpSession(); mockMvc .perform(post("/v1/user/signin") .session(mockHttpSession) .contentType(MediaType.APPLICATION_JSON) .content("{\"username\":\"n02\"," + "\"password\":\"soHardPassword\"}")) .andExpect(status().isOk()) .andExpect(jsonPath("username").value("n02")); assertEquals( ((Integer)mockHttpSession.getAttribute("user")), (Integer)userService.getUser("n02").getId()); }
@Test public void testOK() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest( "GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName()); final Map<String, Object> map = modelAndView.getModel(); assertEquals(SERVICE_NAME, map.get("serviceName")); assertEquals(REDIRECT_URI + "?" + OAuthConstants.CODE + "=" + SERVICE_TICKET, map.get("callbackUrl")); }
@Test public void testOKWithState() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest( "GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName()); final Map<String, Object> map = modelAndView.getModel(); assertEquals(SERVICE_NAME, map.get("serviceName")); assertEquals(REDIRECT_URI + "?" + OAuthConstants.CODE + "=" + SERVICE_TICKET + "&" + OAuthConstants.STATE + "=" + STATE, map.get("callbackUrl")); }
@Test public void testMethodAll() throws Exception { MockHttpSession session = getSession( "ALL" ); String endpoint = "/method/testAll"; mvc.perform( get( endpoint ).session( session ) ) .andExpect( status().isNotFound() ); mvc.perform( get( "/26" + endpoint ).session( session ) ) .andExpect( status().isNotFound() ); mvc.perform( get( "/27" + endpoint ).session( session ) ) .andExpect( status().isNotFound() ); mvc.perform( get( "/26" + endpoint + "/a" ).session( session ) ) .andExpect( status().isOk() ); mvc.perform( get( "/27" + endpoint + "/b" ).session( session ) ) .andExpect( status().isOk() ); }
private MockHttpSession httpSession(MockHttpServletRequest request, final String sessionid) { MockHttpSession session; synchronized (this.sessions) { session = this.sessions.get(sessionid); if (session == null) { session = new HtmlUnitMockHttpSession(request, sessionid); session.setNew(true); synchronized (this.sessions) { this.sessions.put(sessionid, session); } addSessionCookie(request, sessionid); } else { session.setNew(false); } } return session; }
@Test public void startGame_setsGameStarted() throws Exception { List<Player> players = Arrays.asList(new Player(), new Player()); Game game = Game.builder().gameName("gamename").players(players).build(); when(mockGameDataService.findGameByName("gamename")).thenReturn(game); List<Territory> territories = generateTerritoriesForTest(); when(mockTerritoryDataService.getListOfTerritoriesOnMap()).thenReturn(territories); when(mockPlayerTerritoryDataService.getTerritoriesInGame("gamename")).thenReturn(playerTerritoriesForTest()); MockHttpSession session = new MockHttpSession(); session.setAttribute(PlayerController.SESSION_GAME_NAME_FIELD, "gamename"); gameService.startGame(session); verify(mockGameDataService).saveGame(game); assertTrue(game.isStarted()); }
@Test public void startGameRequest_callsMarkUnsuppliedThenSupplied_inSupplyService() throws Exception { List<Player> players = Arrays.asList(Player.builder().playerId(10L).build(), Player.builder().playerId(20L).build()); Game game = Game.builder().gameName("gamename").players(players).build(); when(mockRepository.findOne("gamename")).thenReturn(game); List<Territory> territories = generateTerritoriesForTest(); when(mockTerritoryRepository.findAll()).thenReturn(territories); MockHttpSession session = new MockHttpSession(); session.setAttribute(PlayerController.SESSION_GAME_NAME_FIELD, "gamename"); List<PlayerTerritory> playerTerritories = generatePlayerTerritoriesForTest(); when(mockPlayerTerritoryRepository.findByGameName("gamename")).thenReturn(playerTerritories); mockMvc.perform(post("/game/start").contentType(MediaType.APPLICATION_JSON).session(session)); InOrder inOrder = inOrder(mockSuppliedStatusService); inOrder.verify(mockSuppliedStatusService).markUnsupplied(); ArgumentCaptor<List> listArgumentCaptor = ArgumentCaptor.forClass(List.class); inOrder.verify(mockSuppliedStatusService).markSupplied(listArgumentCaptor.capture(), eq(playerTerritories)); List<PlayerTerritory> value = (List<PlayerTerritory>) listArgumentCaptor.getValue(); assertThat(value .stream() .map(PlayerTerritory::getTerritoryId) .collect(Collectors.toList())).containsExactlyInAnyOrder(5L, 10L, 15L, 20L); }
@Test public void startGame_initializesNonSupplyTerritories_toHave12SurroundingTroops() throws Exception { List<Player> players = Arrays.asList(Player.builder().playerId(10L).build(), Player.builder().playerId(20L).build()); Game game = Game.builder().gameName("gamename").players(players).build(); when(mockRepository.findOne("gamename")).thenReturn(game); List<Territory> territories = generateTerritoriesForTest(); when(mockTerritoryRepository.findAll()).thenReturn(territories); when(mockPlayerTerritoryRepository.findByGameName("gamename")).thenReturn(generatePlayerTerritoriesForTest()); MockHttpSession session = new MockHttpSession(); session.setAttribute(PlayerController.SESSION_GAME_NAME_FIELD, "gamename"); mockMvc.perform(post("/game/start").contentType(MediaType.APPLICATION_JSON).session(session)) .andExpect(status().isOk()); ArgumentCaptor<List> listArgumentCaptor = ArgumentCaptor.forClass(List.class); verify(mockPlayerTerritoryRepository).save(listArgumentCaptor.capture()); List<PlayerTerritory> value = listArgumentCaptor.getValue(); int totalTroops = 0; for (PlayerTerritory pt:value) { totalTroops += pt.getTroops(); } assertThat(totalTroops).isEqualTo(80); // (8 troops per depot + 12 troops per adjacent)*2depotsperplayer*2players }
@Test public void getPlayer_returnsPlayerInGameWhosePlayerNumberMatchesRequest() throws Exception { List<Player> players = Arrays.asList( Player.builder().playerNumber(1).name("zxmbies").build(), Player.builder().playerNumber(2).name("qxc").build(), Player.builder().playerNumber(3).name("eidlyn").build()); when(mockRepository.findPlayersByGameName("gamename")).thenReturn(players); MockHttpSession mockHttpSession = new MockHttpSession(); mockHttpSession.setAttribute(PlayerController.SESSION_GAME_NAME_FIELD, "gamename"); String actualResponse = mockMvc.perform(get("/players/3").contentType(MediaType.APPLICATION_JSON).session(mockHttpSession)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); JSONAssert.assertEquals("{\n" + " \"playerNumber\": 3,\n" + " \"name\": \"eidlyn\"\n" + "}", actualResponse, JSONCompareMode.LENIENT); }
@Test public void skipAction_decrementsCurrentActionNumber_whenPlayerIsActivePlayer() throws Exception { MockHttpSession session = new MockHttpSession(); session.setAttribute(SESSION_PLAYER_NUMBER_FIELD, 2); session.setAttribute(SESSION_GAME_NAME_FIELD, "gamename"); Game game = new Game(); game.setTurnNumber(5); Player thisPlayer = Player.builder().playerNumber(2).remainingActions(3).build(); game.setPlayers(Arrays.asList(new Player(), thisPlayer, new Player())); when(mockGameRepository.findOne("gamename")).thenReturn(game); String contentAsString = mockMvc.perform(post("/actions/skip-action").contentType(MediaType.APPLICATION_JSON).session(session)).andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); ; verify(mockGameRepository).save(game); assertThat(thisPlayer.getRemainingActions()).isEqualTo(2); assertEquals("{\n" + " \"actionsRemaining\": 2\n" + "}", contentAsString, JSONCompareMode.NON_EXTENSIBLE); }
@Test public void skipAction_returnsForbiddenStatus_whenPlayerIsNotActivePlayer() throws Exception { MockHttpSession session = new MockHttpSession(); session.setAttribute(SESSION_PLAYER_NUMBER_FIELD, 3); session.setAttribute(SESSION_GAME_NAME_FIELD, "gamename"); when(mockGameRepository.findOne("gamename")).thenReturn(Game.builder() .turnNumber(1) .players( Arrays.asList( new Player(), Player.builder() .playerNumber(2) .remainingActions(2) .build(), new Player())) .build()); mockMvc.perform(post("/actions/skip-action").contentType(MediaType.APPLICATION_JSON).session(session)).andExpect(status().isForbidden()); verify(mockGameRepository, times(0)).save(any(Game.class)); }
@Test public void skipAction_changesTurn_andSetsRemainingActionsToThree_whenRemainingActionsAreOne() throws Exception { MockHttpSession session = new MockHttpSession(); session.setAttribute(SESSION_PLAYER_NUMBER_FIELD, 2); session.setAttribute(SESSION_GAME_NAME_FIELD, "gamename"); Game game = new Game(); game.setTurnNumber(5); Player thisPlayer = Player.builder().playerNumber(2).remainingActions(1).build(); game.setPlayers(Arrays.asList(new Player(), thisPlayer, new Player())); when(mockGameRepository.findOne("gamename")).thenReturn(game); String contentAsString = mockMvc.perform(post("/actions/skip-action").contentType(MediaType.APPLICATION_JSON).session(session)).andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); ; verify(mockGameRepository).save(game); assertThat(game.getTurnNumber()).isEqualTo(6); assertThat(thisPlayer.getRemainingActions()).isEqualTo(3); assertEquals("{\n" + " \"actionsRemaining\": 0\n" + "}", contentAsString, JSONCompareMode.NON_EXTENSIBLE); }
@Test public void moveTroops_returnsForbiddenStatus_whenPlayerIsNotActive() throws Exception { MockHttpSession session = new MockHttpSession(); session.setAttribute(SESSION_PLAYER_NUMBER_FIELD, 1); session.setAttribute(SESSION_GAME_NAME_FIELD, "gamename"); Game game = Game.builder() .players(Arrays.asList(new Player(), new Player())) .turnNumber(2) .build(); when(mockGameRepository.findOne("gamename")).thenReturn(game); ObjectMapper objectMapper = new ObjectMapper(); String request = objectMapper.writeValueAsString(new ActionsController.MoveRequest()); mockMvc.perform(post("/actions/move-troops").contentType(MediaType.APPLICATION_JSON).content(request).session(session)).andExpect(status().isForbidden()); }
@Test public void getOwnerOfTerritory_returnsNullOwningPlayer_whenNoOwner() throws Exception { PlayerTerritory playerTerritory = PlayerTerritory.builder().playerId(30L).territoryId(1L).player(null).build(); when(mockRepository.findOne(1L)).thenReturn((Territory.builder().name("Location 1").territoryId(1L).build())); when(mockPlayerTerritoryRepository.findPlayerTerritoryByTerritoryIdAndGameName(1L, "gamename")) .thenReturn(playerTerritory); MockHttpSession session = new MockHttpSession(); session.setAttribute(PlayerController.SESSION_GAME_NAME_FIELD, "gamename"); String response = mockMvc.perform(get("/territories/1").accept(MediaType.APPLICATION_JSON).session(session)) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); JSONAssert.assertEquals("{\n" + " \"name\" : \"Location 1\",\n" + " \"owningPlayer\": null\n" + "}", response, JSONCompareMode.LENIENT); }
@Test public void postTerritoryOwner_setsOwnerOfTerritory_toRequestedPlayer() throws Exception { PlayerTerritory playerTerritory = PlayerTerritory.builder().territoryId(2L).build(); when(mockPlayerTerritoryRepository.findPlayerTerritoryByTerritoryIdAndGameName(2L, "gamename")).thenReturn(playerTerritory); Player player = Player.builder().playerNumber(1).playerTerritoriesList(new ArrayList<>()).build(); Player wrongPlayer = Player.builder().playerNumber(4).build(); when(mockPlayerRepository.findPlayersByGameName("gamename")).thenReturn(new ArrayList<>(Arrays.asList(player, wrongPlayer))); TerritoryController.TerritoryRequest territoryRequest = TerritoryController.TerritoryRequest.builder().playerNumber(1).territoryId(2).build(); ObjectMapper objectMapper = new ObjectMapper(); String content = objectMapper.writeValueAsString(territoryRequest); MockHttpSession mockHttpSession = new MockHttpSession(); mockHttpSession.setAttribute(PlayerController.SESSION_GAME_NAME_FIELD, "gamename"); mockMvc.perform(post("/territories/owner").contentType(MediaType.APPLICATION_JSON).content(content).session(mockHttpSession)) .andExpect(status().isOk()); verify(mockPlayerRepository).save(player); assertThat(player.getPlayerTerritoriesList().get(0)).isSameAs(playerTerritory); }
public void loginUserOK() throws Exception { HttpSession session = mockMvc.perform(post("/doLogin").param("username", "admin").param("password", "pass").with(user("admin"))) .andExpect(status().is(HttpStatus.FOUND.value())) .andExpect(redirectedUrl("/")) .andReturn() .getRequest() .getSession(); Assert.assertNotNull(session); Map<String,Object> model = mockMvc.perform(get("/").session((MockHttpSession)session).locale(Locale.ENGLISH)) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("logged_in")) .andExpect(model().attributeExists("user")) .andReturn() .getModelAndView() .getModel(); User userFromModel = (User) model.get("admin"); Assert.assertEquals("admin", userFromModel.getUsername()); }
@Test public void loginVerifiesSecretState() throws Exception { User currentUser = WithAdminUserFactory.create(); when(mockGitHub.getCurrentUser(any(CurrentUserRequest.class))).thenReturn(currentUser); MockHttpSession session = new MockHttpSession(); String redirect = mockMvc.perform(get("/sign/pivotal").session(session)) .andExpect(status().is3xxRedirection()) .andReturn().getResponse().getRedirectedUrl(); redirect = mockMvc.perform(get(redirect)) .andReturn().getResponse().getRedirectedUrl(); // change the expected secret state session.setAttribute("state", "INVALID"); mockMvc.perform(get(redirect).session(session)) .andExpect(status().isBadRequest()); }
@Test public void testCreateValidation() throws Exception { MockHttpSession session = getSession( "F_DATAELEMENT_PUBLIC_ADD" ); DataElement de = createDataElement( 'A' ); de.setName( null ); mvc.perform( post( "/dataElements" ) .session( session ) .contentType( TestUtils.APPLICATION_JSON_UTF8 ) .content( TestUtils.convertObjectToJsonBytes( de ) ) ) ; de = manager.getByName( DataElement.class, "DataElementA" ); assertNull( de ); }
@Test public void testFilterLike() throws Exception { MockHttpSession session = getSession( "F_DATAELEMENT_PUBLIC_ADD" ); DataElement de = createDataElement( 'A' ); manager.save( de ); List<FieldDescriptor> fieldDescriptors = new ArrayList<>(); fieldDescriptors.addAll( ResponseDocumentation.pager() ); fieldDescriptors.add( fieldWithPath( "dataElements" ).description( "Data elements" ) ); mvc.perform( get( "/dataElements?filter=name:like:DataElementA" ) .session( session ) .contentType( TestUtils.APPLICATION_JSON_UTF8 ) ) .andExpect( jsonPath( "$.pager.total", new GreaterThan<Integer>( 0 ) ) ) .andDo( documentPrettyPrint( "data-elements/filter", responseFields( fieldDescriptors.toArray( new FieldDescriptor[fieldDescriptors.size()] ) ) ) ); }
@Test @Override public void testGetAll() throws Exception { manager.save( createDataElementCategory( 'A' ) ); manager.save( createDataElementCategory( 'B' ) ); manager.save( createDataElementCategory( 'C' ) ); manager.save( createDataElementCategory( 'D' ) ); MockHttpSession session = getSession( "ALL" ); List<FieldDescriptor> fieldDescriptors = new ArrayList<>(); fieldDescriptors.addAll( ResponseDocumentation.pager() ); fieldDescriptors.add( fieldWithPath( CategorySchemaDescriptor.PLURAL ).description( "Data element categories" ) ); mvc.perform( get( "/" + CategorySchemaDescriptor.PLURAL ).session( session ).accept( TestUtils.APPLICATION_JSON_UTF8 ) ) .andExpect( status().isOk() ) .andExpect( content().contentTypeCompatibleWith( TestUtils.APPLICATION_JSON_UTF8 ) ) .andExpect( jsonPath( "$." + CategorySchemaDescriptor.PLURAL ).isArray() ) .andExpect( jsonPath( "$." + CategorySchemaDescriptor.PLURAL + ".length()" ).value( 5 ) ) .andDo( documentPrettyPrint( CategorySchemaDescriptor.PLURAL + "/all", responseFields( fieldDescriptors.toArray( new FieldDescriptor[fieldDescriptors.size()] ) ) ) ); }
@Test @Override public void testGetByIdOk() throws Exception { DataElementCategory cat = createDataElementCategory( 'A' ); manager.save( cat ); MockHttpSession session = getSession( "ALL" ); Schema schema = schemaService.getSchema( DataElementCategory.class ); Set<FieldDescriptor> fieldDescriptors = TestUtils.getFieldDescriptors( schema ); mvc.perform( get( "/" + CategorySchemaDescriptor.PLURAL + "/{id}", cat.getUid() ).session( session ).accept( MediaType.APPLICATION_JSON ) ) .andExpect( status().isOk() ) .andExpect( content().contentTypeCompatibleWith( MediaType.APPLICATION_JSON ) ) .andExpect( jsonPath( "$.name" ).value( "DataElementCategoryA" ) ) .andExpect( jsonPath( "$.shortName" ).value( "DataElementCategoryA" ) ) .andDo( documentPrettyPrint( ENDPOINT + "/id", responseFields( fieldDescriptors.toArray( new FieldDescriptor[fieldDescriptors.size()] ) ) ) ); }