Spaces to tabs and license cleanup

This commit is contained in:
Rob Winch
2015-04-02 15:57:00 -05:00
parent 93b8856a20
commit 4dedb4d10a
143 changed files with 8270 additions and 7654 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 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.
@@ -23,40 +23,40 @@ import org.junit.Before;
import org.junit.Test;
public class MapSessionRepositoryTests {
MapSessionRepository repository;
MapSessionRepository repository;
MapSession session;
MapSession session;
@Before
public void setup() {
repository = new MapSessionRepository();
session = new MapSession();
}
@Before
public void setup() {
repository = new MapSessionRepository();
session = new MapSession();
}
@Test
public void getSessionExpired() {
session.setMaxInactiveIntervalInSeconds(1);
session.setLastAccessedTime(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
repository.save(session);
@Test
public void getSessionExpired() {
session.setMaxInactiveIntervalInSeconds(1);
session.setLastAccessedTime(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
repository.save(session);
assertThat(repository.getSession(session.getId())).isNull();
}
assertThat(repository.getSession(session.getId())).isNull();
}
@Test
public void createSessionDefaultExpiration() {
ExpiringSession session = repository.createSession();
@Test
public void createSessionDefaultExpiration() {
ExpiringSession session = repository.createSession();
assertThat(session).isInstanceOf(MapSession.class);
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
}
assertThat(session).isInstanceOf(MapSession.class);
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
}
@Test
public void createSessionCustomDefaultExpiration() {
final int expectedMaxInterval = new MapSession().getMaxInactiveIntervalInSeconds() + 10;
repository.setDefaultMaxInactiveInterval(expectedMaxInterval);
@Test
public void createSessionCustomDefaultExpiration() {
final int expectedMaxInterval = new MapSession().getMaxInactiveIntervalInSeconds() + 10;
repository.setDefaultMaxInactiveInterval(expectedMaxInterval);
ExpiringSession session = repository.createSession();
ExpiringSession session = repository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInterval);
}
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInterval);
}
}

View File

@@ -1,3 +1,18 @@
/*
* Copyright 2002-2015 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;
import static org.fest.assertions.Assertions.assertThat;
@@ -9,107 +24,107 @@ import org.junit.Test;
public class MapSessionTests {
private MapSession session;
private MapSession session;
@Before
public void setup() {
session = new MapSession();
session.setLastAccessedTime(1413258262962L);
}
@Before
public void setup() {
session = new MapSession();
session.setLastAccessedTime(1413258262962L);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullSession() {
new MapSession(null);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullSession() {
new MapSession(null);
}
/**
* Ensure conforms to the javadoc of {@link Session}
*/
@Test
public void setAttributeNullObjectRemoves() {
String attr = "attr";
session.setAttribute(attr, new Object());
session.setAttribute(attr, null);
assertThat(session.getAttributeNames()).isEmpty();
}
/**
* Ensure conforms to the javadoc of {@link Session}
*/
@Test
public void setAttributeNullObjectRemoves() {
String attr = "attr";
session.setAttribute(attr, new Object());
session.setAttribute(attr, null);
assertThat(session.getAttributeNames()).isEmpty();
}
@Test
public void equalsNonSessionFalse() {
assertThat(session.equals(new Object())).isFalse();
}
@Test
public void equalsNonSessionFalse() {
assertThat(session.equals(new Object())).isFalse();
}
@Test
public void equalsCustomSession() {
CustomSession other = new CustomSession();
session.setId(other.getId());
assertThat(session.equals(other)).isTrue();
}
@Test
public void equalsCustomSession() {
CustomSession other = new CustomSession();
session.setId(other.getId());
assertThat(session.equals(other)).isTrue();
}
@Test
public void hashCodeEqualsIdHashCode() {
session.setId("constantId");
assertThat(session.hashCode()).isEqualTo(session.getId().hashCode());
}
@Test
public void hashCodeEqualsIdHashCode() {
session.setId("constantId");
assertThat(session.hashCode()).isEqualTo(session.getId().hashCode());
}
@Test
public void isExpiredExact() {
long now = 1413260062962L;
assertThat(session.isExpired(now)).isTrue();
}
@Test
public void isExpiredExact() {
long now = 1413260062962L;
assertThat(session.isExpired(now)).isTrue();
}
@Test
public void isExpiredOneMsTooSoon() {
long now = 1413260062961L;
assertThat(session.isExpired(now)).isFalse();
}
@Test
public void isExpiredOneMsTooSoon() {
long now = 1413260062961L;
assertThat(session.isExpired(now)).isFalse();
}
@Test
public void isExpiredOneMsAfter() {
long now = 1413260062963L;
assertThat(session.isExpired(now)).isTrue();
}
@Test
public void isExpiredOneMsAfter() {
long now = 1413260062963L;
assertThat(session.isExpired(now)).isTrue();
}
static class CustomSession implements ExpiringSession {
static class CustomSession implements ExpiringSession {
public long getCreationTime() {
return 0;
}
public long getCreationTime() {
return 0;
}
public String getId() {
return "id";
}
public String getId() {
return "id";
}
public long getLastAccessedTime() {
return 0;
}
public long getLastAccessedTime() {
return 0;
}
public void setMaxInactiveIntervalInSeconds(int interval) {
public void setMaxInactiveIntervalInSeconds(int interval) {
}
}
public int getMaxInactiveIntervalInSeconds() {
return 0;
}
public int getMaxInactiveIntervalInSeconds() {
return 0;
}
public Object getAttribute(String attributeName) {
return null;
}
public Object getAttribute(String attributeName) {
return null;
}
public Set<String> getAttributeNames() {
return null;
}
public Set<String> getAttributeNames() {
return null;
}
public void setAttribute(String attributeName, Object attributeValue) {
public void setAttribute(String attributeName, Object attributeValue) {
}
}
public void removeAttribute(String attributeName) {
public void removeAttribute(String attributeName) {
}
}
public boolean isExpired() {
return false;
}
}
public boolean isExpired() {
return false;
}
}
}

View File

