Additional Checkstyle Fixes

Issue gh-393
This commit is contained in:
Rob Winch
2016-03-07 15:32:03 -06:00
parent 7f3302253b
commit f0200696ef
189 changed files with 4591 additions and 3201 deletions

View File

@@ -37,7 +37,8 @@ public class MapSessionRepositoryTests {
@Test
public void getSessionExpired() {
this.session.setMaxInactiveIntervalInSeconds(1);
this.session.setLastAccessedTime(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
this.session.setLastAccessedTime(
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
this.repository.save(this.session);
assertThat(this.repository.getSession(this.session.getId())).isNull();
@@ -48,16 +49,19 @@ public class MapSessionRepositoryTests {
ExpiringSession session = this.repository.createSession();
assertThat(session).isInstanceOf(MapSession.class);
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
}
@Test
public void createSessionCustomDefaultExpiration() {
final int expectedMaxInterval = new MapSession().getMaxInactiveIntervalInSeconds() + 10;
final int expectedMaxInterval = new MapSession().getMaxInactiveIntervalInSeconds()
+ 10;
this.repository.setDefaultMaxInactiveInterval(expectedMaxInterval);
ExpiringSession session = this.repository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInterval);
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(expectedMaxInterval);
}
}

View File

@@ -78,7 +78,8 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests {
@Test
public void usesReadSessionIds() throws Exception {
String sessionId = "sessionId";
given(this.cookieSerializer.readCookieValues(any(HttpServletRequest.class))).willReturn(Arrays.asList(sessionId));
given(this.cookieSerializer.readCookieValues(any(HttpServletRequest.class)))
.willReturn(Arrays.asList(sessionId));
this.sessionRepositoryFilter.doFilter(this.request, this.response, this.chain);
@@ -87,15 +88,16 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests {
@Test
public void usesWrite() throws Exception {
this.sessionRepositoryFilter.doFilter(this.request, this.response, new MockFilterChain() {
this.sessionRepositoryFilter.doFilter(this.request, this.response,
new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletRequest) request).getSession();
super.doFilter(request, response);
}
});
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletRequest) request).getSession();
super.doFilter(request, response);
}
});
verify(this.cookieSerializer).writeCookieValue(any(CookieValue.class));
}

View File

@@ -70,13 +70,17 @@ public class EnableSpringHttpSessionCustomMultiHttpSessionStrategyTests {
@Test
public void wrapRequestAndResponseUsed() throws Exception {
given(this.strategy.wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(this.request);
given(this.strategy.wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(this.response);
given(this.strategy.wrapRequest(any(HttpServletRequest.class),
any(HttpServletResponse.class))).willReturn(this.request);
given(this.strategy.wrapResponse(any(HttpServletRequest.class),
any(HttpServletResponse.class))).willReturn(this.response);
this.sessionRepositoryFilter.doFilter(this.request, this.response, this.chain);
verify(this.strategy).wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.strategy).wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.strategy).wrapRequest(any(HttpServletRequest.class),
any(HttpServletResponse.class));
verify(this.strategy).wrapResponse(any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@EnableSpringHttpSession

View File

@@ -55,8 +55,8 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* The GemFireOperationsSessionRepositoryTest class is a test suite of test cases testing the contract and functionality
* of the GemFireOperationsSessionRepository class.
* The GemFireOperationsSessionRepositoryTest class is a test suite of test cases testing
* the contract and functionality of the GemFireOperationsSessionRepository class.
*
* @author John Blum
* @since 1.1.0
@@ -89,23 +89,32 @@ public class GemFireOperationsSessionRepositoryTest {
@Before
public void setup() throws Exception {
given(this.mockRegion.getAttributesMutator()).willReturn(this.mockAttributesMutator);
given(this.mockRegion.getAttributesMutator())
.willReturn(this.mockAttributesMutator);
given(this.mockRegion.getFullPath()).willReturn("/Example");
given(this.mockTemplate.<Object, ExpiringSession>getRegion()).willReturn(this.mockRegion);
given(this.mockTemplate.<Object, ExpiringSession>getRegion())
.willReturn(this.mockRegion);
this.sessionRepository = new GemFireOperationsSessionRepository(this.mockTemplate);
this.sessionRepository.setApplicationEventPublisher(this.mockApplicationEventPublisher);
this.sessionRepository.setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS);
this.sessionRepository = new GemFireOperationsSessionRepository(
this.mockTemplate);
this.sessionRepository
.setApplicationEventPublisher(this.mockApplicationEventPublisher);
this.sessionRepository
.setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS);
this.sessionRepository.afterPropertiesSet();
assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(this.mockApplicationEventPublisher);
assertThat(this.sessionRepository.getFullyQualifiedRegionName()).isEqualTo("/Example");
assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
assertThat(this.sessionRepository.getApplicationEventPublisher())
.isSameAs(this.mockApplicationEventPublisher);
assertThat(this.sessionRepository.getFullyQualifiedRegionName())
.isEqualTo("/Example");
assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds())
.isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
}
@After
public void tearDown() {
verify(this.mockAttributesMutator, times(1)).addCacheListener(same(this.sessionRepository));
verify(this.mockAttributesMutator, times(1))
.addCacheListener(same(this.sessionRepository));
verify(this.mockRegion, times(1)).getFullPath();
verify(this.mockTemplate, times(1)).getRegion();
}
@@ -119,17 +128,21 @@ public class GemFireOperationsSessionRepositoryTest {
SelectResults<Object> mockSelectResults = mock(SelectResults.class);
given(mockSelectResults.asList()).willReturn(Collections.<Object>singletonList(mockSession));
given(mockSelectResults.asList())
.willReturn(Collections.<Object>singletonList(mockSession));
String indexName = "vip";
String indexValue = "rwinch";
String expectedQql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY,
String expectedQql = String.format(
GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY,
this.sessionRepository.getFullyQualifiedRegionName(), indexName);
given(this.mockTemplate.find(eq(expectedQql), eq(indexValue))).willReturn(mockSelectResults);
given(this.mockTemplate.find(eq(expectedQql), eq(indexValue)))
.willReturn(mockSelectResults);
Map<String, ExpiringSession> sessions = this.sessionRepository.findByIndexNameAndIndexValue(indexName, indexValue);
Map<String, ExpiringSession> sessions = this.sessionRepository
.findByIndexNameAndIndexValue(indexName, indexValue);
assertThat(sessions).isNotNull();
assertThat(sessions.size()).isEqualTo(1);
@@ -145,7 +158,8 @@ public class GemFireOperationsSessionRepositoryTest {
public void findByPrincipalNameFindsMatchingSessions() throws Exception {
ExpiringSession mockSessionOne = mock(ExpiringSession.class, "MockSessionOne");
ExpiringSession mockSessionTwo = mock(ExpiringSession.class, "MockSessionTwo");
ExpiringSession mockSessionThree = mock(ExpiringSession.class, "MockSessionThree");
ExpiringSession mockSessionThree = mock(ExpiringSession.class,
"MockSessionThree");
given(mockSessionOne.getId()).willReturn("1");
given(mockSessionTwo.getId()).willReturn("2");
@@ -153,17 +167,22 @@ public class GemFireOperationsSessionRepositoryTest {
SelectResults<Object> mockSelectResults = mock(SelectResults.class);
given(mockSelectResults.asList()).willReturn(Arrays.<Object>asList(mockSessionOne, mockSessionTwo, mockSessionThree));
given(mockSelectResults.asList()).willReturn(
Arrays.<Object>asList(mockSessionOne, mockSessionTwo, mockSessionThree));
String principalName = "jblum";
String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
String expectedOql = String.format(
GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
this.sessionRepository.getFullyQualifiedRegionName());
given(this.mockTemplate.find(eq(expectedOql), eq(principalName))).willReturn(mockSelectResults);
given(this.mockTemplate.find(eq(expectedOql), eq(principalName)))
.willReturn(mockSelectResults);
Map<String, ExpiringSession> sessions = this.sessionRepository.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName);
Map<String, ExpiringSession> sessions = this.sessionRepository
.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
principalName);
assertThat(sessions).isNotNull();
assertThat(sessions.size()).isEqualTo(3);
@@ -187,13 +206,17 @@ public class GemFireOperationsSessionRepositoryTest {
String principalName = "jblum";
String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
String expectedOql = String.format(
GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
this.sessionRepository.getFullyQualifiedRegionName());
given(this.mockTemplate.find(eq(expectedOql), eq(principalName))).willReturn(mockSelectResults);
given(this.mockTemplate.find(eq(expectedOql), eq(principalName)))
.willReturn(mockSelectResults);
Map<String, ExpiringSession> sessions = this.sessionRepository.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName);
Map<String, ExpiringSession> sessions = this.sessionRepository
.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
principalName);
assertThat(sessions).isNotNull();
assertThat(sessions.isEmpty()).isTrue();
@@ -204,8 +227,10 @@ public class GemFireOperationsSessionRepositoryTest {
@Test
public void prepareQueryReturnsPrincipalNameOql() {
String actualQql = this.sessionRepository.prepareQuery(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
String actualQql = this.sessionRepository
.prepareQuery(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
String expectedOql = String.format(
GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
this.sessionRepository.getFullyQualifiedRegionName());
assertThat(actualQql).isEqualTo(expectedOql);
@@ -215,7 +240,8 @@ public class GemFireOperationsSessionRepositoryTest {
public void prepareQueryReturnsIndexNameValueOql() {
String attributeName = "testAttributeName";
String actualOql = this.sessionRepository.prepareQuery(attributeName);
String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY,
String expectedOql = String.format(
GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY,
this.sessionRepository.getFullyQualifiedRegionName(), attributeName);
assertThat(actualOql).isEqualTo(expectedOql);
@@ -227,12 +253,16 @@ public class GemFireOperationsSessionRepositoryTest {
ExpiringSession session = this.sessionRepository.createSession();
assertThat(session).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class);
assertThat(session).isInstanceOf(
AbstractGemFireOperationsSessionRepository.GemFireSession.class);
assertThat(session.getId()).isNotNull();
assertThat(session.getAttributeNames().isEmpty()).isTrue();
assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime);
assertThat(session.getLastAccessedTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime);
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
assertThat(session.getCreationTime())
.isGreaterThanOrEqualTo(beforeOrAtCreationTime);
assertThat(session.getLastAccessedTime())
.isGreaterThanOrEqualTo(beforeOrAtCreationTime);
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
}
@Test
@@ -248,19 +278,22 @@ public class GemFireOperationsSessionRepositoryTest {
willAnswer(new Answer<Void>() {
public Void answer(final InvocationOnMock invocation) throws Throwable {
ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class);
ApplicationEvent applicationEvent = invocation.getArgumentAt(0,
ApplicationEvent.class);
assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class);
AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent;
assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSource()).isSameAs(
GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSession()).isSameAs(mockSession);
assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId);
return null;
}
}).given(this.mockApplicationEventPublisher).publishEvent(any(ApplicationEvent.class));
}).given(this.mockApplicationEventPublisher)
.publishEvent(any(ApplicationEvent.class));
assertThat(this.sessionRepository.getSession(expectedSessionId)).isNull();
@@ -268,7 +301,8 @@ public class GemFireOperationsSessionRepositoryTest {
verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(mockSession, times(1)).isExpired();
verify(mockSession, times(2)).getId();
verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
verify(this.mockApplicationEventPublisher, times(1))
.publishEvent(isA(SessionDeletedEvent.class));
}
@Test
@@ -276,7 +310,8 @@ public class GemFireOperationsSessionRepositoryTest {
final String expectedId = "1";
final long expectedCreationTime = System.currentTimeMillis();
final long currentLastAccessedTime = (expectedCreationTime + TimeUnit.MINUTES.toMillis(5));
final long currentLastAccessedTime = (expectedCreationTime
+ TimeUnit.MINUTES.toMillis(5));
ExpiringSession mockSession = mock(ExpiringSession.class);
@@ -284,7 +319,8 @@ public class GemFireOperationsSessionRepositoryTest {
given(mockSession.getId()).willReturn(expectedId);
given(mockSession.getCreationTime()).willReturn(expectedCreationTime);
given(mockSession.getLastAccessedTime()).willReturn(currentLastAccessedTime);
given(mockSession.getAttributeNames()).willReturn(Collections.singleton("attrOne"));
given(mockSession.getAttributeNames())
.willReturn(Collections.singleton("attrOne"));
given(mockSession.getAttribute(eq("attrOne"))).willReturn("test");
given(this.mockTemplate.get(eq(expectedId))).willReturn(mockSession);
@@ -293,10 +329,14 @@ public class GemFireOperationsSessionRepositoryTest {
assertThat(actualSession).isNotSameAs(mockSession);
assertThat(actualSession.getId()).isEqualTo(expectedId);
assertThat(actualSession.getCreationTime()).isEqualTo(expectedCreationTime);
assertThat(actualSession.getLastAccessedTime()).isNotEqualTo(currentLastAccessedTime);
assertThat(actualSession.getLastAccessedTime()).isGreaterThanOrEqualTo(expectedCreationTime);
assertThat(actualSession.getAttributeNames()).isEqualTo(Collections.singleton("attrOne"));
assertThat(String.valueOf(actualSession.getAttribute("attrOne"))).isEqualTo("test");
assertThat(actualSession.getLastAccessedTime())
.isNotEqualTo(currentLastAccessedTime);
assertThat(actualSession.getLastAccessedTime())
.isGreaterThanOrEqualTo(expectedCreationTime);
assertThat(actualSession.getAttributeNames())
.isEqualTo(Collections.singleton("attrOne"));
assertThat(String.valueOf(actualSession.getAttribute("attrOne")))
.isEqualTo("test");
verify(this.mockTemplate, times(1)).get(eq(expectedId));
verify(mockSession, times(1)).isExpired();
@@ -318,31 +358,40 @@ public class GemFireOperationsSessionRepositoryTest {
final String expectedSessionId = "1";
final long expectedCreationTime = System.currentTimeMillis();
final long expectedLastAccessTime = (expectedCreationTime + TimeUnit.MINUTES.toMillis(5));
final long expectedLastAccessTime = (expectedCreationTime
+ TimeUnit.MINUTES.toMillis(5));
ExpiringSession mockSession = mock(ExpiringSession.class);
given(mockSession.getId()).willReturn(expectedSessionId);
given(mockSession.getCreationTime()).willReturn(expectedCreationTime);
given(mockSession.getLastAccessedTime()).willReturn(expectedLastAccessTime);
given(mockSession.getMaxInactiveIntervalInSeconds()).willReturn(MAX_INACTIVE_INTERVAL_IN_SECONDS);
given(mockSession.getMaxInactiveIntervalInSeconds())
.willReturn(MAX_INACTIVE_INTERVAL_IN_SECONDS);
given(mockSession.getAttributeNames()).willReturn(Collections.<String>emptySet());
given(this.mockTemplate.put(eq(expectedSessionId), isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class)))
.willAnswer(new Answer<ExpiringSession>() {
public ExpiringSession answer(final InvocationOnMock invocation) throws Throwable {
ExpiringSession session = invocation.getArgumentAt(1, ExpiringSession.class);
given(this.mockTemplate.put(eq(expectedSessionId),
isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class)))
.willAnswer(new Answer<ExpiringSession>() {
public ExpiringSession answer(
final InvocationOnMock invocation) throws Throwable {
ExpiringSession session = invocation.getArgumentAt(1,
ExpiringSession.class);
assertThat(session).isNotNull();
assertThat(session.getId()).isEqualTo(expectedSessionId);
assertThat(session.getCreationTime()).isEqualTo(expectedCreationTime);
assertThat(session.getLastAccessedTime()).isEqualTo(expectedLastAccessTime);
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
assertThat(session.getAttributeNames().isEmpty()).isTrue();
assertThat(session).isNotNull();
assertThat(session.getId()).isEqualTo(expectedSessionId);
assertThat(session.getCreationTime())
.isEqualTo(expectedCreationTime);
assertThat(session.getLastAccessedTime())
.isEqualTo(expectedLastAccessTime);
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
assertThat(session.getAttributeNames().isEmpty())
.isTrue();
return null;
}
});
return null;
}
});
this.sessionRepository.save(mockSession);
@@ -351,7 +400,8 @@ public class GemFireOperationsSessionRepositoryTest {
verify(mockSession, times(1)).getLastAccessedTime();
verify(mockSession, times(1)).getMaxInactiveIntervalInSeconds();
verify(mockSession, times(1)).getAttributeNames();
verify(this.mockTemplate, times(1)).put(eq(expectedSessionId), isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class));
verify(this.mockTemplate, times(1)).put(eq(expectedSessionId),
isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class));
}
@Test
@@ -365,25 +415,29 @@ public class GemFireOperationsSessionRepositoryTest {
willAnswer(new Answer<Void>() {
public Void answer(final InvocationOnMock invocation) throws Throwable {
ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class);
ApplicationEvent applicationEvent = invocation.getArgumentAt(0,
ApplicationEvent.class);
assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class);
AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent;
assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSource()).isSameAs(
GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSession()).isSameAs(mockSession);
assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId);
return null;
}
}).given(this.mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class));
}).given(this.mockApplicationEventPublisher)
.publishEvent(isA(SessionDeletedEvent.class));
this.sessionRepository.delete(expectedSessionId);
verify(mockSession, times(1)).getId();
verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
verify(this.mockApplicationEventPublisher, times(1))
.publishEvent(isA(SessionDeletedEvent.class));
}
@Test
@@ -394,27 +448,32 @@ public class GemFireOperationsSessionRepositoryTest {
willAnswer(new Answer<Void>() {
public Void answer(final InvocationOnMock invocation) throws Throwable {
ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class);
ApplicationEvent applicationEvent = invocation.getArgumentAt(0,
ApplicationEvent.class);
assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class);
AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent;
assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSource()).isSameAs(
GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSession()).isNull();
assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId);
return null;
}
}).given(this.mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class));
}).given(this.mockApplicationEventPublisher)
.publishEvent(isA(SessionDeletedEvent.class));
this.sessionRepository.delete(expectedSessionId);
verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
verify(this.mockApplicationEventPublisher, times(1))
.publishEvent(isA(SessionDeletedEvent.class));
}
protected abstract class GemfireOperationsAccessor extends GemfireAccessor implements GemfireOperations {
protected abstract class GemfireOperationsAccessor extends GemfireAccessor
implements GemfireOperations {
}
}

