private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam, ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception { // Bind request parameter onto object... String name = attrName; if ("".equals(name)) { name = Conventions.getVariableNameForParameter(methodParam); } Class<?> paramType = methodParam.getParameterType(); Object bindObject; if (implicitModel.containsKey(name)) { bindObject = implicitModel.get(name); } else if (this.methodResolver.isSessionAttribute(name, paramType)) { bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name); if (bindObject == null) { raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session"); } } else { bindObject = BeanUtils.instantiateClass(paramType); } WebDataBinder binder = createBinder(webRequest, bindObject, name); initBinder(handler, name, binder, webRequest); return binder; }
@Override public org.springframework.web.servlet.ModelAndView resolveModelAndView(Method handlerMethod, Class<?> handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { if (returnValue instanceof MySpecialArg) { return new org.springframework.web.servlet.ModelAndView(new View() { @Override public String getContentType() { return "text/html"; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.getWriter().write("myValue"); } }); } return UNRESOLVED; }
@Override public ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { if (returnValue instanceof MySpecialArg) { return new ModelAndView(new View() { @Override public String getContentType() { return "text/html"; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.getWriter().write("myValue"); } }); } return UNRESOLVED; }
@Override @SuppressWarnings("rawtypes") public ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { if (returnValue instanceof MySpecialArg) { return new ModelAndView(new View() { @Override public String getContentType() { return "text/html"; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.getWriter().write("myValue"); } }); } return UNRESOLVED; }
public void testBookController() throws Exception { BooksController controller = (BooksController)booksPortletContext.getBean("booksController"); ModelMap model = new ExtendedModelMap(); // ask the controller to handle the request String view = controller.viewBook(Integer.valueOf(1), (Model)model); // show the viewname logger.info("view: " + view); assertEquals("incorrect view", "bookView", view); // show the model includes the book assertTrue("model should contain a book", model.containsAttribute("book")); Book book = (Book)model.get("book"); // check the book's details logger.info("book.author: " + book.getAuthor()); assertEquals("incorrect author", "Neal Stephenson", book.getAuthor()); logger.info("book.title: " + book.getTitle()); assertEquals("incorrect title", "Snow Crash", book.getTitle()); logger.info("book.count: " + book.getCount()); assertEquals("incorrect count", Integer.valueOf(50), book.getCount()); }
@Test public void likeTest() { HttpSession session = new MockHttpSession(); session.setAttribute("user", user); shareController.reshare(ORIGIANL_MESSAGE_ID, "Comment", "", false, Collections.<String>emptyList(), new ExtendedModelMap(), user.getId(), session, new MockHttpServletResponse()); Collection<Message> incomingMessages = messageController .getIncomingMessages(receivingUser, session, DEFAULT_MESSAGE_ID, false); Assert.assertEquals(1, incomingMessages.size()); Message msg = incomingMessages.iterator().next(); Assert.assertEquals(ORIGIANL_MSG_TEXT, msg.getOriginalMessage() .getText()); Assert.assertEquals(1, msg.getOriginalMessage().getAuthor().getScore()); }
@Test public void testExecuteCommand_ModelMap() throws Exception { // given ExtendedModelMap model = new ExtendedModelMap(); String logAccessConfigId ="one-id"; String cmd = "cat file.log"; String encoding = Constants.DEFAULT_ENCODING_OPTION; DisplayType displayType = DisplayType.RAW; // when String viewName = commandController.executeCommand(model, request, logAccessConfigId, cmd, encoding, displayType); // then Assert.assertEquals(Constants.VIEW_RAW, viewName); Assert.assertEquals(true, request.getAttribute(Constants.SHOW_OPTIONS_KEY)); Assert.assertEquals(encoding, request.getAttribute(Constants.ENCODING_KEY)); Assert.assertEquals(displayType, request.getAttribute(Constants.DISPLAY_TYPE_KEY)); Assert.assertNotNull(request.getAttribute(Constants.BREADCRUMBS_KEY)); Assert.assertNotNull(model.get(Constants.RAW_CONTENT_KEY)); }
@SuppressWarnings("unchecked") @Test public void testExecuteCommand_BreadCrumbs_TailFile() throws Exception { // given ExtendedModelMap model = new ExtendedModelMap(); String logAccessConfigId ="one-id"; String cmd = "tail -1000 file.log"; String encoding = Constants.DEFAULT_ENCODING_OPTION; DisplayType displayType = DisplayType.RAW; // when commandController.executeCommand(model, request, logAccessConfigId, cmd, encoding, displayType); // then List<Breadcrumb> breadcrumbs = (List<Breadcrumb>) request.getAttribute(Constants.BREADCRUMBS_KEY); Assert.assertEquals(2, breadcrumbs.size()); Assert.assertEquals(logAccessConfigId, breadcrumbs.get(0).getLabel()); Assert.assertEquals("file.log", breadcrumbs.get(1).getLabel()); }
@Test public void testGetListE() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); Model uiModel = new ExtendedModelMap(); User user = new UserImpl(); user.setLoginName(USER); user.setViewCampus(VIEW_CAMPUS[3]); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_USER_KEY, user); request.setSession(session); String viewName; try { viewName = getController().getList(request, uiModel, TOOL_NAMES[7]); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect: Expected " + REDIRECT_CAMPUS + " and found " + viewName, REDIRECT_CAMPUS.equals(viewName)); }
@SuppressWarnings("unchecked") @Test public void testExecuteCommand_BreadCrumbs_TailSubFolderFile() throws Exception { // given ExtendedModelMap model = new ExtendedModelMap(); String logAccessConfigId ="one-id"; String cmd = "tail -1000 folder1/folder2/file.log"; String encoding = Constants.DEFAULT_ENCODING_OPTION; DisplayType displayType = DisplayType.RAW; // when commandController.executeCommand(model, request, logAccessConfigId, cmd, encoding, displayType); // then List<Breadcrumb> breadcrumbs = (List<Breadcrumb>) request.getAttribute(Constants.BREADCRUMBS_KEY); Assert.assertEquals(4, breadcrumbs.size()); Assert.assertEquals(logAccessConfigId, breadcrumbs.get(0).getLabel()); Assert.assertEquals("folder1", breadcrumbs.get(1).getLabel()); Assert.assertEquals("folder2", breadcrumbs.get(2).getLabel()); Assert.assertEquals("file.log", breadcrumbs.get(3).getLabel()); }
@SuppressWarnings("unchecked") @Test public void testExecuteCommand_BreadCrumbs_ListTarGzEntries() throws Exception { // given ExtendedModelMap model = new ExtendedModelMap(); String logAccessConfigId ="one-id"; String cmd = "tar -ztvf backup/apache-access.tar.gz"; String encoding = Constants.DEFAULT_ENCODING_OPTION; DisplayType displayType = DisplayType.TABLE; // when commandController.executeCommand(model, request, logAccessConfigId, cmd, encoding, displayType); // then List<Breadcrumb> breadcrumbs = (List<Breadcrumb>) request.getAttribute(Constants.BREADCRUMBS_KEY); Assert.assertEquals(3, breadcrumbs.size()); Assert.assertEquals(logAccessConfigId, breadcrumbs.get(0).getLabel()); Assert.assertEquals("backup", breadcrumbs.get(1).getLabel()); Assert.assertEquals("apache-access.tar.gz", breadcrumbs.get(2).getLabel()); }
@SuppressWarnings("unchecked") @Test public void testExecuteCommand_BreadCrumbs_ListTarGzEntry() throws Exception { // given ExtendedModelMap model = new ExtendedModelMap(); String logAccessConfigId ="one-id"; String cmd = "tar -O -zxf backup/apache-access.tar.gz backup/apache-access-3l.log.gz | gzip -dc | tail -1000"; String encoding = Constants.DEFAULT_ENCODING_OPTION; DisplayType displayType = DisplayType.RAW; // when commandController.executeCommand(model, request, logAccessConfigId, cmd, encoding, displayType); // then List<Breadcrumb> breadcrumbs = (List<Breadcrumb>) request.getAttribute(Constants.BREADCRUMBS_KEY); Assert.assertEquals(4, breadcrumbs.size()); Assert.assertEquals(logAccessConfigId, breadcrumbs.get(0).getLabel()); Assert.assertEquals("backup", breadcrumbs.get(1).getLabel()); Assert.assertEquals("apache-access.tar.gz", breadcrumbs.get(2).getLabel()); Assert.assertEquals("apache-access-3l.log.gz", breadcrumbs.get(3).getLabel()); }
@Test public void testViewPreferences() { Model model = new ExtendedModelMap(); Map<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>(); expect(service.getPreferencesAsMap()).andReturn(preferenceMap); replay(service); String view = controller.viewPreferences(null,REFERRER_ID, model); assertEquals(ViewNames.ADMIN_PREFERENCES, view); assertEquals(preferenceMap, model.asMap().get("preferenceMap")); assertFalse(model.containsAttribute("actionresult")); assertTrue(model.containsAttribute("topnav")); assertTrue(model.containsAttribute("tabs")); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); verify(service); }
@Test public void testViewPreferences_afterUpdate() { Model model = new ExtendedModelMap(); Map<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>(); expect(service.getPreferencesAsMap()).andReturn(preferenceMap); replay(service); final String action = "update"; String view = controller.viewPreferences(action,REFERRER_ID, model); assertEquals(ViewNames.ADMIN_PREFERENCES, view); assertEquals(preferenceMap, model.asMap().get("preferenceMap")); assertEquals(action, model.asMap().get("actionresult")); assertTrue(model.containsAttribute("topnav")); assertTrue(model.containsAttribute("tabs")); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); verify(service); }
@Test public void testEditPreferences() { Model model = new ExtendedModelMap(); Map<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>(); expect(service.getPreferencesAsMap()).andReturn(preferenceMap); replay(service); String view = controller.editPreferences(model,REFERRER_ID); assertEquals(ViewNames.ADMIN_PREFERENCE_DETAIL, view); assertTrue(model.asMap().get("preferenceForm") instanceof PortalPreferenceForm); assertTrue(model.containsAttribute(ModelKeys.TOKENCHECK)); assertTrue(model.containsAttribute("topnav")); assertTrue(model.containsAttribute("tabs")); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); }
@Test public void testUpdatePreferences_valid() { ModelMap model = new ExtendedModelMap(); PortalPreferenceForm form = new PortalPreferenceForm(new HashMap<String, PortalPreference>()); final BindingResult errors = new BeanPropertyBindingResult(form, "form"); SessionStatus sessionStatus = createMock(SessionStatus.class); final Set<Map.Entry<String, PortalPreference>> entries = form.getPreferenceMap().entrySet(); for (Map.Entry<String, PortalPreference> entry : entries) { service.savePreference(entry.getValue()); } sessionStatus.setComplete(); expectLastCall(); replay(service, sessionStatus); String view = controller.updatePreferences(form, errors, validToken, validToken,REFERRER_ID, model, sessionStatus); assertEquals("redirect:/app/admin/preferences?action=update&referringPageId=" + REFERRER_ID, view); assertTrue("Model has been cleared", model.isEmpty()); verify(service, sessionStatus); }
@Test(expected = SecurityException.class) public void testUpdatePreferences_invalidToken() { ModelMap model = new ExtendedModelMap(); String invalidToken = AdminControllerUtil.generateSessionToken(); PortalPreferenceForm form = new PortalPreferenceForm(new HashMap<String, PortalPreference>()); final BindingResult errors = new BeanPropertyBindingResult(form, "form"); SessionStatus sessionStatus = createMock(SessionStatus.class); sessionStatus.setComplete(); expectLastCall(); replay(service, sessionStatus); controller.updatePreferences(form, errors, validToken, invalidToken,REFERRER_ID, model, sessionStatus); assertFalse("Should not end up here", true); verify(service, sessionStatus); }
@Test public void testUpdatePreferences_invalidPageSizeValue() { ModelMap model = new ExtendedModelMap(); HashMap<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>(); PortalPreference pageSizePref = new PortalPreferenceImpl(PortalPreferenceKeys.PAGE_SIZE, "invalid"); preferenceMap.put(PortalPreferenceKeys.PAGE_SIZE, pageSizePref); PortalPreferenceForm form = new PortalPreferenceForm(preferenceMap); final BindingResult errors = new BeanPropertyBindingResult(form, "form"); SessionStatus sessionStatus = createMock(SessionStatus.class); replay(service, sessionStatus); String view = controller.updatePreferences(form, errors, validToken, validToken,REFERRER_ID, model, sessionStatus); assertEquals(ViewNames.ADMIN_PREFERENCE_DETAIL, view); assertTrue(errors.hasErrors()); assertTrue(model.containsAttribute("topnav")); assertTrue(model.containsAttribute("tabs")); assertFalse("Model has not been cleared", model.isEmpty()); verify(service, sessionStatus); }
@Test public void adminWidgets() throws Exception { Model model = new ExtendedModelMap(); PortalPreferenceService preferenceService = createMock(PortalPreferenceService.class); expect(preferenceService.getPreference(PortalPreferenceKeys.PAGE_SIZE)).andReturn(null); replay(preferenceService); SearchResult<Widget> widgetSearchResult = populateWidgetSearchResult(); expect(service.getLimitedList(DEFAULT_OFFSET, DEFAULT_PAGESIZE)).andReturn(widgetSearchResult); replay(service); String adminWidgetsView = controller.viewWidgets(DEFAULT_OFFSET, null,REFERRER_ID, model); verify(service); assertEquals(ViewNames.ADMIN_WIDGETS, adminWidgetsView); assertEquals(widgetSearchResult, model.asMap().get(ModelKeys.SEARCHRESULT)); assertTrue(model.containsAttribute(TABS)); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); }
@Test public void searchWidgets() throws Exception { Model model = new ExtendedModelMap(); String searchTerm = "widget"; String type = "OpenSocial"; String status = "published"; PortalPreferenceService preferenceService = createMock(PortalPreferenceService.class); expect(preferenceService.getPreference(PortalPreferenceKeys.PAGE_SIZE)).andReturn(null); replay(preferenceService); SearchResult<Widget> widgetSearchResult = populateWidgetSearchResult(); expect(service.getWidgetsBySearchCriteria(searchTerm, type, status, DEFAULT_OFFSET, DEFAULT_PAGESIZE)).andReturn(widgetSearchResult); replay(service); String searchView = controller.searchWidgets(searchTerm, type, status, DEFAULT_OFFSET,REFERRER_ID, model); verify(service); assertEquals(ViewNames.ADMIN_WIDGETS, searchView); assertEquals(searchTerm, model.asMap().get(ModelKeys.SEARCH_TERM)); assertEquals(type, model.asMap().get("selectedWidgetType")); assertEquals(status, model.asMap().get("selectedWidgetStatus")); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); }
@SuppressWarnings("unchecked") @Test public void viewAdminWidgetDetail() throws Exception { Model model = new ExtendedModelMap(); WidgetImpl widget = new WidgetImpl(); final String entityId = "123"; widget.setId(entityId); widget.setTitle("My widget"); expect(service.getWidget(entityId)).andReturn(widget); expect(categoryService.getAllList()).andReturn(categories); replay(service, categoryService); String adminWidgetDetailView = controller.viewWidgetDetail(entityId,REFERRER_ID, model); verify(service, categoryService); assertEquals(ViewNames.ADMIN_WIDGETDETAIL, adminWidgetDetailView); assertTrue(model.containsAttribute(TABS)); assertEquals(widget, model.asMap().get("widget")); assertThat(model.containsAttribute(ModelKeys.CATEGORIES), is(true)); assertThat((List<Category>) model.asMap().get(ModelKeys.CATEGORIES), is(categories)); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); }
@Test public void testSubmitWithInvalidPassword() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); Model uiModel = new ExtendedModelMap(); MockUser user = (MockUser) getApplicationContext().getBean("user"); user.setUserId(TEST_USER); user.setPassword(INVALID); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_MOCK_USER_KEY, user); request.setSession(session); BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName; try { viewName = getController().submit(request, response, uiModel, user, result); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect.", LOGIN_VIEW.equals(viewName)); }
@Test(expected = SecurityException.class) public void updateWidget_wrongToken() { WidgetImpl widget = new WidgetImpl(); BindingResult errors = new BeanPropertyBindingResult(widget, "widget"); SessionStatus sessionStatus = createMock(SessionStatus.class); ModelMap modelMap = new ExtendedModelMap(); sessionStatus.setComplete(); expectLastCall(); replay(sessionStatus); String otherToken = AdminControllerUtil.generateSessionToken(); controller.updateWidgetDetail(widget, errors, "sessionToken", otherToken,REFERRER_ID, modelMap, sessionStatus); verify(sessionStatus); assertFalse("Can't come here", true); }
@Test public void getCategories_valid(){ List<Category> categories = new ArrayList<Category>(); expect(categoryService.getAllList()).andReturn(categories); replay(categoryService); Model model = new ExtendedModelMap(); String viewName = controller.getCategories("",REFERRER_ID, model); verify(categoryService); assertEquals(ViewNames.ADMIN_CATEGORIES, viewName); assertEquals(categories, model.asMap().get("categories")); assertFalse(model.containsAttribute("actionresult")); assertTrue(model.containsAttribute("category")); assertEquals("Check that the category object available", new CategoryImpl(), model.asMap().get("category")); assertTrue(model.containsAttribute("topnav")); assertTrue(model.containsAttribute("tabs")); assertTrue("verify tokencheck", model.asMap().containsKey(ModelKeys.TOKENCHECK)); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); }
@Test public void getCategory_valid_create(){ List<Category> categories = new ArrayList<Category>(); expect(categoryService.getAllList()).andReturn(categories); replay(categoryService); Model model = new ExtendedModelMap(); String viewName = controller.getCategories(CREATE,REFERRER_ID, model); verify(categoryService); assertEquals(ViewNames.ADMIN_CATEGORIES, viewName); assertEquals(categories, model.asMap().get("categories")); assertTrue(model.containsAttribute("actionresult")); assertEquals(CREATE, model.asMap().get("actionresult")); assertTrue(model.containsAttribute("category")); assertEquals("Check category object available", new CategoryImpl(), model.asMap().get("category")); assertTrue(model.containsAttribute("topnav")); assertTrue(model.containsAttribute("tabs")); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); }
@Test public void createCategory_valid(){ Model model = new ExtendedModelMap(); User user = new UserImpl(); String categoryText = "Social"; CategoryImpl category = new CategoryImpl(); category.setText(categoryText); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); expect(categoryService.create(categoryText, user)).andReturn(new CategoryImpl()); sessionStatus.setComplete(); expectLastCall(); replay(userService, categoryService,sessionStatus); String view = controller.createCategory(category, validToken, validToken,REFERRER_ID, model, sessionStatus); assertEquals("ViewName match", "redirect:/app/admin/categories?action=create&referringPageId=" +REFERRER_ID, view); assertTrue("empty model", model.asMap().isEmpty()); verify(userService, categoryService, sessionStatus); }
@Test(expected = SecurityException.class) public void createCategory_invalidToken(){ Model model = new ExtendedModelMap(); String invalidToken = AdminControllerUtil.generateSessionToken(); User user = new UserImpl(); String categoryText = "Social"; CategoryImpl category = new CategoryImpl(); category.setText(categoryText); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); expect(categoryService.create(categoryText, user)).andReturn(new CategoryImpl()); sessionStatus.setComplete(); expectLastCall(); replay(userService, categoryService,sessionStatus); String view = controller.createCategory(category, validToken, invalidToken,REFERRER_ID, model, sessionStatus); assertTrue("Test should catch exception and never hit this test", false); }
@Test public void testSubmitWithNullUserId() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); Model uiModel = new ExtendedModelMap(); MockUser user = (MockUser) getApplicationContext().getBean("user"); user.setUserId(null); user.setPassword(TEST_PASSWORD); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_MOCK_USER_KEY, user); request.setSession(session); BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName; try { viewName = getController().submit(request, response, uiModel, user, result); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect.", LOGIN_VIEW.equals(viewName)); }
@Test(expected = SecurityException.class) public void updateCategory_invalidToken(){ Model model = new ExtendedModelMap(); User user = new UserImpl(); String id = "1"; String categoryText = "Social"; String invalidToken = AdminControllerUtil.generateSessionToken(); CategoryImpl category = new CategoryImpl(); category.setCreatedUserId(user.getId()); category.setText(categoryText); category.setId(id); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); expect(categoryService.get(id)).andReturn(category); expect(categoryService.update(id, categoryText, user)).andReturn(category); sessionStatus.setComplete(); expectLastCall(); replay(userService, categoryService,sessionStatus); String view = controller.updateCategory(category, validToken, invalidToken,REFERRER_ID, model, sessionStatus);assertTrue("Test should catch exception and never hit this test", false); assertTrue("Test should catch exception and never hit this test", false); }
@Test public void updateCategory_invalidValidRequest_emptyText(){ Model model = new ExtendedModelMap(); User user = new UserImpl(); String id = "1"; String categoryText = ""; CategoryImpl category = new CategoryImpl(); category.setCreatedUserId(user.getId()); category.setText(categoryText); category.setId(id); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); replay(userService); String view = controller.updateCategory(category, validToken, validToken,REFERRER_ID, model, sessionStatus); assertEquals("ViewName match", ViewNames.ADMIN_CATEGORY_DETAIL, view); assertFalse("empty model", model.asMap().isEmpty()); verify(userService); }
@Test public void updateCategory_invalidValidRequest_nullUser(){ Model model = new ExtendedModelMap(); String id = "1"; User user = new UserImpl(); String categoryText = "Social"; CategoryImpl category = new CategoryImpl(); category.setCreatedUserId(user.getId()); category.setText(categoryText); category.setId(id); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); replay(userService); String view = controller.updateCategory(category, validToken, validToken,REFERRER_ID, model, sessionStatus); assertEquals("ViewName match", ViewNames.ADMIN_CATEGORY_DETAIL, view); assertFalse("empty model", model.asMap().isEmpty()); verify(userService); }
@Test public void testRemoveFileFailOnService() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); Model uiModel = new ExtendedModelMap(); Long fileHash = Long.getLong("42"); File file = new File(); file.setId(fileHash); when(getFileService().findFileById(fileHash)).thenReturn(file); when(getFileService().removeFile(file)).thenReturn(false); String viewName; try { viewName = getController().removeFile(uiModel, request, fileHash); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); viewName = null; } assertTrue("Failed to remove file.", INDEX.equals(viewName)); }
@Test public void deleteCategory_valid(){ Model model = new ExtendedModelMap(); User user = new UserImpl(); String id = "1"; String categoryText = "Social"; CategoryImpl category = new CategoryImpl(); category.setCreatedUserId(user.getId()); category.setText(categoryText); category.setId(id); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); expect(categoryService.get(id)).andReturn(category).anyTimes(); categoryService.delete(category); expectLastCall(); sessionStatus.setComplete(); expectLastCall(); replay(userService, categoryService,sessionStatus); String view = controller.deleteCategory(category, validToken, validToken, "true",REFERRER_ID, model,sessionStatus); assertEquals("ViewName match", "redirect:/app/admin/categories?action=delete&referringPageId=" + REFERRER_ID, view); assertTrue("empty model", model.asMap().isEmpty()); verify(userService, categoryService, sessionStatus); }
@Test(expected = SecurityException.class) public void deleteCategory_invalidToken(){ Model model = new ExtendedModelMap(); User user = new UserImpl(); String id = "1"; String categoryText = "Social"; String invalidToken = AdminControllerUtil.generateSessionToken(); CategoryImpl category = new CategoryImpl(); category.setCreatedUserId(user.getId()); category.setText(categoryText); category.setId(id); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); expect(categoryService.get(id)).andReturn(category); categoryService.delete(category); expectLastCall(); sessionStatus.setComplete(); expectLastCall(); replay(userService, categoryService,sessionStatus); String view = controller.deleteCategory(category, validToken, invalidToken, "true",REFERRER_ID, model, sessionStatus);assertTrue("Test should catch exception and never hit this test", false); assertTrue("Test should catch exception and never hit this test", false); }
@Test public void deleteCategory_invalidValidRequest_emptyText(){ Model model = new ExtendedModelMap(); User user = new UserImpl(); String id = "1"; String categoryText = ""; CategoryImpl category = new CategoryImpl(); category.setCreatedUserId(user.getId()); category.setText(categoryText); category.setId(id); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); replay(userService); String view = controller.deleteCategory(category, validToken, validToken, "true",REFERRER_ID, model, sessionStatus); assertEquals("ViewName match", ViewNames.ADMIN_CATEGORY_DETAIL, view); assertFalse("empty model", model.asMap().isEmpty()); verify(userService); }
@Test public void deleteCategory_invalidValidRequest_falseConfirmation(){ Model model = new ExtendedModelMap(); User user = new UserImpl(); String id = "1"; String categoryText = "Social"; CategoryImpl category = new CategoryImpl(); category.setCreatedUserId(user.getId()); category.setText(categoryText); category.setId(id); SessionStatus sessionStatus = createMock(SessionStatus.class); expect(userService.getAuthenticatedUser()).andReturn(user).once(); replay(userService); String view = controller.deleteCategory(category, validToken, validToken,"false",REFERRER_ID, model, sessionStatus); assertEquals("ViewName match", ViewNames.ADMIN_CATEGORY_DETAIL, view); assertEquals("missing confirmation", true, model.asMap().get("missingConfirm")); verify(userService); }
@Test public void editCategory_valid () { User user = new UserImpl(); String id = "1"; String categoryText = "Social"; Model model = new ExtendedModelMap(); CategoryImpl category = new CategoryImpl(); category.setCreatedUserId(user.getId()); category.setText(categoryText); category.setId(id); expect(categoryService.get(id)).andReturn(category).once(); replay(categoryService); String view = controller.editCategory(id,REFERRER_ID, model); assertEquals("ViewName match", ViewNames.ADMIN_CATEGORY_DETAIL, view); assertFalse("model is not empty", model.asMap().isEmpty()); assertSame("check model object", category, model.asMap().get("category")); assertTrue("verify tokencheck", model.asMap().containsKey(ModelKeys.TOKENCHECK)); verify(categoryService); }
@Test public void adminUsers() throws Exception { Model model = new ExtendedModelMap(); final int offset = 0; final int pageSize = 10; final String referer = "http://example.com/index.html"; SearchResult<User> searchResult = createSearchResultWithTwoUsers(); expect(userService.getLimitedList(offset, pageSize)).andReturn(searchResult); replay(userService); String adminUsersView = controller.viewUsers(offset, referer,REFERRER_ID, model); assertEquals(ViewNames.ADMIN_USERS, adminUsersView); assertEquals(searchResult, model.asMap().get(ModelKeys.SEARCHRESULT)); assertTrue(model.containsAttribute(TABS)); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); }
@Test public void searchUsers() throws Exception { Model model = new ExtendedModelMap(); final String searchTerm = "Doe"; final int offset = 0; final int pageSize = 10; SearchResult<User> searchResult = createSearchResultWithTwoUsers(); expect(userService.getUsersByFreeTextSearch(searchTerm, offset, pageSize)).andReturn(searchResult); replay(userService); String adminUsersView = controller.searchUsers(searchTerm, offset,REFERRER_ID, model); assertEquals(ViewNames.ADMIN_USERS, adminUsersView); assertEquals(searchResult, model.asMap().get(ModelKeys.SEARCHRESULT)); assertEquals(searchTerm, model.asMap().get(ModelKeys.SEARCH_TERM)); assertTrue(model.containsAttribute(TABS)); assertThat((String) model.asMap().get(ModelKeys.REFERRING_PAGE_ID), is(equalTo(REFERRER_ID))); }