@@ -1,3 +1,18 @@
/*
* Copyright 2002-2015 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.redis;
import static org.fest.assertions.Assertions.assertThat;
@@ -34,234 +49,231 @@ import org.springframework.session.data.redis.RedisOperationsSessionRepository.R
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings({"unchecked","rawtypes"})
public class RedisOperationsSessionRepositoryTests {
@Mock
RedisConnectionFactory factory;
@Mock
RedisConnection connection;
@Mock
RedisOperations redisOperations;
@Mock
BoundHashOperations<String, Object, Object> boundHashOperations;
@Mock
BoundSetOperations<String, String> boundSetOperations;
@Captor
ArgumentCaptor<Map<String,Object>> delta;
@Mock
RedisConnectionFactory factory;
@Mock
RedisConnection connection;
@Mock
RedisOperations redisOperations;
@Mock
BoundHashOperations<String, Object, Object> boundHashOperations;
@Mock
BoundSetOperations<String, String> boundSetOperations;
@Captor
ArgumentCaptor<Map<String,Object>> delta;
private RedisOperationsSessionRepository redisRepository;
private RedisOperationsSessionRepository redisRepository;
@Before
public void setup() {
this.redisRepository = new RedisOperationsSessionRepository(redisOperations);
}
@Before
public void setup() {
this.redisRepository = new RedisOperationsSessionRepository(redisOperations);
}
@Test(expected=IllegalArgumentException.class)
public void constructorNullConnectionFactory() {
new RedisOperationsSessionRepository((RedisConnectionFactory)null);
}
@Test(expected=IllegalArgumentException.class)
public void constructorNullConnectionFactory() {
new RedisOperationsSessionRepository((RedisConnectionFactory)null);
}
// gh-61
@Test
public void constructorConnectionFactory() {
redisRepository = new RedisOperationsSessionRepository(factory);
RedisSession session = redisRepository.createSession();
// gh-61
@Test
public void constructorConnectionFactory() {
redisRepository = new RedisOperationsSessionRepository(factory);
RedisSession session = redisRepository.createSession();
when(factory.getConnection()).thenReturn(connection);
when(factory.getConnection()).thenReturn(connection);
redisRepository.save(session);
}
redisRepository.save(session);
}
@Test
public void createSessionDefaultMaxInactiveInterval() throws Exception {
ExpiringSession session = redisRepository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
}
@Test
public void createSessionDefaultMaxInactiveInterval() throws Exception {
ExpiringSession session = redisRepository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
}
@Test
public void createSessionCustomMaxInactiveInterval() throws Exception {
int interval = 1;
redisRepository.setDefaultMaxInactiveInterval(interval);
ExpiringSession session = redisRepository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(interval);
}
@Test
public void createSessionCustomMaxInactiveInterval() throws Exception {
int interval = 1;
redisRepository.setDefaultMaxInactiveInterval(interval);
ExpiringSession session = redisRepository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(interval);
}
@Test
public void saveNewSession() {
RedisSession session = redisRepository.createSession();
when(redisOperations.boundHashOps(getKey(session.getId()))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
@Test
public void saveNewSession() {
RedisSession session = redisRepository.createSession();
when(redisOperations.boundHashOps(getKey(session.getId()))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
redisRepository.save(session);
redisRepository.save(session);
Map<String,Object> delta = getDelta();
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta.get(CREATION_TIME_ATTR);
assertThat(creationTime).isInstanceOf(Long.class);
assertThat(delta.get(MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(LAST_ACCESSED_ATTR)).isEqualTo(creationTime);
}
Map<String,Object> delta = getDelta();
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta.get(CREATION_TIME_ATTR);
assertThat(creationTime).isInstanceOf(Long.class);
assertThat(delta.get(MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(LAST_ACCESSED_ATTR)).isEqualTo(creationTime);
}
@Test
public void saveLastAccessChanged() {
RedisSession session = redisRepository.new RedisSession(new MapSession());
session.setLastAccessedTime(12345678L);
when(redisOperations.boundHashOps(getKey(session.getId()))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
@Test
public void saveLastAccessChanged() {
RedisSession session = redisRepository.new RedisSession(new MapSession());
session.setLastAccessedTime(12345678L);
when(redisOperations.boundHashOps(getKey(session.getId()))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
redisRepository.save(session);
redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(LAST_ACCESSED_ATTR, session.getLastAccessedTime()));
}
assertThat(getDelta()).isEqualTo(map(LAST_ACCESSED_ATTR, session.getLastAccessedTime()));
}
@Test
public void saveSetAttribute() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession(new MapSession());
session.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(getKey(session.getId()))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
@Test
public void saveSetAttribute() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession(new MapSession());
session.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(getKey(session.getId()))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
redisRepository.save(session);
redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
assertThat(getDelta()).isEqualTo(map(getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
@Test
public void saveRemoveAttribute() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession(new MapSession());
session.removeAttribute(attrName);
when(redisOperations.boundHashOps(getKey(session.getId()))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
@Test
public void saveRemoveAttribute() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession(new MapSession());
session.removeAttribute(attrName);
when(redisOperations.boundHashOps(getKey(session.getId()))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
redisRepository.save(session);
redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(getSessionAttrNameKey(attrName), null));
}
assertThat(getDelta()).isEqualTo(map(getSessionAttrNameKey(attrName), null));
}
@Test
public void redisSessionGetAttributes() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession(new MapSession());
assertThat(session.getAttributeNames()).isEmpty();
session.setAttribute(attrName, "attrValue");
assertThat(session.getAttributeNames()).containsOnly(attrName);
session.removeAttribute(attrName);
assertThat(session.getAttributeNames()).isEmpty();
}
@Test
public void redisSessionGetAttributes() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession(new MapSession());
assertThat(session.getAttributeNames()).isEmpty();
session.setAttribute(attrName, "attrValue");
assertThat(session.getAttributeNames()).containsOnly(attrName);
session.removeAttribute(attrName);
assertThat(session.getAttributeNames()).isEmpty();
}
@Test
public void delete() {
String attrName = "attrName";
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(getKey(expected.getId()))).thenReturn(boundHashOperations);
Map map = map(
getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
CREATION_TIME_ATTR, expected.getCreationTime(),
MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(),
LAST_ACCESSED_ATTR, expected.getLastAccessedTime());
when(boundHashOperations.entries()).thenReturn(map);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
@Test
public void delete() {
String attrName = "attrName";
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(getKey(expected.getId()))).thenReturn(boundHashOperations);
Map map = map(
getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
CREATION_TIME_ATTR, expected.getCreationTime(),
MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(),
LAST_ACCESSED_ATTR, expected.getLastAccessedTime());
when(boundHashOperations.entries()).thenReturn(map);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
String id = expected.getId();
redisRepository.delete(id);
verify(redisOperations).delete(getKey(id));
}
String id = expected.getId();
redisRepository.delete(id);
verify(redisOperations).delete(getKey(id));
}
@Test
public void deleteNullSession() {
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
@Test
public void deleteNullSession() {
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
String id = "abc";
redisRepository.delete(id);
verify(redisOperations,times(0)).delete(anyString());
verify(redisOperations,times(0)).delete(anyString());
}
String id = "abc";
redisRepository.delete(id);
verify(redisOperations,times(0)).delete(anyString());
verify(redisOperations,times(0)).delete(anyString());
}
@Test
@SuppressWarnings("unchecked")
public void getSessionNotFound() {
String id = "abc";
when(redisOperations.boundHashOps(getKey(id))).thenReturn(boundHashOperations);
when(boundHashOperations.entries()).thenReturn(map());
@Test
public void getSessionNotFound() {
String id = "abc";
when(redisOperations.boundHashOps(getKey(id))).thenReturn(boundHashOperations);
when(boundHashOperations.entries()).thenReturn(map());
assertThat(redisRepository.getSession(id)).isNull();
}
assertThat(redisRepository.getSession(id)).isNull();
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void getSessionFound() {
String attrName = "attrName";
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(getKey(expected.getId()))).thenReturn(boundHashOperations);
Map map = map(
getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
CREATION_TIME_ATTR, expected.getCreationTime(),
MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(),
LAST_ACCESSED_ATTR, expected.getLastAccessedTime());
when(boundHashOperations.entries()).thenReturn(map);
@Test
public void getSessionFound() {
String attrName = "attrName";
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(getKey(expected.getId()))).thenReturn(boundHashOperations);
Map map = map(
getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
CREATION_TIME_ATTR, expected.getCreationTime(),
MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(),
LAST_ACCESSED_ATTR, expected.getLastAccessedTime());
when(boundHashOperations.entries()).thenReturn(map);
long now = System.currentTimeMillis();
RedisSession session = 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.getCreationTime()).isEqualTo(expected.getCreationTime());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expected.getMaxInactiveIntervalInSeconds());
assertThat(session.getLastAccessedTime()).isGreaterThanOrEqualTo(now);
long now = System.currentTimeMillis();
RedisSession session = 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.getCreationTime()).isEqualTo(expected.getCreationTime());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expected.getMaxInactiveIntervalInSeconds());
assertThat(session.getLastAccessedTime()).isGreaterThanOrEqualTo(now);
}
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void getSessionExpired() {
String expiredId = "expired-id";
when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations);
Map map = map(
MAX_INACTIVE_ATTR, 1,
LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
when(boundHashOperations.entries()).thenReturn(map);
@Test
public void getSessionExpired() {
String expiredId = "expired-id";
when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations);
Map map = map(
MAX_INACTIVE_ATTR, 1,
LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
when(boundHashOperations.entries()).thenReturn(map);
assertThat(redisRepository.getSession(expiredId)).isNull();
}
assertThat(redisRepository.getSession(expiredId)).isNull();
}
@Test
public void cleanupExpiredSessions() {
String expiredId = "expired-id";
when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
@Test
public void cleanupExpiredSessions() {
String expiredId = "expired-id";
when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
Set<String> expiredIds = new HashSet<String>(Arrays.asList("expired-key1","expired-key2"));
when(boundSetOperations.members()).thenReturn(expiredIds);
Set<String> expiredIds = new HashSet<String>(Arrays.asList("expired-key1","expired-key2"));
when(boundSetOperations.members()).thenReturn(expiredIds);
redisRepository.cleanupExpiredSessions();
redisRepository.cleanupExpiredSessions();
for(String id : expiredIds) {
String expiredKey = RedisOperationsSessionRepository.BOUNDED_HASH_KEY_PREFIX + id;
// https://github.com/spring-projects/spring-session/issues/93
verify(redisOperations).hasKey(expiredKey);
}
}
for(String id : expiredIds) {
String expiredKey = RedisOperationsSessionRepository.BOUNDED_HASH_KEY_PREFIX + id;
// https://github.com/spring-projects/spring-session/issues/93
verify(redisOperations).hasKey(expiredKey);
}
}
@SuppressWarnings("rawtypes")
private Map map(Object...objects) {
Map<String,Object> result = new HashMap<String,Object>();
if(objects == null) {
return result;
}
for(int i = 0; i < objects.length; i += 2) {
result.put((String)objects[i], objects[i+1]);
}
return result;
}
private Map map(Object...objects) {
Map<String,Object> result = new HashMap<String,Object>();
if(objects == null) {
return result;
}
for(int i = 0; i < objects.length; i += 2) {
result.put((String)objects[i], objects[i+1]);
}
return result;
}
private Map<String,Object> getDelta() {
verify(boundHashOperations).putAll(delta.capture());
return delta.getValue();
}
private Map<String,Object> getDelta() {
verify(boundHashOperations).putAll(delta.capture());
return delta.getValue();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 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.
@@ -40,109 +40,109 @@ import org.springframework.session.events.SessionDestroyedEvent;
*/
@RunWith(MockitoJUnitRunner.class)
public class SessionMessageListenerTests {
@Mock
ApplicationEventPublisher eventPublisher;
@Mock
ApplicationEventPublisher eventPublisher;
@Mock
Message message;
@Mock
Message message;
@Captor
ArgumentCaptor<SessionDestroyedEvent> event;
@Captor
ArgumentCaptor<SessionDestroyedEvent> event;
byte[] pattern;
byte[] pattern;
SessionMessageListener listener;
SessionMessageListener listener;
@Before
public void setup() {
listener = new SessionMessageListener(eventPublisher);
}
@Before
public void setup() {
listener = new SessionMessageListener(eventPublisher);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullEventPublisher() {
new SessionMessageListener(null);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullEventPublisher() {
new SessionMessageListener(null);
}
@Test
public void onMessageNullBody() throws Exception {
listener.onMessage(message, pattern);
@Test
public void onMessageNullBody() throws Exception {
listener.onMessage(message, pattern);
verifyZeroInteractions(eventPublisher);
}
verifyZeroInteractions(eventPublisher);
}
@Test
public void onMessageDel() throws Exception {
mockMessage("__keyevent@0__:del", "spring:session:sessions:123");
@Test
public void onMessageDel() throws Exception {
mockMessage("__keyevent@0__:del", "spring:session:sessions:123");
listener.onMessage(message, pattern);
listener.onMessage(message, pattern);
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getSessionId()).isEqualTo("123");
}
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getSessionId()).isEqualTo("123");
}
@Test
public void onMessageSource() throws Exception {
mockMessage("__keyevent@0__:del","spring:session:sessions:123");
@Test
public void onMessageSource() throws Exception {
mockMessage("__keyevent@0__:del","spring:session:sessions:123");
listener.onMessage(message, pattern);
listener.onMessage(message, pattern);
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getSource()).isEqualTo(listener);
}
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getSource()).isEqualTo(listener);
}
@Test
public void onMessageExpired() throws Exception {
mockMessage("__keyevent@0__:expired","spring:session:sessions:543");
@Test
public void onMessageExpired() throws Exception {
mockMessage("__keyevent@0__:expired","spring:session:sessions:543");
listener.onMessage(message, pattern);
listener.onMessage(message, pattern);
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getSessionId()).isEqualTo("543");
}
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getSessionId()).isEqualTo("543");
}
@Test
public void onMessageHset() throws Exception {
mockMessage("__keyevent@0__:hset","spring:session:sessions:123");
@Test
public void onMessageHset() throws Exception {
mockMessage("__keyevent@0__:hset","spring:session:sessions:123");
listener.onMessage(message, pattern);
listener.onMessage(message, pattern);
verifyZeroInteractions(eventPublisher);
}
verifyZeroInteractions(eventPublisher);
}
@Test
public void onMessageWrongKeyPrefix() throws Exception {
mockMessage("__keyevent@0__:del","spring:session:sessionsNo:123");
@Test
public void onMessageWrongKeyPrefix() throws Exception {
mockMessage("__keyevent@0__:del","spring:session:sessionsNo:123");
listener.onMessage(message, pattern);
listener.onMessage(message, pattern);
verifyZeroInteractions(eventPublisher);
}
verifyZeroInteractions(eventPublisher);
}
@Test
public void onMessageRename() throws Exception {
mockMessage("__keyevent@0__:rename","spring:session:sessions:123");
@Test
public void onMessageRename() throws Exception {
mockMessage("__keyevent@0__:rename","spring:session:sessions:123");
listener.onMessage(message, pattern);
listener.onMessage(message, pattern);
verifyZeroInteractions(eventPublisher);
}
verifyZeroInteractions(eventPublisher);
}
@Test
public void onMessageEventPublisherErrorCaught() throws Exception {
mockMessage("__keyevent@0__:del","spring:session:sessions:123");
doThrow(new IllegalStateException("Test Exceptions are caught")).when(eventPublisher).publishEvent(any(ApplicationEvent.class));
@Test
public void onMessageEventPublisherErrorCaught() throws Exception {
mockMessage("__keyevent@0__:del","spring:session:sessions:123");
doThrow(new IllegalStateException("Test Exceptions are caught")).when(eventPublisher).publishEvent(any(ApplicationEvent.class));
listener.onMessage(message, pattern);
listener.onMessage(message, pattern);
verify(eventPublisher).publishEvent(any(ApplicationEvent.class));
}
verify(eventPublisher).publishEvent(any(ApplicationEvent.class));
}
private void mockMessage(String channel, String body) throws UnsupportedEncodingException {
when(message.getBody()).thenReturn(bytes(body));
when(message.getChannel()).thenReturn(bytes(channel));
}
private void mockMessage(String channel, String body) throws UnsupportedEncodingException {
when(message.getBody()).thenReturn(bytes(body));
when(message.getChannel()).thenReturn(bytes(channel));
}
private static byte[] bytes(String s) throws UnsupportedEncodingException {
return s.getBytes("UTF-8");
}
private static byte[] bytes(String s) throws UnsupportedEncodingException {
return s.getBytes("UTF-8");
}
}