View File

@@ -41,8 +41,8 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* The GemFireHttpSessionConfigurationTest class is a test suite of test cases testing the contract and functionality
* of the {@link GemFireHttpSessionConfiguration} class.
* The GemFireHttpSessionConfigurationTest class is a test suite of test cases testing the
* contract and functionality of the {@link GemFireHttpSessionConfiguration} class.
*
* @author John Blum
* @since 1.1.0
@@ -51,7 +51,8 @@ import static org.mockito.Mockito.verify;
* @see org.springframework.data.gemfire.GemfireOperations
* @see org.springframework.data.gemfire.GemfireTemplate
* @see org.springframework.session.data.gemfire.GemFireOperationsSessionRepository
* @see org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration
* @see org.springframework.session.data.gemfire.config.annotation.web.http.
* GemFireHttpSessionConfiguration
* @see com.gemstone.gemfire.cache.Cache
* @see com.gemstone.gemfire.cache.GemFireCache
* @see com.gemstone.gemfire.cache.Region
@@ -74,9 +75,11 @@ public class GemFireHttpSessionConfigurationTest {
public void setAndGetBeanClassLoader() {
assertThat(this.gemfireConfiguration.getBeanClassLoader()).isNull();
this.gemfireConfiguration.setBeanClassLoader(Thread.currentThread().getContextClassLoader());
this.gemfireConfiguration
.setBeanClassLoader(Thread.currentThread().getContextClassLoader());
assertThat(this.gemfireConfiguration.getBeanClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader());
assertThat(this.gemfireConfiguration.getBeanClassLoader())
.isEqualTo(Thread.currentThread().getContextClassLoader());
this.gemfireConfiguration.setBeanClassLoader(null);
@@ -86,138 +89,168 @@ public class GemFireHttpSessionConfigurationTest {
@Test
public void setAndGetClientRegionShortcut() {
assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT);
GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT);
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY);
this.gemfireConfiguration
.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY);
assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY);
assertThat(this.gemfireConfiguration.getClientRegionShortcut())
.isEqualTo(ClientRegionShortcut.CACHING_PROXY);
this.gemfireConfiguration.setClientRegionShortcut(null);
assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT);
GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT);
}
@Test
public void setAndGetIndexableSessionAttributes() {
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_INDEXABLE_SESSION_ATTRIBUTES);
GemFireHttpSessionConfiguration.DEFAULT_INDEXABLE_SESSION_ATTRIBUTES);
this.gemfireConfiguration.setIndexableSessionAttributes(toArray("one", "two", "three"));
this.gemfireConfiguration
.setIndexableSessionAttributes(toArray("one", "two", "three"));
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three"));
assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression())
.isEqualTo("'one', 'two', 'three'");
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes())
.isEqualTo(toArray("one", "two", "three"));
assertThat(this.gemfireConfiguration
.getIndexableSessionAttributesAsGemFireIndexExpression())
.isEqualTo("'one', 'two', 'three'");
this.gemfireConfiguration.setIndexableSessionAttributes(toArray("one"));
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one"));
assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("'one'");
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes())
.isEqualTo(toArray("one"));
assertThat(this.gemfireConfiguration
.getIndexableSessionAttributesAsGemFireIndexExpression())
.isEqualTo("'one'");
this.gemfireConfiguration.setIndexableSessionAttributes(null);
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_INDEXABLE_SESSION_ATTRIBUTES);
assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("*");
GemFireHttpSessionConfiguration.DEFAULT_INDEXABLE_SESSION_ATTRIBUTES);
assertThat(this.gemfireConfiguration
.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("*");
}
@Test
public void setAndGetMaxInactiveIntervalInSeconds() {
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS);
GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(300);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(300);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds())
.isEqualTo(300);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MAX_VALUE);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MAX_VALUE);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds())
.isEqualTo(Integer.MAX_VALUE);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(-1);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(-1);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds())
.isEqualTo(-1);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MIN_VALUE);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MIN_VALUE);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds())
.isEqualTo(Integer.MIN_VALUE);
}
@Test
public void setAndGetServerRegionShortcut() {
assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT);
GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PERSISTENT);
this.gemfireConfiguration
.setServerRegionShortcut(RegionShortcut.REPLICATE_PERSISTENT);
assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE_PERSISTENT);
assertThat(this.gemfireConfiguration.getServerRegionShortcut())
.isEqualTo(RegionShortcut.REPLICATE_PERSISTENT);
this.gemfireConfiguration.setServerRegionShortcut(null);
assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT);
GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT);
}
@Test
public void setAndGetSpringSessionGemFireRegionName() {
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName())
.isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
this.gemfireConfiguration.setSpringSessionGemFireRegionName("test");
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("test");
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName())
.isEqualTo("test");
this.gemfireConfiguration.setSpringSessionGemFireRegionName(" ");
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName())
.isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
this.gemfireConfiguration.setSpringSessionGemFireRegionName("");
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName())
.isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
this.gemfireConfiguration.setSpringSessionGemFireRegionName(null);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName())
.isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
}
@Test
public void setImportMetadata() {
AnnotationMetadata mockAnnotationMetadata = mock(AnnotationMetadata.class, "testSetImportMetadata");
AnnotationMetadata mockAnnotationMetadata = mock(AnnotationMetadata.class,
"testSetImportMetadata");
Map<String, Object> annotationAttributes = new HashMap<String, Object>(4);
annotationAttributes.put("clientRegionShortcut", ClientRegionShortcut.CACHING_PROXY);
annotationAttributes.put("indexableSessionAttributes", toArray("one", "two", "three"));
annotationAttributes.put("clientRegionShortcut",
ClientRegionShortcut.CACHING_PROXY);
annotationAttributes.put("indexableSessionAttributes",
toArray("one", "two", "three"));
annotationAttributes.put("maxInactiveIntervalInSeconds", 600);
annotationAttributes.put("serverRegionShortcut", RegionShortcut.REPLICATE);
annotationAttributes.put("regionName", "TEST");
given(mockAnnotationMetadata.getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName())))
.willReturn(annotationAttributes);
given(mockAnnotationMetadata
.getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName())))
.willReturn(annotationAttributes);
this.gemfireConfiguration.setImportMetadata(mockAnnotationMetadata);
assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY);
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three"));
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(600);
assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("TEST");
assertThat(this.gemfireConfiguration.getClientRegionShortcut())
.isEqualTo(ClientRegionShortcut.CACHING_PROXY);
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes())
.isEqualTo(toArray("one", "two", "three"));
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds())
.isEqualTo(600);
assertThat(this.gemfireConfiguration.getServerRegionShortcut())
.isEqualTo(RegionShortcut.REPLICATE);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName())
.isEqualTo("TEST");
verify(mockAnnotationMetadata, times(1)).getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName()));
verify(mockAnnotationMetadata, times(1))
.getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName()));
}
@Test
public void createAndInitializeSpringSessionRepositoryBean() {
GemfireOperations mockGemfireOperations = mock(GemfireOperations.class,
"testCreateAndInitializeSpringSessionRepositoryBean");
"testCreateAndInitializeSpringSessionRepositoryBean");
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(120);
GemFireOperationsSessionRepository sessionRepository = this.gemfireConfiguration.sessionRepository(
mockGemfireOperations);
GemFireOperationsSessionRepository sessionRepository = this.gemfireConfiguration
.sessionRepository(mockGemfireOperations);
assertThat(sessionRepository).isNotNull();
assertThat(sessionRepository.getTemplate()).isSameAs(mockGemfireOperations);
@@ -234,9 +267,11 @@ public class GemFireHttpSessionConfigurationTest {
this.gemfireConfiguration.setSpringSessionGemFireRegionName("Example");
GemfireTemplate template = this.gemfireConfiguration.sessionRegionTemplate(mockGemFireCache);
GemfireTemplate template = this.gemfireConfiguration
.sessionRegionTemplate(mockGemFireCache);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("Example");
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName())
.isEqualTo("Example");
assertThat(template).isNotNull();
assertThat(template.getRegion()).isSameAs(mockRegion);
@@ -246,37 +281,45 @@ public class GemFireHttpSessionConfigurationTest {
@Test
public void expirationIsAllowed() {
Cache mockCache = mock(Cache.class, "testExpirationIsAllowed.MockCache");
ClientCache mockClientCache = mock(ClientCache.class, "testExpirationIsAllowed.MockClientCache");
ClientCache mockClientCache = mock(ClientCache.class,
"testExpirationIsAllowed.MockClientCache");
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE);
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue();
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
this.gemfireConfiguration.setServerRegionShortcut(
RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue();
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY);
this.gemfireConfiguration
.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY);
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache))
.isTrue();
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
this.gemfireConfiguration
.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PROXY);
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache))
.isTrue();
}
@Test
public void expirationIsNotAllowed() {
Cache mockCache = mock(Cache.class, "testExpirationIsAllowed.MockCache");
ClientCache mockClientCache = mock(ClientCache.class, "testExpirationIsAllowed.MockClientCache");
ClientCache mockClientCache = mock(ClientCache.class,
"testExpirationIsAllowed.MockClientCache");
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION);
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isFalse();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache))
.isFalse();
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY);

View File

@@ -39,15 +39,17 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* The GemFireCacheTypeAwareRegionFactoryBeanTest class is a test suite of test cases testing the contract
* and functionality of the GemFireCacheTypeAwareRegionFactoryBean class.
* The GemFireCacheTypeAwareRegionFactoryBeanTest class is a test suite of test cases
* testing the contract and functionality of the GemFireCacheTypeAwareRegionFactoryBean
* class.
*
* @author John Blum
* @since 1.1.0
* @see org.junit.Rule
* @see org.junit.Test
* @see org.mockito.Mockito
* @see org.springframework.session.data.gemfire.config.annotation.web.http.support.GemFireCacheTypeAwareRegionFactoryBean
* @see org.springframework.session.data.gemfire.config.annotation.web.http.support.
* GemFireCacheTypeAwareRegionFactoryBean
* @see com.gemstone.gemfire.cache.Cache
* @see com.gemstone.gemfire.cache.GemFireCache
* @see com.gemstone.gemfire.cache.InterestResultPolicy
@@ -81,14 +83,18 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
public void afterPropertiesSetCreatesClientRegionForClientCache() throws Exception {
this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession>() {
@Override
protected Region<Object, ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache);
protected Region<Object, ExpiringSession> newClientRegion(
GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(
GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache);
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion;
}
@Override
protected Region<Object, ExpiringSession> newServerRegion(final GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache);
protected Region<Object, ExpiringSession> newServerRegion(
final GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(
GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache);
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockServerRegion;
}
};
@@ -96,7 +102,8 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
this.regionFactoryBean.setGemfireCache(this.mockClientCache);
this.regionFactoryBean.afterPropertiesSet();
assertThat(this.regionFactoryBean.getGemfireCache()).isSameAs(this.mockClientCache);
assertThat(this.regionFactoryBean.getGemfireCache())
.isSameAs(this.mockClientCache);
assertThat(this.regionFactoryBean.getObject()).isEqualTo(this.mockClientRegion);
}
@@ -106,13 +113,15 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession>() {
@Override
protected Region<Object, ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
protected Region<Object, ExpiringSession> newClientRegion(
GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockCache);
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion;
}
@Override
protected Region<Object, ExpiringSession> newServerRegion(final GemFireCache gemfireCache) throws Exception {
protected Region<Object, ExpiringSession> newServerRegion(
final GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockCache);
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockServerRegion;
}
@@ -158,16 +167,18 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
@Test
public void setAndGetClientRegionShortcut() {
assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT);
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT);
this.regionFactoryBean.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT);
this.regionFactoryBean
.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT);
assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.LOCAL_PERSISTENT);
assertThat(this.regionFactoryBean.getClientRegionShortcut())
.isEqualTo(ClientRegionShortcut.LOCAL_PERSISTENT);
this.regionFactoryBean.setClientRegionShortcut(null);
assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT);
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT);
}
@Test
@@ -182,27 +193,31 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
@Test
public void setGemfireCacheToNullThrowsIllegalArgumentException() {
this.expectedException.expect(IllegalArgumentException.class);
this.expectedException.expectMessage("The GemFireCache reference must not be null");
this.expectedException
.expectMessage("The GemFireCache reference must not be null");
this.regionFactoryBean.setGemfireCache(null);
}
@Test
public void getGemfireCacheWhenNullThrowsIllegalStateException() {
this.expectedException.expect(IllegalStateException.class);
this.expectedException.expectMessage("A reference to a GemFireCache was not properly configured");
this.expectedException.expectMessage(
"A reference to a GemFireCache was not properly configured");
this.regionFactoryBean.getGemfireCache();
}
@Test
@SuppressWarnings("unchecked")
public void setAndGetRegionAttributes() {
RegionAttributes<Object, ExpiringSession> mockRegionAttributes = mock(RegionAttributes.class);
RegionAttributes<Object, ExpiringSession> mockRegionAttributes = mock(
RegionAttributes.class);
assertThat(this.regionFactoryBean.getRegionAttributes()).isNull();
this.regionFactoryBean.setRegionAttributes(mockRegionAttributes);
assertThat(this.regionFactoryBean.getRegionAttributes()).isSameAs(mockRegionAttributes);
assertThat(this.regionFactoryBean.getRegionAttributes())
.isSameAs(mockRegionAttributes);
this.regionFactoryBean.setRegionAttributes(null);
@@ -212,7 +227,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
@Test
public void setAndGetRegionName() {
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
this.regionFactoryBean.setRegionName("Example");
@@ -221,32 +236,33 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
this.regionFactoryBean.setRegionName(" ");
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
this.regionFactoryBean.setRegionName("");
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
this.regionFactoryBean.setRegionName(null);
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
}
@Test
public void setAndGetServerRegionShortcut() {
assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT);
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT);
this.regionFactoryBean.setServerRegionShortcut(RegionShortcut.LOCAL_PERSISTENT);
assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo(RegionShortcut.LOCAL_PERSISTENT);
assertThat(this.regionFactoryBean.getServerRegionShortcut())
.isEqualTo(RegionShortcut.LOCAL_PERSISTENT);
this.regionFactoryBean.setServerRegionShortcut(null);
assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT);
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT);
}
}

