private ArgumentCaptor<HttpHeaders> setupInfoRequest(boolean webSocketEnabled) { ArgumentCaptor<HttpHeaders> headersCaptor = ArgumentCaptor.forClass(HttpHeaders.class); when(this.infoReceiver.executeInfoRequest(any(), headersCaptor.capture())).thenReturn( "{\"entropy\":123," + "\"origins\":[\"*:*\"]," + "\"cookie_needed\":true," + "\"websocket\":" + webSocketEnabled + "}"); return headersCaptor; }
@Test public void headerConversionLazilyInvoked() throws JMSException { javax.jms.Message jmsMessage = mock(javax.jms.Message.class); when(jmsMessage.getPropertyNames()).thenThrow(new IllegalArgumentException("Header failure")); MessagingMessageListenerAdapter listener = getSimpleInstance("simple", Message.class); Message<?> message = listener.toMessagingMessage(jmsMessage); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Header failure"); message.getHeaders(); // Triggers headers resolution }
@Test public void handleMessage() { TestSimpUser simpUser = new TestSimpUser("joe"); simpUser.addSessions(new TestSimpSession("123")); when(this.registry.getUser("joe")).thenReturn(simpUser); given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true); this.handler.handleMessage(createWith(SimpMessageType.MESSAGE, "joe", "123", "/user/joe/queue/foo")); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); Mockito.verify(this.brokerChannel).send(captor.capture()); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(captor.getValue()); assertEquals("/queue/foo-user123", accessor.getDestination()); assertEquals("/user/queue/foo", accessor.getFirstNativeHeader(ORIGINAL_DESTINATION)); }
private void setUpSessions() { Session session1 = createSession(SESSION_ID, USER_NAME, NOW); session1.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE); Session session2 = createSession(SESSION_ID2, USER_NAME, NOW); Map<String, Session> sessions = new LinkedHashMap<>(); sessions.put(session1.getId(), session1); sessions.put(session2.getId(), session2); when(this.sessionRepository.findByPrincipalName(USER_NAME)) .thenReturn(sessions); }
@Test public void testExpressionInStringArray() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); BeanExpressionResolver beanExpressionResolver = mock(BeanExpressionResolver.class); when(beanExpressionResolver.evaluate(eq("#{foo}"), ArgumentMatchers.any(BeanExpressionContext.class))) .thenReturn("classpath:/org/springframework/beans/factory/xml/util.properties"); bf.setBeanExpressionResolver(beanExpressionResolver); RootBeanDefinition rbd = new RootBeanDefinition(PropertiesFactoryBean.class); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("locations", new String[]{"#{foo}"}); rbd.setPropertyValues(pvs); bf.registerBeanDefinition("myProperties", rbd); Properties properties = (Properties) bf.getBean("myProperties"); assertEquals("bar", properties.getProperty("foo")); }
@Test public void expireNow() { Session session = createSession(SESSION_ID, USER_NAME, NOW); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); SessionInformation sessionInfo = this.sessionRegistry .getSessionInformation(SESSION_ID); assertThat(sessionInfo.isExpired()).isFalse(); sessionInfo.expireNow(); assertThat(sessionInfo.isExpired()).isTrue(); ArgumentCaptor<Session> captor = ArgumentCaptor.forClass(Session.class); verify(this.sessionRepository).save(captor.capture()); assertThat(captor.getValue().<Boolean>getAttribute( SpringSessionBackedSessionInformation.EXPIRED_ATTR)) .isEqualTo(Boolean.TRUE); }
@Test public void sessionInformationForExistingSession() { Session session = createSession(SESSION_ID, USER_NAME, NOW); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); SessionInformation sessionInfo = this.sessionRegistry .getSessionInformation(SESSION_ID); assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID); assertThat( sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS)); assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME); assertThat(sessionInfo.isExpired()).isFalse(); }
@Test public void sessionInformationForExpiredSession() { Session session = createSession(SESSION_ID, USER_NAME, NOW); session.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); SessionInformation sessionInfo = this.sessionRegistry .getSessionInformation(SESSION_ID); assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID); assertThat( sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS)); assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME); assertThat(sessionInfo.isExpired()).isTrue(); }
private Session createSession(String sessionId, String userName, Instant lastAccessed) { MapSession session = new MapSession(sessionId); session.setLastAccessedTime(lastAccessed); Authentication authentication = mock(Authentication.class); when(authentication.getName()).thenReturn(userName); SecurityContextImpl securityContext = new SecurityContextImpl(); securityContext.setAuthentication(authentication); session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext); return session; }
@Test public void handleMessageFromBrokerWithActiveSession() { TestSimpUser simpUser = new TestSimpUser("joe"); simpUser.addSessions(new TestSimpSession("123")); when(this.registry.getUser("joe")).thenReturn(simpUser); this.handler.setBroadcastDestination("/topic/unresolved"); given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.MESSAGE); accessor.setSessionId("system123"); accessor.setDestination("/topic/unresolved"); accessor.setNativeHeader(ORIGINAL_DESTINATION, "/user/joe/queue/foo"); accessor.setNativeHeader("customHeader", "customHeaderValue"); accessor.setLeaveMutable(true); byte[] payload = "payload".getBytes(StandardCharsets.UTF_8); this.handler.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); Mockito.verify(this.brokerChannel).send(captor.capture()); assertNotNull(captor.getValue()); SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(captor.getValue()); assertEquals("/queue/foo-user123", headers.getDestination()); assertEquals("/user/queue/foo", headers.getFirstNativeHeader(ORIGINAL_DESTINATION)); assertEquals("customHeaderValue", headers.getFirstNativeHeader("customHeader")); assertArrayEquals(payload, (byte[]) captor.getValue().getPayload()); }
@Test // SPR-14210 public void resourceLoaderPath() throws Exception { MockServletContext servletContext = new MockServletContext(); this.wac.setServletContext(servletContext); this.wac.refresh(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.wac); MockHttpServletResponse response = new MockHttpServletResponse(); Map<String, Object> model = new HashMap<>(); InvocableScriptEngine engine = mock(InvocableScriptEngine.class); when(engine.invokeFunction(any(), any(), any(), any())).thenReturn("foo"); this.view.setEngine(engine); this.view.setRenderFunction("render"); this.view.setApplicationContext(this.wac); this.view.setUrl("org/springframework/web/servlet/view/script/empty.txt"); this.view.render(model, request, response); assertEquals("foo", response.getContentAsString()); response = new MockHttpServletResponse(); this.view.setResourceLoaderPath("classpath:org/springframework/web/servlet/view/script/"); this.view.setUrl("empty.txt"); this.view.render(model, request, response); assertEquals("foo", response.getContentAsString()); response = new MockHttpServletResponse(); this.view.setResourceLoaderPath("classpath:org/springframework/web/servlet/view/script"); this.view.setUrl("empty.txt"); this.view.render(model, request, response); assertEquals("foo", response.getContentAsString()); }
@Test public void testViewMap() { UIViewRoot viewRoot = mock(UIViewRoot.class); when(this.facesContext.getViewRoot()).thenReturn(viewRoot); assertThat(this.jsfBeansAutoConfiguration.viewRoot()).isEqualTo(viewRoot); Map<String, Object> map = Collections.emptyMap(); when(viewRoot.getViewMap()).thenReturn(map); assertThat(this.jsfBeansAutoConfiguration.viewMap()).isSameAs(map); } }
@Test public void processEvent() { PreDestroyViewMapEvent event = mock(PreDestroyViewMapEvent.class); UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot(); when(event.getSource()).thenReturn(viewRoot); this.viewScope.getPreDestroyViewMapListener().processEvent(event); }
@Test public void testRequestMap() { HashMap<String, Object> map = new HashMap<>(); when(this.jsfBeansAutoConfiguration.requestMap()).thenReturn(map); Object bean = new Object() { @Autowired @RequestMap private Map<String, Object> map; }; this.jsfBeansAnnotationPostProcessor.postProcessBeforeInitialization(bean, ""); verify(this.jsfBeansAutoConfiguration).requestMap(); assertThat(bean).hasFieldOrPropertyWithValue("map", map); }
@Test public void testApplicationMap() { HashMap<String, Object> map = new HashMap<>(); when(this.jsfBeansAutoConfiguration.applicationMap()).thenReturn(map); Object bean = new Object() { @Autowired @ApplicationMap private Map<String, Object> map; }; this.jsfBeansAnnotationPostProcessor.postProcessBeforeInitialization(bean, ""); verify(this.jsfBeansAutoConfiguration).applicationMap(); assertThat(bean).hasFieldOrPropertyWithValue("map", map); }
@Test public void testHeaderValuesMap() { HashMap<String, String[]> map = new HashMap<>(); when(this.jsfBeansAutoConfiguration.headerValuesMap()).thenReturn(map); Object bean = new Object() { @Autowired @HeaderValuesMap private Map<String, Object> map; }; this.jsfBeansAnnotationPostProcessor.postProcessBeforeInitialization(bean, ""); verify(this.jsfBeansAutoConfiguration).headerValuesMap(); assertThat(bean).hasFieldOrPropertyWithValue("map", map); }
@Test public void testRequestCookieMap() { HashMap<String, Object> map = new HashMap<>(); when(this.jsfBeansAutoConfiguration.requestCookieMap()).thenReturn(map); Object bean = new Object() { @Autowired @RequestCookieMap private Map<String, Object> map; }; this.jsfBeansAnnotationPostProcessor.postProcessBeforeInitialization(bean, ""); verify(this.jsfBeansAutoConfiguration).requestCookieMap(); assertThat(bean).hasFieldOrPropertyWithValue("map", map); }
@Test public void testServletContextAttributes_added() { this.webApplicationContextRunner .run(context -> { ServletRegistrationBean<FacesServlet> facesServletRegistrationBean = (ServletRegistrationBean<FacesServlet>) context.getBean("facesServletRegistrationBean"); ServletContext servletContext = mock(ServletContext.class); when(servletContext.addServlet(anyString(), any(Servlet.class))).thenReturn(mock(ServletRegistration.Dynamic.class)); facesServletRegistrationBean.onStartup(servletContext); verify(servletContext, times(2)).setAttribute(any(), any()); }); }
@Test public void testCleanup() { ViewScope.DestructionCallbackWrapper mock1 = mock(ViewScope.DestructionCallbackWrapper.class); ViewScope.DestructionCallbackWrapper mock2 = mock(ViewScope.DestructionCallbackWrapper.class); this.sessionListener.register(mock1); this.sessionListener.register(mock2); assertThat(this.sessionListener.getDestructionCallbackWrappers()).containsExactly(mock1, mock2); when(mock1.isCallbackCalled()).thenReturn(true); this.sessionListener.cleanup(); assertThat(this.sessionListener.getDestructionCallbackWrappers()).containsExactly(mock2); } }
@Test public void testJsfManagedBeans() { this.applicationContextRunner .withUserConfiguration(DummyConfiguration.class) .run(context -> { assertThat(context.getBeanNamesForAnnotation(ManagedBean.class)).isNotEmpty(); ApplicationStartedEvent applicationStartedEvent = mock(ApplicationStartedEvent.class); when(applicationStartedEvent.getApplicationContext()).thenReturn(context.getSourceApplicationContext()); this.joinfacesApplicationAnalyzer.onApplicationEvent(applicationStartedEvent); }); }