View File

@@ -1,3 +1,18 @@
/*
* Copyright 2002-2015 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.redis.config.annotation.web.http;
import static org.fest.assertions.Assertions.assertThat;
@@ -20,132 +35,132 @@ import java.util.Arrays;
@RunWith(MockitoJUnitRunner.class)
public class EnableRedisKeyspaceNotificationsInitializerTests {
static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events";
static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events";
@Mock
RedisConnectionFactory connectionFactory;
@Mock
RedisConnection connection;
@Captor
ArgumentCaptor<String> options;
@Mock
RedisConnectionFactory connectionFactory;
@Mock
RedisConnection connection;
@Captor
ArgumentCaptor<String> options;
EnableRedisKeyspaceNotificationsInitializer initializer;
EnableRedisKeyspaceNotificationsInitializer initializer;
@Before
public void setup() {
when(connectionFactory.getConnection()).thenReturn(connection);
@Before
public void setup() {
when(connectionFactory.getConnection()).thenReturn(connection);
initializer = new EnableRedisKeyspaceNotificationsInitializer(connectionFactory);
}
initializer = new EnableRedisKeyspaceNotificationsInitializer(connectionFactory);
}
@Test
public void afterPropertiesSetUnset() throws Exception {
setConfigNotification("");
@Test
public void afterPropertiesSetUnset() throws Exception {
setConfigNotification("");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("E","g","x");
}
assertOptionsContains("E","g","x");
}
@Test
public void afterPropertiesSetA() throws Exception {
setConfigNotification("A");
@Test
public void afterPropertiesSetA() throws Exception {
setConfigNotification("A");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("A", "E");
}
assertOptionsContains("A", "E");
}
@Test
public void afterPropertiesSetE() throws Exception {
setConfigNotification("E");
@Test
public void afterPropertiesSetE() throws Exception {
setConfigNotification("E");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("E", "g", "x");
}
assertOptionsContains("E", "g", "x");
}
@Test
public void afterPropertiesSetK() throws Exception {
setConfigNotification("K");
@Test
public void afterPropertiesSetK() throws Exception {
setConfigNotification("K");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("K", "E", "g", "x");
}
assertOptionsContains("K", "E", "g", "x");
}
@Test
public void afterPropertiesSetAE() throws Exception {
setConfigNotification("AE");
@Test
public void afterPropertiesSetAE() throws Exception {
setConfigNotification("AE");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
verify(connection, never()).setConfig(anyString(), anyString());
}
verify(connection, never()).setConfig(anyString(), anyString());
}
@Test
public void afterPropertiesSetAK() throws Exception {
setConfigNotification("AK");
@Test
public void afterPropertiesSetAK() throws Exception {
setConfigNotification("AK");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("A", "K", "E");
}
assertOptionsContains("A", "K", "E");
}
@Test
public void afterPropertiesSetEK() throws Exception {
setConfigNotification("EK");
@Test
public void afterPropertiesSetEK() throws Exception {
setConfigNotification("EK");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("E", "K", "g", "x");
}
assertOptionsContains("E", "K", "g", "x");
}
@Test
public void afterPropertiesSetEg() throws Exception {
setConfigNotification("Eg");
@Test
public void afterPropertiesSetEg() throws Exception {
setConfigNotification("Eg");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("E", "g", "x");
}
assertOptionsContains("E", "g", "x");
}
@Test
public void afterPropertiesSetE$() throws Exception {
setConfigNotification("E$");
@Test
public void afterPropertiesSetE$() throws Exception {
setConfigNotification("E$");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("E", "$", "g", "x");
}
assertOptionsContains("E", "$", "g", "x");
}
@Test
public void afterPropertiesSetKg() throws Exception {
setConfigNotification("Kg");
@Test
public void afterPropertiesSetKg() throws Exception {
setConfigNotification("Kg");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
assertOptionsContains("K", "g", "E", "x");
}
assertOptionsContains("K", "g", "E", "x");
}
@Test
public void afterPropertiesSetAEK() throws Exception {
setConfigNotification("AEK");
@Test
public void afterPropertiesSetAEK() throws Exception {
setConfigNotification("AEK");
initializer.afterPropertiesSet();
initializer.afterPropertiesSet();
verify(connection, never()).setConfig(anyString(), anyString());
}
verify(connection, never()).setConfig(anyString(), anyString());
}
private void assertOptionsContains(String... expectedValues) {
verify(connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), options.capture());
for(String expectedValue : expectedValues) {
assertThat(options.getValue()).contains(expectedValue);
}
assertThat(options.getValue().length()).isEqualTo(expectedValues.length);
}
private void assertOptionsContains(String... expectedValues) {
verify(connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), options.capture());
for(String expectedValue : expectedValues) {
assertThat(options.getValue()).contains(expectedValue);
}
assertThat(options.getValue().length()).isEqualTo(expectedValues.length);
}
private void setConfigNotification(String value) {
when(connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)).thenReturn(Arrays.asList(CONFIG_NOTIFY_KEYSPACE_EVENTS, value));
}
private void setConfigNotification(String value) {
when(connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)).thenReturn(Arrays.asList(CONFIG_NOTIFY_KEYSPACE_EVENTS, value));
}
}

View File

@@ -1,3 +1,18 @@
/*
* Copyright 2002-2015 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.web.http;
import static org.fest.assertions.Assertions.*;
@@ -13,405 +28,405 @@ import javax.servlet.http.Cookie;
import java.util.Map;
public class CookieHttpSessionStrategyTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private CookieHttpSessionStrategy strategy;
private String cookieName;
private Session session;
@Before
public void setup() throws Exception {
cookieName = "SESSION";
session = new MapSession();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
strategy = new CookieHttpSessionStrategy();
}
@Test
public void getRequestedSessionIdNull() throws Exception {
assertThat(strategy.getRequestedSessionId(request)).isNull();
}
@Test
public void getRequestedSessionIdNotNull() throws Exception {
setSessionCookie(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
}
@Test
public void getRequestedSessionIdNotNullCustomCookieName() throws Exception {
setCookieName("CUSTOM");
setSessionCookie(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
}
@Test
public void onNewSession() throws Exception {
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onNewSessionExistingSessionSameAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie(existing.getId());
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onNewSessionExistingSessionNewAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie(existing.getId());
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo("0 " + existing.getId() + " new " + session.getId());
}
@Test
public void onNewSessionCookiePath() throws Exception {
request.setContextPath("/somethingunique");
strategy.onNewSession(session, request, response);
Cookie sessionCookie = response.getCookie(cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(request.getContextPath() + "/");
}
@Test
public void onNewSessionCustomCookieName() throws Exception {
setCookieName("CUSTOM");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onDeleteSession() throws Exception {
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionCookiePath() throws Exception {
request.setContextPath("/somethingunique");
strategy.onInvalidateSession(request, response);
Cookie sessionCookie = response.getCookie(cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(request.getContextPath() + "/");
}
@Test
public void onDeleteSessionCustomCookieName() throws Exception {
setCookieName("CUSTOM");
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionExistingSessionSameAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie("0 " + existing.getId() + " new " + session.getId());
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onDeleteSessionExistingSessionNewAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie("0 " + existing.getId() + " new " + session.getId());
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEqualTo(existing.getId());
}
@Test(expected = IllegalArgumentException.class)
public void setCookieNameNull() throws Exception {
strategy.setCookieName(null);
}
@Test
public void encodeURLNoExistingQuery() {
assertThat(strategy.encodeURL("/url", "2")).isEqualTo("/url?_s=2");
}
@Test
public void encodeURLNoExistingQueryEmpty() {
assertThat(strategy.encodeURL("/url?", "2")).isEqualTo("/url?_s=2");
}
@Test
public void encodeURLExistingQueryNoAlias() {
assertThat(strategy.encodeURL("/url?a=b", "2")).isEqualTo("/url?a=b&_s=2");
}
@Test
public void encodeURLExistingQueryExistingAliasStart() {
assertThat(strategy.encodeURL("/url?_s=1&y=z", "2")).isEqualTo("/url?_s=2&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasMiddle() {
assertThat(strategy.encodeURL("/url?a=b&_s=1&y=z", "2")).isEqualTo("/url?a=b&_s=2&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasEnd() {
assertThat(strategy.encodeURL("/url?a=b&_s=1", "2")).isEqualTo("/url?a=b&_s=2");
}
//
@Test
public void encodeURLExistingQueryParamEndsWithActualParamStart() {
assertThat(strategy.encodeURL("/url?x_s=1&y=z", "2")).isEqualTo("/url?x_s=1&y=z&_s=2");
}
@Test
public void encodeURLExistingQueryParamEndsWithActualParamMiddle() {
assertThat(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(strategy.encodeURL("/url?a=b&x_s=1", "2")).isEqualTo("/url?a=b&x_s=1&_s=2");
}
//
@Test
public void encodeURLNoExistingQueryDefaultAlias() {
assertThat(strategy.encodeURL("/url", "0")).isEqualTo("/url");
}
@Test
public void encodeURLNoExistingQueryEmptyDefaultAlias() {
assertThat(strategy.encodeURL("/url?", "0")).isEqualTo("/url?");
}
@Test
public void encodeURLExistingQueryNoAliasDefaultAlias() {
assertThat(strategy.encodeURL("/url?a=b", "0")).isEqualTo("/url?a=b");
}
@Test
public void encodeURLExistingQueryExistingAliasStartDefaultAlias() {
// relaxed constraint as result /url?&y=z does not hurt anything (ideally should remove the &)
assertThat(strategy.encodeURL("/url?_s=1&y=z", "0")).doesNotContain("_s=0&_s=1");
}
@Test
public void encodeURLExistingQueryExistingAliasMiddleDefaultAlias() {
assertThat(strategy.encodeURL("/url?a=b&_s=1&y=z", "0")).isEqualTo("/url?a=b&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasEndDefaultAlias() {
assertThat(strategy.encodeURL("/url?a=b&_s=1", "0")).isEqualTo("/url?a=b");
}
@Test
public void encodeURLMaliciousAlias() {
assertThat(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(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasNullParamName() {
strategy.setSessionAliasParamName(null);
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "NOT USED");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
// protect against malicious users
@Test
public void getCurrentSessionAliasContainsQuote() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here\"this");
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private CookieHttpSessionStrategy strategy;
private String cookieName;
private Session session;
@Before
public void setup() throws Exception {
cookieName = "SESSION";
session = new MapSession();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
strategy = new CookieHttpSessionStrategy();
}
@Test
public void getRequestedSessionIdNull() throws Exception {
assertThat(strategy.getRequestedSessionId(request)).isNull();
}
@Test
public void getRequestedSessionIdNotNull() throws Exception {
setSessionCookie(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
}
@Test
public void getRequestedSessionIdNotNullCustomCookieName() throws Exception {
setCookieName("CUSTOM");
setSessionCookie(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
}
@Test
public void onNewSession() throws Exception {
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onNewSessionExistingSessionSameAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie(existing.getId());
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onNewSessionExistingSessionNewAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie(existing.getId());
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo("0 " + existing.getId() + " new " + session.getId());
}
@Test
public void onNewSessionCookiePath() throws Exception {
request.setContextPath("/somethingunique");
strategy.onNewSession(session, request, response);
Cookie sessionCookie = response.getCookie(cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(request.getContextPath() + "/");
}
@Test
public void onNewSessionCustomCookieName() throws Exception {
setCookieName("CUSTOM");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onDeleteSession() throws Exception {
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionCookiePath() throws Exception {
request.setContextPath("/somethingunique");
strategy.onInvalidateSession(request, response);
Cookie sessionCookie = response.getCookie(cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(request.getContextPath() + "/");
}
@Test
public void onDeleteSessionCustomCookieName() throws Exception {
setCookieName("CUSTOM");
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionExistingSessionSameAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie("0 " + existing.getId() + " new " + session.getId());
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onDeleteSessionExistingSessionNewAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie("0 " + existing.getId() + " new " + session.getId());
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEqualTo(existing.getId());
}
@Test(expected = IllegalArgumentException.class)
public void setCookieNameNull() throws Exception {
strategy.setCookieName(null);
}
@Test
public void encodeURLNoExistingQuery() {
assertThat(strategy.encodeURL("/url", "2")).isEqualTo("/url?_s=2");
}
@Test
public void encodeURLNoExistingQueryEmpty() {
assertThat(strategy.encodeURL("/url?", "2")).isEqualTo("/url?_s=2");
}
@Test
public void encodeURLExistingQueryNoAlias() {
assertThat(strategy.encodeURL("/url?a=b", "2")).isEqualTo("/url?a=b&_s=2");
}
@Test
public void encodeURLExistingQueryExistingAliasStart() {
assertThat(strategy.encodeURL("/url?_s=1&y=z", "2")).isEqualTo("/url?_s=2&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasMiddle() {
assertThat(strategy.encodeURL("/url?a=b&_s=1&y=z", "2")).isEqualTo("/url?a=b&_s=2&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasEnd() {
assertThat(strategy.encodeURL("/url?a=b&_s=1", "2")).isEqualTo("/url?a=b&_s=2");
}
//
@Test
public void encodeURLExistingQueryParamEndsWithActualParamStart() {
assertThat(strategy.encodeURL("/url?x_s=1&y=z", "2")).isEqualTo("/url?x_s=1&y=z&_s=2");
}
@Test
public void encodeURLExistingQueryParamEndsWithActualParamMiddle() {
assertThat(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(strategy.encodeURL("/url?a=b&x_s=1", "2")).isEqualTo("/url?a=b&x_s=1&_s=2");
}
//
@Test
public void encodeURLNoExistingQueryDefaultAlias() {
assertThat(strategy.encodeURL("/url", "0")).isEqualTo("/url");
}
@Test
public void encodeURLNoExistingQueryEmptyDefaultAlias() {
assertThat(strategy.encodeURL("/url?", "0")).isEqualTo("/url?");
}
@Test
public void encodeURLExistingQueryNoAliasDefaultAlias() {
assertThat(strategy.encodeURL("/url?a=b", "0")).isEqualTo("/url?a=b");
}
@Test
public void encodeURLExistingQueryExistingAliasStartDefaultAlias() {
// relaxed constraint as result /url?&y=z does not hurt anything (ideally should remove the &)
assertThat(strategy.encodeURL("/url?_s=1&y=z", "0")).doesNotContain("_s=0&_s=1");
}
@Test
public void encodeURLExistingQueryExistingAliasMiddleDefaultAlias() {
assertThat(strategy.encodeURL("/url?a=b&_s=1&y=z", "0")).isEqualTo("/url?a=b&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasEndDefaultAlias() {
assertThat(strategy.encodeURL("/url?a=b&_s=1", "0")).isEqualTo("/url?a=b");
}
@Test
public void encodeURLMaliciousAlias() {
assertThat(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(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasNullParamName() {
strategy.setSessionAliasParamName(null);
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "NOT USED");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
// protect against malicious users
@Test
public void getCurrentSessionAliasContainsQuote() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here\"this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsSingleQuote() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here'this");
@Test
public void getCurrentSessionAliasContainsSingleQuote() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here'this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsSpace() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here this");
@Test
public void getCurrentSessionAliasContainsSpace() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsLt() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here<this");
@Test
public void getCurrentSessionAliasContainsLt() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here<this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsGt() {
strategy.setSessionAliasParamName(null);
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here>this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsGt() {
strategy.setSessionAliasParamName(null);
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here>this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasTooLong() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "012345678901234567890123456789012345678901234567890");
@Test
public void getCurrentSessionAliasTooLong() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "012345678901234567890123456789012345678901234567890");
assertThat(strategy.getCurrentSessionAlias(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
@Test
public void getCurrentSessionAliasAllows50() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "01234567890123456789012345678901234567890123456789");
assertThat(strategy.getCurrentSessionAlias(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
@Test
public void getCurrentSessionAliasAllows50() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "01234567890123456789012345678901234567890123456789");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo("01234567890123456789012345678901234567890123456789");
}
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo("01234567890123456789012345678901234567890123456789");
}
@Test
public void getCurrentSession() {
String expectedAlias = "1";
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, expectedAlias);
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(expectedAlias);
}
@Test
public void getCurrentSession() {
String expectedAlias = "1";
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, expectedAlias);
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(expectedAlias);
}
// --- getNewSessionAlias
// --- getNewSessionAlias
@Test
public void getNewSessionAliasNoSessions() {
assertThat(strategy.getNewSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getNewSessionAliasSingleSession() {
setSessionCookie("abc");
@Test
public void getNewSessionAliasNoSessions() {
assertThat(strategy.getNewSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getNewSessionAliasSingleSession() {
setSessionCookie("abc");
assertThat(strategy.getNewSessionAlias(request)).isEqualTo("1");
}
assertThat(strategy.getNewSessionAlias(request)).isEqualTo("1");
}
@Test
public void getNewSessionAlias2Sessions() {
setCookieWithNSessions(2);
@Test
public void getNewSessionAlias2Sessions() {
setCookieWithNSessions(2);
assertThat(strategy.getNewSessionAlias(request)).isEqualTo("2");
}
assertThat(strategy.getNewSessionAlias(request)).isEqualTo("2");
}
@Test
public void getNewSessionAlias9Sessions() {
setCookieWithNSessions(9);
@Test
public void getNewSessionAlias9Sessions() {
setCookieWithNSessions(9);
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("9");
}
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("9");
}
@Test
public void getNewSessionAlias10Sessions() {
setCookieWithNSessions(10);
@Test
public void getNewSessionAlias10Sessions() {
setCookieWithNSessions(10);
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("a");
}
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("a");
}
@Test
public void getNewSessionAlias16Sessions() {
setCookieWithNSessions(16);
@Test
public void getNewSessionAlias16Sessions() {
setCookieWithNSessions(16);
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("10");
}
@Test
public void getNewSessionAliasInvalidAlias() {
setSessionCookie("0 1 $ b");
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("10");
}
@Test
public void getNewSessionAliasInvalidAlias() {
setSessionCookie("0 1 $ b");
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("1");
}
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("1");
}
// --- getSessionIds
// --- getSessionIds
@Test
public void getSessionIdsNone() {
assertThat(strategy.getSessionIds(request)).isEmpty();
}
@Test
public void getSessionIdsNone() {
assertThat(strategy.getSessionIds(request)).isEmpty();
}
@Test
public void getSessionIdsSingle() {
String expectedId = "a";
setSessionCookie(expectedId);
Map<String, String> sessionIds = strategy.getSessionIds(request);
assertThat(sessionIds.size()).isEqualTo(1);
assertThat(sessionIds.get("0")).isEqualTo(expectedId);
}
@Test
public void getSessionIdsMulti() {
setSessionCookie("0 a 1 b");
Map<String, String> sessionIds = strategy.getSessionIds(request);
assertThat(sessionIds.size()).isEqualTo(2);
assertThat(sessionIds.get("0")).isEqualTo("a");
assertThat(sessionIds.get("1")).isEqualTo("b");
}
@Test
public void getSessionIdsDangling() {
setSessionCookie("0 a 1 b noValue");
Map<String, String> sessionIds = strategy.getSessionIds(request);
assertThat(sessionIds.size()).isEqualTo(2);
assertThat(sessionIds.get("0")).isEqualTo("a");
assertThat(sessionIds.get("1")).isEqualTo("b");
}
// --- helper
@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");
}
private void setCookieWithNSessions(long size) {
setSessionCookie(createSessionCookieValue(size));
}
private String createSessionCookieValue(long size) {
StringBuffer buffer = new StringBuffer();
@Test
public void getSessionIdsSingle() {
String expectedId = "a";
setSessionCookie(expectedId);
Map<String, String> sessionIds = strategy.getSessionIds(request);
assertThat(sessionIds.size()).isEqualTo(1);
assertThat(sessionIds.get("0")).isEqualTo(expectedId);
}
@Test
public void getSessionIdsMulti() {
setSessionCookie("0 a 1 b");
Map<String, String> sessionIds = strategy.getSessionIds(request);
assertThat(sessionIds.size()).isEqualTo(2);
assertThat(sessionIds.get("0")).isEqualTo("a");
assertThat(sessionIds.get("1")).isEqualTo("b");
}
@Test
public void getSessionIdsDangling() {
setSessionCookie("0 a 1 b noValue");
Map<String, String> sessionIds = strategy.getSessionIds(request);
assertThat(sessionIds.size()).isEqualTo(2);
assertThat(sessionIds.get("0")).isEqualTo("a");
assertThat(sessionIds.get("1")).isEqualTo("b");
}
// --- helper
@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");
}
private void setCookieWithNSessions(long size) {
setSessionCookie(createSessionCookieValue(size));
}
private String createSessionCookieValue(long size) {
StringBuffer buffer = new StringBuffer();
for(long i=0;i < size; i++) {
String hex = Long.toHexString(i);
buffer.append(hex);
buffer.append(" ");
buffer.append(i);
if(i < size - 1) {
buffer.append(" ");
}
}
return buffer.toString();
}
public void setCookieName(String cookieName) {
strategy.setCookieName(cookieName);
this.cookieName = cookieName;
}
public void setSessionCookie(String value) {
request.setCookies(new Cookie(cookieName, value));
}
public String getSessionId() {
return response.getCookie(cookieName).getValue();
}
for(long i=0;i < size; i++) {
String hex = Long.toHexString(i);
buffer.append(hex);
buffer.append(" ");
buffer.append(i);
if(i < size - 1) {
buffer.append(" ");
}
}
return buffer.toString();
}
public void setCookieName(String cookieName) {
strategy.setCookieName(cookieName);
this.cookieName = cookieName;
}
public void setSessionCookie(String value) {
request.setCookies(new Cookie(cookieName, value));
}
public String getSessionId() {
return response.getCookie(cookieName).getValue();
}
}

View File

@@ -1,3 +1,18 @@
/*
* Copyright 2002-2015 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.web.http;
import org.junit.Before;
@@ -11,102 +26,102 @@ import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import static org.fest.assertions.Assertions.assertThat;
public class HeaderSessionStrategyTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HeaderHttpSessionStrategy strategy;
private String headerName;
private Session session;
private HeaderHttpSessionStrategy strategy;
private String headerName;
private Session session;
@Before
public void setup() throws Exception {
headerName = "x-auth-token";
session = new MapSession();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
strategy = new HeaderHttpSessionStrategy();
}
@Before
public void setup() throws Exception {
headerName = "x-auth-token";
session = new MapSession();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
strategy = new HeaderHttpSessionStrategy();
}
@Test
public void getRequestedSessionIdNull() throws Exception {
assertThat(strategy.getRequestedSessionId(request)).isNull();
}
@Test
public void getRequestedSessionIdNull() throws Exception {
assertThat(strategy.getRequestedSessionId(request)).isNull();
}
@Test
public void getRequestedSessionIdNotNull() throws Exception {
setSessionId(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
}
@Test
public void getRequestedSessionIdNotNull() throws Exception {
setSessionId(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
}
@Test
public void getRequestedSessionIdNotNullCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
setSessionId(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
}
@Test
public void getRequestedSessionIdNotNullCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
setSessionId(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
}
@Test
public void onNewSession() throws Exception {
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onNewSession() throws Exception {
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
// the header is set as apposed to added
@Test
public void onNewSessionMulti() throws Exception {
strategy.onNewSession(session, request, response);
strategy.onNewSession(session, request, response);
// the header is set as apposed to added
@Test
public void onNewSessionMulti() throws Exception {
strategy.onNewSession(session, request, response);
strategy.onNewSession(session, request, response);
assertThat(response.getHeaders(headerName).size()).isEqualTo(1);
assertThat(response.getHeaders(headerName)).containsOnly(session.getId());
}
assertThat(response.getHeaders(headerName).size()).isEqualTo(1);
assertThat(response.getHeaders(headerName)).containsOnly(session.getId());
}
@Test
public void onNewSessionCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onNewSessionCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
}
@Test
public void onDeleteSession() throws Exception {
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSession() throws Exception {
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEmpty();
}
// the header is set as apposed to added
@Test
public void onDeleteSessionMulti() throws Exception {
strategy.onInvalidateSession(request, response);
strategy.onInvalidateSession(request, response);
// the header is set as apposed to added
@Test
public void onDeleteSessionMulti() throws Exception {
strategy.onInvalidateSession(request, response);
strategy.onInvalidateSession(request, response);
assertThat(response.getHeaders(headerName).size()).isEqualTo(1);
assertThat(getSessionId()).isEmpty();
}
assertThat(response.getHeaders(headerName).size()).isEqualTo(1);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
strategy.onInvalidateSession(request, response);
assertThat(getSessionId()).isEmpty();
}
@Test(expected = IllegalArgumentException.class)
public void setHeaderNameNull() throws Exception {
strategy.setHeaderName(null);
}
@Test(expected = IllegalArgumentException.class)
public void setHeaderNameNull() throws Exception {
strategy.setHeaderName(null);
}
public void setHeaderName(String headerName) {
strategy.setHeaderName(headerName);
this.headerName = headerName;
}
public void setHeaderName(String headerName) {
strategy.setHeaderName(headerName);
this.headerName = headerName;
}
public void setSessionId(String id) {
request.addHeader(headerName, id);
}
public void setSessionId(String id) {
request.addHeader(headerName, id);
}
public String getSessionId() {
return response.getHeader(headerName);
}
public String getSessionId() {
return response.getHeader(headerName);
}
}

View File

@@ -1,3 +1,18 @@
/*
* Copyright 2002-2015 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.web.http;
import org.junit.Before;
@@ -20,57 +35,57 @@ import java.util.List;
import static org.fest.assertions.Assertions.*;
public class OncePerRequestFilterTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockFilterChain chain;
private OncePerRequestFilter filter;
private HttpServlet servlet;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockFilterChain chain;
private OncePerRequestFilter filter;
private HttpServlet servlet;
private List<OncePerRequestFilter> invocations;
private List<OncePerRequestFilter> invocations;
@Before
@SuppressWarnings("serial")
public void setup() {
servlet = new HttpServlet() {};
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
chain = new MockFilterChain();
invocations = new ArrayList<OncePerRequestFilter>();
filter = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
invocations.add(this);
filterChain.doFilter(request, response);
}
};
}
@Before
@SuppressWarnings("serial")
public void setup() {
servlet = new HttpServlet() {};
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
chain = new MockFilterChain();
invocations = new ArrayList<OncePerRequestFilter>();
filter = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
invocations.add(this);
filterChain.doFilter(request, response);
}
};
}
@Test
public void doFilterOnce() throws ServletException, IOException {
filter.doFilter(request, response, chain);
@Test
public void doFilterOnce() throws ServletException, IOException {
filter.doFilter(request, response, chain);
assertThat(invocations).containsOnly(filter);
}
assertThat(invocations).containsOnly(filter);
}
@Test
public void doFilterMultiOnlyIvokesOnce() throws ServletException, IOException {
filter.doFilter(request, response, new MockFilterChain(servlet, filter));
@Test
public void doFilterMultiOnlyIvokesOnce() throws ServletException, IOException {
filter.doFilter(request, response, new MockFilterChain(servlet, filter));
assertThat(invocations).containsOnly(filter);
}
assertThat(invocations).containsOnly(filter);
}
@Test
public void doFilterOtherSubclassInvoked() throws ServletException, IOException {
OncePerRequestFilter filter2 = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
invocations.add(this);
filterChain.doFilter(request, response);
}
};
filter.doFilter(request, response, new MockFilterChain(servlet, filter2));
@Test
public void doFilterOtherSubclassInvoked() throws ServletException, IOException {
OncePerRequestFilter filter2 = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
invocations.add(this);
filterChain.doFilter(request, response);
}
};
filter.doFilter(request, response, new MockFilterChain(servlet, filter2));
assertThat(invocations).containsOnly(filter, filter2);
}
assertThat(invocations).containsOnly(filter, filter2);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 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.
@@ -33,44 +33,44 @@ import org.springframework.web.socket.WebSocketSession;
@RunWith(MockitoJUnitRunner.class)
public class WebSocketConnectHandlerDecoratorFactoryTests {
@Mock
ApplicationEventPublisher eventPublisher;
@Mock
WebSocketHandler delegate;
@Mock
WebSocketSession session;
@Captor
ArgumentCaptor<SessionConnectEvent> event;
@Mock
ApplicationEventPublisher eventPublisher;
@Mock
WebSocketHandler delegate;
@Mock
WebSocketSession session;
@Captor
ArgumentCaptor<SessionConnectEvent> event;
WebSocketConnectHandlerDecoratorFactory factory;
WebSocketConnectHandlerDecoratorFactory factory;
@Before
public void setup() {
factory = new WebSocketConnectHandlerDecoratorFactory(eventPublisher);
}
@Before
public void setup() {
factory = new WebSocketConnectHandlerDecoratorFactory(eventPublisher);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullEventPublisher() {
new WebSocketConnectHandlerDecoratorFactory(null);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullEventPublisher() {
new WebSocketConnectHandlerDecoratorFactory(null);
}
@Test
public void decorateAfterConnectionEstablished() throws Exception {
WebSocketHandler decorated = factory.decorate(delegate);
@Test
public void decorateAfterConnectionEstablished() throws Exception {
WebSocketHandler decorated = factory.decorate(delegate);
decorated.afterConnectionEstablished(session);
decorated.afterConnectionEstablished(session);
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getWebSocketSession()).isSameAs(session);
}
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getWebSocketSession()).isSameAs(session);
}
@Test
public void decorateAfterConnectionEstablishedEventError() throws Exception {
WebSocketHandler decorated = factory.decorate(delegate);
doThrow(new IllegalStateException("Test throw on publishEvent")).when(eventPublisher).publishEvent(any(ApplicationEvent.class));
@Test
public void decorateAfterConnectionEstablishedEventError() throws Exception {
WebSocketHandler decorated = factory.decorate(delegate);
doThrow(new IllegalStateException("Test throw on publishEvent")).when(eventPublisher).publishEvent(any(ApplicationEvent.class));
decorated.afterConnectionEstablished(session);
decorated.afterConnectionEstablished(session);
verify(eventPublisher).publishEvent(any(SessionConnectEvent.class));
}
verify(eventPublisher).publishEvent(any(SessionConnectEvent.class));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 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.
@@ -16,7 +16,10 @@
package org.springframework.session.web.socket.handler;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.security.Principal;
import java.util.HashMap;
@@ -26,7 +29,6 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
@@ -41,115 +43,116 @@ import org.springframework.web.socket.messaging.SessionDisconnectEvent;
@RunWith(MockitoJUnitRunner.class)
public class WebSocketRegistryListenerTests {
@Mock
WebSocketSession wsSession;
@Mock
WebSocketSession wsSession2;
@Mock
Message<byte[]> message;
@Mock
Principal principal;
@Mock
WebSocketSession wsSession;
@Mock
WebSocketSession wsSession2;
@Mock
Message<byte[]> message;
@Mock
Principal principal;
SessionConnectEvent connect;
SessionConnectEvent connect;
SessionConnectEvent connect2;
SessionConnectEvent connect2;
SessionDisconnectEvent disconnect;
SessionDisconnectEvent disconnect;
SessionDestroyedEvent destroyed;
SessionDestroyedEvent destroyed;
Map<String, Object> attributes;
Map<String, Object> attributes;
String sessionId;
String sessionId;
WebSocketRegistryListener listener;
WebSocketRegistryListener listener;
@Before
public void setup() {
sessionId = "session-id";
attributes = new HashMap<String,Object>();
SessionRepositoryMessageInterceptor.setSessionId(attributes, sessionId);
@Before
public void setup() {
sessionId = "session-id";
attributes = new HashMap<String,Object>();
SessionRepositoryMessageInterceptor.setSessionId(attributes, sessionId);
when(wsSession.getAttributes()).thenReturn(attributes);
when(wsSession.getPrincipal()).thenReturn(principal);
when(wsSession.getId()).thenReturn("wsSession-id");
when(wsSession.getAttributes()).thenReturn(attributes);
when(wsSession.getPrincipal()).thenReturn(principal);
when(wsSession.getId()).thenReturn("wsSession-id");
when(wsSession2.getAttributes()).thenReturn(attributes);
when(wsSession2.getPrincipal()).thenReturn(principal);
when(wsSession2.getId()).thenReturn("wsSession-id2");
when(wsSession2.getAttributes()).thenReturn(attributes);
when(wsSession2.getPrincipal()).thenReturn(principal);
when(wsSession2.getId()).thenReturn("wsSession-id2");
Map<String,Object> headers = new HashMap<String,Object>();
headers.put(SimpMessageHeaderAccessor.SESSION_ATTRIBUTES, attributes);
when(message.getHeaders()).thenReturn(new MessageHeaders(headers));
Map<String,Object> headers = new HashMap<String,Object>();
headers.put(SimpMessageHeaderAccessor.SESSION_ATTRIBUTES, attributes);
when(message.getHeaders()).thenReturn(new MessageHeaders(headers));
listener = new WebSocketRegistryListener();
connect = new SessionConnectEvent(listener,wsSession);
connect2 = new SessionConnectEvent(listener,wsSession2);
disconnect = new SessionDisconnectEvent(listener, message, wsSession.getId(), CloseStatus.NORMAL);
destroyed = new SessionDestroyedEvent(listener, sessionId);
}
listener = new WebSocketRegistryListener();
connect = new SessionConnectEvent(listener,wsSession);
connect2 = new SessionConnectEvent(listener,wsSession2);
disconnect = new SessionDisconnectEvent(listener, message, wsSession.getId(), CloseStatus.NORMAL);
destroyed = new SessionDestroyedEvent(listener, sessionId);
}
@Test
public void onApplicationEventConnectSessionDestroyed() throws Exception {
listener.onApplicationEvent(connect);
@Test
public void onApplicationEventConnectSessionDestroyed() throws Exception {
listener.onApplicationEvent(connect);
listener.onApplicationEvent(destroyed);
listener.onApplicationEvent(destroyed);
verify(wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
}
verify(wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
}
@Test
public void onApplicationEventConnectSessionDestroyedNullPrincipal() throws Exception {
when(wsSession.getPrincipal()).thenReturn(null);
listener.onApplicationEvent(connect);
@Test
public void onApplicationEventConnectSessionDestroyedNullPrincipal() throws Exception {
when(wsSession.getPrincipal()).thenReturn(null);
listener.onApplicationEvent(connect);
listener.onApplicationEvent(destroyed);
listener.onApplicationEvent(destroyed);
verify(wsSession,times(0)).close(any(CloseStatus.class));
}
verify(wsSession,times(0)).close(any(CloseStatus.class));
}
@Test
public void onApplicationEventConnectDisconnect() throws Exception {
listener.onApplicationEvent(connect);
listener.onApplicationEvent(disconnect);
@Test
public void onApplicationEventConnectDisconnect() throws Exception {
listener.onApplicationEvent(connect);
listener.onApplicationEvent(disconnect);
listener.onApplicationEvent(destroyed);
listener.onApplicationEvent(destroyed);
verify(wsSession,times(0)).close(any(CloseStatus.class));
}
verify(wsSession,times(0)).close(any(CloseStatus.class));
}
// gh-76
@Test
public void onApplicationEventConnectDisconnectCleanup() {
listener.onApplicationEvent(connect);
// gh-76
@Test
@SuppressWarnings("unchecked")
public void onApplicationEventConnectDisconnectCleanup() {
listener.onApplicationEvent(connect);
listener.onApplicationEvent(disconnect);
listener.onApplicationEvent(disconnect);
Map<String,Map<String,WebSocketSession>> httpSessionIdToWsSessions =
(Map<String, Map<String, WebSocketSession>>) ReflectionTestUtils.getField(listener, "httpSessionIdToWsSessions");
assertThat(httpSessionIdToWsSessions).isEmpty();
}
Map<String,Map<String,WebSocketSession>> httpSessionIdToWsSessions =
(Map<String, Map<String, WebSocketSession>>) ReflectionTestUtils.getField(listener, "httpSessionIdToWsSessions");
assertThat(httpSessionIdToWsSessions).isEmpty();
}
@Test
public void onApplicationEventConnectDisconnectNullSession() throws Exception {
listener.onApplicationEvent(connect);
attributes.clear();
@Test
public void onApplicationEventConnectDisconnectNullSession() throws Exception {
listener.onApplicationEvent(connect);
attributes.clear();
listener.onApplicationEvent(disconnect);
listener.onApplicationEvent(disconnect);
// no exception
}
// no exception
}
@Test
public void onApplicationEventConnectConnectDisonnect() throws Exception {
listener.onApplicationEvent(connect);
listener.onApplicationEvent(connect2);
listener.onApplicationEvent(disconnect);
@Test
public void onApplicationEventConnectConnectDisonnect() throws Exception {
listener.onApplicationEvent(connect);
listener.onApplicationEvent(connect2);
listener.onApplicationEvent(disconnect);
listener.onApplicationEvent(destroyed);
listener.onApplicationEvent(destroyed);
verify(wsSession2).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
verify(wsSession,times(0)).close(any(CloseStatus.class));
}
verify(wsSession2).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
verify(wsSession,times(0)).close(any(CloseStatus.class));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 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.
@@ -43,214 +43,214 @@ import org.springframework.session.SessionRepository;
@RunWith(MockitoJUnitRunner.class)
public class SessionRepositoryMessageInterceptorTests {
@Mock
SessionRepository<ExpiringSession> sessionRepository;
@Mock
MessageChannel channel;
@Mock
ExpiringSession session;
@Mock
SessionRepository<ExpiringSession> sessionRepository;
@Mock
MessageChannel channel;
@Mock
ExpiringSession session;
Message<?> createMessage;
Message<?> createMessage;
SimpMessageHeaderAccessor headers;
SimpMessageHeaderAccessor headers;
SessionRepositoryMessageInterceptor<ExpiringSession> interceptor;
SessionRepositoryMessageInterceptor<ExpiringSession> interceptor;
@Before
public void setup() {
interceptor = new SessionRepositoryMessageInterceptor<ExpiringSession>(sessionRepository);
headers = SimpMessageHeaderAccessor.create();
headers.setSessionId("session");
headers.setSessionAttributes(new HashMap<String,Object>());
setMessageType(SimpMessageType.MESSAGE);
String sessionId = "http-session";
setSessionId(sessionId);
when(sessionRepository.getSession(sessionId)).thenReturn(session);
}
@Before
public void setup() {
interceptor = new SessionRepositoryMessageInterceptor<ExpiringSession>(sessionRepository);
headers = SimpMessageHeaderAccessor.create();
headers.setSessionId("session");
headers.setSessionAttributes(new HashMap<String,Object>());
setMessageType(SimpMessageType.MESSAGE);
String sessionId = "http-session";
setSessionId(sessionId);
when(sessionRepository.getSession(sessionId)).thenReturn(session);
}
@Test(expected = IllegalArgumentException.class)
public void preSendconstructorNullRepository() {
new SessionRepositoryMessageInterceptor<ExpiringSession>(null);
}
@Test(expected = IllegalArgumentException.class)
public void preSendconstructorNullRepository() {
new SessionRepositoryMessageInterceptor<ExpiringSession>(null);
}
@Test
public void preSendNullMessage() {
assertThat(interceptor.preSend(null, channel)).isNull();
}
@Test
public void preSendNullMessage() {
assertThat(interceptor.preSend(null, channel)).isNull();
}
@Test
public void preSendConnectAckDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.CONNECT_ACK);
@Test
public void preSendConnectAckDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.CONNECT_ACK);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
@Test
public void preSendHeartbeatDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.HEARTBEAT);
@Test
public void preSendHeartbeatDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.HEARTBEAT);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
@Test
public void preSendDisconnectDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.DISCONNECT);
@Test
public void preSendDisconnectDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.DISCONNECT);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
@Test
public void preSendOtherDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.OTHER);
@Test
public void preSendOtherDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.OTHER);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
@Test(expected = IllegalArgumentException.class)
public void setMatchingMessageTypesNull() {
interceptor.setMatchingMessageTypes(null);
}
@Test(expected = IllegalArgumentException.class)
public void setMatchingMessageTypesNull() {
interceptor.setMatchingMessageTypes(null);
}
@Test(expected = IllegalArgumentException.class)
public void setMatchingMessageTypesEmpty() {
interceptor.setMatchingMessageTypes(Collections.<SimpMessageType>emptySet());
}
@Test(expected = IllegalArgumentException.class)
public void setMatchingMessageTypesEmpty() {
interceptor.setMatchingMessageTypes(Collections.<SimpMessageType>emptySet());
}
@Test
public void preSendSetMatchingMessageTypes() {
interceptor.setMatchingMessageTypes(EnumSet.of(SimpMessageType.DISCONNECT));
setMessageType(SimpMessageType.DISCONNECT);
@Test
public void preSendSetMatchingMessageTypes() {
interceptor.setMatchingMessageTypes(EnumSet.of(SimpMessageType.DISCONNECT));
setMessageType(SimpMessageType.DISCONNECT);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
@Test
public void preSendConnectUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.CONNECT);
@Test
public void preSendConnectUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.CONNECT);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
@Test
public void preSendMessageUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.MESSAGE);
@Test
public void preSendMessageUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.MESSAGE);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
@Test
public void preSendSubscribeUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.SUBSCRIBE);
@Test
public void preSendSubscribeUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.SUBSCRIBE);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
@Test
public void preSendUnsubscribeUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.UNSUBSCRIBE);
@Test
public void preSendUnsubscribeUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.UNSUBSCRIBE);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
}
// This will updated when SPR-12288 is resolved
@Test
public void preSendExpiredSession() {
setSessionId("expired");
// This will updated when SPR-12288 is resolved
@Test
public void preSendExpiredSession() {
setSessionId("expired");
interceptor.preSend(createMessage(), channel);
interceptor.preSend(createMessage(), channel);
verify(sessionRepository,times(0)).save(any(ExpiringSession.class));
}
verify(sessionRepository,times(0)).save(any(ExpiringSession.class));
}
@Test
public void preSendNullSessionId() {
setSessionId(null);
@Test
public void preSendNullSessionId() {
setSessionId(null);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
@Test
public void preSendNullSessionAttributes() {
headers.setSessionAttributes(null);
@Test
public void preSendNullSessionAttributes() {
headers.setSessionAttributes(null);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
@Test
public void beforeHandshakeNotServletServerHttpRequest() throws Exception {
assertThat(interceptor.beforeHandshake(null,null,null,null)).isTrue();
@Test
public void beforeHandshakeNotServletServerHttpRequest() throws Exception {
assertThat(interceptor.beforeHandshake(null,null,null,null)).isTrue();
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
@Test
public void beforeHandshakeNullSession() throws Exception {
ServletServerHttpRequest request = new ServletServerHttpRequest(new MockHttpServletRequest());
assertThat(interceptor.beforeHandshake(request,null,null,null)).isTrue();
@Test
public void beforeHandshakeNullSession() throws Exception {
ServletServerHttpRequest request = new ServletServerHttpRequest(new MockHttpServletRequest());
assertThat(interceptor.beforeHandshake(request,null,null,null)).isTrue();
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
@Test
public void beforeHandshakeSession() throws Exception {
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
HttpSession httpSession = httpRequest.getSession();
ServletServerHttpRequest request = new ServletServerHttpRequest(httpRequest);
Map<String,Object> attributes = new HashMap<String,Object>();
@Test
public void beforeHandshakeSession() throws Exception {
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
HttpSession httpSession = httpRequest.getSession();
ServletServerHttpRequest request = new ServletServerHttpRequest(httpRequest);
Map<String,Object> attributes = new HashMap<String,Object>();
assertThat(interceptor.beforeHandshake(request,null,null,attributes)).isTrue();
assertThat(interceptor.beforeHandshake(request,null,null,attributes)).isTrue();
assertThat(attributes.size()).isEqualTo(1);
assertThat(SessionRepositoryMessageInterceptor.getSessionId(attributes)).isEqualTo(httpSession.getId());
}
assertThat(attributes.size()).isEqualTo(1);
assertThat(SessionRepositoryMessageInterceptor.getSessionId(attributes)).isEqualTo(httpSession.getId());
}
/**
* At the moment there is no need for afterHandshake to do anything.
*/
@Test
public void afterHandshakeDoesNothing() {
interceptor.afterHandshake(null,null,null,null);
/**
* At the moment there is no need for afterHandshake to do anything.
*/
@Test
public void afterHandshakeDoesNothing() {
interceptor.afterHandshake(null,null,null,null);
verifyZeroInteractions(sessionRepository);
}
verifyZeroInteractions(sessionRepository);
}
private void setSessionId(String id) {
SessionRepositoryMessageInterceptor.setSessionId(headers.getSessionAttributes(), id);
}
private void setSessionId(String id) {
SessionRepositoryMessageInterceptor.setSessionId(headers.getSessionAttributes(), id);
}
private Message<?> createMessage() {
createMessage = MessageBuilder.createMessage("", headers.getMessageHeaders());
return createMessage;
}
private Message<?> createMessage() {
createMessage = MessageBuilder.createMessage("", headers.getMessageHeaders());
return createMessage;
}
private void setMessageType(SimpMessageType type) {
headers.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, type);
}
private void setMessageType(SimpMessageType type) {
headers.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, type);
}
}