View File

@@ -33,8 +33,8 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* The GemFireUtilsTest class is a test suite of test cases testing the contract and functionality of the GemFireUtils
* utility class.
* The GemFireUtilsTest class is a test suite of test cases testing the contract and
* functionality of the GemFireUtils utility class.
*
* @author John Blum
* @since 1.1.0
@@ -52,7 +52,8 @@ public class GemFireUtilsTest {
}
@Test
public void closeNonNullCloseableObjectThrowingIOExceptionReturnsFalse() throws IOException {
public void closeNonNullCloseableObjectThrowingIOExceptionReturnsFalse()
throws IOException {
Closeable mockCloseable = mock(Closeable.class);
willThrow(new IOException("test")).given(mockCloseable).close();
assertThat(GemFireUtils.close(mockCloseable)).isFalse();
@@ -100,14 +101,17 @@ public class GemFireUtilsTest {
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.LOCAL_HEAP_LRU)).isTrue();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.LOCAL_OVERFLOW)).isTrue();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.LOCAL_PERSISTENT)).isTrue();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW)).isTrue();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW))
.isTrue();
}
@Test
public void clientRegionShortcutIsNotLocal() {
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.CACHING_PROXY)).isFalse();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.CACHING_PROXY_HEAP_LRU)).isFalse();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.CACHING_PROXY_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.CACHING_PROXY_HEAP_LRU))
.isFalse();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.CACHING_PROXY_OVERFLOW))
.isFalse();
assertThat(GemFireUtils.isLocal(ClientRegionShortcut.PROXY)).isFalse();
}
@@ -119,19 +123,23 @@ public class GemFireUtilsTest {
@Test
public void clientRegionShortcutIsNotProxy() {
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.CACHING_PROXY)).isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.CACHING_PROXY_HEAP_LRU)).isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.CACHING_PROXY_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.CACHING_PROXY_HEAP_LRU))
.isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.CACHING_PROXY_OVERFLOW))
.isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.LOCAL)).isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.LOCAL_HEAP_LRU)).isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.LOCAL_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.LOCAL_PERSISTENT)).isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW))
.isFalse();
}
@Test
public void regionShortcutIsProxy() {
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_PROXY)).isTrue();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_PROXY_REDUNDANT)).isTrue();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_PROXY_REDUNDANT))
.isTrue();
assertThat(GemFireUtils.isProxy(RegionShortcut.REPLICATE_PROXY)).isTrue();
}
@@ -141,22 +149,30 @@ public class GemFireUtilsTest {
assertThat(GemFireUtils.isProxy(RegionShortcut.LOCAL_HEAP_LRU)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.LOCAL_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.LOCAL_PERSISTENT)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW))
.isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.REPLICATE)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.REPLICATE_HEAP_LRU)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.REPLICATE_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.REPLICATE_PERSISTENT)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW))
.isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_HEAP_LRU)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_PERSISTENT)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW))
.isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_REDUNDANT)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_REDUNDANT_HEAP_LRU)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW)).isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_REDUNDANT_HEAP_LRU))
.isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW))
.isFalse();
assertThat(GemFireUtils.isProxy(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT))
.isFalse();
assertThat(GemFireUtils
.isProxy(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW))
.isFalse();
}
@Test

View File

@@ -1,6 +1,22 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.data.mongo;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextImpl;
@@ -13,16 +29,17 @@ public class AuthenticationParserTests {
@Test
public void shouldExtractName() {
//given
// given
String principalName = "john_the_springer";
SecurityContextImpl context = new SecurityContextImpl();
context.setAuthentication(new UsernamePasswordAuthenticationToken(principalName, null));
context.setAuthentication(
new UsernamePasswordAuthenticationToken(principalName, null));
//when
// when
String extractedName = AuthenticationParser.extractName(context);
//then
// then
assertThat(extractedName).isEqualTo(principalName);
}
}
}

View File

@@ -1,7 +1,23 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.data.mongo;
import com.mongodb.DBObject;
import org.junit.Test;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextImpl;
@@ -19,53 +35,60 @@ public class JdkMongoSessionConverterTests {
@Test
public void verifyRoundTripSerialization() throws Exception {
//given
// given
MongoExpiringSession toSerialize = new MongoExpiringSession();
toSerialize.setAttribute("username", "john_the_springer");
//when
// when
DBObject dbObject = convertToDBObject(toSerialize);
ExpiringSession deserialized = convertToSession(dbObject);
//then
// then
assertThat(deserialized).isEqualToComparingFieldByField(toSerialize);
}
@Test
public void shouldExtractPrincipalNameFromAttributes() throws Exception {
//given
// given
MongoExpiringSession toSerialize = new MongoExpiringSession();
String principalName = "john_the_springer";
toSerialize.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName);
toSerialize.setAttribute(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
principalName);
//when
// when
DBObject dbObject = convertToDBObject(toSerialize);
//then
// then
assertThat(dbObject.get("principal")).isEqualTo(principalName);
}
@Test
public void shouldExtractPrincipalNameFromAuthentication() throws Exception {
//given
// given
MongoExpiringSession toSerialize = new MongoExpiringSession();
String principalName = "john_the_springer";
SecurityContextImpl context = new SecurityContextImpl();
context.setAuthentication(new UsernamePasswordAuthenticationToken(principalName, null));
context.setAuthentication(
new UsernamePasswordAuthenticationToken(principalName, null));
toSerialize.setAttribute("SPRING_SECURITY_CONTEXT", context);
//when
// when
DBObject dbObject = convertToDBObject(toSerialize);
//then
// then
assertThat(dbObject.get("principal")).isEqualTo(principalName);
}
MongoExpiringSession convertToSession(DBObject session) {
return (MongoExpiringSession) sut.convert(session, TypeDescriptor.valueOf(DBObject.class), TypeDescriptor.valueOf(MongoExpiringSession.class));
return (MongoExpiringSession) this.sut.convert(session,
TypeDescriptor.valueOf(DBObject.class),
TypeDescriptor.valueOf(MongoExpiringSession.class));
}
DBObject convertToDBObject(MongoExpiringSession session) {
return (DBObject) sut.convert(session, TypeDescriptor.valueOf(MongoExpiringSession.class), TypeDescriptor.valueOf(DBObject.class));
return (DBObject) this.sut.convert(session,
TypeDescriptor.valueOf(MongoExpiringSession.class),
TypeDescriptor.valueOf(DBObject.class));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,10 @@
*/
package org.springframework.session.data.mongo;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
@@ -24,23 +28,20 @@ import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Jakub Kubrynski
@@ -57,114 +58,132 @@ public class MongoOperationsSessionRepositoryTests {
@Before
public void setUp() throws Exception {
sut = new MongoOperationsSessionRepository(mongoOperations);
sut.setMongoSessionConverter(converter);
this.sut = new MongoOperationsSessionRepository(this.mongoOperations);
this.sut.setMongoSessionConverter(this.converter);
}
@Test
public void shouldCreateSession() throws Exception {
//when
ExpiringSession session = sut.createSession();
// when
ExpiringSession session = this.sut.createSession();
//then
// then
assertThat(session.getId()).isNotEmpty();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL);
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL);
}
@Test
public void shouldSaveSession() throws Exception {
//given
// given
MongoExpiringSession session = new MongoExpiringSession();
BasicDBObject dbSession = new BasicDBObject();
DBCollection collection = mock(DBCollection.class);
when(converter.convert(session, TypeDescriptor.valueOf(MongoExpiringSession.class), TypeDescriptor.valueOf(DBObject.class))).thenReturn(dbSession);
when(mongoOperations.getCollection(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).thenReturn(collection);
//when
sut.save(session);
given(this.converter.convert(session,
TypeDescriptor.valueOf(MongoExpiringSession.class),
TypeDescriptor.valueOf(DBObject.class))).willReturn(dbSession);
given(this.mongoOperations
.getCollection(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME))
.willReturn(collection);
// when
this.sut.save(session);
//then
// then
verify(collection).save(dbSession);
}
@Test
public void shouldGetSession() throws Exception {
//given
// given
String sessionId = UUID.randomUUID().toString();
BasicDBObject dbSession = new BasicDBObject();
when(mongoOperations.findById(sessionId, DBObject.class, MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).thenReturn(dbSession);
given(this.mongoOperations.findById(sessionId, DBObject.class,
MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME))
.willReturn(dbSession);
MongoExpiringSession session = new MongoExpiringSession();
when(converter.convert(dbSession, TypeDescriptor.valueOf(DBObject.class), TypeDescriptor.valueOf(MongoExpiringSession.class))).thenReturn(session);
given(this.converter.convert(dbSession, TypeDescriptor.valueOf(DBObject.class),
TypeDescriptor.valueOf(MongoExpiringSession.class))).willReturn(session);
//when
ExpiringSession retrievedSession = sut.getSession(sessionId);
// when
ExpiringSession retrievedSession = this.sut.getSession(sessionId);
//then
// then
assertThat(retrievedSession).isEqualTo(session);
}
@Test
public void shouldHandleExpiredSession() throws Exception {
//given
// given
String sessionId = UUID.randomUUID().toString();
BasicDBObject dbSession = new BasicDBObject();
when(mongoOperations.findById(sessionId, DBObject.class, MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).thenReturn(dbSession);
given(this.mongoOperations.findById(sessionId, DBObject.class,
MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME))
.willReturn(dbSession);
MongoExpiringSession session = mock(MongoExpiringSession.class);
when(session.isExpired()).thenReturn(true);
when(session.getId()).thenReturn(sessionId);
when(converter.convert(dbSession, TypeDescriptor.valueOf(DBObject.class), TypeDescriptor.valueOf(MongoExpiringSession.class))).thenReturn(session);
given(session.isExpired()).willReturn(true);
given(session.getId()).willReturn(sessionId);
given(this.converter.convert(dbSession, TypeDescriptor.valueOf(DBObject.class),
TypeDescriptor.valueOf(MongoExpiringSession.class))).willReturn(session);
//when
sut.getSession(sessionId);
// when
this.sut.getSession(sessionId);
//then
verify(mongoOperations).remove(any(DBObject.class), eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME));
// then
verify(this.mongoOperations).remove(any(DBObject.class),
eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME));
}
@Test
public void shouldDeleteSession() throws Exception {
//given
// given
String sessionId = UUID.randomUUID().toString();
//when
sut.delete(sessionId);
// when
this.sut.delete(sessionId);
//then
verify(mongoOperations).remove(any(DBObject.class), eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME));
// then
verify(this.mongoOperations).remove(any(DBObject.class),
eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME));
}
@Test
public void shouldGetSessionsMapByPrincipal() throws Exception {
//given
// given
String principalNameIndexName = FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME;
DBObject dbSession = new BasicDBObject();
when(converter.getQueryForIndex(anyString(), Matchers.anyObject())).thenReturn(mock(Query.class));
when(mongoOperations.find(any(Query.class), eq(DBObject.class), eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)))
.thenReturn(Collections.singletonList(dbSession));
given(this.converter.getQueryForIndex(anyString(), Matchers.anyObject()))
.willReturn(mock(Query.class));
given(this.mongoOperations.find(any(Query.class), eq(DBObject.class),
eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)))
.willReturn(Collections.singletonList(dbSession));
String sessionId = UUID.randomUUID().toString();
MongoExpiringSession session = new MongoExpiringSession(sessionId, 1800);
when(converter.convert(dbSession, TypeDescriptor.valueOf(DBObject.class), TypeDescriptor.valueOf(MongoExpiringSession.class))).thenReturn(session);
//when
Map<String, MongoExpiringSession> sessionsMap = sut.findByIndexNameAndIndexValue(principalNameIndexName, "john");
given(this.converter.convert(dbSession, TypeDescriptor.valueOf(DBObject.class),
TypeDescriptor.valueOf(MongoExpiringSession.class))).willReturn(session);
// when
Map<String, MongoExpiringSession> sessionsMap = this.sut
.findByIndexNameAndIndexValue(principalNameIndexName, "john");
//then
// then
assertThat(sessionsMap).containsOnlyKeys(sessionId);
assertThat(sessionsMap).containsValues(session);
}
@Test
public void shouldReturnEmptyMapForNotSupportedIndex() throws Exception {
//given
// given
String index = "some_not_supported_index_name";
//when
Map<String, MongoExpiringSession> sessionsMap = sut.findByIndexNameAndIndexValue(index, "some_value");
// when
Map<String, MongoExpiringSession> sessionsMap = this.sut
.findByIndexNameAndIndexValue(index, "some_value");
//then
// then
assertThat(sessionsMap).isEmpty();
}
}
}

View File

@@ -67,7 +67,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings({"unchecked", "rawtypes"})
@SuppressWarnings({ "unchecked", "rawtypes" })
public class RedisOperationsSessionRepositoryTests {
static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";
@@ -96,7 +96,6 @@ public class RedisOperationsSessionRepositoryTests {
private RedisOperationsSessionRepository redisRepository;
@Before
public void setup() {
this.redisRepository = new RedisOperationsSessionRepository(this.redisOperations);
@@ -132,7 +131,8 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void createSessionDefaultMaxInactiveInterval() throws Exception {
ExpiringSession session = this.redisRepository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
}
@Test
@@ -146,18 +146,24 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void saveNewSession() {
RedisSession session = this.redisRepository.createSession();
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
Map<String, Object> delta = getDelta();
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR);
Object creationTime = delta
.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR);
assertThat(creationTime).isEqualTo(session.getCreationTime());
assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime());
assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR))
.isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR))
.isEqualTo(session.getCreationTime());
}
@Test
@@ -165,19 +171,28 @@ public class RedisOperationsSessionRepositoryTests {
RedisSession session = this.redisRepository.createSession();
String sessionKey = "spring:session:sessions:" + session.getId();
String backgroundExpireKey = "spring:session:expirations:" + RedisSessionExpirationPolicy.roundUpToNextMinute(RedisSessionExpirationPolicy.expiresInMillis(session));
String backgroundExpireKey = "spring:session:expirations:"
+ RedisSessionExpirationPolicy.roundUpToNextMinute(
RedisSessionExpirationPolicy.expiresInMillis(session));
String destroyedTriggerKey = "spring:session:sessions:expires:" + session.getId();
given(this.redisOperations.boundHashOps(sessionKey)).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(backgroundExpireKey)).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(destroyedTriggerKey)).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(sessionKey))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(backgroundExpireKey))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(destroyedTriggerKey))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
// the actual data in the session expires 5 minutes after expiration so the data can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since getSession checks if it is expired
long fiveMinutesAfterExpires = session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5);
verify(this.boundHashOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS);
// the actual data in the session expires 5 minutes after expiration so the data
// can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since
// getSession checks if it is expired
long fiveMinutesAfterExpires = session.getMaxInactiveIntervalInSeconds()
+ TimeUnit.MINUTES.toSeconds(5);
verify(this.boundHashOperations).expire(fiveMinutesAfterExpires,
TimeUnit.SECONDS);
verify(this.boundSetOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS);
verify(this.boundSetOperations).add("expires:" + session.getId());
verify(this.boundValueOperations).expire(1800L, TimeUnit.SECONDS);
@@ -188,28 +203,43 @@ public class RedisOperationsSessionRepositoryTests {
public void saveJavadoc() {
RedisSession session = this.redisRepository.new RedisSession(this.cached);
given(this.redisOperations.boundHashOps("spring:session:sessions:session-id")).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps("spring:session:expirations:1404361860000")).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps("spring:session:sessions:expires:session-id")).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps("spring:session:sessions:session-id"))
.willReturn(this.boundHashOperations);
given(this.redisOperations
.boundSetOps("spring:session:expirations:1404361860000"))
.willReturn(this.boundSetOperations);
given(this.redisOperations
.boundValueOps("spring:session:sessions:expires:session-id"))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
// the actual data in the session expires 5 minutes after expiration so the data can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since getSession checks if it is expired
verify(this.boundHashOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
// the actual data in the session expires 5 minutes after expiration so the data
// can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since
// getSession checks if it is expired
verify(this.boundHashOperations).expire(
session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5),
TimeUnit.SECONDS);
}
@Test
public void saveLastAccessChanged() {
RedisSession session = this.redisRepository.new RedisSession(new MapSession(this.cached));
RedisSession session = this.redisRepository.new RedisSession(
new MapSession(this.cached));
session.setLastAccessedTime(12345678L);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, session.getLastAccessedTime()));
assertThat(getDelta())
.isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
session.getLastAccessedTime()));
}
@Test
@@ -217,13 +247,18 @@ public class RedisOperationsSessionRepositoryTests {
String attrName = "attrName";
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.setAttribute(attrName, "attrValue");
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
assertThat(getDelta()).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
}
@Test
@@ -231,22 +266,29 @@ public class RedisOperationsSessionRepositoryTests {
String attrName = "attrName";
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.removeAttribute(attrName);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null));
assertThat(getDelta()).isEqualTo(map(
RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null));
}
@Test
public void saveExpired() {
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.setMaxInactiveIntervalInSeconds(0);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
@@ -272,30 +314,41 @@ public class RedisOperationsSessionRepositoryTests {
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setAttribute(attrName, "attrValue");
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
Map map = map(
RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
RedisOperationsSessionRepository.CREATION_TIME_ATTR, expected.getCreationTime(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, expected.getLastAccessedTime());
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
expected.getAttribute(attrName),
RedisOperationsSessionRepository.CREATION_TIME_ATTR,
expected.getCreationTime(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR,
expected.getMaxInactiveIntervalInSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
expected.getLastAccessedTime());
given(this.boundHashOperations.entries()).willReturn(map);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
String id = expected.getId();
this.redisRepository.delete(id);
assertThat(getDelta().get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(0);
assertThat(getDelta().get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR))
.isEqualTo(0);
verify(this.redisOperations, atLeastOnce()).delete(getKey("expires:" + id));
verify(this.redisOperations, never()).boundValueOps(getKey("expires:" + id));
}
@Test
public void deleteNullSession() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
String id = "abc";
this.redisRepository.delete(id);
@@ -306,7 +359,8 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void getSessionNotFound() {
String id = "abc";
given(this.redisOperations.boundHashOps(getKey(id))).willReturn(this.boundHashOperations);
given(this.redisOperations.boundHashOps(getKey(id)))
.willReturn(this.boundHashOperations);
given(this.boundHashOperations.entries()).willReturn(map());
assertThat(this.redisRepository.getSession(id)).isNull();
@@ -318,31 +372,39 @@ public class RedisOperationsSessionRepositoryTests {
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setAttribute(attrName, "attrValue");
given(this.redisOperations.boundHashOps(getKey(expected.getId()))).willReturn(this.boundHashOperations);
Map map = map(
RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
RedisOperationsSessionRepository.CREATION_TIME_ATTR, expected.getCreationTime(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, expected.getLastAccessedTime());
given(this.redisOperations.boundHashOps(getKey(expected.getId())))
.willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
expected.getAttribute(attrName),
RedisOperationsSessionRepository.CREATION_TIME_ATTR,
expected.getCreationTime(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR,
expected.getMaxInactiveIntervalInSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
expected.getLastAccessedTime());
given(this.boundHashOperations.entries()).willReturn(map);
RedisSession session = this.redisRepository.getSession(expected.getId());
assertThat(session.getId()).isEqualTo(expected.getId());
assertThat(session.getAttributeNames()).isEqualTo(expected.getAttributeNames());
assertThat(session.getAttribute(attrName)).isEqualTo(expected.getAttribute(attrName));
assertThat(session.getAttribute(attrName))
.isEqualTo(expected.getAttribute(attrName));
assertThat(session.getCreationTime()).isEqualTo(expected.getCreationTime());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expected.getMaxInactiveIntervalInSeconds());
assertThat(session.getLastAccessedTime()).isEqualTo(expected.getLastAccessedTime());
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(expected.getMaxInactiveIntervalInSeconds());
assertThat(session.getLastAccessedTime())
.isEqualTo(expected.getLastAccessedTime());
}
@Test
public void getSessionExpired() {
String expiredId = "expired-id";
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
Map map = map(
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
given(this.redisOperations.boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
given(this.boundHashOperations.entries()).willReturn(map);
assertThat(this.redisRepository.getSession(expiredId)).isNull();
@@ -351,15 +413,20 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void findByPrincipalNameExpired() {
String expiredId = "expired-id";
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.<Object>singleton(expiredId));
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
Map map = map(
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.boundSetOperations.members())
.willReturn(Collections.<Object>singleton(expiredId));
given(this.redisOperations.boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
given(this.boundHashOperations.entries()).willReturn(map);
assertThat(this.redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal")).isEmpty();
assertThat(this.redisRepository.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"))
.isEmpty();
}
@Test
@@ -368,16 +435,21 @@ public class RedisOperationsSessionRepositoryTests {
long createdTime = lastAccessed - 10;
int maxInactive = 3600;
String sessionId = "some-id";
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.<Object>singleton(sessionId));
given(this.redisOperations.boundHashOps(getKey(sessionId))).willReturn(this.boundHashOperations);
Map map = map(
RedisOperationsSessionRepository.CREATION_TIME_ATTR, createdTime,
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.boundSetOperations.members())
.willReturn(Collections.<Object>singleton(sessionId));
given(this.redisOperations.boundHashOps(getKey(sessionId)))
.willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.CREATION_TIME_ATTR, createdTime,
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, maxInactive,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, lastAccessed);
given(this.boundHashOperations.entries()).willReturn(map);
Map<String, RedisSession> sessionIdToSessions = this.redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal");
Map<String, RedisSession> sessionIdToSessions = this.redisRepository
.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
"principal");
assertThat(sessionIdToSessions).hasSize(1);
RedisSession session = sessionIdToSessions.get(sessionId);
@@ -391,10 +463,13 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void cleanupExpiredSessions() {
String expiredId = "expired-id";
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
Set<Object> expiredIds = new HashSet<Object>(Arrays.asList("expired-key1", "expired-key2"));
Set<Object> expiredIds = new HashSet<Object>(
Arrays.asList("expired-key1", "expired-key2"));
given(this.boundSetOperations.members()).willReturn(expiredIds);
this.redisRepository.cleanupExpiredSessions();
@@ -431,7 +506,8 @@ public class RedisOperationsSessionRepositoryTests {
byte[] pattern = "".getBytes("UTF-8");
byte[] body = new byte[0];
String channel = "spring:session:event:created:" + session.getId();
given(this.defaultSerializer.deserialize(body)).willReturn(new HashMap<String, Object>());
given(this.defaultSerializer.deserialize(body))
.willReturn(new HashMap<String, Object>());
DefaultMessage message = new DefaultMessage(channel.getBytes("UTF-8"), body);
this.redisRepository.setApplicationEventPublisher(this.publisher);
@@ -447,7 +523,8 @@ public class RedisOperationsSessionRepositoryTests {
PrincipalNameResolver resolver = RedisOperationsSessionRepository.PRINCIPAL_NAME_RESOLVER;
String username = "username";
RedisSession session = this.redisRepository.createSession();
session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);
session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
username);
assertThat(resolver.resolvePrincipal(session)).isEqualTo(username);
}
@@ -455,7 +532,8 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void resolveIndexOnSecurityContext() {
String principal = "resolveIndexOnSecurityContext";
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused", AuthorityUtils.createAuthorityList("ROLE_USER"));
Authentication authentication = new UsernamePasswordAuthenticationToken(principal,
"notused", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContext context = new SecurityContextImpl();
context.setAuthentication(authentication);
@@ -508,26 +586,35 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void flushModeImmediateCreate() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
Map<String, Object> delta = getDelta();
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR);
Object creationTime = delta
.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR);
assertThat(creationTime).isEqualTo(session.getCreationTime());
assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime());
assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR))
.isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR))
.isEqualTo(session.getCreationTime());
}
@Test
public void flushModeImmediateSetAttribute() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -536,14 +623,19 @@ public class RedisOperationsSessionRepositoryTests {
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
assertThat(delta).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
}
@Test
public void flushModeImmediateRemoveAttribute() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -552,14 +644,19 @@ public class RedisOperationsSessionRepositoryTests {
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
assertThat(delta).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
}
@Test
public void flushModeSetMaxInactiveIntervalInSeconds() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -573,9 +670,12 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void flushModeSetLastAccessedTime() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -585,7 +685,9 @@ public class RedisOperationsSessionRepositoryTests {
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, session.getLastAccessedTime()));
assertThat(delta)
.isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
session.getLastAccessedTime()));
}
@Test(expected = IllegalArgumentException.class)
@@ -597,7 +699,7 @@ public class RedisOperationsSessionRepositoryTests {
return "spring:session:sessions:" + id;
}
private Map map(Object...objects) {
private Map map(Object... objects) {
Map<String, Object> result = new HashMap<String, Object>();
if (objects == null) {
return result;

View File

@@ -61,23 +61,31 @@ public class RedisSessionExpirationPolicyTests {
@Before
public void setup() {
RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(this.sessionRedisOperations);
this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations, repository);
RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(
this.sessionRedisOperations);
this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations,
repository);
this.session = new MapSession();
this.session.setLastAccessedTime(1429116694675L);
this.session.setId("12345");
given(this.sessionRedisOperations.boundSetOps(anyString())).willReturn(this.setOperations);
given(this.sessionRedisOperations.boundHashOps(anyString())).willReturn(this.hashOperations);
given(this.sessionRedisOperations.boundValueOps(anyString())).willReturn(this.valueOperations);
given(this.sessionRedisOperations.boundSetOps(anyString()))
.willReturn(this.setOperations);
given(this.sessionRedisOperations.boundHashOps(anyString()))
.willReturn(this.hashOperations);
given(this.sessionRedisOperations.boundValueOps(anyString()))
.willReturn(this.valueOperations);
}
// gh-169
@Test
public void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp() throws Exception {
public void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp()
throws Exception {
long originalExpirationTimeInMs = ONE_MINUTE_AGO;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs);
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy
.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = this.policy
.getExpirationKey(originalRoundedToNextMinInMs);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);
@@ -87,10 +95,14 @@ public class RedisSessionExpirationPolicyTests {
}
@Test
public void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange() throws Exception {
long originalExpirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session) - 10;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs);
public void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange()
throws Exception {
long originalExpirationTimeInMs = RedisSessionExpirationPolicy
.expiresInMillis(this.session) - 10;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy
.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = this.policy
.getExpirationKey(originalRoundedToNextMinInMs);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);
@@ -101,15 +113,18 @@ public class RedisSessionExpirationPolicyTests {
@Test
public void onExpirationUpdatedAddsExpirationTimeRoundedUp() throws Exception {
long expirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session);
long expirationRoundedUpInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(expirationTimeInMs);
long expirationTimeInMs = RedisSessionExpirationPolicy
.expiresInMillis(this.session);
long expirationRoundedUpInMs = RedisSessionExpirationPolicy
.roundUpToNextMinute(expirationTimeInMs);
String expectedExpireKey = this.policy.getExpirationKey(expirationRoundedUpInMs);
this.policy.onExpirationUpdated(null, this.session);
verify(this.sessionRedisOperations).boundSetOps(expectedExpireKey);
verify(this.setOperations).add("expires:" + this.session.getId());
verify(this.setOperations).expire(this.session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
verify(this.setOperations).expire(this.session.getMaxInactiveIntervalInSeconds()
+ TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
}
@Test
@@ -119,6 +134,7 @@ public class RedisSessionExpirationPolicyTests {
this.policy.onExpirationUpdated(null, this.session);
verify(this.sessionRedisOperations).boundHashOps(sessionKey);
verify(this.hashOperations).expire(this.session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
verify(this.hashOperations).expire(this.session.getMaxInactiveIntervalInSeconds()
+ TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
}
}

View File

@@ -151,14 +151,16 @@ public class SessionMessageListenerTests {
@Test
public void onMessageEventPublisherErrorCaught() throws Exception {
mockMessage("__keyevent@0__:del", "spring:session:sessions:123");
willThrow(new IllegalStateException("Test Exceptions are caught")).given(this.eventPublisher).publishEvent(any(ApplicationEvent.class));
willThrow(new IllegalStateException("Test Exceptions are caught"))
.given(this.eventPublisher).publishEvent(any(ApplicationEvent.class));
this.listener.onMessage(this.message, this.pattern);
verify(this.eventPublisher).publishEvent(any(ApplicationEvent.class));
}
private void mockMessage(String channel, String body) throws UnsupportedEncodingException {
private void mockMessage(String channel, String body)
throws UnsupportedEncodingException {
given(this.message.getBody()).willReturn(bytes(body));
given(this.message.getChannel()).willReturn(bytes(channel));
}

View File

@@ -54,7 +54,8 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void setup() {
given(this.connectionFactory.getConnection()).willReturn(this.connection);
this.initializer = new RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer(this.connectionFactory, new ConfigureNotifyKeyspaceEventsAction());
this.initializer = new RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer(
this.connectionFactory, new ConfigureNotifyKeyspaceEventsAction());
}
@Test
@@ -157,7 +158,8 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
private void assertOptionsContains(String... expectedValues) {
verify(this.connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), this.options.capture());
verify(this.connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS),
this.options.capture());
for (String expectedValue : expectedValues) {
assertThat(this.options.getValue()).contains(expectedValue);
}
@@ -165,6 +167,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
private void setConfigNotification(String value) {
given(this.connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)).willReturn(Arrays.asList(CONFIG_NOTIFY_KEYSPACE_EVENTS, value));
given(this.connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS))
.willReturn(Arrays.asList(CONFIG_NOTIFY_KEYSPACE_EVENTS, value));
}
}

View File

@@ -51,7 +51,8 @@ public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests {
@Test
public void overrideDefaultRedisTemplate() {
assertThat(this.template.getDefaultSerializer()).isSameAs(this.defaultRedisSerializer);
assertThat(this.template.getDefaultSerializer())
.isSameAs(this.defaultRedisSerializer);
}
@EnableRedisHttpSession

View File

@@ -55,7 +55,8 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor {
@Test
public void overrideSessionTaskExecutor() {
verify(this.springSessionRedisTaskExecutor, times(1)).execute(any(SchedulingAwareRunnable.class));
verify(this.springSessionRedisTaskExecutor, times(1))
.execute(any(SchedulingAwareRunnable.class));
}
@EnableRedisHttpSession

View File

@@ -59,7 +59,8 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors {
@Test
public void overrideSessionTaskExecutors() {
verify(this.springSessionRedisSubscriptionExecutor, times(1)).execute(any(SchedulingAwareRunnable.class));
verify(this.springSessionRedisSubscriptionExecutor, times(1))
.execute(any(SchedulingAwareRunnable.class));
verify(this.springSessionRedisTaskExecutor, never()).execute(any(Runnable.class));
}

View File

@@ -56,12 +56,13 @@ public class Gh109Tests {
int sessionTimeout = 100;
/**
* override sessionRepository construction to set the custom
* session-timeout
* override sessionRepository construction to set the custom session-timeout
*/
@Bean
@Override
public RedisOperationsSessionRepository sessionRepository(RedisOperations<Object, Object> sessionRedisTemplate, ApplicationEventPublisher applicationEventPublisher) {
public RedisOperationsSessionRepository sessionRepository(
RedisOperations<Object, Object> sessionRedisTemplate,
ApplicationEventPublisher applicationEventPublisher) {
RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(
sessionRedisTemplate);
sessionRepository.setDefaultMaxInactiveInterval(this.sessionTimeout);

View File

@@ -42,6 +42,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.AdditionalMatchers.and;
import static org.mockito.AdditionalMatchers.not;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.contains;
import static org.mockito.Matchers.eq;
@@ -50,7 +51,6 @@ import static org.mockito.Matchers.startsWith;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests for {@link JdbcOperationsSessionRepository}.
@@ -81,10 +81,11 @@ public class JdbcOperationsSessionRepositoryTests {
@Test
public void constructorDataSource() {
JdbcOperationsSessionRepository repository =
new JdbcOperationsSessionRepository(this.dataSource);
JdbcOperationsSessionRepository repository = new JdbcOperationsSessionRepository(
this.dataSource);
assertThat(ReflectionTestUtils.getField(repository, "jdbcOperations")).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "jdbcOperations"))
.isNotNull();
}
@Test
@@ -137,11 +138,12 @@ public class JdbcOperationsSessionRepositoryTests {
@Test
public void createSessionDefaultMaxInactiveInterval() throws Exception {
JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession();
JdbcOperationsSessionRepository.JdbcSession session = this.repository
.createSession();
assertThat(session.isNew()).isTrue();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(
new MapSession().getMaxInactiveIntervalInSeconds());
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
verifyZeroInteractions(this.jdbcOperations);
}
@@ -150,7 +152,8 @@ public class JdbcOperationsSessionRepositoryTests {
int interval = 1;
this.repository.setDefaultMaxInactiveInterval(interval);
JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession();
JdbcOperationsSessionRepository.JdbcSession session = this.repository
.createSession();
assertThat(session.isNew()).isTrue();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(interval);
@@ -159,41 +162,48 @@ public class JdbcOperationsSessionRepositoryTests {
@Test
public void saveNew() {
JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession();
JdbcOperationsSessionRepository.JdbcSession session = this.repository
.createSession();
this.repository.save(session);
assertThat(session.isNew()).isFalse();
verify(this.jdbcOperations, times(1)).update(startsWith("INSERT"), isA(PreparedStatementSetter.class));
verify(this.jdbcOperations, times(1)).update(startsWith("INSERT"),
isA(PreparedStatementSetter.class));
}
@Test
public void saveUpdatedAttributes() {
JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession(new MapSession());
JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession(
new MapSession());
session.setAttribute("testName", "testValue");
this.repository.save(session);
assertThat(session.isNew()).isFalse();
verify(this.jdbcOperations, times(1))
.update(and(startsWith("UPDATE"), contains("SESSION_BYTES")), isA(PreparedStatementSetter.class));
verify(this.jdbcOperations, times(1)).update(
and(startsWith("UPDATE"), contains("SESSION_BYTES")),
isA(PreparedStatementSetter.class));
}
@Test
public void saveUpdatedLastAccessedTime() {
JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession(new MapSession());
JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession(
new MapSession());
session.setLastAccessedTime(System.currentTimeMillis());
this.repository.save(session);
assertThat(session.isNew()).isFalse();
verify(this.jdbcOperations, times(1))
.update(and(startsWith("UPDATE"), not(contains("SESSION_BYTES"))), isA(PreparedStatementSetter.class));
verify(this.jdbcOperations, times(1)).update(
and(startsWith("UPDATE"), not(contains("SESSION_BYTES"))),
isA(PreparedStatementSetter.class));
}
@Test
public void saveUnchanged() {
JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession(new MapSession());
JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession(
new MapSession());
this.repository.save(session);
@@ -206,11 +216,12 @@ public class JdbcOperationsSessionRepositoryTests {
public void getSessionNotFound() {
String sessionId = "testSessionId";
JdbcOperationsSessionRepository.JdbcSession session = this.repository.getSession(sessionId);
JdbcOperationsSessionRepository.JdbcSession session = this.repository
.getSession(sessionId);
assertThat(session).isNull();
verify(this.jdbcOperations, times(1)).queryForObject(
startsWith("SELECT"), eq(new Object[] { sessionId }), isA(RowMapper.class));
verify(this.jdbcOperations, times(1)).queryForObject(startsWith("SELECT"),
eq(new Object[] { sessionId }), isA(RowMapper.class));
}
@Test
@@ -218,15 +229,18 @@ public class JdbcOperationsSessionRepositoryTests {
public void getSessionExpired() {
MapSession expired = new MapSession();
expired.setMaxInactiveIntervalInSeconds(0);
when(this.jdbcOperations.queryForObject(startsWith("SELECT"), eq(new Object[] { expired.getId() }), isA(RowMapper.class)))
.thenReturn(expired);
given(this.jdbcOperations.queryForObject(startsWith("SELECT"),
eq(new Object[] { expired.getId() }), isA(RowMapper.class)))
.willReturn(expired);
JdbcOperationsSessionRepository.JdbcSession session = this.repository.getSession(expired.getId());
JdbcOperationsSessionRepository.JdbcSession session = this.repository
.getSession(expired.getId());
assertThat(session).isNull();
verify(this.jdbcOperations, times(1)).queryForObject(
startsWith("SELECT"), eq(new Object[] { expired.getId() }), isA(RowMapper.class));
verify(this.jdbcOperations, times(1)).update(startsWith("DELETE"), eq(expired.getId()));
verify(this.jdbcOperations, times(1)).queryForObject(startsWith("SELECT"),
eq(new Object[] { expired.getId() }), isA(RowMapper.class));
verify(this.jdbcOperations, times(1)).update(startsWith("DELETE"),
eq(expired.getId()));
}
@Test
@@ -234,16 +248,18 @@ public class JdbcOperationsSessionRepositoryTests {
public void getSessionFound() {
MapSession saved = new MapSession();
saved.setAttribute("savedName", "savedValue");
when(this.jdbcOperations.queryForObject(startsWith("SELECT"), eq(new Object[] { saved.getId() }), isA(RowMapper.class)))
.thenReturn(saved);
given(this.jdbcOperations.queryForObject(startsWith("SELECT"),
eq(new Object[] { saved.getId() }), isA(RowMapper.class)))
.willReturn(saved);
JdbcOperationsSessionRepository.JdbcSession session = this.repository.getSession(saved.getId());
JdbcOperationsSessionRepository.JdbcSession session = this.repository
.getSession(saved.getId());
assertThat(session.getId()).isEqualTo(saved.getId());
assertThat(session.isNew()).isFalse();
assertThat(session.getAttribute("savedName")).isEqualTo("savedValue");
verify(this.jdbcOperations, times(1)).queryForObject(
startsWith("SELECT"), eq(new Object[] { saved.getId() }), isA(RowMapper.class));
verify(this.jdbcOperations, times(1)).queryForObject(startsWith("SELECT"),
eq(new Object[] { saved.getId() }), isA(RowMapper.class));
}
@Test
@@ -259,8 +275,8 @@ public class JdbcOperationsSessionRepositoryTests {
public void findByIndexNameAndIndexValueUnknownIndexName() {
String indexValue = "testIndexValue";
Map<String, JdbcOperationsSessionRepository.JdbcSession> sessions =
this.repository.findByIndexNameAndIndexValue("testIndexName", indexValue);
Map<String, JdbcOperationsSessionRepository.JdbcSession> sessions = this.repository
.findByIndexNameAndIndexValue("testIndexName", indexValue);
assertThat(sessions).isEmpty();
verifyZeroInteractions(this.jdbcOperations);
@@ -272,19 +288,21 @@ public class JdbcOperationsSessionRepositoryTests {
String principal = "username";
Map<String, JdbcOperationsSessionRepository.JdbcSession> sessions = this.repository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
principal);
assertThat(sessions).isEmpty();
verify(this.jdbcOperations, times(1)).query(
startsWith("SELECT"), eq(new Object[] { principal }), isA(RowMapper.class));
verify(this.jdbcOperations, times(1)).query(startsWith("SELECT"),
eq(new Object[] { principal }), isA(RowMapper.class));
}
@Test
@SuppressWarnings("unchecked")
public void findByIndexNameAndIndexValuePrincipalIndexNameFound() {
String principal = "username";
Authentication authentication = new UsernamePasswordAuthenticationToken(
principal, "notused", AuthorityUtils.createAuthorityList("ROLE_USER"));
Authentication authentication = new UsernamePasswordAuthenticationToken(principal,
"notused", AuthorityUtils.createAuthorityList("ROLE_USER"));
List<MapSession> saved = new ArrayList<MapSession>(2);
MapSession saved1 = new MapSession();
saved1.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
@@ -292,15 +310,17 @@ public class JdbcOperationsSessionRepositoryTests {
MapSession saved2 = new MapSession();
saved2.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
saved.add(saved2);
when(this.jdbcOperations.query(startsWith("SELECT"), eq(new Object[] { principal }), isA(RowMapper.class)))
.thenReturn(saved);
given(this.jdbcOperations.query(startsWith("SELECT"),
eq(new Object[] { principal }), isA(RowMapper.class))).willReturn(saved);
Map<String, JdbcOperationsSessionRepository.JdbcSession> sessions = this.repository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
principal);
assertThat(sessions).hasSize(2);
verify(this.jdbcOperations, times(1)).query(
startsWith("SELECT"), eq(new Object[] { principal }), isA(RowMapper.class));
verify(this.jdbcOperations, times(1)).query(startsWith("SELECT"),
eq(new Object[] { principal }), isA(RowMapper.class));
}
@Test

View File

@@ -74,16 +74,19 @@ public class JdbcHttpSessionConfigurationTests {
public void defaultConfiguration() {
registerAndRefresh(DefaultConfiguration.class);
assertThat(this.context.getBean(JdbcOperationsSessionRepository.class)).isNotNull();
assertThat(this.context.getBean(JdbcOperationsSessionRepository.class))
.isNotNull();
}
@Test
public void customTableName() {
registerAndRefresh(CustomTableNameConfiguration.class);
JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class);
JdbcOperationsSessionRepository repository = this.context
.getBean(JdbcOperationsSessionRepository.class);
assertThat(repository).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "tableName")).isEqualTo(TABLE_NAME);
assertThat(ReflectionTestUtils.getField(repository, "tableName"))
.isEqualTo(TABLE_NAME);
}
@Test
@@ -93,9 +96,11 @@ public class JdbcHttpSessionConfigurationTests {
try {
registerAndRefresh(DefaultConfiguration.class);
JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class);
JdbcOperationsSessionRepository repository = this.context
.getBean(JdbcOperationsSessionRepository.class);
assertThat(repository).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "tableName")).isEqualTo(TABLE_NAME);
assertThat(ReflectionTestUtils.getField(repository, "tableName"))
.isEqualTo(TABLE_NAME);
}
finally {
System.clearProperty(TABLE_NAME_SYSTEM_PROPERTY);
@@ -106,7 +111,8 @@ public class JdbcHttpSessionConfigurationTests {
public void customMaxInactiveIntervalInSeconds() {
registerAndRefresh(CustomMaxInactiveIntervalInSecondsConfiguration.class);
JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class);
JdbcOperationsSessionRepository repository = this.context
.getBean(JdbcOperationsSessionRepository.class);
assertThat(repository).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "defaultMaxInactiveInterval"))
.isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
@@ -116,22 +122,27 @@ public class JdbcHttpSessionConfigurationTests {
public void customLobHandlerConfiguration() {
registerAndRefresh(CustomLobHandlerConfiguration.class);
JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class);
JdbcOperationsSessionRepository repository = this.context
.getBean(JdbcOperationsSessionRepository.class);
LobHandler lobHandler = this.context.getBean(LobHandler.class);
assertThat(repository).isNotNull();
assertThat(lobHandler).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "lobHandler")).isEqualTo(lobHandler);
assertThat(ReflectionTestUtils.getField(repository, "lobHandler"))
.isEqualTo(lobHandler);
}
@Test
public void customConversionServiceConfiguration() {
registerAndRefresh(CustomDeserializingConverterConfiguration.class);
JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class);
ConversionService conversionService = this.context.getBean("springSessionConversionService", ConversionService.class);
JdbcOperationsSessionRepository repository = this.context
.getBean(JdbcOperationsSessionRepository.class);
ConversionService conversionService = this.context
.getBean("springSessionConversionService", ConversionService.class);
assertThat(repository).isNotNull();
assertThat(conversionService).isNotNull();
Object repositoryConversionService = ReflectionTestUtils.getField(repository, "conversionService");
Object repositoryConversionService = ReflectionTestUtils.getField(repository,
"conversionService");
assertThat(repositoryConversionService).isEqualTo(conversionService);
}
@@ -166,7 +177,8 @@ public class JdbcHttpSessionConfigurationTests {
@Configuration
@EnableJdbcHttpSession(maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS)
static class CustomMaxInactiveIntervalInSecondsConfiguration extends BaseConfiguration {
static class CustomMaxInactiveIntervalInSecondsConfiguration
extends BaseConfiguration {
}
@Configuration

View File

@@ -55,14 +55,16 @@ public class CookieHttpSessionStrategyTests {
@Test
public void getRequestedSessionIdNotNull() throws Exception {
setSessionCookie(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request))
.isEqualTo(this.session.getId());
}
@Test
public void getRequestedSessionIdNotNullCustomCookieName() throws Exception {
setCookieName("CUSTOM");
setSessionCookie(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request))
.isEqualTo(this.session.getId());
}
@Test
@@ -105,15 +107,18 @@ public class CookieHttpSessionStrategyTests {
public void onNewSessionExistingSessionNewAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie(existing.getId());
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo("0 " + existing.getId() + " new " + this.session.getId());
assertThat(getSessionId())
.isEqualTo("0 " + existing.getId() + " new " + this.session.getId());
}
// gh-321
@Test
public void onNewSessionExplicitAlias() throws Exception {
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo("new " + this.session.getId());
}
@@ -124,7 +129,8 @@ public class CookieHttpSessionStrategyTests {
this.strategy.onNewSession(this.session, this.request, this.response);
Cookie sessionCookie = this.response.getCookie(this.cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(this.request.getContextPath() + "/");
assertThat(sessionCookie.getPath())
.isEqualTo(this.request.getContextPath() + "/");
}
@Test
@@ -146,7 +152,8 @@ public class CookieHttpSessionStrategyTests {
this.strategy.onInvalidateSession(this.request, this.response);
Cookie sessionCookie = this.response.getCookie(this.cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(this.request.getContextPath() + "/");
assertThat(sessionCookie.getPath())
.isEqualTo(this.request.getContextPath() + "/");
}
@Test
@@ -160,7 +167,8 @@ public class CookieHttpSessionStrategyTests {
public void onDeleteSessionExistingSessionSameAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie("0 " + existing.getId() + " new " + this.session.getId());
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(getSessionId()).isEqualTo(existing.getId());
}
@@ -169,7 +177,8 @@ public class CookieHttpSessionStrategyTests {
public void onDeleteSessionExistingSessionNewAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie("0 " + existing.getId() + " new " + this.session.getId());
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(getSessionId()).isEqualTo(existing.getId());
}
@@ -197,34 +206,40 @@ public class CookieHttpSessionStrategyTests {
@Test
public void encodeURLExistingQueryExistingAliasStart() {
assertThat(this.strategy.encodeURL("/url?_s=1&y=z", "2")).isEqualTo("/url?_s=2&y=z");
assertThat(this.strategy.encodeURL("/url?_s=1&y=z", "2"))
.isEqualTo("/url?_s=2&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasMiddle() {
assertThat(this.strategy.encodeURL("/url?a=b&_s=1&y=z", "2")).isEqualTo("/url?a=b&_s=2&y=z");
assertThat(this.strategy.encodeURL("/url?a=b&_s=1&y=z", "2"))
.isEqualTo("/url?a=b&_s=2&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasEnd() {
assertThat(this.strategy.encodeURL("/url?a=b&_s=1", "2")).isEqualTo("/url?a=b&_s=2");
assertThat(this.strategy.encodeURL("/url?a=b&_s=1", "2"))
.isEqualTo("/url?a=b&_s=2");
}
//
@Test
public void encodeURLExistingQueryParamEndsWithActualParamStart() {
assertThat(this.strategy.encodeURL("/url?x_s=1&y=z", "2")).isEqualTo("/url?x_s=1&y=z&_s=2");
assertThat(this.strategy.encodeURL("/url?x_s=1&y=z", "2"))
.isEqualTo("/url?x_s=1&y=z&_s=2");
}
@Test
public void encodeURLExistingQueryParamEndsWithActualParamMiddle() {
assertThat(this.strategy.encodeURL("/url?a=b&x_s=1&y=z", "2")).isEqualTo("/url?a=b&x_s=1&y=z&_s=2");
assertThat(this.strategy.encodeURL("/url?a=b&x_s=1&y=z", "2"))
.isEqualTo("/url?a=b&x_s=1&y=z&_s=2");
}
@Test
public void encodeURLExistingQueryParamEndsWithActualParamEnd() {
assertThat(this.strategy.encodeURL("/url?a=b&x_s=1", "2")).isEqualTo("/url?a=b&x_s=1&_s=2");
assertThat(this.strategy.encodeURL("/url?a=b&x_s=1", "2"))
.isEqualTo("/url?a=b&x_s=1&_s=2");
}
//
@@ -246,13 +261,16 @@ public class CookieHttpSessionStrategyTests {
@Test
public void encodeURLExistingQueryExistingAliasStartDefaultAlias() {
// relaxed constraint as result /url?&y=z does not hurt anything (ideally should remove the &)
assertThat(this.strategy.encodeURL("/url?_s=1&y=z", "0")).doesNotContain("_s=0&_s=1");
// relaxed constraint as result /url?&y=z does not hurt anything (ideally should
// remove the &)
assertThat(this.strategy.encodeURL("/url?_s=1&y=z", "0"))
.doesNotContain("_s=0&_s=1");
}
@Test
public void encodeURLExistingQueryExistingAliasMiddleDefaultAlias() {
assertThat(this.strategy.encodeURL("/url?a=b&_s=1&y=z", "0")).isEqualTo("/url?a=b&y=z");
assertThat(this.strategy.encodeURL("/url?a=b&_s=1&y=z", "0"))
.isEqualTo("/url?a=b&y=z");
}
@Test
@@ -262,88 +280,114 @@ public class CookieHttpSessionStrategyTests {
@Test
public void encodeURLMaliciousAlias() {
assertThat(this.strategy.encodeURL("/url?a=b&_s=1", "\"> <script>alert('hi')</script>")).isEqualTo("/url?a=b&_s=%22%3E+%3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E");
assertThat(this.strategy.encodeURL("/url?a=b&_s=1",
"\"> <script>alert('hi')</script>")).isEqualTo(
"/url?a=b&_s=%22%3E+%3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E");
}
// --- getCurrentSessionAlias
@Test
public void getCurrentSessionAliasNull() {
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasNullParamName() {
this.strategy.setSessionAliasParamName(null);
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "NOT USED");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "NOT USED");
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
// protect against malicious users
@Test
public void getCurrentSessionAliasContainsQuote() {
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here\"this");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here\"this");
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsSingleQuote() {
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here'this");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here'this");
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsSpace() {
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here this");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here this");
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsLt() {
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here<this");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here<this");
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsGt() {
this.strategy.setSessionAliasParamName(null);
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here>this");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here>this");
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasTooLong() {
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "012345678901234567890123456789012345678901234567890");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME,
"012345678901234567890123456789012345678901234567890");
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
// We want some sort of length restrictions, but want to ensure some sort of length Technically no hard limit, but chose 50
// We want some sort of length restrictions, but want to ensure some sort of length
// Technically no hard limit, but chose 50
@Test
public void getCurrentSessionAliasAllows50() {
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "01234567890123456789012345678901234567890123456789");
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME,
"01234567890123456789012345678901234567890123456789");
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo("01234567890123456789012345678901234567890123456789");
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo("01234567890123456789012345678901234567890123456789");
}
@Test
public void getCurrentSession() {
String expectedAlias = "1";
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, expectedAlias);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(expectedAlias);
this.request.setParameter(
CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME,
expectedAlias);
assertThat(this.strategy.getCurrentSessionAlias(this.request))
.isEqualTo(expectedAlias);
}
// --- getNewSessionAlias
@Test
public void getNewSessionAliasNoSessions() {
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getNewSessionAlias(this.request))
.isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
@@ -364,28 +408,32 @@ public class CookieHttpSessionStrategyTests {
public void getNewSessionAlias9Sessions() {
setCookieWithNSessions(9);
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("9");
assertThat(this.strategy.getNewSessionAlias(this.request))
.isEqualToIgnoringCase("9");
}
@Test
public void getNewSessionAlias10Sessions() {
setCookieWithNSessions(10);
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("a");
assertThat(this.strategy.getNewSessionAlias(this.request))
.isEqualToIgnoringCase("a");
}
@Test
public void getNewSessionAlias16Sessions() {
setCookieWithNSessions(16);
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("10");
assertThat(this.strategy.getNewSessionAlias(this.request))
.isEqualToIgnoringCase("10");
}
@Test
public void getNewSessionAliasInvalidAlias() {
setSessionCookie("0 1 $ b");
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("1");
assertThat(this.strategy.getNewSessionAlias(this.request))
.isEqualToIgnoringCase("1");
}
// --- getSessionIds
@@ -429,7 +477,8 @@ public class CookieHttpSessionStrategyTests {
@Test
public void createSessionCookieValue() {
assertThat(createSessionCookieValue(17)).isEqualToIgnoringCase("0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 a 10 b 11 c 12 d 13 e 14 f 15 10 16");
assertThat(createSessionCookieValue(17)).isEqualToIgnoringCase(
"0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 a 10 b 11 c 12 d 13 e 14 f 15 10 16");
}
private void setCookieWithNSessions(long size) {

View File

@@ -63,31 +63,38 @@ public class DefaultCookieSerializerTests {
public void readCookieValuesSingle() {
this.request.setCookies(new Cookie(this.cookieName, this.sessionId));
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
assertThat(this.serializer.readCookieValues(this.request))
.containsOnly(this.sessionId);
}
@Test
public void readCookieValuesSingleAndInvalidName() {
this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName + "INVALID", this.sessionId + "INVALID"));
this.request.setCookies(new Cookie(this.cookieName, this.sessionId),
new Cookie(this.cookieName + "INVALID", this.sessionId + "INVALID"));
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
assertThat(this.serializer.readCookieValues(this.request))
.containsOnly(this.sessionId);
}
@Test
public void readCookieValuesMulti() {
String secondSession = "secondSessionId";
this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName, secondSession));
this.request.setCookies(new Cookie(this.cookieName, this.sessionId),
new Cookie(this.cookieName, secondSession));
assertThat(this.serializer.readCookieValues(this.request)).containsExactly(this.sessionId, secondSession);
assertThat(this.serializer.readCookieValues(this.request))
.containsExactly(this.sessionId, secondSession);
}
@Test
public void readCookieValuesMultiCustomSessionCookieName() {
setCookieName("JSESSIONID");
String secondSession = "secondSessionId";
this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName, secondSession));
this.request.setCookies(new Cookie(this.cookieName, this.sessionId),
new Cookie(this.cookieName, secondSession));
assertThat(this.serializer.readCookieValues(this.request)).containsExactly(this.sessionId, secondSession);
assertThat(this.serializer.readCookieValues(this.request))
.containsExactly(this.sessionId, secondSession);
}
// gh-392
@@ -109,9 +116,11 @@ public class DefaultCookieSerializerTests {
@Test
public void readCookieValuesNullCookieValueAndNotNullCookie() {
this.serializer.setJvmRoute("123");
this.request.setCookies(new Cookie(this.cookieName, null), new Cookie(this.cookieName, this.sessionId));
this.request.setCookies(new Cookie(this.cookieName, null),
new Cookie(this.cookieName, this.sessionId));
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
assertThat(this.serializer.readCookieValues(this.request))
.containsOnly(this.sessionId);
}
// --- writeCookie ---
@@ -182,7 +191,7 @@ public class DefaultCookieSerializerTests {
String domainNamePattern = "^.+?\\.(\\w+\\.[a-z]+)$";
this.serializer.setDomainNamePattern(domainNamePattern);
String[] matchingDomains = {"child.sub.example.com", "www.example.com"};
String[] matchingDomains = { "child.sub.example.com", "www.example.com" };
for (String domain : matchingDomains) {
this.request.setServerName(domain);
this.serializer.writeCookieValue(cookieValue(this.sessionId));
@@ -191,7 +200,7 @@ public class DefaultCookieSerializerTests {
this.response = new MockHttpServletResponse();
}
String[] notMatchingDomains = {"example.com", "localhost", "127.0.0.1"};
String[] notMatchingDomains = { "example.com", "localhost", "127.0.0.1" };
for (String domain : notMatchingDomains) {
this.request.setServerName(domain);
this.serializer.writeCookieValue(cookieValue(this.sessionId));
@@ -361,9 +370,11 @@ public class DefaultCookieSerializerTests {
public void readCookieJvmRoute() {
String jvmRoute = "route";
this.serializer.setJvmRoute(jvmRoute);
this.request.setCookies(new Cookie(this.cookieName, this.sessionId + "." + jvmRoute));
this.request
.setCookies(new Cookie(this.cookieName, this.sessionId + "." + jvmRoute));
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
assertThat(this.serializer.readCookieValues(this.request))
.containsOnly(this.sessionId);
}
@Test
@@ -372,7 +383,8 @@ public class DefaultCookieSerializerTests {
this.serializer.setJvmRoute(jvmRoute);
this.request.setCookies(new Cookie(this.cookieName, this.sessionId));
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
assertThat(this.serializer.readCookieValues(this.request))
.containsOnly(this.sessionId);
}
@Test

View File

@@ -51,14 +51,16 @@ public class HeaderSessionStrategyTests {
@Test
public void getRequestedSessionIdNotNull() throws Exception {
setSessionId(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request))
.isEqualTo(this.session.getId());
}
@Test
public void getRequestedSessionIdNotNullCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
setSessionId(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request))
.isEqualTo(this.session.getId());
}
@Test
@@ -74,7 +76,8 @@ public class HeaderSessionStrategyTests {
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(this.response.getHeaders(this.headerName).size()).isEqualTo(1);
assertThat(this.response.getHeaders(this.headerName)).containsOnly(this.session.getId());
assertThat(this.response.getHeaders(this.headerName))
.containsOnly(this.session.getId());
}
@Test
@@ -90,7 +93,6 @@ public class HeaderSessionStrategyTests {
assertThat(getSessionId()).isEmpty();
}
// the header is set as apposed to added
@Test
public void onDeleteSessionMulti() throws Exception {

View File

@@ -60,7 +60,6 @@ public class OnCommittedResponseWrapperTests {
given(this.delegate.getOutputStream()).willReturn(this.out);
}
// --- printwriter
@Test
@@ -338,7 +337,6 @@ public class OnCommittedResponseWrapperTests {
verify(this.writer).format(l, format, args);
}
@Test
public void printWriterAppendCharSequence() throws Exception {
String x = "a";
@@ -359,7 +357,6 @@ public class OnCommittedResponseWrapperTests {
verify(this.writer).append(x, start, end);
}
@Test
public void printWriterAppendChar() throws Exception {
char x = 1;
@@ -371,7 +368,6 @@ public class OnCommittedResponseWrapperTests {
// servletoutputstream
@Test
public void outputStreamHashCode() throws Exception {
int expected = this.out.hashCode();
@@ -565,7 +561,8 @@ public class OnCommittedResponseWrapperTests {
}
@Test
public void contentLengthPlus1PrintWriterWriteIntMultiDigitCommits() throws Exception {
public void contentLengthPlus1PrintWriterWriteIntMultiDigitCommits()
throws Exception {
int expected = 10000;
this.response.setContentLength(String.valueOf(expected).length() + 1);
@@ -578,7 +575,6 @@ public class OnCommittedResponseWrapperTests {
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterWriteCharIntIntCommits() throws Exception {
char[] buff = new char[0];
@@ -613,7 +609,6 @@ public class OnCommittedResponseWrapperTests {
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterWriteStringCommits() throws IOException {
String body = "something";
@@ -843,7 +838,8 @@ public class OnCommittedResponseWrapperTests {
}
@Test
public void contentLengthPrintWriterAppendCharSequenceIntIntCommits() throws Exception {
public void contentLengthPrintWriterAppendCharSequenceIntIntCommits()
throws Exception {
String x = "abcdef";
int start = 1;
int end = 3;
@@ -885,7 +881,8 @@ public class OnCommittedResponseWrapperTests {
}
@Test
public void contentLengthPlus1OutputStreamWriteIntMultiDigitCommits() throws Exception {
public void contentLengthPlus1OutputStreamWriteIntMultiDigitCommits()
throws Exception {
int expected = 10000;
this.response.setContentLength(String.valueOf(expected).length() + 1);
@@ -900,12 +897,11 @@ public class OnCommittedResponseWrapperTests {
// gh-171
@Test
public void contentLengthPlus1OutputStreamWriteByteArrayMultiDigitCommits() throws Exception {
String expected = "{\n" +
" \"parameterName\" : \"_csrf\",\n" +
" \"token\" : \"06300b65-c4aa-4c8f-8cda-39ee17f545a0\",\n" +
" \"headerName\" : \"X-CSRF-TOKEN\"\n" +
"}";
public void contentLengthPlus1OutputStreamWriteByteArrayMultiDigitCommits()
throws Exception {
String expected = "{\n" + " \"parameterName\" : \"_csrf\",\n"
+ " \"token\" : \"06300b65-c4aa-4c8f-8cda-39ee17f545a0\",\n"
+ " \"headerName\" : \"X-CSRF-TOKEN\"\n" + "}";
this.response.setContentLength(expected.length() + 1);
this.response.getOutputStream().write(expected.getBytes());
@@ -1088,7 +1084,8 @@ public class OnCommittedResponseWrapperTests {
@Test
public void addHeaderContentLengthPrintWriterWriteStringCommits() throws Exception {
int expected = 1234;
this.response.addHeader("Content-Length", String.valueOf(String.valueOf(expected).length()));
this.response.addHeader("Content-Length",
String.valueOf(String.valueOf(expected).length()));
this.response.getWriter().write(expected);

View File

@@ -42,7 +42,6 @@ public class OncePerRequestFilterTests {
private OncePerRequestFilter filter;
private HttpServlet servlet;
private List<OncePerRequestFilter> invocations;
@Before
@@ -56,7 +55,9 @@ public class OncePerRequestFilterTests {
this.invocations = new ArrayList<OncePerRequestFilter>();
this.filter = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
OncePerRequestFilterTests.this.invocations.add(this);
filterChain.doFilter(request, response);
}
@@ -72,7 +73,8 @@ public class OncePerRequestFilterTests {
@Test
public void doFilterMultiOnlyIvokesOnce() throws ServletException, IOException {
this.filter.doFilter(this.request, this.response, new MockFilterChain(this.servlet, this.filter));
this.filter.doFilter(this.request, this.response,
new MockFilterChain(this.servlet, this.filter));
assertThat(this.invocations).containsOnly(this.filter);
}
@@ -81,12 +83,15 @@ public class OncePerRequestFilterTests {
public void doFilterOtherSubclassInvoked() throws ServletException, IOException {
OncePerRequestFilter filter2 = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
OncePerRequestFilterTests.this.invocations.add(this);
filterChain.doFilter(request, response);
}
};
this.filter.doFilter(this.request, this.response, new MockFilterChain(this.servlet, filter2));
this.filter.doFilter(this.request, this.response,
new MockFilterChain(this.servlet, filter2));
assertThat(this.invocations).containsOnly(this.filter, filter2);
}

View File

@@ -62,7 +62,8 @@ public class SessionEventHttpSessionListenerAdapterTests {
@Before
public void setup() {
this.listener = new SessionEventHttpSessionListenerAdapter(Arrays.asList(this.listener1, this.listener2));
this.listener = new SessionEventHttpSessionListenerAdapter(
Arrays.asList(this.listener1, this.listener2));
Session session = new MapSession();
this.destroyed = new SessionDestroyedEvent(this, session);
@@ -70,18 +71,22 @@ public class SessionEventHttpSessionListenerAdapterTests {
}
// We want relaxed constructor that will allow for an empty listeners to
// make configuration easier (i.e. autowire all HttpSessionListeners and might get none)
// make configuration easier (i.e. autowire all HttpSessionListeners and might get
// none)
@Test
public void constructorEmptyWorks() {
new SessionEventHttpSessionListenerAdapter(Collections.<HttpSessionListener>emptyList());
new SessionEventHttpSessionListenerAdapter(
Collections.<HttpSessionListener>emptyList());
}
/**
* Make sure that we short circuit onApplicationEvent as early as possible if no listeners
* Make sure that we short circuit onApplicationEvent as early as possible if no
* listeners
*/
@Test
public void onApplicationEventEmptyListenersDoesNotUseEvent() {
this.listener = new SessionEventHttpSessionListenerAdapter(Collections.<HttpSessionListener>emptyList());
this.listener = new SessionEventHttpSessionListenerAdapter(
Collections.<HttpSessionListener>emptyList());
this.destroyed = mock(SessionDestroyedEvent.class);
this.listener.onApplicationEvent(this.destroyed);
@@ -96,7 +101,8 @@ public class SessionEventHttpSessionListenerAdapterTests {
verify(this.listener1).sessionDestroyed(this.sessionEvent.capture());
verify(this.listener2).sessionDestroyed(this.sessionEvent.capture());
assertThat(this.sessionEvent.getValue().getSession().getId()).isEqualTo(this.destroyed.getSessionId());
assertThat(this.sessionEvent.getValue().getSession().getId())
.isEqualTo(this.destroyed.getSessionId());
}
@Test
@@ -106,6 +112,7 @@ public class SessionEventHttpSessionListenerAdapterTests {
verify(this.listener1).sessionCreated(this.sessionEvent.capture());
verify(this.listener2).sessionCreated(this.sessionEvent.capture());
assertThat(this.sessionEvent.getValue().getSession().getId()).isEqualTo(this.created.getSessionId());
assertThat(this.sessionEvent.getValue().getSession().getId())
.isEqualTo(this.created.getSessionId());
}
}

View File

@@ -87,7 +87,8 @@ public class SessionRepositoryFilterTests {
public void setup() throws Exception {
this.sessions = new HashMap<String, ExpiringSession>();
this.sessionRepository = new MapSessionRepository(this.sessions);
this.filter = new SessionRepositoryFilter<ExpiringSession>(this.sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(
this.sessionRepository);
setupRequest();
}
@@ -100,7 +101,8 @@ public class SessionRepositoryFilterTests {
long creationTime = wrappedRequest.getSession().getCreationTime();
long now = System.currentTimeMillis();
assertThat(now - creationTime).isGreaterThanOrEqualTo(0).isLessThan(5000);
SessionRepositoryFilterTests.this.request.setAttribute(CREATE_ATTR, creationTime);
SessionRepositoryFilterTests.this.request.setAttribute(CREATE_ATTR,
creationTime);
}
});
@@ -124,7 +126,8 @@ public class SessionRepositoryFilterTests {
session.setLastAccessedTime(0L);
this.sessionRepository = spy(this.sessionRepository);
given(this.sessionRepository.createSession()).willReturn(session);
this.filter = new SessionRepositoryFilter<ExpiringSession>(this.sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(
this.sessionRepository);
doFilter(new DoInFilter() {
@Override
@@ -133,7 +136,8 @@ public class SessionRepositoryFilterTests {
long now = System.currentTimeMillis();
long fiveSecondsAgo = now - TimeUnit.SECONDS.toMillis(5);
assertThat(session.getLastAccessedTime()).isLessThanOrEqualTo(now);
assertThat(session.getLastAccessedTime()).isGreaterThanOrEqualTo(fiveSecondsAgo);
assertThat(session.getLastAccessedTime())
.isGreaterThanOrEqualTo(fiveSecondsAgo);
}
});
}
@@ -145,8 +149,10 @@ public class SessionRepositoryFilterTests {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
long lastAccessed = wrappedRequest.getSession().getLastAccessedTime();
assertThat(lastAccessed).isEqualTo(wrappedRequest.getSession().getCreationTime());
SessionRepositoryFilterTests.this.request.setAttribute(ACCESS_ATTR, lastAccessed);
assertThat(lastAccessed)
.isEqualTo(wrappedRequest.getSession().getCreationTime());
SessionRepositoryFilterTests.this.request.setAttribute(ACCESS_ATTR,
lastAccessed);
}
});
@@ -158,7 +164,8 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest) {
long lastAccessed = wrappedRequest.getSession().getLastAccessedTime();
assertThat(lastAccessed).isGreaterThan(wrappedRequest.getSession().getCreationTime());
assertThat(lastAccessed)
.isGreaterThan(wrappedRequest.getSession().getCreationTime());
}
});
}
@@ -225,7 +232,8 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterServletContextExplicit() throws Exception {
final ServletContext expectedContext = new MockServletContext();
this.filter = new SessionRepositoryFilter<ExpiringSession>(this.sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(
this.sessionRepository);
this.filter.setServletContext(expectedContext);
doFilter(new DoInFilter() {
@@ -243,7 +251,9 @@ public class SessionRepositoryFilterTests {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
int interval = wrappedRequest.getSession().getMaxInactiveInterval();
assertThat(interval).isEqualTo(1800); // 30 minute default (same as Tomcat)
// 30 minute default (same as
// Tomcat)
assertThat(interval).isEqualTo(1800);
}
});
}
@@ -255,7 +265,8 @@ public class SessionRepositoryFilterTests {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
wrappedRequest.getSession().setMaxInactiveInterval(interval);
assertThat(wrappedRequest.getSession().getMaxInactiveInterval()).isEqualTo(interval);
assertThat(wrappedRequest.getSession().getMaxInactiveInterval())
.isEqualTo(interval);
}
});
@@ -264,7 +275,8 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
assertThat(wrappedRequest.getSession().getMaxInactiveInterval()).isEqualTo(interval);
assertThat(wrappedRequest.getSession().getMaxInactiveInterval())
.isEqualTo(interval);
}
});
}
@@ -277,8 +289,11 @@ public class SessionRepositoryFilterTests {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
wrappedRequest.getSession().setAttribute(ATTR, VALUE);
assertThat(wrappedRequest.getSession().getAttribute(ATTR)).isEqualTo(VALUE);
assertThat(Collections.list(wrappedRequest.getSession().getAttributeNames())).containsOnly(ATTR);
assertThat(wrappedRequest.getSession().getAttribute(ATTR))
.isEqualTo(VALUE);
assertThat(
Collections.list(wrappedRequest.getSession().getAttributeNames()))
.containsOnly(ATTR);
}
});
@@ -287,8 +302,11 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
assertThat(wrappedRequest.getSession().getAttribute(ATTR)).isEqualTo(VALUE);
assertThat(Collections.list(wrappedRequest.getSession().getAttributeNames())).containsOnly(ATTR);
assertThat(wrappedRequest.getSession().getAttribute(ATTR))
.isEqualTo(VALUE);
assertThat(
Collections.list(wrappedRequest.getSession().getAttributeNames()))
.containsOnly(ATTR);
}
});
@@ -297,7 +315,8 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
assertThat(wrappedRequest.getSession().getAttribute(ATTR)).isEqualTo(VALUE);
assertThat(wrappedRequest.getSession().getAttribute(ATTR))
.isEqualTo(VALUE);
wrappedRequest.getSession().removeAttribute(ATTR);
@@ -324,7 +343,8 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest) {
wrappedRequest.getSession().putValue(ATTR, VALUE);
assertThat(wrappedRequest.getSession().getValue(ATTR)).isEqualTo(VALUE);
assertThat(Arrays.asList(wrappedRequest.getSession().getValueNames())).containsOnly(ATTR);
assertThat(Arrays.asList(wrappedRequest.getSession().getValueNames()))
.containsOnly(ATTR);
}
});
@@ -334,7 +354,8 @@ public class SessionRepositoryFilterTests {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
assertThat(wrappedRequest.getSession().getValue(ATTR)).isEqualTo(VALUE);
assertThat(Arrays.asList(wrappedRequest.getSession().getValueNames())).containsOnly(ATTR);
assertThat(Arrays.asList(wrappedRequest.getSession().getValueNames()))
.containsOnly(ATTR);
}
});
@@ -402,7 +423,8 @@ public class SessionRepositoryFilterTests {
return createSession();
}
};
this.filter = new SessionRepositoryFilter<ExpiringSession>(this.sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(
this.sessionRepository);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
@@ -470,7 +492,7 @@ public class SessionRepositoryFilterTests {
});
nextRequest();
this.request.setRequestedSessionIdValid(false); // ensure we are using wrapped request
this.request.setRequestedSessionIdValid(false);
doFilter(new DoInFilter() {
@Override
@@ -503,7 +525,8 @@ public class SessionRepositoryFilterTests {
HttpSession originalSession = wrappedRequest.getSession();
assertThat(originalSession.getId()).isEqualTo(originalSessionId);
String changeSessionId = ReflectionTestUtils.invokeMethod(wrappedRequest, "changeSessionId");
String changeSessionId = ReflectionTestUtils.invokeMethod(wrappedRequest,
"changeSessionId");
assertThat(changeSessionId).isNotEqualTo(originalSessionId);
// gh-227
assertThat(originalSession.getId()).isEqualTo(changeSessionId);
@@ -521,7 +544,8 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
assertThat(wrappedRequest.getSession().getAttribute(ATTR)).isEqualTo(VALUE);
assertThat(wrappedRequest.getSession().getAttribute(ATTR))
.isEqualTo(VALUE);
}
});
}
@@ -546,7 +570,7 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterIsRequestedValidSessionFalseInvalidId() throws Exception {
setSessionCookie("invalid");
this.request.setRequestedSessionIdValid(true); // ensure we are using wrapped request
this.request.setRequestedSessionIdValid(true);
doFilter(new DoInFilter() {
@Override
@@ -558,7 +582,7 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterIsRequestedValidSessionFalse() throws Exception {
this.request.setRequestedSessionIdValid(true); // ensure we are using wrapped request
this.request.setRequestedSessionIdValid(true);
doFilter(new DoInFilter() {
@Override
@@ -620,8 +644,10 @@ public class SessionRepositoryFilterTests {
});
Cookie session = getSessionCookie();
assertThat(session.isHttpOnly()).describedAs("Session Cookie should be HttpOnly").isTrue();
assertThat(session.getSecure()).describedAs("Session Cookie should be marked as Secure").isTrue();
assertThat(session.isHttpOnly()).describedAs("Session Cookie should be HttpOnly")
.isTrue();
assertThat(session.getSecure())
.describedAs("Session Cookie should be marked as Secure").isTrue();
}
@Test
@@ -629,7 +655,8 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
HttpSessionContext sessionContext = wrappedRequest.getSession().getSessionContext();
HttpSessionContext sessionContext = wrappedRequest.getSession()
.getSessionContext();
assertThat(sessionContext).isNotNull();
assertThat(sessionContext.getSession("a")).isNull();
assertThat(sessionContext.getIds()).isNotNull();
@@ -645,8 +672,6 @@ public class SessionRepositoryFilterTests {
});
}
// --- saving
@Test
@@ -671,8 +696,10 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME)).isEqualTo(ATTR_VALUE);
assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME2)).isEqualTo(ATTR_VALUE2);
assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME))
.isEqualTo(ATTR_VALUE);
assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME2))
.isEqualTo(ATTR_VALUE2);
}
});
}
@@ -963,7 +990,8 @@ public class SessionRepositoryFilterTests {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME)).isNull();
assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME2)).isEqualTo(ATTR_VALUE2);
assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME2))
.isEqualTo(ATTR_VALUE2);
}
});
}
@@ -1015,10 +1043,12 @@ public class SessionRepositoryFilterTests {
public void doFilterSendError() throws Exception {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository
.getSession(id)).isNotNull();
}
});
}
@@ -1027,10 +1057,13 @@ public class SessionRepositoryFilterTests {
public void doFilterSendErrorAndMessage() throws Exception {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error");
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Error");
assertThat(SessionRepositoryFilterTests.this.sessionRepository
.getSession(id)).isNotNull();
}
});
}
@@ -1039,10 +1072,12 @@ public class SessionRepositoryFilterTests {
public void doFilterSendRedirect() throws Exception {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.sendRedirect("/");
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository
.getSession(id)).isNotNull();
}
});
}
@@ -1051,10 +1086,12 @@ public class SessionRepositoryFilterTests {
public void doFilterFlushBuffer() throws Exception {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.flushBuffer();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository
.getSession(id)).isNotNull();
}
});
}
@@ -1063,10 +1100,12 @@ public class SessionRepositoryFilterTests {
public void doFilterOutputFlush() throws Exception {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.getOutputStream().flush();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository
.getSession(id)).isNotNull();
}
});
}
@@ -1075,10 +1114,12 @@ public class SessionRepositoryFilterTests {
public void doFilterOutputClose() throws Exception {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.getOutputStream().close();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository
.getSession(id)).isNotNull();
}
});
}
@@ -1087,10 +1128,12 @@ public class SessionRepositoryFilterTests {
public void doFilterWriterFlush() throws Exception {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.getWriter().flush();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository
.getSession(id)).isNotNull();
}
});
}
@@ -1099,10 +1142,12 @@ public class SessionRepositoryFilterTests {
public void doFilterWriterClose() throws Exception {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.getWriter().close();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository
.getSession(id)).isNotNull();
}
});
}
@@ -1113,11 +1158,13 @@ public class SessionRepositoryFilterTests {
public void doFilterAdapterGetRequestedSessionId() throws Exception {
this.filter.setHttpSessionStrategy(this.strategy);
final String expectedId = "MultiHttpSessionStrategyAdapter-requested-id";
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(expectedId);
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class)))
.willReturn(expectedId);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
String actualId = wrappedRequest.getRequestedSessionId();
assertThat(actualId).isEqualTo(expectedId);
}
@@ -1130,14 +1177,16 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession();
}
});
HttpServletRequest request = (HttpServletRequest) this.chain.getRequest();
Session session = this.sessionRepository.getSession(request.getSession().getId());
verify(this.strategy).onNewSession(eq(session), any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.strategy).onNewSession(eq(session), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@Test
@@ -1146,61 +1195,73 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession().getId();
}
});
HttpServletRequest request = (HttpServletRequest) this.chain.getRequest();
String id = request.getSession().getId();
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(id);
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class)))
.willReturn(id);
setupRequest();
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession().invalidate();
}
});
verify(this.strategy).onInvalidateSession(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.strategy).onInvalidateSession(any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
// gh-188
@Test
public void doFilterRequestSessionNoRequestSessionDoesNotInvalidate() throws Exception {
public void doFilterRequestSessionNoRequestSessionDoesNotInvalidate()
throws Exception {
this.filter.setHttpSessionStrategy(this.strategy);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession().getId();
}
});
HttpServletRequest request = (HttpServletRequest) this.chain.getRequest();
String id = request.getSession().getId();
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(id);
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class)))
.willReturn(id);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
}
});
verify(this.strategy, never()).onInvalidateSession(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.strategy, never()).onInvalidateSession(any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@Test
@SuppressWarnings("unchecked")
public void doFilterRequestSessionNoRequestSessionNoSessionRepositoryInteractions() throws Exception {
SessionRepository<ExpiringSession> sessionRepository = spy(new MapSessionRepository());
public void doFilterRequestSessionNoRequestSessionNoSessionRepositoryInteractions()
throws Exception {
SessionRepository<ExpiringSession> sessionRepository = spy(
new MapSessionRepository());
this.filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession().getId();
}
});
@@ -1210,7 +1271,8 @@ public class SessionRepositoryFilterTests {
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
}
});
@@ -1219,13 +1281,15 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterLazySessionCreation() throws Exception {
SessionRepository<ExpiringSession> sessionRepository = spy(new MapSessionRepository());
SessionRepository<ExpiringSession> sessionRepository = spy(
new MapSessionRepository());
this.filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
}
});
@@ -1236,14 +1300,16 @@ public class SessionRepositoryFilterTests {
public void doFilterLazySessionUpdates() throws Exception {
ExpiringSession session = this.sessionRepository.createSession();
this.sessionRepository.save(session);
SessionRepository<ExpiringSession> sessionRepository = spy(this.sessionRepository);
SessionRepository<ExpiringSession> sessionRepository = spy(
this.sessionRepository);
setSessionCookie(session.getId());
this.filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
public void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse) throws IOException {
}
});
@@ -1254,7 +1320,8 @@ public class SessionRepositoryFilterTests {
@Test
public void order() {
assertThat(AnnotationAwareOrderComparator.INSTANCE.compare(this.filter, new SessionRepositoryFilterDefaultOrder()));
assertThat(AnnotationAwareOrderComparator.INSTANCE.compare(this.filter,
new SessionRepositoryFilterDefaultOrder()));
}
// We want the filter to work without any dependencies on Spring
@@ -1281,15 +1348,23 @@ public class SessionRepositoryFilterTests {
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isEqualTo(-1);
assertThat(cookie.getValue()).isNotEqualTo("INVALID");
assertThat(cookie.isHttpOnly()).describedAs("Cookie is expected to be HTTP Only").isTrue();
assertThat(cookie.getSecure()).describedAs("Cookie secured is expected to be " + this.request.isSecure()).isEqualTo(this.request.isSecure());
assertThat(this.request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull();
assertThat(cookie.isHttpOnly()).describedAs("Cookie is expected to be HTTP Only")
.isTrue();
assertThat(cookie.getSecure())
.describedAs(
"Cookie secured is expected to be " + this.request.isSecure())
.isEqualTo(this.request.isSecure());
assertThat(this.request.getSession(false))
.describedAs("The original HttpServletRequest HttpSession should be null")
.isNull();
}
private void assertNoSession() {
Cookie cookie = getSessionCookie();
assertThat(cookie).isNull();
assertThat(this.request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull();
assertThat(this.request.getSession(false))
.describedAs("The original HttpServletRequest HttpSession should be null")
.isNull();
}
private Cookie getSessionCookie() {
@@ -1297,7 +1372,7 @@ public class SessionRepositoryFilterTests {
}
private void setSessionCookie(String sessionId) {
this.request.setCookies(new Cookie[]{new Cookie("SESSION", sessionId)});
this.request.setCookies(new Cookie[] { new Cookie("SESSION", sessionId) });
}
private void setupRequest() {
@@ -1318,7 +1393,8 @@ public class SessionRepositoryFilterTests {
nameToCookie.put(cookie.getName(), cookie);
}
}
Cookie[] nextRequestCookies = new ArrayList<Cookie>(nameToCookie.values()).toArray(new Cookie[0]);
Cookie[] nextRequestCookies = new ArrayList<Cookie>(nameToCookie.values())
.toArray(new Cookie[0]);
setupRequest();
@@ -1326,11 +1402,14 @@ public class SessionRepositoryFilterTests {
}
@SuppressWarnings("serial")
private void doFilter(final DoInFilter doInFilter) throws ServletException, IOException {
private void doFilter(final DoInFilter doInFilter)
throws ServletException, IOException {
this.chain = new MockFilterChain(new HttpServlet() {
}, new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
doInFilter.doFilter(request, response);
}
});
@@ -1338,9 +1417,12 @@ public class SessionRepositoryFilterTests {
}
abstract class DoInFilter {
void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws ServletException, IOException {
void doFilter(HttpServletRequest wrappedRequest,
HttpServletResponse wrappedResponse)
throws ServletException, IOException {
doFilter(wrappedRequest);
}
void doFilter(HttpServletRequest wrappedRequest) {
}
}

View File

@@ -71,7 +71,8 @@ public class WebSocketConnectHandlerDecoratorFactoryTests {
@Test
public void decorateAfterConnectionEstablishedEventError() throws Exception {
WebSocketHandler decorated = this.factory.decorate(this.delegate);
willThrow(new IllegalStateException("Test throw on publishEvent")).given(this.eventPublisher).publishEvent(any(ApplicationEvent.class));
willThrow(new IllegalStateException("Test throw on publishEvent"))
.given(this.eventPublisher).publishEvent(any(ApplicationEvent.class));
decorated.afterConnectionEstablished(this.session);

View File

@@ -71,7 +71,6 @@ public class WebSocketRegistryListenerTests {
WebSocketRegistryListener listener;
@Before
public void setup() {
this.sessionId = "session-id";
@@ -93,7 +92,8 @@ public class WebSocketRegistryListenerTests {
this.listener = new WebSocketRegistryListener();
this.connect = new SessionConnectEvent(this.listener, this.wsSession);
this.connect2 = new SessionConnectEvent(this.listener, this.wsSession2);
this.disconnect = new SessionDisconnectEvent(this.listener, this.message, this.wsSession.getId(), CloseStatus.NORMAL);
this.disconnect = new SessionDisconnectEvent(this.listener, this.message,
this.wsSession.getId(), CloseStatus.NORMAL);
this.deleted = new SessionDeletedEvent(this.listener, this.sessionId);
this.expired = new SessionExpiredEvent(this.listener, this.sessionId);
}
@@ -116,7 +116,6 @@ public class WebSocketRegistryListenerTests {
verify(this.wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
}
@Test
public void onApplicationEventConnectSessionDeletedNullPrincipal() throws Exception {
given(this.wsSession.getPrincipal()).willReturn(null);
@@ -145,8 +144,8 @@ public class WebSocketRegistryListenerTests {
this.listener.onApplicationEvent(this.disconnect);
Map<String, Map<String, WebSocketSession>> httpSessionIdToWsSessions =
(Map<String, Map<String, WebSocketSession>>) ReflectionTestUtils.getField(this.listener, "httpSessionIdToWsSessions");
Map<String, Map<String, WebSocketSession>> httpSessionIdToWsSessions = (Map<String, Map<String, WebSocketSession>>) ReflectionTestUtils
.getField(this.listener, "httpSessionIdToWsSessions");
assertThat(httpSessionIdToWsSessions).isEmpty();
}

View File

@@ -67,7 +67,8 @@ public class SessionRepositoryMessageInterceptorTests {
@Before
public void setup() {
this.interceptor = new SessionRepositoryMessageInterceptor<ExpiringSession>(this.sessionRepository);
this.interceptor = new SessionRepositoryMessageInterceptor<ExpiringSession>(
this.sessionRepository);
this.headers = SimpMessageHeaderAccessor.create();
this.headers.setSessionId("session");
this.headers.setSessionAttributes(new HashMap<String, Object>());
@@ -91,7 +92,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendConnectAckDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.CONNECT_ACK);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verifyZeroInteractions(this.sessionRepository);
}
@@ -100,7 +102,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendHeartbeatDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.HEARTBEAT);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verifyZeroInteractions(this.sessionRepository);
}
@@ -109,7 +112,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendDisconnectDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.DISCONNECT);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verifyZeroInteractions(this.sessionRepository);
}
@@ -118,7 +122,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendOtherDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.OTHER);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verifyZeroInteractions(this.sessionRepository);
}
@@ -138,7 +143,8 @@ public class SessionRepositoryMessageInterceptorTests {
this.interceptor.setMatchingMessageTypes(EnumSet.of(SimpMessageType.DISCONNECT));
setMessageType(SimpMessageType.DISCONNECT);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.sessionRepository).getSession(anyString());
verify(this.sessionRepository).save(this.session);
@@ -148,7 +154,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendConnectUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.CONNECT);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
@@ -158,7 +165,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendMessageUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.MESSAGE);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
@@ -168,7 +176,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendSubscribeUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.SUBSCRIBE);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
@@ -179,7 +188,8 @@ public class SessionRepositoryMessageInterceptorTests {
setMessageType(SimpMessageType.UNSUBSCRIBE);
this.session.setLastAccessedTime(0L);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
@@ -199,7 +209,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendNullSessionId() {
setSessionId(null);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verifyZeroInteractions(this.sessionRepository);
}
@@ -208,7 +219,8 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendNullSessionAttributes() {
this.headers.setSessionAttributes(null);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verifyZeroInteractions(this.sessionRepository);
}
@@ -222,7 +234,8 @@ public class SessionRepositoryMessageInterceptorTests {
@Test
public void beforeHandshakeNullSession() throws Exception {
ServletServerHttpRequest request = new ServletServerHttpRequest(new MockHttpServletRequest());
ServletServerHttpRequest request = new ServletServerHttpRequest(
new MockHttpServletRequest());
assertThat(this.interceptor.beforeHandshake(request, null, null, null)).isTrue();
verifyZeroInteractions(this.sessionRepository);
@@ -235,10 +248,12 @@ public class SessionRepositoryMessageInterceptorTests {
ServletServerHttpRequest request = new ServletServerHttpRequest(httpRequest);
Map<String, Object> attributes = new HashMap<String, Object>();
assertThat(this.interceptor.beforeHandshake(request, null, null, attributes)).isTrue();
assertThat(this.interceptor.beforeHandshake(request, null, null, attributes))
.isTrue();
assertThat(attributes.size()).isEqualTo(1);
assertThat(SessionRepositoryMessageInterceptor.getSessionId(attributes)).isEqualTo(httpSession.getId());
assertThat(SessionRepositoryMessageInterceptor.getSessionId(attributes))
.isEqualTo(httpSession.getId());
}
/**
@@ -252,11 +267,13 @@ public class SessionRepositoryMessageInterceptorTests {
}
private void setSessionId(String id) {
SessionRepositoryMessageInterceptor.setSessionId(this.headers.getSessionAttributes(), id);
SessionRepositoryMessageInterceptor
.setSessionId(this.headers.getSessionAttributes(), id);
}
private Message<?> createMessage() {
this.createMessage = MessageBuilder.createMessage("", this.headers.getMessageHeaders());
this.createMessage = MessageBuilder.createMessage("",
this.headers.getMessageHeaders());
return this.createMessage;
}