Prepare codebase to adhere to Checkstyle rules

Issue gh-393
This commit is contained in:
Vedran Pavic
2016-03-05 20:27:06 +01:00
committed by Rob Winch
parent 9e3bcafa75
commit 7f3302253b
222 changed files with 4071 additions and 3556 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,15 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session;
import static org.assertj.core.api.Assertions.*;
package org.springframework.session;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MapSessionRepositoryTests {
MapSessionRepository repository;
@@ -29,22 +30,22 @@ public class MapSessionRepositoryTests {
@Before
public void setup() {
repository = new MapSessionRepository();
session = new MapSession();
this.repository = new MapSessionRepository();
this.session = new MapSession();
}
@Test
public void getSessionExpired() {
session.setMaxInactiveIntervalInSeconds(1);
session.setLastAccessedTime(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
repository.save(session);
this.session.setMaxInactiveIntervalInSeconds(1);
this.session.setLastAccessedTime(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
this.repository.save(this.session);
assertThat(repository.getSession(session.getId())).isNull();
assertThat(this.repository.getSession(this.session.getId())).isNull();
}
@Test
public void createSessionDefaultExpiration() {
ExpiringSession session = repository.createSession();
ExpiringSession session = this.repository.createSession();
assertThat(session).isInstanceOf(MapSession.class);
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
@@ -53,10 +54,10 @@ public class MapSessionRepositoryTests {
@Test
public void createSessionCustomDefaultExpiration() {
final int expectedMaxInterval = new MapSession().getMaxInactiveIntervalInSeconds() + 10;
repository.setDefaultMaxInactiveInterval(expectedMaxInterval);
this.repository.setDefaultMaxInactiveInterval(expectedMaxInterval);
ExpiringSession session = repository.createSession();
ExpiringSession session = this.repository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInterval);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,23 +13,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session;
import static org.assertj.core.api.Assertions.*;
package org.springframework.session;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MapSessionTests {
private MapSession session;
@Before
public void setup() {
session = new MapSession();
session.setLastAccessedTime(1413258262962L);
this.session = new MapSession();
this.session.setLastAccessedTime(1413258262962L);
}
@Test(expected = IllegalArgumentException.class)
@@ -43,45 +44,45 @@ public class MapSessionTests {
@Test
public void setAttributeNullObjectRemoves() {
String attr = "attr";
session.setAttribute(attr, new Object());
session.setAttribute(attr, null);
assertThat(session.getAttributeNames()).isEmpty();
this.session.setAttribute(attr, new Object());
this.session.setAttribute(attr, null);
assertThat(this.session.getAttributeNames()).isEmpty();
}
@Test
public void equalsNonSessionFalse() {
assertThat(session.equals(new Object())).isFalse();
assertThat(this.session.equals(new Object())).isFalse();
}
@Test
public void equalsCustomSession() {
CustomSession other = new CustomSession();
session.setId(other.getId());
assertThat(session.equals(other)).isTrue();
this.session.setId(other.getId());
assertThat(this.session.equals(other)).isTrue();
}
@Test
public void hashCodeEqualsIdHashCode() {
session.setId("constantId");
assertThat(session.hashCode()).isEqualTo(session.getId().hashCode());
this.session.setId("constantId");
assertThat(this.session.hashCode()).isEqualTo(this.session.getId().hashCode());
}
@Test
public void isExpiredExact() {
long now = 1413260062962L;
assertThat(session.isExpired(now)).isTrue();
assertThat(this.session.isExpired(now)).isTrue();
}
@Test
public void isExpiredOneMsTooSoon() {
long now = 1413260062961L;
assertThat(session.isExpired(now)).isFalse();
assertThat(this.session.isExpired(now)).isFalse();
}
@Test
public void isExpiredOneMsAfter() {
long now = 1413260062963L;
assertThat(session.isExpired(now)).isTrue();
assertThat(this.session.isExpired(now)).isTrue();
}
static class CustomSession implements ExpiringSession {
@@ -131,4 +132,4 @@ public class MapSessionTests {
}
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,13 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.config.annotation.web.http;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package org.springframework.session.config.annotation.web.http;
import java.io.IOException;
import java.util.Arrays;
@@ -32,6 +27,7 @@ import javax.servlet.http.HttpServletRequest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -47,6 +43,12 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*
@@ -70,22 +72,22 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests {
@Before
public void setup() {
chain = new MockFilterChain();
this.chain = new MockFilterChain();
}
@Test
public void usesReadSessionIds() throws Exception {
String sessionId = "sessionId";
when(cookieSerializer.readCookieValues(any(HttpServletRequest.class))).thenReturn(Arrays.asList(sessionId));
given(this.cookieSerializer.readCookieValues(any(HttpServletRequest.class))).willReturn(Arrays.asList(sessionId));
sessionRepositoryFilter.doFilter(request, response, chain);
this.sessionRepositoryFilter.doFilter(this.request, this.response, this.chain);
assertThat(getRequest().getRequestedSessionId()).isEqualTo(sessionId);
}
@Test
public void usesWrite() throws Exception {
sessionRepositoryFilter.doFilter(request, response, new MockFilterChain() {
this.sessionRepositoryFilter.doFilter(this.request, this.response, new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
@@ -95,11 +97,11 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests {
}
});
verify(cookieSerializer).writeCookieValue(any(CookieValue.class));
verify(this.cookieSerializer).writeCookieValue(any(CookieValue.class));
}
private HttpServletRequest getRequest() {
return (HttpServletRequest) chain.getRequest();
return (HttpServletRequest) this.chain.getRequest();
}
@EnableSpringHttpSession

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,12 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.config.annotation.web.http;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package org.springframework.session.config.annotation.web.http;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -26,6 +22,7 @@ import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -40,6 +37,11 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*
@@ -63,18 +65,18 @@ public class EnableSpringHttpSessionCustomMultiHttpSessionStrategyTests {
@Before
public void setup() {
chain = new MockFilterChain();
this.chain = new MockFilterChain();
}
@Test
public void wrapRequestAndResponseUsed() throws Exception {
when(strategy.wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(request);
when(strategy.wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(response);
given(this.strategy.wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(this.request);
given(this.strategy.wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(this.response);
sessionRepositoryFilter.doFilter(request, response, chain);
this.sessionRepositoryFilter.doFilter(this.request, this.response, this.chain);
verify(strategy).wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(strategy).wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.strategy).wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.strategy).wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@EnableSpringHttpSession

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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,
@@ -16,27 +16,14 @@
package org.springframework.session.data.gemfire;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME;
import static org.springframework.session.data.gemfire.GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY;
import static org.springframework.session.data.gemfire.GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY;
import static org.springframework.session.data.gemfire.GemFireOperationsSessionRepository.GemFireSession;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.gemstone.gemfire.cache.AttributesMutator;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.query.SelectResults;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -45,23 +32,34 @@ import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.gemfire.GemfireAccessor;
import org.springframework.data.gemfire.GemfireOperations;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.events.AbstractSessionEvent;
import org.springframework.session.events.SessionDeletedEvent;
import com.gemstone.gemfire.cache.AttributesMutator;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.query.SelectResults;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* The GemFireOperationsSessionRepositoryTest class is a test suite of test cases testing the contract and functionality
* of the GemFireOperationsSessionRepository class.
*
* @author John Blum
* @since 1.1.0
* @see org.junit.Test
* @see org.junit.runner.RunWith
* @see org.mockito.Mock
@@ -69,7 +67,6 @@ import com.gemstone.gemfire.cache.query.SelectResults;
* @see org.mockito.runners.MockitoJUnitRunner
* @see org.springframework.session.data.gemfire.GemFireOperationsSessionRepository
* @see com.gemstone.gemfire.cache.Region
* @since 1.1.0
*/
@RunWith(MockitoJUnitRunner.class)
public class GemFireOperationsSessionRepositoryTest {
@@ -92,25 +89,25 @@ public class GemFireOperationsSessionRepositoryTest {
@Before
public void setup() throws Exception {
when(mockRegion.getAttributesMutator()).thenReturn(mockAttributesMutator);
when(mockRegion.getFullPath()).thenReturn("/Example");
when(mockTemplate.<Object, ExpiringSession>getRegion()).thenReturn(mockRegion);
given(this.mockRegion.getAttributesMutator()).willReturn(this.mockAttributesMutator);
given(this.mockRegion.getFullPath()).willReturn("/Example");
given(this.mockTemplate.<Object, ExpiringSession>getRegion()).willReturn(this.mockRegion);
sessionRepository = new GemFireOperationsSessionRepository(mockTemplate);
sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher);
sessionRepository.setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS);
sessionRepository.afterPropertiesSet();
this.sessionRepository = new GemFireOperationsSessionRepository(this.mockTemplate);
this.sessionRepository.setApplicationEventPublisher(this.mockApplicationEventPublisher);
this.sessionRepository.setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS);
this.sessionRepository.afterPropertiesSet();
assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher);
assertThat(sessionRepository.getFullyQualifiedRegionName()).isEqualTo("/Example");
assertThat(sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(this.mockApplicationEventPublisher);
assertThat(this.sessionRepository.getFullyQualifiedRegionName()).isEqualTo("/Example");
assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
}
@After
public void tearDown() {
verify(mockAttributesMutator, times(1)).addCacheListener(same(sessionRepository));
verify(mockRegion, times(1)).getFullPath();
verify(mockTemplate, times(1)).getRegion();
verify(this.mockAttributesMutator, times(1)).addCacheListener(same(this.sessionRepository));
verify(this.mockRegion, times(1)).getFullPath();
verify(this.mockTemplate, times(1)).getRegion();
}
@Test
@@ -118,27 +115,27 @@ public class GemFireOperationsSessionRepositoryTest {
public void findByIndexNameValueFindsMatchingSession() {
ExpiringSession mockSession = mock(ExpiringSession.class, "MockSession");
when(mockSession.getId()).thenReturn("1");
given(mockSession.getId()).willReturn("1");
SelectResults<Object> mockSelectResults = mock(SelectResults.class);
when(mockSelectResults.asList()).thenReturn(Collections.<Object>singletonList(mockSession));
given(mockSelectResults.asList()).willReturn(Collections.<Object>singletonList(mockSession));
String indexName = "vip";
String indexValue = "rwinch";
String expectedQql = String.format(FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY,
sessionRepository.getFullyQualifiedRegionName(), indexName);
String expectedQql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY,
this.sessionRepository.getFullyQualifiedRegionName(), indexName);
when(mockTemplate.find(eq(expectedQql), eq(indexValue))).thenReturn(mockSelectResults);
given(this.mockTemplate.find(eq(expectedQql), eq(indexValue))).willReturn(mockSelectResults);
Map<String, ExpiringSession> sessions = sessionRepository.findByIndexNameAndIndexValue(indexName, indexValue);
Map<String, ExpiringSession> sessions = this.sessionRepository.findByIndexNameAndIndexValue(indexName, indexValue);
assertThat(sessions).isNotNull();
assertThat(sessions.size()).isEqualTo(1);
assertThat(sessions.get("1")).isEqualTo(mockSession);
verify(mockTemplate, times(1)).find(eq(expectedQql), eq(indexValue));
verify(this.mockTemplate, times(1)).find(eq(expectedQql), eq(indexValue));
verify(mockSelectResults, times(1)).asList();
verify(mockSession, times(1)).getId();
}
@@ -150,23 +147,23 @@ public class GemFireOperationsSessionRepositoryTest {
ExpiringSession mockSessionTwo = mock(ExpiringSession.class, "MockSessionTwo");
ExpiringSession mockSessionThree = mock(ExpiringSession.class, "MockSessionThree");
when(mockSessionOne.getId()).thenReturn("1");
when(mockSessionTwo.getId()).thenReturn("2");
when(mockSessionThree.getId()).thenReturn("3");
given(mockSessionOne.getId()).willReturn("1");
given(mockSessionTwo.getId()).willReturn("2");
given(mockSessionThree.getId()).willReturn("3");
SelectResults<Object> mockSelectResults = mock(SelectResults.class);
when(mockSelectResults.asList()).thenReturn(Arrays.<Object>asList(mockSessionOne, mockSessionTwo, mockSessionThree));
given(mockSelectResults.asList()).willReturn(Arrays.<Object>asList(mockSessionOne, mockSessionTwo, mockSessionThree));
String principalName = "jblum";
String expectedOql = String.format(FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
sessionRepository.getFullyQualifiedRegionName());
String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
this.sessionRepository.getFullyQualifiedRegionName());
when(mockTemplate.find(eq(expectedOql), eq(principalName))).thenReturn(mockSelectResults);
given(this.mockTemplate.find(eq(expectedOql), eq(principalName))).willReturn(mockSelectResults);
Map<String, ExpiringSession> sessions = sessionRepository.findByIndexNameAndIndexValue(
PRINCIPAL_NAME_INDEX_NAME, principalName);
Map<String, ExpiringSession> sessions = this.sessionRepository.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName);
assertThat(sessions).isNotNull();
assertThat(sessions.size()).isEqualTo(3);
@@ -174,7 +171,7 @@ public class GemFireOperationsSessionRepositoryTest {
assertThat(sessions.get("2")).isEqualTo(mockSessionTwo);
assertThat(sessions.get("3")).isEqualTo(mockSessionThree);
verify(mockTemplate, times(1)).find(eq(expectedOql), eq(principalName));
verify(this.mockTemplate, times(1)).find(eq(expectedOql), eq(principalName));
verify(mockSelectResults, times(1)).asList();
verify(mockSessionOne, times(1)).getId();
verify(mockSessionTwo, times(1)).getId();
@@ -186,30 +183,30 @@ public class GemFireOperationsSessionRepositoryTest {
public void findByPrincipalNameReturnsNoMatchingSessions() {
SelectResults<Object> mockSelectResults = mock(SelectResults.class);
when(mockSelectResults.asList()).thenReturn(Collections.emptyList());
given(mockSelectResults.asList()).willReturn(Collections.emptyList());
String principalName = "jblum";
String expectedOql = String.format(FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
sessionRepository.getFullyQualifiedRegionName());
String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
this.sessionRepository.getFullyQualifiedRegionName());
when(mockTemplate.find(eq(expectedOql), eq(principalName))).thenReturn(mockSelectResults);
given(this.mockTemplate.find(eq(expectedOql), eq(principalName))).willReturn(mockSelectResults);
Map<String, ExpiringSession> sessions = sessionRepository.findByIndexNameAndIndexValue(
PRINCIPAL_NAME_INDEX_NAME, principalName);
Map<String, ExpiringSession> sessions = this.sessionRepository.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName);
assertThat(sessions).isNotNull();
assertThat(sessions.isEmpty()).isTrue();
verify(mockTemplate, times(1)).find(eq(expectedOql), eq(principalName));
verify(this.mockTemplate, times(1)).find(eq(expectedOql), eq(principalName));
verify(mockSelectResults, times(1)).asList();
}
@Test
public void prepareQueryReturnsPrincipalNameOql() {
String actualQql = sessionRepository.prepareQuery(PRINCIPAL_NAME_INDEX_NAME);
String expectedOql = String.format(FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
sessionRepository.getFullyQualifiedRegionName());
String actualQql = this.sessionRepository.prepareQuery(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY,
this.sessionRepository.getFullyQualifiedRegionName());
assertThat(actualQql).isEqualTo(expectedOql);
}
@@ -217,9 +214,9 @@ public class GemFireOperationsSessionRepositoryTest {
@Test
public void prepareQueryReturnsIndexNameValueOql() {
String attributeName = "testAttributeName";
String actualOql = sessionRepository.prepareQuery(attributeName);
String expectedOql = String.format(FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY,
sessionRepository.getFullyQualifiedRegionName(), attributeName);
String actualOql = this.sessionRepository.prepareQuery(attributeName);
String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY,
this.sessionRepository.getFullyQualifiedRegionName(), attributeName);
assertThat(actualOql).isEqualTo(expectedOql);
}
@@ -228,9 +225,9 @@ public class GemFireOperationsSessionRepositoryTest {
public void createProperlyInitializedSession() {
final long beforeOrAtCreationTime = System.currentTimeMillis();
ExpiringSession session = sessionRepository.createSession();
ExpiringSession session = this.sessionRepository.createSession();
assertThat(session).isInstanceOf(GemFireSession.class);
assertThat(session).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class);
assertThat(session.getId()).isNotNull();
assertThat(session.getAttributeNames().isEmpty()).isTrue();
assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime);
@@ -244,12 +241,12 @@ public class GemFireOperationsSessionRepositoryTest {
final ExpiringSession mockSession = mock(ExpiringSession.class);
when(mockSession.isExpired()).thenReturn(true);
when(mockSession.getId()).thenReturn(expectedSessionId);
when(mockTemplate.get(eq(expectedSessionId))).thenReturn(mockSession);
when(mockTemplate.remove(eq(expectedSessionId))).thenReturn(mockSession);
given(mockSession.isExpired()).willReturn(true);
given(mockSession.getId()).willReturn(expectedSessionId);
given(this.mockTemplate.get(eq(expectedSessionId))).willReturn(mockSession);
given(this.mockTemplate.remove(eq(expectedSessionId))).willReturn(mockSession);
doAnswer(new Answer<Void>() {
willAnswer(new Answer<Void>() {
public Void answer(final InvocationOnMock invocation) throws Throwable {
ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class);
@@ -257,21 +254,21 @@ public class GemFireOperationsSessionRepositoryTest {
AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent;
assertThat(sessionEvent.getSource()).isSameAs(sessionRepository);
assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSession()).isSameAs(mockSession);
assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId);
return null;
}
}).when(mockApplicationEventPublisher).publishEvent(any(ApplicationEvent.class));
}).given(this.mockApplicationEventPublisher).publishEvent(any(ApplicationEvent.class));
assertThat(sessionRepository.getSession(expectedSessionId)).isNull();
assertThat(this.sessionRepository.getSession(expectedSessionId)).isNull();
verify(mockTemplate, times(1)).get(eq(expectedSessionId));
verify(mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(this.mockTemplate, times(1)).get(eq(expectedSessionId));
verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(mockSession, times(1)).isExpired();
verify(mockSession, times(2)).getId();
verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
}
@Test
@@ -283,15 +280,15 @@ public class GemFireOperationsSessionRepositoryTest {
ExpiringSession mockSession = mock(ExpiringSession.class);
when(mockSession.isExpired()).thenReturn(false);
when(mockSession.getId()).thenReturn(expectedId);
when(mockSession.getCreationTime()).thenReturn(expectedCreationTime);
when(mockSession.getLastAccessedTime()).thenReturn(currentLastAccessedTime);
when(mockSession.getAttributeNames()).thenReturn(Collections.singleton("attrOne"));
when(mockSession.getAttribute(eq("attrOne"))).thenReturn("test");
when(mockTemplate.get(eq(expectedId))).thenReturn(mockSession);
given(mockSession.isExpired()).willReturn(false);
given(mockSession.getId()).willReturn(expectedId);
given(mockSession.getCreationTime()).willReturn(expectedCreationTime);
given(mockSession.getLastAccessedTime()).willReturn(currentLastAccessedTime);
given(mockSession.getAttributeNames()).willReturn(Collections.singleton("attrOne"));
given(mockSession.getAttribute(eq("attrOne"))).willReturn("test");
given(this.mockTemplate.get(eq(expectedId))).willReturn(mockSession);
ExpiringSession actualSession = sessionRepository.getSession(expectedId);
ExpiringSession actualSession = this.sessionRepository.getSession(expectedId);
assertThat(actualSession).isNotSameAs(mockSession);
assertThat(actualSession.getId()).isEqualTo(expectedId);
@@ -301,7 +298,7 @@ public class GemFireOperationsSessionRepositoryTest {
assertThat(actualSession.getAttributeNames()).isEqualTo(Collections.singleton("attrOne"));
assertThat(String.valueOf(actualSession.getAttribute("attrOne"))).isEqualTo("test");
verify(mockTemplate, times(1)).get(eq(expectedId));
verify(this.mockTemplate, times(1)).get(eq(expectedId));
verify(mockSession, times(1)).isExpired();
verify(mockSession, times(1)).getId();
verify(mockSession, times(1)).getCreationTime();
@@ -312,8 +309,8 @@ public class GemFireOperationsSessionRepositoryTest {
@Test
public void getSessionReturnsNull() {
when(mockTemplate.get(anyString())).thenReturn(null);
assertThat(sessionRepository.getSession("1")).isNull();
given(this.mockTemplate.get(anyString())).willReturn(null);
assertThat(this.sessionRepository.getSession("1")).isNull();
}
@Test
@@ -325,14 +322,14 @@ public class GemFireOperationsSessionRepositoryTest {
ExpiringSession mockSession = mock(ExpiringSession.class);
when(mockSession.getId()).thenReturn(expectedSessionId);
when(mockSession.getCreationTime()).thenReturn(expectedCreationTime);
when(mockSession.getLastAccessedTime()).thenReturn(expectedLastAccessTime);
when(mockSession.getMaxInactiveIntervalInSeconds()).thenReturn(MAX_INACTIVE_INTERVAL_IN_SECONDS);
when(mockSession.getAttributeNames()).thenReturn(Collections.<String>emptySet());
given(mockSession.getId()).willReturn(expectedSessionId);
given(mockSession.getCreationTime()).willReturn(expectedCreationTime);
given(mockSession.getLastAccessedTime()).willReturn(expectedLastAccessTime);
given(mockSession.getMaxInactiveIntervalInSeconds()).willReturn(MAX_INACTIVE_INTERVAL_IN_SECONDS);
given(mockSession.getAttributeNames()).willReturn(Collections.<String>emptySet());
when(mockTemplate.put(eq(expectedSessionId), isA(GemFireSession.class)))
.thenAnswer(new Answer<ExpiringSession>() {
given(this.mockTemplate.put(eq(expectedSessionId), isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class)))
.willAnswer(new Answer<ExpiringSession>() {
public ExpiringSession answer(final InvocationOnMock invocation) throws Throwable {
ExpiringSession session = invocation.getArgumentAt(1, ExpiringSession.class);
@@ -347,14 +344,14 @@ public class GemFireOperationsSessionRepositoryTest {
}
});
sessionRepository.save(mockSession);
this.sessionRepository.save(mockSession);
verify(mockSession, times(2)).getId();
verify(mockSession, times(1)).getCreationTime();
verify(mockSession, times(1)).getLastAccessedTime();
verify(mockSession, times(1)).getMaxInactiveIntervalInSeconds();
verify(mockSession, times(1)).getAttributeNames();
verify(mockTemplate, times(1)).put(eq(expectedSessionId), isA(GemFireSession.class));
verify(this.mockTemplate, times(1)).put(eq(expectedSessionId), isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class));
}
@Test
@@ -363,10 +360,10 @@ public class GemFireOperationsSessionRepositoryTest {
final ExpiringSession mockSession = mock(ExpiringSession.class);
when(mockSession.getId()).thenReturn(expectedSessionId);
when(mockTemplate.remove(eq(expectedSessionId))).thenReturn(mockSession);
given(mockSession.getId()).willReturn(expectedSessionId);
given(this.mockTemplate.remove(eq(expectedSessionId))).willReturn(mockSession);
doAnswer(new Answer<Void>() {
willAnswer(new Answer<Void>() {
public Void answer(final InvocationOnMock invocation) throws Throwable {
ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class);
@@ -374,28 +371,28 @@ public class GemFireOperationsSessionRepositoryTest {
AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent;
assertThat(sessionEvent.getSource()).isSameAs(sessionRepository);
assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSession()).isSameAs(mockSession);
assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId);
return null;
}
}).when(mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class));
}).given(this.mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class));
sessionRepository.delete(expectedSessionId);
this.sessionRepository.delete(expectedSessionId);
verify(mockSession, times(1)).getId();
verify(mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
}
@Test
public void deleteRemovesNonExistingSessionAndHandlesDelete() {
final String expectedSessionId = "1";
when(mockTemplate.remove(anyString())).thenReturn(null);
given(this.mockTemplate.remove(anyString())).willReturn(null);
doAnswer(new Answer<Void>() {
willAnswer(new Answer<Void>() {
public Void answer(final InvocationOnMock invocation) throws Throwable {
ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class);
@@ -403,18 +400,18 @@ public class GemFireOperationsSessionRepositoryTest {
AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent;
assertThat(sessionEvent.getSource()).isSameAs(sessionRepository);
assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository);
assertThat(sessionEvent.getSession()).isNull();
assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId);
return null;
}
}).when(mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class));
}).given(this.mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class));
sessionRepository.delete(expectedSessionId);
this.sessionRepository.delete(expectedSessionId);
verify(mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId));
verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class));
}
protected abstract class GemfireOperationsAccessor extends GemfireAccessor implements GemfireOperations {

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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,
@@ -16,35 +16,36 @@
package org.springframework.session.data.gemfire.config.annotation.web.http;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.data.gemfire.GemfireOperations;
import org.springframework.data.gemfire.GemfireTemplate;
import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.GemFireCache;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.data.gemfire.GemfireOperations;
import org.springframework.data.gemfire.GemfireTemplate;
import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* The GemFireHttpSessionConfigurationTest class is a test suite of test cases testing the contract and functionality
* of the {@link GemFireHttpSessionConfiguration} class.
*
* @author John Blum
* @since 1.1.0
* @see org.junit.Test
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.GemfireOperations
@@ -55,7 +56,6 @@ import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
* @see com.gemstone.gemfire.cache.GemFireCache
* @see com.gemstone.gemfire.cache.Region
* @see com.gemstone.gemfire.cache.client.ClientCache
* @since 1.1.0
*/
public class GemFireHttpSessionConfigurationTest {
@@ -67,119 +67,119 @@ public class GemFireHttpSessionConfigurationTest {
@Before
public void setup() {
gemfireConfiguration = new GemFireHttpSessionConfiguration();
this.gemfireConfiguration = new GemFireHttpSessionConfiguration();
}
@Test
public void setAndGetBeanClassLoader() {
assertThat(gemfireConfiguration.getBeanClassLoader()).isNull();
assertThat(this.gemfireConfiguration.getBeanClassLoader()).isNull();
gemfireConfiguration.setBeanClassLoader(Thread.currentThread().getContextClassLoader());
this.gemfireConfiguration.setBeanClassLoader(Thread.currentThread().getContextClassLoader());
assertThat(gemfireConfiguration.getBeanClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader());
assertThat(this.gemfireConfiguration.getBeanClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader());
gemfireConfiguration.setBeanClassLoader(null);
this.gemfireConfiguration.setBeanClassLoader(null);
assertThat(gemfireConfiguration.getBeanClassLoader()).isNull();
assertThat(this.gemfireConfiguration.getBeanClassLoader()).isNull();
}
@Test
public void setAndGetClientRegionShortcut() {
assertThat(gemfireConfiguration.getClientRegionShortcut()).isEqualTo(
assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT);
gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY);
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY);
assertThat(gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY);
assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY);
gemfireConfiguration.setClientRegionShortcut(null);
this.gemfireConfiguration.setClientRegionShortcut(null);
assertThat(gemfireConfiguration.getClientRegionShortcut()).isEqualTo(
assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT);
}
@Test
public void setAndGetIndexableSessionAttributes() {
assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_INDEXABLE_SESSION_ATTRIBUTES);
gemfireConfiguration.setIndexableSessionAttributes(toArray("one", "two", "three"));
this.gemfireConfiguration.setIndexableSessionAttributes(toArray("one", "two", "three"));
assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three"));
assertThat(gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression())
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three"));
assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression())
.isEqualTo("'one', 'two', 'three'");
gemfireConfiguration.setIndexableSessionAttributes(toArray("one"));
this.gemfireConfiguration.setIndexableSessionAttributes(toArray("one"));
assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one"));
assertThat(gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("'one'");
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one"));
assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("'one'");
gemfireConfiguration.setIndexableSessionAttributes(null);
this.gemfireConfiguration.setIndexableSessionAttributes(null);
assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_INDEXABLE_SESSION_ATTRIBUTES);
assertThat(gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("*");
assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("*");
}
@Test
public void setAndGetMaxInactiveIntervalInSeconds() {
assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS);
gemfireConfiguration.setMaxInactiveIntervalInSeconds(300);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(300);
assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(300);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(300);
gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MAX_VALUE);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MAX_VALUE);
assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MAX_VALUE);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MAX_VALUE);
gemfireConfiguration.setMaxInactiveIntervalInSeconds(-1);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(-1);
assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(-1);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(-1);
gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MIN_VALUE);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MIN_VALUE);
assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MIN_VALUE);
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MIN_VALUE);
}
@Test
public void setAndGetServerRegionShortcut() {
assertThat(gemfireConfiguration.getServerRegionShortcut()).isEqualTo(
assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT);
gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PERSISTENT);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PERSISTENT);
assertThat(gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE_PERSISTENT);
assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE_PERSISTENT);
gemfireConfiguration.setServerRegionShortcut(null);
this.gemfireConfiguration.setServerRegionShortcut(null);
assertThat(gemfireConfiguration.getServerRegionShortcut()).isEqualTo(
assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT);
}
@Test
public void setAndGetSpringSessionGemFireRegionName() {
assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
gemfireConfiguration.setSpringSessionGemFireRegionName("test");
this.gemfireConfiguration.setSpringSessionGemFireRegionName("test");
assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("test");
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("test");
gemfireConfiguration.setSpringSessionGemFireRegionName(" ");
this.gemfireConfiguration.setSpringSessionGemFireRegionName(" ");
assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
gemfireConfiguration.setSpringSessionGemFireRegionName("");
this.gemfireConfiguration.setSpringSessionGemFireRegionName("");
assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
gemfireConfiguration.setSpringSessionGemFireRegionName(null);
this.gemfireConfiguration.setSpringSessionGemFireRegionName(null);
assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo(
GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
}
@@ -195,16 +195,16 @@ public class GemFireHttpSessionConfigurationTest {
annotationAttributes.put("serverRegionShortcut", RegionShortcut.REPLICATE);
annotationAttributes.put("regionName", "TEST");
when(mockAnnotationMetadata.getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName())))
.thenReturn(annotationAttributes);
given(mockAnnotationMetadata.getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName())))
.willReturn(annotationAttributes);
gemfireConfiguration.setImportMetadata(mockAnnotationMetadata);
this.gemfireConfiguration.setImportMetadata(mockAnnotationMetadata);
assertThat(gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY);
assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three"));
assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(600);
assertThat(gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE);
assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("TEST");
assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY);
assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three"));
assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(600);
assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE);
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("TEST");
verify(mockAnnotationMetadata, times(1)).getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName()));
}
@@ -214,9 +214,9 @@ public class GemFireHttpSessionConfigurationTest {
GemfireOperations mockGemfireOperations = mock(GemfireOperations.class,
"testCreateAndInitializeSpringSessionRepositoryBean");
gemfireConfiguration.setMaxInactiveIntervalInSeconds(120);
this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(120);
GemFireOperationsSessionRepository sessionRepository = gemfireConfiguration.sessionRepository(
GemFireOperationsSessionRepository sessionRepository = this.gemfireConfiguration.sessionRepository(
mockGemfireOperations);
assertThat(sessionRepository).isNotNull();
@@ -228,15 +228,15 @@ public class GemFireHttpSessionConfigurationTest {
@SuppressWarnings("unchecked")
public void createAndInitializeSpringSessionGemFireRegionTemplate() {
GemFireCache mockGemFireCache = mock(GemFireCache.class);
Region<Object,Object> mockRegion = mock(Region.class);
Region<Object, Object> mockRegion = mock(Region.class);
when(mockGemFireCache.getRegion(eq("Example"))).thenReturn(mockRegion);
given(mockGemFireCache.getRegion(eq("Example"))).willReturn(mockRegion);
gemfireConfiguration.setSpringSessionGemFireRegionName("Example");
this.gemfireConfiguration.setSpringSessionGemFireRegionName("Example");
GemfireTemplate template = gemfireConfiguration.sessionRegionTemplate(mockGemFireCache);
GemfireTemplate template = this.gemfireConfiguration.sessionRegionTemplate(mockGemFireCache);
assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("Example");
assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("Example");
assertThat(template).isNotNull();
assertThat(template.getRegion()).isSameAs(mockRegion);
@@ -248,24 +248,24 @@ public class GemFireHttpSessionConfigurationTest {
Cache mockCache = mock(Cache.class, "testExpirationIsAllowed.MockCache");
ClientCache mockClientCache = mock(ClientCache.class, "testExpirationIsAllowed.MockClientCache");
gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY);
gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE);
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE);
assertThat(gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue();
gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
assertThat(gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue();
gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY);
gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY);
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY);
assertThat(gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue();
gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PROXY);
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PROXY);
assertThat(gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue();
}
@Test
@@ -273,15 +273,15 @@ public class GemFireHttpSessionConfigurationTest {
Cache mockCache = mock(Cache.class, "testExpirationIsAllowed.MockCache");
ClientCache mockClientCache = mock(ClientCache.class, "testExpirationIsAllowed.MockClientCache");
gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY);
gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION);
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION);
assertThat(gemfireConfiguration.isExpirationAllowed(mockClientCache)).isFalse();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isFalse();
gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL);
gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY);
this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL);
this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY);
assertThat(gemfireConfiguration.isExpirationAllowed(mockCache)).isFalse();
assertThat(this.gemfireConfiguration.isExpirationAllowed(mockCache)).isFalse();
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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,
@@ -16,19 +16,6 @@
package org.springframework.session.data.gemfire.config.annotation.web.http.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.gemfire.client.Interest;
import org.springframework.session.ExpiringSession;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.GemFireCache;
import com.gemstone.gemfire.cache.InterestResultPolicy;
@@ -37,12 +24,26 @@ import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.gemfire.client.Interest;
import org.springframework.session.ExpiringSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* The GemFireCacheTypeAwareRegionFactoryBeanTest class is a test suite of test cases testing the contract
* and functionality of the GemFireCacheTypeAwareRegionFactoryBean class.
*
* @author John Blum
* @since 1.1.0
* @see org.junit.Rule
* @see org.junit.Test
* @see org.mockito.Mockito
@@ -55,7 +56,6 @@ import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
* @see com.gemstone.gemfire.cache.RegionShortcut
* @see com.gemstone.gemfire.cache.client.ClientCache
* @see com.gemstone.gemfire.cache.client.ClientRegionShortcut
* @since 1.1.0
*/
@RunWith(MockitoJUnitRunner.class)
public class GemFireCacheTypeAwareRegionFactoryBeanTest {
@@ -64,66 +64,70 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
public ExpectedException expectedException = ExpectedException.none();
@Mock
Region<Object,ExpiringSession> mockClientRegion;
Region<Object, ExpiringSession> mockClientRegion;
@Mock
Region<Object,ExpiringSession> mockServerRegion;
Region<Object, ExpiringSession> mockServerRegion;
@Mock
ClientCache mockClientCache;
private GemFireCacheTypeAwareRegionFactoryBean<Object,ExpiringSession> regionFactoryBean;
private GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession> regionFactoryBean;
@Before
public void setup() {
regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object,ExpiringSession>();
this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession>();
}
@Test
public void afterPropertiesSetCreatesClientRegionForClientCache() throws Exception {
regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object,ExpiringSession>() {
@Override protected Region<Object,ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockClientCache);
return mockClientRegion;
this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession>() {
@Override
protected Region<Object, ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache);
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion;
}
@Override protected Region<Object,ExpiringSession> newServerRegion(final GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockClientCache);
return mockServerRegion;
@Override
protected Region<Object, ExpiringSession> newServerRegion(final GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache);
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockServerRegion;
}
};
regionFactoryBean.setGemfireCache(mockClientCache);
regionFactoryBean.afterPropertiesSet();
this.regionFactoryBean.setGemfireCache(this.mockClientCache);
this.regionFactoryBean.afterPropertiesSet();
assertThat(regionFactoryBean.getGemfireCache()).isSameAs(mockClientCache);
assertThat(regionFactoryBean.getObject()).isEqualTo(mockClientRegion);
assertThat(this.regionFactoryBean.getGemfireCache()).isSameAs(this.mockClientCache);
assertThat(this.regionFactoryBean.getObject()).isEqualTo(this.mockClientRegion);
}
@Test
public void afterPropertiesSetCreatesServerRegionForPeerCache() throws Exception {
final Cache mockCache = mock(Cache.class);
regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object,ExpiringSession>() {
@Override protected Region<Object,ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession>() {
@Override
protected Region<Object, ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockCache);
return mockClientRegion;
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion;
}
@Override protected Region<Object,ExpiringSession> newServerRegion(final GemFireCache gemfireCache) throws Exception {
@Override
protected Region<Object, ExpiringSession> newServerRegion(final GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockCache);
return mockServerRegion;
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockServerRegion;
}
};
regionFactoryBean.setGemfireCache(mockCache);
regionFactoryBean.afterPropertiesSet();
this.regionFactoryBean.setGemfireCache(mockCache);
this.regionFactoryBean.afterPropertiesSet();
assertThat(regionFactoryBean.getGemfireCache()).isSameAs(mockCache);
assertThat(regionFactoryBean.getObject()).isEqualTo(mockServerRegion);
assertThat(this.regionFactoryBean.getGemfireCache()).isSameAs(mockCache);
assertThat(this.regionFactoryBean.getObject()).isEqualTo(this.mockServerRegion);
}
@Test
public void allKeysInterestRegistration() {
Interest<Object>[] interests = regionFactoryBean.registerInterests(true);
Interest<Object>[] interests = this.regionFactoryBean.registerInterests(true);
assertThat(interests).isNotNull();
assertThat(interests.length).isEqualTo(1);
@@ -135,7 +139,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
@Test
public void emptyInterestsRegistration() {
Interest<Object>[] interests = regionFactoryBean.registerInterests(false);
Interest<Object>[] interests = this.regionFactoryBean.registerInterests(false);
assertThat(interests).isNotNull();
assertThat(interests.length).isEqualTo(0);
@@ -143,26 +147,26 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
@Test
public void getObjectTypeBeforeInitializationIsRegionClass() {
assertThat(regionFactoryBean.getObjectType()).isEqualTo(Region.class);
assertThat(this.regionFactoryBean.getObjectType()).isEqualTo(Region.class);
}
@Test
public void isSingletonIsTrue() {
assertThat(regionFactoryBean.isSingleton()).isTrue();
assertThat(this.regionFactoryBean.isSingleton()).isTrue();
}
@Test
public void setAndGetClientRegionShortcut() {
assertThat(regionFactoryBean.getClientRegionShortcut()).isEqualTo(
assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT);
regionFactoryBean.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT);
this.regionFactoryBean.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT);
assertThat(regionFactoryBean.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.LOCAL_PERSISTENT);
assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.LOCAL_PERSISTENT);
regionFactoryBean.setClientRegionShortcut(null);
this.regionFactoryBean.setClientRegionShortcut(null);
assertThat(regionFactoryBean.getClientRegionShortcut()).isEqualTo(
assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT);
}
@@ -170,78 +174,78 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest {
public void setAndGetGemfireCache() {
Cache mockCache = mock(Cache.class);
regionFactoryBean.setGemfireCache(mockCache);
this.regionFactoryBean.setGemfireCache(mockCache);
assertThat(regionFactoryBean.getGemfireCache()).isEqualTo(mockCache);
assertThat(this.regionFactoryBean.getGemfireCache()).isEqualTo(mockCache);
}
@Test
public void setGemfireCacheToNullThrowsIllegalArgumentException() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The GemFireCache reference must not be null");
regionFactoryBean.setGemfireCache(null);
this.expectedException.expect(IllegalArgumentException.class);
this.expectedException.expectMessage("The GemFireCache reference must not be null");
this.regionFactoryBean.setGemfireCache(null);
}
@Test
public void getGemfireCacheWhenNullThrowsIllegalStateException() {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("A reference to a GemFireCache was not properly configured");
regionFactoryBean.getGemfireCache();
this.expectedException.expect(IllegalStateException.class);
this.expectedException.expectMessage("A reference to a GemFireCache was not properly configured");
this.regionFactoryBean.getGemfireCache();
}
@Test
@SuppressWarnings("unchecked")
public void setAndGetRegionAttributes() {
RegionAttributes<Object,ExpiringSession> mockRegionAttributes = mock(RegionAttributes.class);
RegionAttributes<Object, ExpiringSession> mockRegionAttributes = mock(RegionAttributes.class);
assertThat(regionFactoryBean.getRegionAttributes()).isNull();
assertThat(this.regionFactoryBean.getRegionAttributes()).isNull();
regionFactoryBean.setRegionAttributes(mockRegionAttributes);
this.regionFactoryBean.setRegionAttributes(mockRegionAttributes);
assertThat(regionFactoryBean.getRegionAttributes()).isSameAs(mockRegionAttributes);
assertThat(this.regionFactoryBean.getRegionAttributes()).isSameAs(mockRegionAttributes);
regionFactoryBean.setRegionAttributes(null);
this.regionFactoryBean.setRegionAttributes(null);
assertThat(regionFactoryBean.getRegionAttributes()).isNull();
assertThat(this.regionFactoryBean.getRegionAttributes()).isNull();
}
@Test
public void setAndGetRegionName() {
assertThat(regionFactoryBean.getRegionName()).isEqualTo(
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
regionFactoryBean.setRegionName("Example");
this.regionFactoryBean.setRegionName("Example");
assertThat(regionFactoryBean.getRegionName()).isEqualTo("Example");
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo("Example");
regionFactoryBean.setRegionName(" ");
this.regionFactoryBean.setRegionName(" ");
assertThat(regionFactoryBean.getRegionName()).isEqualTo(
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
regionFactoryBean.setRegionName("");
this.regionFactoryBean.setRegionName("");
assertThat(regionFactoryBean.getRegionName()).isEqualTo(
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
regionFactoryBean.setRegionName(null);
this.regionFactoryBean.setRegionName(null);
assertThat(regionFactoryBean.getRegionName()).isEqualTo(
assertThat(this.regionFactoryBean.getRegionName()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME);
}
@Test
public void setAndGetServerRegionShortcut() {
assertThat(regionFactoryBean.getServerRegionShortcut()).isEqualTo(
assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT);
regionFactoryBean.setServerRegionShortcut(RegionShortcut.LOCAL_PERSISTENT);
this.regionFactoryBean.setServerRegionShortcut(RegionShortcut.LOCAL_PERSISTENT);
assertThat(regionFactoryBean.getServerRegionShortcut()).isEqualTo(RegionShortcut.LOCAL_PERSISTENT);
assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo(RegionShortcut.LOCAL_PERSISTENT);
regionFactoryBean.setServerRegionShortcut(null);
this.regionFactoryBean.setServerRegionShortcut(null);
assertThat(regionFactoryBean.getServerRegionShortcut()).isEqualTo(
assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo(
GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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,
@@ -16,32 +16,31 @@
package org.springframework.session.data.gemfire.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.Closeable;
import java.io.IOException;
import org.junit.Test;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.GemFireCache;
import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* The GemFireUtilsTest class is a test suite of test cases testing the contract and functionality of the GemFireUtils
* utility class.
*
* @author John Blum
* @since 1.1.0
* @see org.junit.Test
* @see org.mockito.Mockito
* @see org.springframework.session.data.gemfire.support.GemFireUtils
* @since 1.1.0
*/
public class GemFireUtilsTest {
@@ -55,7 +54,7 @@ public class GemFireUtilsTest {
@Test
public void closeNonNullCloseableObjectThrowingIOExceptionReturnsFalse() throws IOException {
Closeable mockCloseable = mock(Closeable.class);
doThrow(new IOException("test")).when(mockCloseable).close();
willThrow(new IOException("test")).given(mockCloseable).close();
assertThat(GemFireUtils.close(mockCloseable)).isFalse();
verify(mockCloseable, times(1)).close();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,23 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.data.redis;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.session.data.redis.RedisOperationsSessionRepository.CREATION_TIME_ATTR;
import static org.springframework.session.data.redis.RedisOperationsSessionRepository.LAST_ACCESSED_ATTR;
import static org.springframework.session.data.redis.RedisOperationsSessionRepository.MAX_INACTIVE_ATTR;
import static org.springframework.session.data.redis.RedisOperationsSessionRepository.getSessionAttrNameKey;
package org.springframework.session.data.redis;
import java.util.Arrays;
import java.util.Collections;
@@ -46,6 +31,7 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.connection.DefaultMessage;
import org.springframework.data.redis.connection.RedisConnection;
@@ -68,9 +54,20 @@ import org.springframework.session.data.redis.RedisOperationsSessionRepository.P
import org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession;
import org.springframework.session.events.AbstractSessionEvent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings({"unchecked","rawtypes"})
@SuppressWarnings({"unchecked", "rawtypes"})
public class RedisOperationsSessionRepositoryTests {
static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";
@@ -79,7 +76,7 @@ public class RedisOperationsSessionRepositoryTests {
@Mock
RedisConnection connection;
@Mock
RedisOperations<Object,Object> redisOperations;
RedisOperations<Object, Object> redisOperations;
@Mock
BoundValueOperations<Object, Object> boundValueOperations;
@Mock
@@ -93,7 +90,7 @@ public class RedisOperationsSessionRepositoryTests {
@Captor
ArgumentCaptor<AbstractSessionEvent> event;
@Captor
ArgumentCaptor<Map<String,Object>> delta;
ArgumentCaptor<Map<String, Object>> delta;
private MapSession cached;
@@ -102,166 +99,166 @@ public class RedisOperationsSessionRepositoryTests {
@Before
public void setup() {
this.redisRepository = new RedisOperationsSessionRepository(redisOperations);
this.redisRepository.setDefaultSerializer(defaultSerializer);
this.redisRepository = new RedisOperationsSessionRepository(this.redisOperations);
this.redisRepository.setDefaultSerializer(this.defaultSerializer);
cached = new MapSession();
cached.setId("session-id");
cached.setCreationTime(1404360000000L);
cached.setLastAccessedTime(1404360000000L);
this.cached = new MapSession();
this.cached.setId("session-id");
this.cached.setCreationTime(1404360000000L);
this.cached.setLastAccessedTime(1404360000000L);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void constructorNullConnectionFactory() {
new RedisOperationsSessionRepository((RedisConnectionFactory)null);
new RedisOperationsSessionRepository((RedisConnectionFactory) null);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void setApplicationEventPublisherNull() {
redisRepository.setApplicationEventPublisher(null);
this.redisRepository.setApplicationEventPublisher(null);
}
// gh-61
@Test
public void constructorConnectionFactory() {
redisRepository = new RedisOperationsSessionRepository(factory);
RedisSession session = redisRepository.createSession();
this.redisRepository = new RedisOperationsSessionRepository(this.factory);
RedisSession session = this.redisRepository.createSession();
when(factory.getConnection()).thenReturn(connection);
given(this.factory.getConnection()).willReturn(this.connection);
redisRepository.save(session);
this.redisRepository.save(session);
}
@Test
public void createSessionDefaultMaxInactiveInterval() throws Exception {
ExpiringSession session = redisRepository.createSession();
ExpiringSession session = this.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();
this.redisRepository.setDefaultMaxInactiveInterval(interval);
ExpiringSession session = this.redisRepository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(interval);
}
@Test
public void saveNewSession() {
RedisSession session = redisRepository.createSession();
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
RedisSession session = this.redisRepository.createSession();
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.save(session);
this.redisRepository.save(session);
Map<String,Object> delta = getDelta();
Map<String, Object> delta = getDelta();
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta.get(CREATION_TIME_ATTR);
Object creationTime = delta.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR);
assertThat(creationTime).isEqualTo(session.getCreationTime());
assertThat(delta.get(MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime());
assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime());
}
@Test
public void saveJavadocSummary() {
RedisSession session = redisRepository.createSession();
RedisSession session = this.redisRepository.createSession();
String sessionKey = "spring:session:sessions:" + session.getId();
String backgroundExpireKey = "spring:session:expirations:" + RedisSessionExpirationPolicy.roundUpToNextMinute(RedisSessionExpirationPolicy.expiresInMillis(session));
String destroyedTriggerKey = "spring:session:sessions:expires:" + session.getId();
when(redisOperations.boundHashOps(sessionKey)).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(backgroundExpireKey)).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(destroyedTriggerKey)).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(sessionKey)).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(backgroundExpireKey)).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(destroyedTriggerKey)).willReturn(this.boundValueOperations);
redisRepository.save(session);
this.redisRepository.save(session);
// the actual data in the session expires 5 minutes after expiration so the data can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since getSession checks if it is expired
long fiveMinutesAfterExpires = session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5);
verify(boundHashOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS);
verify(boundSetOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS);
verify(boundSetOperations).add("expires:" + session.getId());
verify(boundValueOperations).expire(1800L, TimeUnit.SECONDS);
verify(boundValueOperations).append("");
verify(this.boundHashOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS);
verify(this.boundSetOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS);
verify(this.boundSetOperations).add("expires:" + session.getId());
verify(this.boundValueOperations).expire(1800L, TimeUnit.SECONDS);
verify(this.boundValueOperations).append("");
}
@Test
public void saveJavadoc() {
RedisSession session = redisRepository.new RedisSession(cached);
RedisSession session = this.redisRepository.new RedisSession(this.cached);
when(redisOperations.boundHashOps("spring:session:sessions:session-id")).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps("spring:session:expirations:1404361860000")).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps("spring:session:sessions:expires:session-id")).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps("spring:session:sessions:session-id")).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps("spring:session:expirations:1404361860000")).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps("spring:session:sessions:expires:session-id")).willReturn(this.boundValueOperations);
redisRepository.save(session);
this.redisRepository.save(session);
// the actual data in the session expires 5 minutes after expiration so the data can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since getSession checks if it is expired
verify(boundHashOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
verify(this.boundHashOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
}
@Test
public void saveLastAccessChanged() {
RedisSession session = redisRepository.new RedisSession(new MapSession(cached));
RedisSession session = this.redisRepository.new RedisSession(new MapSession(this.cached));
session.setLastAccessedTime(12345678L);
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.save(session);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(LAST_ACCESSED_ATTR, session.getLastAccessedTime()));
assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, session.getLastAccessedTime()));
}
@Test
public void saveSetAttribute() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession(new MapSession());
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.save(session);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
@Test
public void saveRemoveAttribute() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession(new MapSession());
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.removeAttribute(attrName);
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.save(session);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(getSessionAttrNameKey(attrName), null));
assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null));
}
@Test
public void saveExpired() {
RedisSession session = redisRepository.new RedisSession(new MapSession());
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.setMaxInactiveIntervalInSeconds(0);
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.save(session);
this.redisRepository.save(session);
String id = session.getId();
verify(redisOperations,atLeastOnce()).delete(getKey("expires:"+id));
verify(redisOperations,never()).boundValueOps(getKey("expires:"+id));
verify(this.redisOperations, atLeastOnce()).delete(getKey("expires:" + id));
verify(this.redisOperations, never()).boundValueOps(getKey("expires:" + id));
}
@Test
public void redisSessionGetAttributes() {
String attrName = "attrName";
RedisSession session = redisRepository.new RedisSession();
RedisSession session = this.redisRepository.new RedisSession();
assertThat(session.getAttributeNames()).isEmpty();
session.setAttribute(attrName, "attrValue");
assertThat(session.getAttributeNames()).containsOnly(attrName);
@@ -275,44 +272,44 @@ public class RedisOperationsSessionRepositoryTests {
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
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);
RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
RedisOperationsSessionRepository.CREATION_TIME_ATTR, expected.getCreationTime(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, expected.getLastAccessedTime());
given(this.boundHashOperations.entries()).willReturn(map);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
String id = expected.getId();
redisRepository.delete(id);
this.redisRepository.delete(id);
assertThat(getDelta().get(MAX_INACTIVE_ATTR)).isEqualTo(0);
verify(redisOperations,atLeastOnce()).delete(getKey("expires:"+id));
verify(redisOperations,never()).boundValueOps(getKey("expires:"+id));
assertThat(getDelta().get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(0);
verify(this.redisOperations, atLeastOnce()).delete(getKey("expires:" + id));
verify(this.redisOperations, never()).boundValueOps(getKey("expires:" + id));
}
@Test
public void deleteNullSession() {
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
String id = "abc";
redisRepository.delete(id);
verify(redisOperations,times(0)).delete(anyString());
verify(redisOperations,times(0)).delete(anyString());
this.redisRepository.delete(id);
verify(this.redisOperations, times(0)).delete(anyString());
verify(this.redisOperations, times(0)).delete(anyString());
}
@Test
public void getSessionNotFound() {
String id = "abc";
when(redisOperations.boundHashOps(getKey(id))).thenReturn(boundHashOperations);
when(boundHashOperations.entries()).thenReturn(map());
given(this.redisOperations.boundHashOps(getKey(id))).willReturn(this.boundHashOperations);
given(this.boundHashOperations.entries()).willReturn(map());
assertThat(redisRepository.getSession(id)).isNull();
assertThat(this.redisRepository.getSession(id)).isNull();
}
@Test
@@ -321,15 +318,15 @@ public class RedisOperationsSessionRepositoryTests {
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setAttribute(attrName, "attrValue");
when(redisOperations.boundHashOps(getKey(expected.getId()))).thenReturn(boundHashOperations);
given(this.redisOperations.boundHashOps(getKey(expected.getId()))).willReturn(this.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);
RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
RedisOperationsSessionRepository.CREATION_TIME_ATTR, expected.getCreationTime(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, expected.getLastAccessedTime());
given(this.boundHashOperations.entries()).willReturn(map);
RedisSession session = redisRepository.getSession(expected.getId());
RedisSession session = this.redisRepository.getSession(expected.getId());
assertThat(session.getId()).isEqualTo(expected.getId());
assertThat(session.getAttributeNames()).isEqualTo(expected.getAttributeNames());
assertThat(session.getAttribute(attrName)).isEqualTo(expected.getAttribute(attrName));
@@ -342,27 +339,27 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void getSessionExpired() {
String expiredId = "expired-id";
when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations);
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
Map map = map(
MAX_INACTIVE_ATTR, 1,
LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
when(boundHashOperations.entries()).thenReturn(map);
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
given(this.boundHashOperations.entries()).willReturn(map);
assertThat(redisRepository.getSession(expiredId)).isNull();
assertThat(this.redisRepository.getSession(expiredId)).isNull();
}
@Test
public void findByPrincipalNameExpired() {
String expiredId = "expired-id";
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(boundSetOperations.members()).thenReturn(Collections.<Object>singleton(expiredId));
when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.<Object>singleton(expiredId));
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
Map map = map(
MAX_INACTIVE_ATTR, 1,
LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
when(boundHashOperations.entries()).thenReturn(map);
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
given(this.boundHashOperations.entries()).willReturn(map);
assertThat(redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal")).isEmpty();
assertThat(this.redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal")).isEmpty();
}
@Test
@@ -371,16 +368,16 @@ public class RedisOperationsSessionRepositoryTests {
long createdTime = lastAccessed - 10;
int maxInactive = 3600;
String sessionId = "some-id";
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(boundSetOperations.members()).thenReturn(Collections.<Object>singleton(sessionId));
when(redisOperations.boundHashOps(getKey(sessionId))).thenReturn(boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.<Object>singleton(sessionId));
given(this.redisOperations.boundHashOps(getKey(sessionId))).willReturn(this.boundHashOperations);
Map map = map(
CREATION_TIME_ATTR, createdTime,
MAX_INACTIVE_ATTR, maxInactive,
LAST_ACCESSED_ATTR, lastAccessed);
when(boundHashOperations.entries()).thenReturn(map);
RedisOperationsSessionRepository.CREATION_TIME_ATTR, createdTime,
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, maxInactive,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, lastAccessed);
given(this.boundHashOperations.entries()).willReturn(map);
Map<String, RedisSession> sessionIdToSessions = redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal");
Map<String, RedisSession> sessionIdToSessions = this.redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal");
assertThat(sessionIdToSessions).hasSize(1);
RedisSession session = sessionIdToSessions.get(sessionId);
@@ -394,62 +391,62 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void cleanupExpiredSessions() {
String expiredId = "expired-id";
when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
Set<Object> expiredIds = new HashSet<Object>(Arrays.asList("expired-key1","expired-key2"));
when(boundSetOperations.members()).thenReturn(expiredIds);
Set<Object> expiredIds = new HashSet<Object>(Arrays.asList("expired-key1", "expired-key2"));
given(this.boundSetOperations.members()).willReturn(expiredIds);
redisRepository.cleanupExpiredSessions();
this.redisRepository.cleanupExpiredSessions();
for(Object id : expiredIds) {
for (Object id : expiredIds) {
String expiredKey = "spring:session:sessions:" + id;
// https://github.com/spring-projects/spring-session/issues/93
verify(redisOperations).hasKey(expiredKey);
verify(this.redisOperations).hasKey(expiredKey);
}
}
@Test
public void onMessageCreated() throws Exception {
MapSession session = cached;
MapSession session = this.cached;
byte[] pattern = "".getBytes("UTF-8");
String channel = "spring:session:event:created:" + session.getId();
JdkSerializationRedisSerializer defaultSerailizer = new JdkSerializationRedisSerializer();
redisRepository.setDefaultSerializer(defaultSerailizer);
this.redisRepository.setDefaultSerializer(defaultSerailizer);
byte[] body = defaultSerailizer.serialize(new HashMap());
DefaultMessage message = new DefaultMessage(channel.getBytes("UTF-8"), body);
redisRepository.setApplicationEventPublisher(publisher);
this.redisRepository.setApplicationEventPublisher(this.publisher);
redisRepository.onMessage(message, pattern);
this.redisRepository.onMessage(message, pattern);
verify(publisher).publishEvent(event.capture());
assertThat(event.getValue().getSessionId()).isEqualTo(session.getId());
verify(this.publisher).publishEvent(this.event.capture());
assertThat(this.event.getValue().getSessionId()).isEqualTo(session.getId());
}
// gh-309
@Test
public void onMessageCreatedCustomSerializer() throws Exception {
MapSession session = cached;
MapSession session = this.cached;
byte[] pattern = "".getBytes("UTF-8");
byte[] body = new byte[0];
String channel = "spring:session:event:created:" + session.getId();
when(defaultSerializer.deserialize(body)).thenReturn(new HashMap<String,Object>());
given(this.defaultSerializer.deserialize(body)).willReturn(new HashMap<String, Object>());
DefaultMessage message = new DefaultMessage(channel.getBytes("UTF-8"), body);
redisRepository.setApplicationEventPublisher(publisher);
this.redisRepository.setApplicationEventPublisher(this.publisher);
redisRepository.onMessage(message, pattern);
this.redisRepository.onMessage(message, pattern);
verify(publisher).publishEvent(event.capture());
assertThat(event.getValue().getSessionId()).isEqualTo(session.getId());
verify(defaultSerializer).deserialize(body);
verify(this.publisher).publishEvent(this.event.capture());
assertThat(this.event.getValue().getSessionId()).isEqualTo(session.getId());
verify(this.defaultSerializer).deserialize(body);
}
@Test
public void resolvePrincipalIndex() {
PrincipalNameResolver resolver = RedisOperationsSessionRepository.PRINCIPAL_NAME_RESOLVER;
String username = "username";
RedisSession session = redisRepository.createSession();
RedisSession session = this.redisRepository.createSession();
session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);
assertThat(resolver.resolvePrincipal(session)).isEqualTo(username);
@@ -464,7 +461,7 @@ public class RedisOperationsSessionRepositoryTests {
PrincipalNameResolver resolver = RedisOperationsSessionRepository.PRINCIPAL_NAME_RESOLVER;
RedisSession session = redisRepository.createSession();
RedisSession session = this.redisRepository.createSession();
session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, context);
assertThat(resolver.resolvePrincipal(session)).isEqualTo(principal);
@@ -472,128 +469,128 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void flushModeOnSaveCreate() {
redisRepository.createSession();
this.redisRepository.createSession();
verifyZeroInteractions(boundHashOperations);
verifyZeroInteractions(this.boundHashOperations);
}
@Test
public void flushModeOnSaveSetAttribute() {
RedisSession session = redisRepository.createSession();
RedisSession session = this.redisRepository.createSession();
session.setAttribute("something", "here");
verifyZeroInteractions(boundHashOperations);
verifyZeroInteractions(this.boundHashOperations);
}
@Test
public void flushModeOnSaveRemoveAttribute() {
RedisSession session = redisRepository.createSession();
RedisSession session = this.redisRepository.createSession();
session.removeAttribute("remove");
verifyZeroInteractions(boundHashOperations);
verifyZeroInteractions(this.boundHashOperations);
}
@Test
public void flushModeOnSaveSetLastAccessedTime() {
RedisSession session = redisRepository.createSession();
RedisSession session = this.redisRepository.createSession();
session.setLastAccessedTime(1L);
verifyZeroInteractions(boundHashOperations);
verifyZeroInteractions(this.boundHashOperations);
}
@Test
public void flushModeOnSaveSetMaxInactiveIntervalInSeconds() {
RedisSession session = redisRepository.createSession();
RedisSession session = this.redisRepository.createSession();
session.setMaxInactiveIntervalInSeconds(1);
verifyZeroInteractions(boundHashOperations);
verifyZeroInteractions(this.boundHashOperations);
}
@Test
public void flushModeImmediateCreate() {
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = redisRepository.createSession();
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
Map<String, Object> delta = getDelta();
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta.get(CREATION_TIME_ATTR);
Object creationTime = delta.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR);
assertThat(creationTime).isEqualTo(session.getCreationTime());
assertThat(delta.get(MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime());
assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime());
}
@Test
public void flushModeImmediateSetAttribute() {
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = redisRepository.createSession();
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
String attrName = "someAttribute";
session.setAttribute(attrName, "someValue");
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(map(getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
@Test
public void flushModeImmediateRemoveAttribute() {
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = redisRepository.createSession();
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
String attrName = "someAttribute";
session.removeAttribute(attrName);
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(map(getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
@Test
public void flushModeSetMaxInactiveIntervalInSeconds() {
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = redisRepository.createSession();
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
reset(boundHashOperations);
reset(this.boundHashOperations);
session.setMaxInactiveIntervalInSeconds(1);
verify(boundHashOperations).expire(anyLong(), any(TimeUnit.class));
verify(this.boundHashOperations).expire(anyLong(), any(TimeUnit.class));
}
@Test
public void flushModeSetLastAccessedTime() {
when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations);
when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations);
when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = redisRepository.createSession();
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
long now = System.currentTimeMillis();
session.setLastAccessedTime(now);
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(map(LAST_ACCESSED_ATTR, session.getLastAccessedTime()));
assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, session.getLastAccessedTime()));
}
@Test(expected = IllegalArgumentException.class)
public void setRedisFlushModeNull() {
redisRepository.setRedisFlushMode(null);
this.redisRepository.setRedisFlushMode(null);
}
private String getKey(String id) {
@@ -601,22 +598,22 @@ public class RedisOperationsSessionRepositoryTests {
}
private Map map(Object...objects) {
Map<String,Object> result = new HashMap<String,Object>();
if(objects == null) {
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]);
for (int i = 0; i < objects.length; i += 2) {
result.put((String) objects[i], objects[i + 1]);
}
return result;
}
private Map<String,Object> getDelta() {
private Map<String, Object> getDelta() {
return getDelta(1);
}
private Map<String,Object> getDelta(int times) {
verify(boundHashOperations,times(times)).putAll(delta.capture());
return delta.getAllValues().get(times - 1);
private Map<String, Object> getDelta(int times) {
verify(this.boundHashOperations, times(times)).putAll(this.delta.capture());
return this.delta.getAllValues().get(times - 1);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,9 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.data.redis;
import static org.mockito.Mockito.*;
package org.springframework.session.data.redis;
import java.util.concurrent.TimeUnit;
@@ -24,12 +23,18 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.session.MapSession;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*/
@@ -42,11 +47,11 @@ public class RedisSessionExpirationPolicyTests {
final static Long ONE_MINUTE_AGO = 1429111652346L;
@Mock
RedisOperations<Object,Object> sessionRedisOperations;
RedisOperations<Object, Object> sessionRedisOperations;
@Mock
BoundSetOperations<Object,Object> setOperations;
BoundSetOperations<Object, Object> setOperations;
@Mock
BoundHashOperations<Object,Object, Object> hashOperations;
BoundHashOperations<Object, Object, Object> hashOperations;
@Mock
BoundValueOperations<Object, Object> valueOperations;
@@ -56,15 +61,15 @@ public class RedisSessionExpirationPolicyTests {
@Before
public void setup() {
RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(sessionRedisOperations);
policy = new RedisSessionExpirationPolicy(sessionRedisOperations, repository);
session = new MapSession();
session.setLastAccessedTime(1429116694675L);
session.setId("12345");
RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(this.sessionRedisOperations);
this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations, repository);
this.session = new MapSession();
this.session.setLastAccessedTime(1429116694675L);
this.session.setId("12345");
when(sessionRedisOperations.boundSetOps(anyString())).thenReturn(setOperations);
when(sessionRedisOperations.boundHashOps(anyString())).thenReturn(hashOperations);
when(sessionRedisOperations.boundValueOps(anyString())).thenReturn(valueOperations);
given(this.sessionRedisOperations.boundSetOps(anyString())).willReturn(this.setOperations);
given(this.sessionRedisOperations.boundHashOps(anyString())).willReturn(this.hashOperations);
given(this.sessionRedisOperations.boundValueOps(anyString())).willReturn(this.valueOperations);
}
// gh-169
@@ -72,48 +77,48 @@ public class RedisSessionExpirationPolicyTests {
public void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp() throws Exception {
long originalExpirationTimeInMs = ONE_MINUTE_AGO;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = policy.getExpirationKey(originalRoundedToNextMinInMs);
String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs);
policy.onExpirationUpdated(originalExpirationTimeInMs, session);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);
// verify the original is removed
verify(sessionRedisOperations).boundSetOps(originalExpireKey);
verify(setOperations).remove("expires:"+ session.getId());
verify(this.sessionRedisOperations).boundSetOps(originalExpireKey);
verify(this.setOperations).remove("expires:" + this.session.getId());
}
@Test
public void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange() throws Exception {
long originalExpirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(session) - 10;
long originalExpirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session) - 10;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = policy.getExpirationKey(originalRoundedToNextMinInMs);
String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs);
policy.onExpirationUpdated(originalExpirationTimeInMs, session);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);
// verify the original is not removed
verify(sessionRedisOperations).boundSetOps(originalExpireKey);
verify(setOperations, never()).remove("expires:"+ session.getId());
verify(this.sessionRedisOperations).boundSetOps(originalExpireKey);
verify(this.setOperations, never()).remove("expires:" + this.session.getId());
}
@Test
public void onExpirationUpdatedAddsExpirationTimeRoundedUp() throws Exception {
long expirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(session);
long expirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session);
long expirationRoundedUpInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(expirationTimeInMs);
String expectedExpireKey = policy.getExpirationKey(expirationRoundedUpInMs);
String expectedExpireKey = this.policy.getExpirationKey(expirationRoundedUpInMs);
policy.onExpirationUpdated(null, session);
this.policy.onExpirationUpdated(null, this.session);
verify(sessionRedisOperations).boundSetOps(expectedExpireKey);
verify(setOperations).add("expires:" + session.getId());
verify(setOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
verify(this.sessionRedisOperations).boundSetOps(expectedExpireKey);
verify(this.setOperations).add("expires:" + this.session.getId());
verify(this.setOperations).expire(this.session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
}
@Test
public void onExpirationUpdatedSetExpireSession() throws Exception {
String sessionKey = policy.getSessionKey(session.getId());
String sessionKey = this.policy.getSessionKey(this.session.getId());
policy.onExpirationUpdated(null, session);
this.policy.onExpirationUpdated(null, this.session);
verify(sessionRedisOperations).boundHashOps(sessionKey);
verify(hashOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
verify(this.sessionRedisOperations).boundHashOps(sessionKey);
verify(this.hashOperations).expire(this.session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.data.redis;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
package org.springframework.session.data.redis;
import java.io.UnsupportedEncodingException;
@@ -27,12 +25,19 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.connection.Message;
import org.springframework.session.events.SessionDestroyedEvent;
import org.springframework.session.events.SessionExpiredEvent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
*
@@ -61,7 +66,7 @@ public class SessionMessageListenerTests {
@Before
public void setup() {
listener = new SessionMessageListener(eventPublisher);
this.listener = new SessionMessageListener(this.eventPublisher);
}
@Test(expected = IllegalArgumentException.class)
@@ -71,91 +76,91 @@ public class SessionMessageListenerTests {
@Test
public void onMessageNullBody() throws Exception {
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verifyZeroInteractions(eventPublisher);
verifyZeroInteractions(this.eventPublisher);
}
@Test
public void onMessageDel() throws Exception {
mockMessage("__keyevent@0__:del", "spring:session:sessions:123");
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verify(eventPublisher).publishEvent(deletedEvent.capture());
assertThat(deletedEvent.getValue().getSessionId()).isEqualTo("123");
verify(this.eventPublisher).publishEvent(this.deletedEvent.capture());
assertThat(this.deletedEvent.getValue().getSessionId()).isEqualTo("123");
}
@Test
public void onMessageDelSource() throws Exception {
mockMessage("__keyevent@0__:del","spring:session:sessions:123");
mockMessage("__keyevent@0__:del", "spring:session:sessions:123");
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verify(eventPublisher).publishEvent(deletedEvent.capture());
assertThat(deletedEvent.getValue().getSource()).isEqualTo(listener);
verify(this.eventPublisher).publishEvent(this.deletedEvent.capture());
assertThat(this.deletedEvent.getValue().getSource()).isEqualTo(this.listener);
}
@Test
public void onMessageExpiredSource() throws Exception {
mockMessage("__keyevent@0__:expired","spring:session:sessions:123");
mockMessage("__keyevent@0__:expired", "spring:session:sessions:123");
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verify(eventPublisher).publishEvent(expiredEvent.capture());
assertThat(expiredEvent.getValue().getSource()).isEqualTo(listener);
verify(this.eventPublisher).publishEvent(this.expiredEvent.capture());
assertThat(this.expiredEvent.getValue().getSource()).isEqualTo(this.listener);
}
@Test
public void onMessageExpired() throws Exception {
mockMessage("__keyevent@0__:expired","spring:session:sessions:543");
mockMessage("__keyevent@0__:expired", "spring:session:sessions:543");
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verify(eventPublisher).publishEvent(expiredEvent.capture());
assertThat(expiredEvent.getValue().getSessionId()).isEqualTo("543");
verify(this.eventPublisher).publishEvent(this.expiredEvent.capture());
assertThat(this.expiredEvent.getValue().getSessionId()).isEqualTo("543");
}
@Test
public void onMessageHset() throws Exception {
mockMessage("__keyevent@0__:hset","spring:session:sessions:123");
mockMessage("__keyevent@0__:hset", "spring:session:sessions:123");
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verifyZeroInteractions(eventPublisher);
verifyZeroInteractions(this.eventPublisher);
}
@Test
public void onMessageWrongKeyPrefix() throws Exception {
mockMessage("__keyevent@0__:del","spring:session:sessionsNo:123");
mockMessage("__keyevent@0__:del", "spring:session:sessionsNo:123");
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verifyZeroInteractions(eventPublisher);
verifyZeroInteractions(this.eventPublisher);
}
@Test
public void onMessageRename() throws Exception {
mockMessage("__keyevent@0__:rename","spring:session:sessions:123");
mockMessage("__keyevent@0__:rename", "spring:session:sessions:123");
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verifyZeroInteractions(eventPublisher);
verifyZeroInteractions(this.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));
mockMessage("__keyevent@0__:del", "spring:session:sessions:123");
willThrow(new IllegalStateException("Test Exceptions are caught")).given(this.eventPublisher).publishEvent(any(ApplicationEvent.class));
listener.onMessage(message, pattern);
this.listener.onMessage(this.message, this.pattern);
verify(eventPublisher).publishEvent(any(ApplicationEvent.class));
verify(this.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));
given(this.message.getBody()).willReturn(bytes(body));
given(this.message.getChannel()).willReturn(bytes(channel));
}
private static byte[] bytes(String s) throws UnsupportedEncodingException {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,13 +13,10 @@
* 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.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration.*;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
@@ -28,11 +25,17 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.session.data.redis.config.ConfigureNotifyKeyspaceEventsAction;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class EnableRedisKeyspaceNotificationsInitializerTests {
@@ -45,29 +48,29 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
@Captor
ArgumentCaptor<String> options;
EnableRedisKeyspaceNotificationsInitializer initializer;
RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer initializer;
@Before
public void setup() {
when(connectionFactory.getConnection()).thenReturn(connection);
given(this.connectionFactory.getConnection()).willReturn(this.connection);
initializer = new EnableRedisKeyspaceNotificationsInitializer(connectionFactory, new ConfigureNotifyKeyspaceEventsAction());
this.initializer = new RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer(this.connectionFactory, new ConfigureNotifyKeyspaceEventsAction());
}
@Test
public void afterPropertiesSetUnset() throws Exception {
setConfigNotification("");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("E","g","x");
assertOptionsContains("E", "g", "x");
}
@Test
public void afterPropertiesSetA() throws Exception {
setConfigNotification("A");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("A", "E");
}
@@ -76,7 +79,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void afterPropertiesSetE() throws Exception {
setConfigNotification("E");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("E", "g", "x");
}
@@ -85,7 +88,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void afterPropertiesSetK() throws Exception {
setConfigNotification("K");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("K", "E", "g", "x");
}
@@ -94,16 +97,16 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void afterPropertiesSetAE() throws Exception {
setConfigNotification("AE");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
verify(connection, never()).setConfig(anyString(), anyString());
verify(this.connection, never()).setConfig(anyString(), anyString());
}
@Test
public void afterPropertiesSetAK() throws Exception {
setConfigNotification("AK");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("A", "K", "E");
}
@@ -112,7 +115,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void afterPropertiesSetEK() throws Exception {
setConfigNotification("EK");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("E", "K", "g", "x");
}
@@ -121,7 +124,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void afterPropertiesSetEg() throws Exception {
setConfigNotification("Eg");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("E", "g", "x");
}
@@ -130,7 +133,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void afterPropertiesSetE$() throws Exception {
setConfigNotification("E$");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("E", "$", "g", "x");
}
@@ -139,7 +142,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void afterPropertiesSetKg() throws Exception {
setConfigNotification("Kg");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
assertOptionsContains("K", "g", "E", "x");
}
@@ -148,20 +151,20 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
public void afterPropertiesSetAEK() throws Exception {
setConfigNotification("AEK");
initializer.afterPropertiesSet();
this.initializer.afterPropertiesSet();
verify(connection, never()).setConfig(anyString(), anyString());
verify(this.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);
verify(this.connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), this.options.capture());
for (String expectedValue : expectedValues) {
assertThat(this.options.getValue()).contains(expectedValue);
}
assertThat(options.getValue().length()).isEqualTo(expectedValues.length);
assertThat(this.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));
given(this.connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)).willReturn(Arrays.asList(CONFIG_NOTIFY_KEYSPACE_EVENTS, value));
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,18 +13,20 @@
* 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.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package org.springframework.session.data.redis.config.annotation.web.http;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* @author Rob Winch
*
@@ -35,13 +37,14 @@ public class RedisHttpSessionConfigurationClassPathXmlApplicationContextTests {
// gh-318
@Test
public void contextLoads() {}
public void contextLoads() {
}
static RedisConnectionFactory connectionFactory() {
RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
RedisConnection connection = mock(RedisConnection.class);
when(factory.getConnection()).thenReturn(connection);
given(factory.getConnection()).willReturn(connection);
return factory;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,12 +13,12 @@
* 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.mockito.Mockito.mock;
package org.springframework.session.data.redis.config.annotation.web.http;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@@ -27,6 +27,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.mockito.Mockito.mock;
/**
* @author Rob Winch
*/
@@ -36,7 +38,8 @@ import org.springframework.test.context.web.WebAppConfiguration;
public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests {
@Test
public void redisConnectionFactoryNotUsedSinceNoValidation() {}
public void redisConnectionFactoryNotUsedSinceNoValidation() {
}
@EnableRedisHttpSession
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,13 +13,12 @@
* 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.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
package org.springframework.session.data.redis.config.annotation.web.http;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -31,6 +30,10 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* @author Rob Winch
*
@@ -41,14 +44,14 @@ import org.springframework.test.context.web.WebAppConfiguration;
public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests {
@Autowired
RedisTemplate<Object,Object> template;
RedisTemplate<Object, Object> template;
@Autowired
RedisSerializer<Object> defaultRedisSerializer;
@Test
public void overrideDefaultRedisTemplate() {
assertThat(template.getDefaultSerializer()).isSameAs(defaultRedisSerializer);
assertThat(this.template.getDefaultSerializer()).isSameAs(this.defaultRedisSerializer);
}
@EnableRedisHttpSession
@@ -64,7 +67,7 @@ public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests {
public RedisConnectionFactory connectionFactory() {
RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
RedisConnection connection = mock(RedisConnection.class);
when(factory.getConnection()).thenReturn(connection);
given(factory.getConnection()).willReturn(connection);
return factory;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,18 +13,14 @@
* 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.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package org.springframework.session.data.redis.config.annotation.web.http;
import java.util.concurrent.Executor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -36,6 +32,12 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author Vladimir Tsanev
*
@@ -53,7 +55,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor {
@Test
public void overrideSessionTaskExecutor() {
verify(springSessionRedisTaskExecutor, times(1)).execute(any(SchedulingAwareRunnable.class));
verify(this.springSessionRedisTaskExecutor, times(1)).execute(any(SchedulingAwareRunnable.class));
}
@EnableRedisHttpSession
@@ -68,7 +70,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor {
public RedisConnectionFactory connectionFactory() {
RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
RedisConnection connection = mock(RedisConnection.class);
when(factory.getConnection()).thenReturn(connection);
given(factory.getConnection()).willReturn(connection);
return factory;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +13,14 @@
* 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 java.util.concurrent.Executor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -28,14 +32,12 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.concurrent.Executor;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Vladimir Tsanev
@@ -57,8 +59,8 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors {
@Test
public void overrideSessionTaskExecutors() {
verify(springSessionRedisSubscriptionExecutor, times(1)).execute(any(SchedulingAwareRunnable.class));
verify(springSessionRedisTaskExecutor, never()).execute(any(Runnable.class));
verify(this.springSessionRedisSubscriptionExecutor, times(1)).execute(any(SchedulingAwareRunnable.class));
verify(this.springSessionRedisTaskExecutor, never()).execute(any(Runnable.class));
}
@EnableRedisHttpSession
@@ -78,7 +80,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors {
public RedisConnectionFactory connectionFactory() {
RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
RedisConnection connection = mock(RedisConnection.class);
when(factory.getConnection()).thenReturn(connection);
given(factory.getConnection()).willReturn(connection);
return factory;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,32 +13,35 @@
* 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.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package org.springframework.session.data.redis.config.annotation.web.http;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class RedisHttpSessionConfigurationXmlCustomExpireTests {
@Test
public void contextLoads() {}
public void contextLoads() {
}
static RedisConnectionFactory connectionFactory() {
RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
RedisConnection connection = mock(RedisConnection.class);
when(factory.getConnection()).thenReturn(connection);
given(factory.getConnection()).willReturn(connection);
return factory;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,32 +13,35 @@
* 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.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package org.springframework.session.data.redis.config.annotation.web.http;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class RedisHttpSessionConfigurationXmlTests {
@Test
public void contextLoads() {}
public void contextLoads() {
}
static RedisConnectionFactory connectionFactory() {
RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
RedisConnection connection = mock(RedisConnection.class);
when(factory.getConnection()).thenReturn(connection);
given(factory.getConnection()).willReturn(connection);
return factory;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,12 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.data.redis.config.annotation.web.http.gh109;
import static org.mockito.Mockito.*;
package org.springframework.session.data.redis.config.annotation.web.http.gh109;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -31,6 +31,9 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* This test must be in a different package than RedisHttpSessionConfiguration.
*
@@ -61,7 +64,7 @@ public class Gh109Tests {
public RedisOperationsSessionRepository sessionRepository(RedisOperations<Object, Object> sessionRedisTemplate, ApplicationEventPublisher applicationEventPublisher) {
RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(
sessionRedisTemplate);
sessionRepository.setDefaultMaxInactiveInterval(sessionTimeout);
sessionRepository.setDefaultMaxInactiveInterval(this.sessionTimeout);
return sessionRepository;
}
@@ -70,7 +73,7 @@ public class Gh109Tests {
RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
RedisConnection connection = mock(RedisConnection.class);
when(factory.getConnection()).thenReturn(connection);
given(factory.getConnection()).willReturn(connection);
return factory;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,19 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import static org.assertj.core.api.Assertions.*;
import java.util.Map;
import javax.servlet.http.Cookie;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.session.MapSession;
import org.springframework.session.Session;
import javax.servlet.http.Cookie;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class CookieHttpSessionStrategyTests {
private MockHttpServletRequest request;
@@ -37,56 +40,56 @@ public class CookieHttpSessionStrategyTests {
@Before
public void setup() throws Exception {
cookieName = "SESSION";
session = new MapSession();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
strategy = new CookieHttpSessionStrategy();
this.cookieName = "SESSION";
this.session = new MapSession();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.strategy = new CookieHttpSessionStrategy();
}
@Test
public void getRequestedSessionIdNull() throws Exception {
assertThat(strategy.getRequestedSessionId(request)).isNull();
assertThat(this.strategy.getRequestedSessionId(this.request)).isNull();
}
@Test
public void getRequestedSessionIdNotNull() throws Exception {
setSessionCookie(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
setSessionCookie(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId());
}
@Test
public void getRequestedSessionIdNotNullCustomCookieName() throws Exception {
setCookieName("CUSTOM");
setSessionCookie(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
setSessionCookie(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId());
}
@Test
public void onNewSession() throws Exception {
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo(this.session.getId());
}
@Test
public void onNewSessionTwiceSameId() throws Exception {
strategy.onNewSession(session, request, response);
strategy.onNewSession(session, request, response);
this.strategy.onNewSession(this.session, this.request, this.response);
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(response.getCookies()).hasSize(1);
assertThat(this.response.getCookies()).hasSize(1);
}
@Test
public void onNewSessionTwiceNewId() throws Exception {
Session newSession = new MapSession();
strategy.onNewSession(session, request, response);
strategy.onNewSession(newSession, request, response);
this.strategy.onNewSession(this.session, this.request, this.response);
this.strategy.onNewSession(newSession, this.request, this.response);
Cookie[] cookies = response.getCookies();
Cookie[] cookies = this.response.getCookies();
assertThat(cookies).hasSize(2);
assertThat(cookies[0].getValue()).isEqualTo(session.getId());
assertThat(cookies[0].getValue()).isEqualTo(this.session.getId());
assertThat(cookies[1].getValue()).isEqualTo(newSession.getId());
}
@@ -94,302 +97,302 @@ public class CookieHttpSessionStrategyTests {
public void onNewSessionExistingSessionSameAlias() throws Exception {
Session existing = new MapSession();
setSessionCookie(existing.getId());
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo(this.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());
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo("0 " + existing.getId() + " new " + this.session.getId());
}
// gh-321
@Test
public void onNewSessionExplicitAlias() throws Exception {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo("new " + session.getId());
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo("new " + this.session.getId());
}
@Test
public void onNewSessionCookiePath() throws Exception {
request.setContextPath("/somethingunique");
strategy.onNewSession(session, request, response);
this.request.setContextPath("/somethingunique");
this.strategy.onNewSession(this.session, this.request, this.response);
Cookie sessionCookie = response.getCookie(cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(request.getContextPath() + "/");
Cookie sessionCookie = this.response.getCookie(this.cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(this.request.getContextPath() + "/");
}
@Test
public void onNewSessionCustomCookieName() throws Exception {
setCookieName("CUSTOM");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo(this.session.getId());
}
@Test
public void onDeleteSession() throws Exception {
strategy.onInvalidateSession(request, response);
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionCookiePath() throws Exception {
request.setContextPath("/somethingunique");
strategy.onInvalidateSession(request, response);
this.request.setContextPath("/somethingunique");
this.strategy.onInvalidateSession(this.request, this.response);
Cookie sessionCookie = response.getCookie(cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(request.getContextPath() + "/");
Cookie sessionCookie = this.response.getCookie(this.cookieName);
assertThat(sessionCookie.getPath()).isEqualTo(this.request.getContextPath() + "/");
}
@Test
public void onDeleteSessionCustomCookieName() throws Exception {
setCookieName("CUSTOM");
strategy.onInvalidateSession(request, response);
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionExistingSessionSameAlias() 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);
setSessionCookie("0 " + existing.getId() + " new " + this.session.getId());
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(getSessionId()).isEqualTo(existing.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);
setSessionCookie("0 " + existing.getId() + " new " + this.session.getId());
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new");
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(getSessionId()).isEqualTo(existing.getId());
}
@SuppressWarnings("deprecation")
@Test(expected = IllegalArgumentException.class)
public void setCookieNameNull() throws Exception {
strategy.setCookieName(null);
this.strategy.setCookieName(null);
}
@Test
public void encodeURLNoExistingQuery() {
assertThat(strategy.encodeURL("/url", "2")).isEqualTo("/url?_s=2");
assertThat(this.strategy.encodeURL("/url", "2")).isEqualTo("/url?_s=2");
}
@Test
public void encodeURLNoExistingQueryEmpty() {
assertThat(strategy.encodeURL("/url?", "2")).isEqualTo("/url?_s=2");
assertThat(this.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");
assertThat(this.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");
assertThat(this.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");
assertThat(this.strategy.encodeURL("/url?a=b&_s=1&y=z", "2")).isEqualTo("/url?a=b&_s=2&y=z");
}
@Test
public void encodeURLExistingQueryExistingAliasEnd() {
assertThat(strategy.encodeURL("/url?a=b&_s=1", "2")).isEqualTo("/url?a=b&_s=2");
assertThat(this.strategy.encodeURL("/url?a=b&_s=1", "2")).isEqualTo("/url?a=b&_s=2");
}
//
@Test
public void encodeURLExistingQueryParamEndsWithActualParamStart() {
assertThat(strategy.encodeURL("/url?x_s=1&y=z", "2")).isEqualTo("/url?x_s=1&y=z&_s=2");
assertThat(this.strategy.encodeURL("/url?x_s=1&y=z", "2")).isEqualTo("/url?x_s=1&y=z&_s=2");
}
@Test
public void encodeURLExistingQueryParamEndsWithActualParamMiddle() {
assertThat(strategy.encodeURL("/url?a=b&x_s=1&y=z", "2")).isEqualTo("/url?a=b&x_s=1&y=z&_s=2");
assertThat(this.strategy.encodeURL("/url?a=b&x_s=1&y=z", "2")).isEqualTo("/url?a=b&x_s=1&y=z&_s=2");
}
@Test
public void encodeURLExistingQueryParamEndsWithActualParamEnd() {
assertThat(strategy.encodeURL("/url?a=b&x_s=1", "2")).isEqualTo("/url?a=b&x_s=1&_s=2");
assertThat(this.strategy.encodeURL("/url?a=b&x_s=1", "2")).isEqualTo("/url?a=b&x_s=1&_s=2");
}
//
@Test
public void encodeURLNoExistingQueryDefaultAlias() {
assertThat(strategy.encodeURL("/url", "0")).isEqualTo("/url");
assertThat(this.strategy.encodeURL("/url", "0")).isEqualTo("/url");
}
@Test
public void encodeURLNoExistingQueryEmptyDefaultAlias() {
assertThat(strategy.encodeURL("/url?", "0")).isEqualTo("/url?");
assertThat(this.strategy.encodeURL("/url?", "0")).isEqualTo("/url?");
}
@Test
public void encodeURLExistingQueryNoAliasDefaultAlias() {
assertThat(strategy.encodeURL("/url?a=b", "0")).isEqualTo("/url?a=b");
assertThat(this.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");
assertThat(this.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");
assertThat(this.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");
assertThat(this.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");
assertThat(this.strategy.encodeURL("/url?a=b&_s=1", "\"> <script>alert('hi')</script>")).isEqualTo("/url?a=b&_s=%22%3E+%3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E");
}
// --- getCurrentSessionAlias
@Test
public void getCurrentSessionAliasNull() {
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasNullParamName() {
strategy.setSessionAliasParamName(null);
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "NOT USED");
this.strategy.setSessionAliasParamName(null);
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "NOT USED");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
// protect against malicious users
@Test
public void getCurrentSessionAliasContainsQuote() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here\"this");
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here\"this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsSingleQuote() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here'this");
public void getCurrentSessionAliasContainsSingleQuote() {
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here'this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsSpace() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here this");
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsLt() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here<this");
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here<this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasContainsGt() {
strategy.setSessionAliasParamName(null);
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here>this");
this.strategy.setSessionAliasParamName(null);
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here>this");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getCurrentSessionAliasTooLong() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "012345678901234567890123456789012345678901234567890");
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "012345678901234567890123456789012345678901234567890");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
// We want some sort of length restrictions, but want to ensure some sort of length Technically no hard limit, but chose 50
@Test
public void getCurrentSessionAliasAllows50() {
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "01234567890123456789012345678901234567890123456789");
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "01234567890123456789012345678901234567890123456789");
assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo("01234567890123456789012345678901234567890123456789");
assertThat(this.strategy.getCurrentSessionAlias(this.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);
this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, expectedAlias);
assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(expectedAlias);
}
// --- getNewSessionAlias
@Test
public void getNewSessionAliasNoSessions() {
assertThat(strategy.getNewSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS);
}
@Test
public void getNewSessionAliasSingleSession() {
setSessionCookie("abc");
assertThat(strategy.getNewSessionAlias(request)).isEqualTo("1");
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualTo("1");
}
@Test
public void getNewSessionAlias2Sessions() {
setCookieWithNSessions(2);
assertThat(strategy.getNewSessionAlias(request)).isEqualTo("2");
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualTo("2");
}
@Test
public void getNewSessionAlias9Sessions() {
setCookieWithNSessions(9);
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("9");
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("9");
}
@Test
public void getNewSessionAlias10Sessions() {
setCookieWithNSessions(10);
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("a");
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("a");
}
@Test
public void getNewSessionAlias16Sessions() {
setCookieWithNSessions(16);
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("10");
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("10");
}
@Test
public void getNewSessionAliasInvalidAlias() {
setSessionCookie("0 1 $ b");
assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("1");
assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("1");
}
// --- getSessionIds
@Test
public void getSessionIdsNone() {
assertThat(strategy.getSessionIds(request)).isEmpty();
assertThat(this.strategy.getSessionIds(this.request)).isEmpty();
}
@Test
@@ -397,7 +400,7 @@ public class CookieHttpSessionStrategyTests {
String expectedId = "a";
setSessionCookie(expectedId);
Map<String, String> sessionIds = strategy.getSessionIds(request);
Map<String, String> sessionIds = this.strategy.getSessionIds(this.request);
assertThat(sessionIds.size()).isEqualTo(1);
assertThat(sessionIds.get("0")).isEqualTo(expectedId);
}
@@ -406,7 +409,7 @@ public class CookieHttpSessionStrategyTests {
public void getSessionIdsMulti() {
setSessionCookie("0 a 1 b");
Map<String, String> sessionIds = strategy.getSessionIds(request);
Map<String, String> sessionIds = this.strategy.getSessionIds(this.request);
assertThat(sessionIds.size()).isEqualTo(2);
assertThat(sessionIds.get("0")).isEqualTo("a");
assertThat(sessionIds.get("1")).isEqualTo("b");
@@ -416,7 +419,7 @@ public class CookieHttpSessionStrategyTests {
public void getSessionIdsDangling() {
setSessionCookie("0 a 1 b noValue");
Map<String, String> sessionIds = strategy.getSessionIds(request);
Map<String, String> sessionIds = this.strategy.getSessionIds(this.request);
assertThat(sessionIds.size()).isEqualTo(2);
assertThat(sessionIds.get("0")).isEqualTo("a");
assertThat(sessionIds.get("1")).isEqualTo("b");
@@ -436,12 +439,12 @@ public class CookieHttpSessionStrategyTests {
private String createSessionCookieValue(long size) {
StringBuffer buffer = new StringBuffer();
for(long i=0;i < size; i++) {
for (long i = 0; i < size; i++) {
String hex = Long.toHexString(i);
buffer.append(hex);
buffer.append(" ");
buffer.append(i);
if(i < size - 1) {
if (i < size - 1) {
buffer.append(" ");
}
}
@@ -451,15 +454,15 @@ public class CookieHttpSessionStrategyTests {
@SuppressWarnings("deprecation")
public void setCookieName(String cookieName) {
strategy.setCookieName(cookieName);
this.strategy.setCookieName(cookieName);
this.cookieName = cookieName;
}
public void setSessionCookie(String value) {
request.setCookies(new Cookie(cookieName, value));
this.request.setCookies(new Cookie(this.cookieName, value));
}
public String getSessionId() {
return response.getCookie(cookieName).getValue();
return this.response.getCookie(this.cookieName).getValue();
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,18 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import static org.assertj.core.api.Assertions.*;
package org.springframework.session.web.http;
import javax.servlet.http.Cookie;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.session.web.http.CookieSerializer.CookieValue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
*
@@ -43,107 +45,107 @@ public class DefaultCookieSerializerTests {
@Before
public void setup() {
cookieName = "SESSION";
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
sessionId = "sessionId";
serializer = new DefaultCookieSerializer();
this.cookieName = "SESSION";
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.sessionId = "sessionId";
this.serializer = new DefaultCookieSerializer();
}
// --- readCookieValues ---
@Test
public void readCookieValuesNull() {
assertThat(serializer.readCookieValues(request)).isEmpty();
assertThat(this.serializer.readCookieValues(this.request)).isEmpty();
}
@Test
public void readCookieValuesSingle() {
request.setCookies(new Cookie(cookieName, sessionId));
this.request.setCookies(new Cookie(this.cookieName, this.sessionId));
assertThat(serializer.readCookieValues(request)).containsOnly(sessionId);
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
}
@Test
public void readCookieValuesSingleAndInvalidName() {
request.setCookies(new Cookie(cookieName, sessionId), new Cookie(cookieName+"INVALID", sessionId + "INVALID"));
this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName + "INVALID", this.sessionId + "INVALID"));
assertThat(serializer.readCookieValues(request)).containsOnly(sessionId);
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
}
@Test
public void readCookieValuesMulti() {
String secondSession = "secondSessionId";
request.setCookies(new Cookie(cookieName, sessionId), new Cookie(cookieName, secondSession));
this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName, secondSession));
assertThat(serializer.readCookieValues(request)).containsExactly(sessionId, secondSession);
assertThat(this.serializer.readCookieValues(this.request)).containsExactly(this.sessionId, secondSession);
}
@Test
public void readCookieValuesMultiCustomSessionCookieName() {
setCookieName("JSESSIONID");
String secondSession = "secondSessionId";
request.setCookies(new Cookie(cookieName, sessionId), new Cookie(cookieName, secondSession));
this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName, secondSession));
assertThat(serializer.readCookieValues(request)).containsExactly(sessionId, secondSession);
assertThat(this.serializer.readCookieValues(this.request)).containsExactly(this.sessionId, secondSession);
}
// gh-392
@Test
public void readCookieValuesNullCookieValue() {
request.setCookies(new Cookie(cookieName, null));
this.request.setCookies(new Cookie(this.cookieName, null));
assertThat(serializer.readCookieValues(request)).isEmpty();
assertThat(this.serializer.readCookieValues(this.request)).isEmpty();
}
@Test
public void readCookieValuesNullCookieValueAndJvmRoute() {
serializer.setJvmRoute("123");
request.setCookies(new Cookie(cookieName, null));
this.serializer.setJvmRoute("123");
this.request.setCookies(new Cookie(this.cookieName, null));
assertThat(serializer.readCookieValues(request)).isEmpty();
assertThat(this.serializer.readCookieValues(this.request)).isEmpty();
}
@Test
public void readCookieValuesNullCookieValueAndNotNullCookie() {
serializer.setJvmRoute("123");
request.setCookies(new Cookie(cookieName, null), new Cookie(cookieName, sessionId));
this.serializer.setJvmRoute("123");
this.request.setCookies(new Cookie(this.cookieName, null), new Cookie(this.cookieName, this.sessionId));
assertThat(serializer.readCookieValues(request)).containsOnly(sessionId);
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
}
// --- writeCookie ---
@Test
public void writeCookie() {
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getValue()).isEqualTo(sessionId);
assertThat(getCookie().getValue()).isEqualTo(this.sessionId);
}
// --- httpOnly ---
@Test
public void writeCookieHttpOnlyDefault() {
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().isHttpOnly()).isTrue();
}
@Test
public void writeCookieHttpOnlySetTrue() {
serializer.setUseHttpOnlyCookie(true);
this.serializer.setUseHttpOnlyCookie(true);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().isHttpOnly()).isTrue();
}
@Test
public void writeCookieHttpOnlySetFalse() {
serializer.setUseHttpOnlyCookie(false);
this.serializer.setUseHttpOnlyCookie(false);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().isHttpOnly()).isFalse();
}
@@ -152,7 +154,7 @@ public class DefaultCookieSerializerTests {
@Test
public void writeCookieDomainNameDefault() {
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getDomain()).isNull();
}
@@ -160,17 +162,17 @@ public class DefaultCookieSerializerTests {
@Test
public void writeCookieDomainNameCustom() {
String domainName = "example.com";
serializer.setDomainName(domainName);
this.serializer.setDomainName(domainName);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getDomain()).isEqualTo(domainName);
}
@Test(expected=IllegalStateException.class)
@Test(expected = IllegalStateException.class)
public void setDomainNameAndDomainNamePatternThrows() {
serializer.setDomainName("example.com");
serializer.setDomainNamePattern(".*");
this.serializer.setDomainName("example.com");
this.serializer.setDomainNamePattern(".*");
}
// --- domainNamePattern ---
@@ -178,38 +180,38 @@ public class DefaultCookieSerializerTests {
@Test
public void writeCookieDomainNamePattern() {
String domainNamePattern = "^.+?\\.(\\w+\\.[a-z]+)$";
serializer.setDomainNamePattern(domainNamePattern);
this.serializer.setDomainNamePattern(domainNamePattern);
String[] matchingDomains = {"child.sub.example.com","www.example.com"};
for(String domain : matchingDomains) {
request.setServerName(domain);
serializer.writeCookieValue(cookieValue(sessionId));
String[] matchingDomains = {"child.sub.example.com", "www.example.com"};
for (String domain : matchingDomains) {
this.request.setServerName(domain);
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getDomain()).isEqualTo("example.com");
response = new MockHttpServletResponse();
this.response = new MockHttpServletResponse();
}
String[] notMatchingDomains = {"example.com", "localhost","127.0.0.1"};
for(String domain : notMatchingDomains) {
request.setServerName(domain);
serializer.writeCookieValue(cookieValue(sessionId));
String[] notMatchingDomains = {"example.com", "localhost", "127.0.0.1"};
for (String domain : notMatchingDomains) {
this.request.setServerName(domain);
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getDomain()).isNull();
response = new MockHttpServletResponse();
this.response = new MockHttpServletResponse();
}
}
@Test(expected=IllegalStateException.class)
@Test(expected = IllegalStateException.class)
public void setDomainNamePatternAndDomainNameThrows() {
serializer.setDomainNamePattern(".*");
serializer.setDomainName("example.com");
this.serializer.setDomainNamePattern(".*");
this.serializer.setDomainName("example.com");
}
// --- cookieName ---
@Test
public void writeCookieCookieNameDefault() {
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getName()).isEqualTo("SESSION");
}
@@ -219,52 +221,52 @@ public class DefaultCookieSerializerTests {
String cookieName = "JSESSIONID";
setCookieName(cookieName);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getName()).isEqualTo(cookieName);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void setCookieNameNullThrows() {
serializer.setCookieName(null);
this.serializer.setCookieName(null);
}
// --- cookiePath ---
@Test
public void writeCookieCookiePathDefaultEmptyContextPathUsed() {
request.setContextPath("");
this.request.setContextPath("");
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getPath()).isEqualTo("/");
}
@Test
public void writeCookieCookiePathDefaultContextPathUsed() {
request.setContextPath("/context");
this.request.setContextPath("/context");
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getPath()).isEqualTo("/context/");
}
@Test
public void writeCookieCookiePathExplicitNullCookiePathContextPathUsed() {
request.setContextPath("/context");
serializer.setCookiePath(null);
this.request.setContextPath("/context");
this.serializer.setCookiePath(null);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getPath()).isEqualTo("/context/");
}
@Test
public void writeCookieCookiePathExplicitCookiePath() {
request.setContextPath("/context");
serializer.setCookiePath("/");
this.request.setContextPath("/context");
this.serializer.setCookiePath("/");
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getPath()).isEqualTo("/");
}
@@ -273,25 +275,25 @@ public class DefaultCookieSerializerTests {
@Test
public void writeCookieCookieMaxAgeDefault() {
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getMaxAge()).isEqualTo(-1);
}
@Test
public void writeCookieCookieMaxAgeExplicit() {
serializer.setCookieMaxAge(100);
this.serializer.setCookieMaxAge(100);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getMaxAge()).isEqualTo(100);
}
@Test
public void writeCookieCookieMaxAgeExplicitEmptyCookie() {
serializer.setCookieMaxAge(100);
this.serializer.setCookieMaxAge(100);
serializer.writeCookieValue(cookieValue(""));
this.serializer.writeCookieValue(cookieValue(""));
assertThat(getCookie().getMaxAge()).isEqualTo(0);
}
@@ -300,45 +302,45 @@ public class DefaultCookieSerializerTests {
@Test
public void writeCookieDefaultInsecureRequest() {
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getSecure()).isFalse();
}
@Test
public void writeCookieSecureSecureRequest() {
request.setSecure(true);
serializer.setUseSecureCookie(true);
this.request.setSecure(true);
this.serializer.setUseSecureCookie(true);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getSecure()).isTrue();
}
@Test
public void writeCookieSecureInsecureRequest() {
serializer.setUseSecureCookie(true);
this.serializer.setUseSecureCookie(true);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getSecure()).isTrue();
}
@Test
public void writeCookieInsecureSecureRequest() {
request.setSecure(true);
serializer.setUseSecureCookie(false);
this.request.setSecure(true);
this.serializer.setUseSecureCookie(false);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getSecure()).isFalse();
}
@Test
public void writeCookieInecureInsecureRequest() {
serializer.setUseSecureCookie(false);
this.serializer.setUseSecureCookie(false);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getSecure()).isFalse();
}
@@ -348,38 +350,38 @@ public class DefaultCookieSerializerTests {
@Test
public void writeCookieJvmRoute() {
String jvmRoute = "route";
serializer.setJvmRoute(jvmRoute);
this.serializer.setJvmRoute(jvmRoute);
serializer.writeCookieValue(cookieValue(sessionId));
this.serializer.writeCookieValue(cookieValue(this.sessionId));
assertThat(getCookie().getValue()).isEqualTo(sessionId + "." + jvmRoute);
assertThat(getCookie().getValue()).isEqualTo(this.sessionId + "." + jvmRoute);
}
@Test
public void readCookieJvmRoute() {
String jvmRoute = "route";
serializer.setJvmRoute(jvmRoute);
request.setCookies(new Cookie(cookieName, sessionId + "." + jvmRoute));
this.serializer.setJvmRoute(jvmRoute);
this.request.setCookies(new Cookie(this.cookieName, this.sessionId + "." + jvmRoute));
assertThat(serializer.readCookieValues(request)).containsOnly(sessionId);
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
}
@Test
public void readCookieJvmRouteRouteMissing() {
String jvmRoute = "route";
serializer.setJvmRoute(jvmRoute);
request.setCookies(new Cookie(cookieName, sessionId));
this.serializer.setJvmRoute(jvmRoute);
this.request.setCookies(new Cookie(this.cookieName, this.sessionId));
assertThat(serializer.readCookieValues(request)).containsOnly(sessionId);
assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId);
}
@Test
public void readCookieJvmRouteOnlyRoute() {
String jvmRoute = "route";
serializer.setJvmRoute(jvmRoute);
request.setCookies(new Cookie(cookieName, "." + jvmRoute));
this.serializer.setJvmRoute(jvmRoute);
this.request.setCookies(new Cookie(this.cookieName, "." + jvmRoute));
assertThat(serializer.readCookieValues(request)).containsOnly("");
assertThat(this.serializer.readCookieValues(this.request)).containsOnly("");
}
public void setCookieName(String cookieName) {
@@ -388,10 +390,10 @@ public class DefaultCookieSerializerTests {
}
private Cookie getCookie() {
return response.getCookie(cookieName);
return this.response.getCookie(this.cookieName);
}
private CookieValue cookieValue(String cookieValue) {
return new CookieValue(request, response, cookieValue);
return new CookieValue(this.request, this.response, cookieValue);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,17 +13,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.session.MapSession;
import org.springframework.session.Session;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class HeaderSessionStrategyTests {
private MockHttpServletRequest request;
@@ -35,57 +36,57 @@ public class HeaderSessionStrategyTests {
@Before
public void setup() throws Exception {
headerName = "x-auth-token";
session = new MapSession();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
strategy = new HeaderHttpSessionStrategy();
this.headerName = "x-auth-token";
this.session = new MapSession();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.strategy = new HeaderHttpSessionStrategy();
}
@Test
public void getRequestedSessionIdNull() throws Exception {
assertThat(strategy.getRequestedSessionId(request)).isNull();
assertThat(this.strategy.getRequestedSessionId(this.request)).isNull();
}
@Test
public void getRequestedSessionIdNotNull() throws Exception {
setSessionId(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
setSessionId(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId());
}
@Test
public void getRequestedSessionIdNotNullCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
setSessionId(session.getId());
assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId());
setSessionId(this.session.getId());
assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId());
}
@Test
public void onNewSession() throws Exception {
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo(this.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);
this.strategy.onNewSession(this.session, this.request, this.response);
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(response.getHeaders(headerName).size()).isEqualTo(1);
assertThat(response.getHeaders(headerName)).containsOnly(session.getId());
assertThat(this.response.getHeaders(this.headerName).size()).isEqualTo(1);
assertThat(this.response.getHeaders(this.headerName)).containsOnly(this.session.getId());
}
@Test
public void onNewSessionCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
strategy.onNewSession(session, request, response);
assertThat(getSessionId()).isEqualTo(session.getId());
this.strategy.onNewSession(this.session, this.request, this.response);
assertThat(getSessionId()).isEqualTo(this.session.getId());
}
@Test
public void onDeleteSession() throws Exception {
strategy.onInvalidateSession(request, response);
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(getSessionId()).isEmpty();
}
@@ -93,35 +94,35 @@ public class HeaderSessionStrategyTests {
// the header is set as apposed to added
@Test
public void onDeleteSessionMulti() throws Exception {
strategy.onInvalidateSession(request, response);
strategy.onInvalidateSession(request, response);
this.strategy.onInvalidateSession(this.request, this.response);
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(response.getHeaders(headerName).size()).isEqualTo(1);
assertThat(this.response.getHeaders(this.headerName).size()).isEqualTo(1);
assertThat(getSessionId()).isEmpty();
}
@Test
public void onDeleteSessionCustomHeaderName() throws Exception {
setHeaderName("CUSTOM");
strategy.onInvalidateSession(request, response);
this.strategy.onInvalidateSession(this.request, this.response);
assertThat(getSessionId()).isEmpty();
}
@Test(expected = IllegalArgumentException.class)
public void setHeaderNameNull() throws Exception {
strategy.setHeaderName(null);
this.strategy.setHeaderName(null);
}
public void setHeaderName(String headerName) {
strategy.setHeaderName(headerName);
this.strategy.setHeaderName(headerName);
this.headerName = headerName;
}
public void setSessionId(String id) {
request.addHeader(headerName, id);
this.request.addHeader(this.headerName, id);
}
public String getSessionId() {
return response.getHeader(headerName);
return this.response.getHeader(this.headerName);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,14 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.session.web.http.OncePerRequestFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
@@ -28,11 +26,14 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
public class OncePerRequestFilterTests {
private MockHttpServletRequest request;
@@ -47,15 +48,16 @@ public class OncePerRequestFilterTests {
@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() {
this.servlet = new HttpServlet() {
};
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
this.invocations = new ArrayList<OncePerRequestFilter>();
this.filter = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
invocations.add(this);
OncePerRequestFilterTests.this.invocations.add(this);
filterChain.doFilter(request, response);
}
};
@@ -63,16 +65,16 @@ public class OncePerRequestFilterTests {
@Test
public void doFilterOnce() throws ServletException, IOException {
filter.doFilter(request, response, chain);
this.filter.doFilter(this.request, this.response, this.chain);
assertThat(invocations).containsOnly(filter);
assertThat(this.invocations).containsOnly(this.filter);
}
@Test
public void doFilterMultiOnlyIvokesOnce() throws ServletException, IOException {
filter.doFilter(request, response, new MockFilterChain(servlet, filter));
this.filter.doFilter(this.request, this.response, new MockFilterChain(this.servlet, this.filter));
assertThat(invocations).containsOnly(filter);
assertThat(this.invocations).containsOnly(this.filter);
}
@Test
@@ -80,12 +82,12 @@ public class OncePerRequestFilterTests {
OncePerRequestFilter filter2 = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
invocations.add(this);
OncePerRequestFilterTests.this.invocations.add(this);
filterChain.doFilter(request, response);
}
};
filter.doFilter(request, response, new MockFilterChain(servlet, filter2));
this.filter.doFilter(this.request, this.response, new MockFilterChain(this.servlet, filter2));
assertThat(invocations).containsOnly(filter, filter2);
assertThat(this.invocations).containsOnly(this.filter, filter2);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
package org.springframework.session.web.http;
import java.util.Arrays;
import java.util.Collections;
@@ -32,11 +30,17 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.session.MapSession;
import org.springframework.session.Session;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionDestroyedEvent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
* @author Rob Winch
* @since 1.1
@@ -58,11 +62,11 @@ public class SessionEventHttpSessionListenerAdapterTests {
@Before
public void setup() {
this.listener = new SessionEventHttpSessionListenerAdapter(Arrays.asList(listener1, listener2));
this.listener = new SessionEventHttpSessionListenerAdapter(Arrays.asList(this.listener1, this.listener2));
Session session = new MapSession();
destroyed = new SessionDestroyedEvent(this, session);
created = new SessionCreatedEvent(this, session);
this.destroyed = new SessionDestroyedEvent(this, session);
this.created = new SessionCreatedEvent(this, session);
}
// We want relaxed constructor that will allow for an empty listeners to
@@ -77,31 +81,31 @@ public class SessionEventHttpSessionListenerAdapterTests {
*/
@Test
public void onApplicationEventEmptyListenersDoesNotUseEvent() {
listener = new SessionEventHttpSessionListenerAdapter(Collections.<HttpSessionListener>emptyList());
destroyed = mock(SessionDestroyedEvent.class);
this.listener = new SessionEventHttpSessionListenerAdapter(Collections.<HttpSessionListener>emptyList());
this.destroyed = mock(SessionDestroyedEvent.class);
listener.onApplicationEvent(destroyed);
this.listener.onApplicationEvent(this.destroyed);
verifyZeroInteractions(destroyed, listener1, listener2);
verifyZeroInteractions(this.destroyed, this.listener1, this.listener2);
}
@Test
public void onApplicationEventDestroyed() {
listener.onApplicationEvent(destroyed);
this.listener.onApplicationEvent(this.destroyed);
verify(listener1).sessionDestroyed(sessionEvent.capture());
verify(listener2).sessionDestroyed(sessionEvent.capture());
verify(this.listener1).sessionDestroyed(this.sessionEvent.capture());
verify(this.listener2).sessionDestroyed(this.sessionEvent.capture());
assertThat(sessionEvent.getValue().getSession().getId()).isEqualTo(destroyed.getSessionId());
assertThat(this.sessionEvent.getValue().getSession().getId()).isEqualTo(this.destroyed.getSessionId());
}
@Test
public void onApplicationEventCreated() {
listener.onApplicationEvent(created);
this.listener.onApplicationEvent(this.created);
verify(listener1).sessionCreated(sessionEvent.capture());
verify(listener2).sessionCreated(sessionEvent.capture());
verify(this.listener1).sessionCreated(this.sessionEvent.capture());
verify(this.listener2).sessionCreated(this.sessionEvent.capture());
assertThat(sessionEvent.getValue().getSession().getId()).isEqualTo(created.getSessionId());
assertThat(this.sessionEvent.getValue().getSession().getId()).isEqualTo(this.created.getSessionId());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,18 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
package org.springframework.session.web.http;
import java.io.IOException;
import java.util.ArrayList;
@@ -50,6 +40,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.mock.web.MockFilterChain;
@@ -63,6 +54,17 @@ import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings("deprecation")
public class SessionRepositoryFilterTests {
@@ -83,9 +85,9 @@ public class SessionRepositoryFilterTests {
@Before
public void setup() throws Exception {
sessions = new HashMap<String, ExpiringSession>();
sessionRepository = new MapSessionRepository(sessions);
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.sessions = new HashMap<String, ExpiringSession>();
this.sessionRepository = new MapSessionRepository(this.sessions);
this.filter = new SessionRepositoryFilter<ExpiringSession>(this.sessionRepository);
setupRequest();
}
@@ -98,11 +100,11 @@ public class SessionRepositoryFilterTests {
long creationTime = wrappedRequest.getSession().getCreationTime();
long now = System.currentTimeMillis();
assertThat(now - creationTime).isGreaterThanOrEqualTo(0).isLessThan(5000);
request.setAttribute(CREATE_ATTR, creationTime);
SessionRepositoryFilterTests.this.request.setAttribute(CREATE_ATTR, creationTime);
}
});
final long expectedCreationTime = (Long) request.getAttribute(CREATE_ATTR);
final long expectedCreationTime = (Long) this.request.getAttribute(CREATE_ATTR);
Thread.sleep(50L);
nextRequest();
@@ -121,8 +123,8 @@ public class SessionRepositoryFilterTests {
MapSession session = new MapSession();
session.setLastAccessedTime(0L);
this.sessionRepository = spy(this.sessionRepository);
when(this.sessionRepository.createSession()).thenReturn(session);
this.filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
given(this.sessionRepository.createSession()).willReturn(session);
this.filter = new SessionRepositoryFilter<ExpiringSession>(this.sessionRepository);
doFilter(new DoInFilter() {
@Override
@@ -144,7 +146,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest) {
long lastAccessed = wrappedRequest.getSession().getLastAccessedTime();
assertThat(lastAccessed).isEqualTo(wrappedRequest.getSession().getCreationTime());
request.setAttribute(ACCESS_ATTR, lastAccessed);
SessionRepositoryFilterTests.this.request.setAttribute(ACCESS_ATTR, lastAccessed);
}
});
@@ -170,11 +172,11 @@ public class SessionRepositoryFilterTests {
String id = wrappedRequest.getSession().getId();
assertThat(id).isNotNull();
assertThat(wrappedRequest.getSession().getId()).isEqualTo(id);
request.setAttribute(ID_ATTR, id);
SessionRepositoryFilterTests.this.request.setAttribute(ID_ATTR, id);
}
});
final String id = (String) request.getAttribute(ID_ATTR);
final String id = (String) this.request.getAttribute(ID_ATTR);
assertThat(getSessionCookie().getValue()).isEqualTo(id);
setSessionCookie(id);
@@ -193,11 +195,11 @@ public class SessionRepositoryFilterTests {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
String id = wrappedRequest.getSession().getId();
request.setAttribute(ID_ATTR, id);
SessionRepositoryFilterTests.this.request.setAttribute(ID_ATTR, id);
}
});
final String id = (String) request.getAttribute(ID_ATTR);
final String id = (String) this.request.getAttribute(ID_ATTR);
setupRequest();
doFilter(new DoInFilter() {
@@ -223,8 +225,8 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterServletContextExplicit() throws Exception {
final ServletContext expectedContext = new MockServletContext();
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
filter.setServletContext(expectedContext);
this.filter = new SessionRepositoryFilter<ExpiringSession>(this.sessionRepository);
this.filter.setServletContext(expectedContext);
doFilter(new DoInFilter() {
@Override
@@ -380,7 +382,7 @@ public class SessionRepositoryFilterTests {
});
nextRequest();
response.reset();
this.response.reset();
doFilter(new DoInFilter() {
@Override
@@ -389,29 +391,29 @@ public class SessionRepositoryFilterTests {
}
});
assertThat(response.getCookie("SESSION")).isNull();
assertThat(this.response.getCookie("SESSION")).isNull();
}
@Test
public void doFilterSetsCookieIfChanged() throws Exception {
sessionRepository = new MapSessionRepository() {
this.sessionRepository = new MapSessionRepository() {
@Override
public ExpiringSession getSession(String id) {
return createSession();
}
};
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(this.sessionRepository);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
wrappedRequest.getSession();
}
});
assertThat(response.getCookie("SESSION")).isNotNull();
assertThat(this.response.getCookie("SESSION")).isNotNull();
nextRequest();
response.reset();
this.response.reset();
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
@@ -419,7 +421,7 @@ public class SessionRepositoryFilterTests {
}
});
assertThat(response.getCookie("SESSION")).isNotNull();
assertThat(this.response.getCookie("SESSION")).isNotNull();
}
@Test
@@ -468,7 +470,7 @@ public class SessionRepositoryFilterTests {
});
nextRequest();
request.setRequestedSessionIdValid(false); // ensure we are using wrapped request
this.request.setRequestedSessionIdValid(false); // ensure we are using wrapped request
doFilter(new DoInFilter() {
@Override
@@ -511,7 +513,7 @@ public class SessionRepositoryFilterTests {
// the old session was removed
final String changedSessionId = getSessionCookie().getValue();
assertThat(originalSessionId).isNotEqualTo(changedSessionId);
assertThat(sessionRepository.getSession(originalSessionId)).isNull();
assertThat(this.sessionRepository.getSession(originalSessionId)).isNull();
nextRequest();
@@ -533,7 +535,9 @@ public class SessionRepositoryFilterTests {
try {
ReflectionTestUtils.invokeMethod(wrappedRequest, "changeSessionId");
fail("Exected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -542,7 +546,7 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterIsRequestedValidSessionFalseInvalidId() throws Exception {
setSessionCookie("invalid");
request.setRequestedSessionIdValid(true); // ensure we are using wrapped request
this.request.setRequestedSessionIdValid(true); // ensure we are using wrapped request
doFilter(new DoInFilter() {
@Override
@@ -554,7 +558,7 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterIsRequestedValidSessionFalse() throws Exception {
request.setRequestedSessionIdValid(true); // ensure we are using wrapped request
this.request.setRequestedSessionIdValid(true); // ensure we are using wrapped request
doFilter(new DoInFilter() {
@Override
@@ -607,7 +611,7 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterCookieSecuritySettings() throws Exception {
request.setSecure(true);
this.request.setSecure(true);
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
@@ -634,7 +638,9 @@ public class SessionRepositoryFilterTests {
try {
sessionContext.getIds().nextElement();
fail("Expected Exception");
} catch(NoSuchElementException success) {}
}
catch (NoSuchElementException success) {
}
}
});
}
@@ -683,7 +689,9 @@ public class SessionRepositoryFilterTests {
try {
session.invalidate();
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -698,7 +706,9 @@ public class SessionRepositoryFilterTests {
try {
session.getCreationTime();
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -713,7 +723,9 @@ public class SessionRepositoryFilterTests {
try {
session.getAttribute("attr");
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -728,7 +740,9 @@ public class SessionRepositoryFilterTests {
try {
session.getValue("attr");
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -743,7 +757,9 @@ public class SessionRepositoryFilterTests {
try {
session.getAttributeNames();
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -758,7 +774,9 @@ public class SessionRepositoryFilterTests {
try {
session.getValueNames();
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -773,7 +791,9 @@ public class SessionRepositoryFilterTests {
try {
session.setAttribute("a", "b");
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -788,7 +808,9 @@ public class SessionRepositoryFilterTests {
try {
session.putValue("a", "b");
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -803,7 +825,9 @@ public class SessionRepositoryFilterTests {
try {
session.removeAttribute("name");
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -818,7 +842,9 @@ public class SessionRepositoryFilterTests {
try {
session.removeValue("name");
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -833,7 +859,9 @@ public class SessionRepositoryFilterTests {
try {
session.isNew();
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -848,7 +876,9 @@ public class SessionRepositoryFilterTests {
try {
session.getLastAccessedTime();
fail("Expected Exception");
} catch(IllegalStateException success) {}
}
catch (IllegalStateException success) {
}
}
});
}
@@ -988,7 +1018,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
assertThat(sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
}
});
}
@@ -1000,7 +1030,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error");
assertThat(sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
}
});
}
@@ -1012,7 +1042,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.sendRedirect("/");
assertThat(sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
}
});
}
@@ -1024,7 +1054,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.flushBuffer();
assertThat(sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
}
});
}
@@ -1036,7 +1066,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.getOutputStream().flush();
assertThat(sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
}
});
}
@@ -1048,7 +1078,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.getOutputStream().close();
assertThat(sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
}
});
}
@@ -1060,7 +1090,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.getWriter().flush();
assertThat(sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
}
});
}
@@ -1072,7 +1102,7 @@ public class SessionRepositoryFilterTests {
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String id = wrappedRequest.getSession().getId();
wrappedResponse.getWriter().close();
assertThat(sessionRepository.getSession(id)).isNotNull();
assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull();
}
});
}
@@ -1081,11 +1111,11 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterAdapterGetRequestedSessionId() throws Exception {
filter.setHttpSessionStrategy(strategy);
this.filter.setHttpSessionStrategy(this.strategy);
final String expectedId = "MultiHttpSessionStrategyAdapter-requested-id";
when(strategy.getRequestedSessionId(any(HttpServletRequest.class))).thenReturn(expectedId);
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(expectedId);
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
String actualId = wrappedRequest.getRequestedSessionId();
@@ -1096,69 +1126,69 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterAdapterOnNewSession() throws Exception {
filter.setHttpSessionStrategy(strategy);
this.filter.setHttpSessionStrategy(this.strategy);
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession();
}
});
HttpServletRequest request = (HttpServletRequest) chain.getRequest();
Session session = sessionRepository.getSession(request.getSession().getId());
verify(strategy).onNewSession(eq(session), any(HttpServletRequest.class),any(HttpServletResponse.class));
HttpServletRequest request = (HttpServletRequest) this.chain.getRequest();
Session session = this.sessionRepository.getSession(request.getSession().getId());
verify(this.strategy).onNewSession(eq(session), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterAdapterOnInvalidate() throws Exception {
filter.setHttpSessionStrategy(strategy);
this.filter.setHttpSessionStrategy(this.strategy);
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession().getId();
}
});
HttpServletRequest request = (HttpServletRequest) chain.getRequest();
HttpServletRequest request = (HttpServletRequest) this.chain.getRequest();
String id = request.getSession().getId();
when(strategy.getRequestedSessionId(any(HttpServletRequest.class))).thenReturn(id);
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(id);
setupRequest();
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession().invalidate();
}
});
verify(strategy).onInvalidateSession(any(HttpServletRequest.class),any(HttpServletResponse.class));
verify(this.strategy).onInvalidateSession(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
// gh-188
@Test
public void doFilterRequestSessionNoRequestSessionDoesNotInvalidate() throws Exception {
filter.setHttpSessionStrategy(strategy);
this.filter.setHttpSessionStrategy(this.strategy);
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession().getId();
}
});
HttpServletRequest request = (HttpServletRequest) chain.getRequest();
HttpServletRequest request = (HttpServletRequest) this.chain.getRequest();
String id = request.getSession().getId();
when(strategy.getRequestedSessionId(any(HttpServletRequest.class))).thenReturn(id);
given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(id);
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
}
});
verify(strategy,never()).onInvalidateSession(any(HttpServletRequest.class),any(HttpServletResponse.class));
verify(this.strategy, never()).onInvalidateSession(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
@@ -1166,9 +1196,9 @@ public class SessionRepositoryFilterTests {
public void doFilterRequestSessionNoRequestSessionNoSessionRepositoryInteractions() throws Exception {
SessionRepository<ExpiringSession> sessionRepository = spy(new MapSessionRepository());
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
wrappedRequest.getSession().getId();
@@ -1178,7 +1208,7 @@ public class SessionRepositoryFilterTests {
reset(sessionRepository);
setupRequest();
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
}
@@ -1191,9 +1221,9 @@ public class SessionRepositoryFilterTests {
public void doFilterLazySessionCreation() throws Exception {
SessionRepository<ExpiringSession> sessionRepository = spy(new MapSessionRepository());
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
}
@@ -1209,9 +1239,9 @@ public class SessionRepositoryFilterTests {
SessionRepository<ExpiringSession> sessionRepository = spy(this.sessionRepository);
setSessionCookie(session.getId());
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
doFilter(new DoInFilter(){
doFilter(new DoInFilter() {
@Override
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException {
}
@@ -1224,24 +1254,24 @@ public class SessionRepositoryFilterTests {
@Test
public void order() {
assertThat(AnnotationAwareOrderComparator.INSTANCE.compare(filter, new SessionRepositoryFilterDefaultOrder()));
assertThat(AnnotationAwareOrderComparator.INSTANCE.compare(this.filter, new SessionRepositoryFilterDefaultOrder()));
}
// We want the filter to work without any dependencies on Spring
@Test(expected = ClassCastException.class)
@SuppressWarnings("unused")
public void doesNotImplementOrdered() {
Ordered o = (Ordered) filter;
Ordered o = (Ordered) this.filter;
}
@Test(expected = IllegalArgumentException.class)
public void setHttpSessionStrategyNull() {
filter.setHttpSessionStrategy((HttpSessionStrategy) null);
this.filter.setHttpSessionStrategy((HttpSessionStrategy) null);
}
@Test(expected = IllegalArgumentException.class)
public void setMultiHttpSessionStrategyNull() {
filter.setHttpSessionStrategy((MultiHttpSessionStrategy) null);
this.filter.setHttpSessionStrategy((MultiHttpSessionStrategy) null);
}
// --- helper methods
@@ -1252,39 +1282,39 @@ public class SessionRepositoryFilterTests {
assertThat(cookie.getMaxAge()).isEqualTo(-1);
assertThat(cookie.getValue()).isNotEqualTo("INVALID");
assertThat(cookie.isHttpOnly()).describedAs("Cookie is expected to be HTTP Only").isTrue();
assertThat(cookie.getSecure()).describedAs("Cookie secured is expected to be " + request.isSecure()).isEqualTo(request.isSecure());
assertThat(request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull();
assertThat(cookie.getSecure()).describedAs("Cookie secured is expected to be " + this.request.isSecure()).isEqualTo(this.request.isSecure());
assertThat(this.request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull();
}
private void assertNoSession() {
Cookie cookie = getSessionCookie();
assertThat(cookie).isNull();
assertThat(request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull();
assertThat(this.request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull();
}
private Cookie getSessionCookie() {
return response.getCookie("SESSION");
return this.response.getCookie("SESSION");
}
private void setSessionCookie(String sessionId) {
request.setCookies(new Cookie[]{new Cookie("SESSION", sessionId)});
this.request.setCookies(new Cookie[]{new Cookie("SESSION", sessionId)});
}
private void setupRequest() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
chain = new MockFilterChain();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}
private void nextRequest() throws Exception {
Map<String,Cookie> nameToCookie = new HashMap<String,Cookie>();
if (request.getCookies() != null) {
for(Cookie cookie : request.getCookies()) {
Map<String, Cookie> nameToCookie = new HashMap<String, Cookie>();
if (this.request.getCookies() != null) {
for (Cookie cookie : this.request.getCookies()) {
nameToCookie.put(cookie.getName(), cookie);
}
}
if (response.getCookies() != null) {
for(Cookie cookie : response.getCookies()) {
if (this.response.getCookies() != null) {
for (Cookie cookie : this.response.getCookies()) {
nameToCookie.put(cookie.getName(), cookie);
}
}
@@ -1292,25 +1322,27 @@ public class SessionRepositoryFilterTests {
setupRequest();
request.setCookies(nextRequestCookies);
this.request.setCookies(nextRequestCookies);
}
@SuppressWarnings("serial")
private void doFilter(final DoInFilter doInFilter) throws ServletException, IOException {
chain = new MockFilterChain(new HttpServlet() {}, new OncePerRequestFilter() {
this.chain = new MockFilterChain(new HttpServlet() {
}, new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
doInFilter.doFilter(request, response);
}
});
filter.doFilter(request, response, chain);
this.filter.doFilter(this.request, this.response, this.chain);
}
abstract class DoInFilter {
void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws ServletException, IOException {
doFilter(wrappedRequest);
}
void doFilter(HttpServletRequest wrappedRequest) {}
void doFilter(HttpServletRequest wrappedRequest) {
}
}
static class SessionRepositoryFilterDefaultOrder implements Ordered {
@@ -1318,4 +1350,4 @@ public class SessionRepositoryFilterTests {
return SessionRepositoryFilter.DEFAULT_ORDER;
}
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.socket.handler;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
package org.springframework.session.web.socket.handler;
import org.junit.Before;
import org.junit.Test;
@@ -25,12 +23,18 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.session.web.socket.events.SessionConnectEvent;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class WebSocketConnectHandlerDecoratorFactoryTests {
@Mock
@@ -46,7 +50,7 @@ public class WebSocketConnectHandlerDecoratorFactoryTests {
@Before
public void setup() {
factory = new WebSocketConnectHandlerDecoratorFactory(eventPublisher);
this.factory = new WebSocketConnectHandlerDecoratorFactory(this.eventPublisher);
}
@Test(expected = IllegalArgumentException.class)
@@ -56,21 +60,21 @@ public class WebSocketConnectHandlerDecoratorFactoryTests {
@Test
public void decorateAfterConnectionEstablished() throws Exception {
WebSocketHandler decorated = factory.decorate(delegate);
WebSocketHandler decorated = this.factory.decorate(this.delegate);
decorated.afterConnectionEstablished(session);
decorated.afterConnectionEstablished(this.session);
verify(eventPublisher).publishEvent(event.capture());
assertThat(event.getValue().getWebSocketSession()).isSameAs(session);
verify(this.eventPublisher).publishEvent(this.event.capture());
assertThat(this.event.getValue().getWebSocketSession()).isSameAs(this.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));
WebSocketHandler decorated = this.factory.decorate(this.delegate);
willThrow(new IllegalStateException("Test throw on publishEvent")).given(this.eventPublisher).publishEvent(any(ApplicationEvent.class));
decorated.afterConnectionEstablished(session);
decorated.afterConnectionEstablished(this.session);
verify(eventPublisher).publishEvent(any(SessionConnectEvent.class));
verify(this.eventPublisher).publishEvent(any(SessionConnectEvent.class));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,13 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.socket.handler;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package org.springframework.session.web.socket.handler;
import java.security.Principal;
import java.util.HashMap;
@@ -30,6 +25,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
@@ -42,6 +38,12 @@ import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class WebSocketRegistryListenerTests {
@Mock
@@ -60,7 +62,7 @@ public class WebSocketRegistryListenerTests {
SessionDisconnectEvent disconnect;
SessionDeletedEvent deleted;
SessionExpiredEvent expired;
Map<String, Object> attributes;
@@ -72,101 +74,101 @@ public class WebSocketRegistryListenerTests {
@Before
public void setup() {
sessionId = "session-id";
attributes = new HashMap<String,Object>();
SessionRepositoryMessageInterceptor.setSessionId(attributes, sessionId);
this.sessionId = "session-id";
this.attributes = new HashMap<String, Object>();
SessionRepositoryMessageInterceptor.setSessionId(this.attributes, this.sessionId);
when(wsSession.getAttributes()).thenReturn(attributes);
when(wsSession.getPrincipal()).thenReturn(principal);
when(wsSession.getId()).thenReturn("wsSession-id");
given(this.wsSession.getAttributes()).willReturn(this.attributes);
given(this.wsSession.getPrincipal()).willReturn(this.principal);
given(this.wsSession.getId()).willReturn("wsSession-id");
when(wsSession2.getAttributes()).thenReturn(attributes);
when(wsSession2.getPrincipal()).thenReturn(principal);
when(wsSession2.getId()).thenReturn("wsSession-id2");
given(this.wsSession2.getAttributes()).willReturn(this.attributes);
given(this.wsSession2.getPrincipal()).willReturn(this.principal);
given(this.wsSession2.getId()).willReturn("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, this.attributes);
given(this.message.getHeaders()).willReturn(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);
deleted = new SessionDeletedEvent(listener, sessionId);
expired = new SessionExpiredEvent(listener, sessionId);
this.listener = new WebSocketRegistryListener();
this.connect = new SessionConnectEvent(this.listener, this.wsSession);
this.connect2 = new SessionConnectEvent(this.listener, this.wsSession2);
this.disconnect = new SessionDisconnectEvent(this.listener, this.message, this.wsSession.getId(), CloseStatus.NORMAL);
this.deleted = new SessionDeletedEvent(this.listener, this.sessionId);
this.expired = new SessionExpiredEvent(this.listener, this.sessionId);
}
@Test
public void onApplicationEventConnectSessionDeleted() throws Exception {
listener.onApplicationEvent(connect);
this.listener.onApplicationEvent(this.connect);
listener.onApplicationEvent(deleted);
this.listener.onApplicationEvent(this.deleted);
verify(wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
verify(this.wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
}
@Test
public void onApplicationEventConnectSessionExpired() throws Exception {
listener.onApplicationEvent(connect);
this.listener.onApplicationEvent(this.connect);
listener.onApplicationEvent(expired);
this.listener.onApplicationEvent(this.expired);
verify(wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
verify(this.wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
}
@Test
public void onApplicationEventConnectSessionDeletedNullPrincipal() throws Exception {
when(wsSession.getPrincipal()).thenReturn(null);
listener.onApplicationEvent(connect);
given(this.wsSession.getPrincipal()).willReturn(null);
this.listener.onApplicationEvent(this.connect);
listener.onApplicationEvent(deleted);
this.listener.onApplicationEvent(this.deleted);
verify(wsSession,times(0)).close(any(CloseStatus.class));
verify(this.wsSession, times(0)).close(any(CloseStatus.class));
}
@Test
public void onApplicationEventConnectDisconnect() throws Exception {
listener.onApplicationEvent(connect);
listener.onApplicationEvent(disconnect);
this.listener.onApplicationEvent(this.connect);
this.listener.onApplicationEvent(this.disconnect);
listener.onApplicationEvent(deleted);
this.listener.onApplicationEvent(this.deleted);
verify(wsSession,times(0)).close(any(CloseStatus.class));
verify(this.wsSession, times(0)).close(any(CloseStatus.class));
}
// gh-76
@Test
@SuppressWarnings("unchecked")
public void onApplicationEventConnectDisconnectCleanup() {
listener.onApplicationEvent(connect);
this.listener.onApplicationEvent(this.connect);
listener.onApplicationEvent(disconnect);
this.listener.onApplicationEvent(this.disconnect);
Map<String,Map<String,WebSocketSession>> httpSessionIdToWsSessions =
(Map<String, Map<String, WebSocketSession>>) ReflectionTestUtils.getField(listener, "httpSessionIdToWsSessions");
Map<String, Map<String, WebSocketSession>> httpSessionIdToWsSessions =
(Map<String, Map<String, WebSocketSession>>) ReflectionTestUtils.getField(this.listener, "httpSessionIdToWsSessions");
assertThat(httpSessionIdToWsSessions).isEmpty();
}
@Test
public void onApplicationEventConnectDisconnectNullSession() throws Exception {
listener.onApplicationEvent(connect);
attributes.clear();
this.listener.onApplicationEvent(this.connect);
this.attributes.clear();
listener.onApplicationEvent(disconnect);
this.listener.onApplicationEvent(this.disconnect);
// no exception
}
@Test
public void onApplicationEventConnectConnectDisonnect() throws Exception {
listener.onApplicationEvent(connect);
listener.onApplicationEvent(connect2);
listener.onApplicationEvent(disconnect);
this.listener.onApplicationEvent(this.connect);
this.listener.onApplicationEvent(this.connect2);
this.listener.onApplicationEvent(this.disconnect);
listener.onApplicationEvent(deleted);
this.listener.onApplicationEvent(this.deleted);
verify(wsSession2).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
verify(wsSession,times(0)).close(any(CloseStatus.class));
verify(this.wsSession2).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS);
verify(this.wsSession, times(0)).close(any(CloseStatus.class));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,11 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.socket.server;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
package org.springframework.session.web.socket.server;
import java.util.Collections;
import java.util.EnumSet;
@@ -33,6 +30,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
@@ -43,6 +41,15 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.session.ExpiringSession;
import org.springframework.session.SessionRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.longThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@RunWith(MockitoJUnitRunner.class)
public class SessionRepositoryMessageInterceptorTests {
@Mock
@@ -60,14 +67,14 @@ public class SessionRepositoryMessageInterceptorTests {
@Before
public void setup() {
interceptor = new SessionRepositoryMessageInterceptor<ExpiringSession>(sessionRepository);
headers = SimpMessageHeaderAccessor.create();
headers.setSessionId("session");
headers.setSessionAttributes(new HashMap<String,Object>());
this.interceptor = new SessionRepositoryMessageInterceptor<ExpiringSession>(this.sessionRepository);
this.headers = SimpMessageHeaderAccessor.create();
this.headers.setSessionId("session");
this.headers.setSessionAttributes(new HashMap<String, Object>());
setMessageType(SimpMessageType.MESSAGE);
String sessionId = "http-session";
setSessionId(sessionId);
when(sessionRepository.getSession(sessionId)).thenReturn(session);
given(this.sessionRepository.getSession(sessionId)).willReturn(this.session);
}
@Test(expected = IllegalArgumentException.class)
@@ -77,105 +84,105 @@ public class SessionRepositoryMessageInterceptorTests {
@Test
public void preSendNullMessage() {
assertThat(interceptor.preSend(null, channel)).isNull();
assertThat(this.interceptor.preSend(null, this.channel)).isNull();
}
@Test
public void preSendConnectAckDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.CONNECT_ACK);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
@Test
public void preSendHeartbeatDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.HEARTBEAT);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
@Test
public void preSendDisconnectDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.DISCONNECT);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
@Test
public void preSendOtherDoesNotInvokeSessionRepository() {
setMessageType(SimpMessageType.OTHER);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
@Test(expected = IllegalArgumentException.class)
public void setMatchingMessageTypesNull() {
interceptor.setMatchingMessageTypes(null);
this.interceptor.setMatchingMessageTypes(null);
}
@Test(expected = IllegalArgumentException.class)
public void setMatchingMessageTypesEmpty() {
interceptor.setMatchingMessageTypes(Collections.<SimpMessageType>emptySet());
this.interceptor.setMatchingMessageTypes(Collections.<SimpMessageType>emptySet());
}
@Test
public void preSendSetMatchingMessageTypes() {
interceptor.setMatchingMessageTypes(EnumSet.of(SimpMessageType.DISCONNECT));
this.interceptor.setMatchingMessageTypes(EnumSet.of(SimpMessageType.DISCONNECT));
setMessageType(SimpMessageType.DISCONNECT);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verify(sessionRepository).getSession(anyString());
verify(sessionRepository).save(session);
verify(this.sessionRepository).getSession(anyString());
verify(this.sessionRepository).save(this.session);
}
@Test
public void preSendConnectUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.CONNECT);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verify(session).setLastAccessedTime(longThat(isAlmostNow()));
verify(sessionRepository).save(session);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
}
@Test
public void preSendMessageUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.MESSAGE);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verify(session).setLastAccessedTime(longThat(isAlmostNow()));
verify(sessionRepository).save(session);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
}
@Test
public void preSendSubscribeUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.SUBSCRIBE);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verify(session).setLastAccessedTime(longThat(isAlmostNow()));
verify(sessionRepository).save(session);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
}
@Test
public void preSendUnsubscribeUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.UNSUBSCRIBE);
session.setLastAccessedTime(0L);
this.session.setLastAccessedTime(0L);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verify(session).setLastAccessedTime(longThat(isAlmostNow()));
verify(sessionRepository).save(session);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
}
// This will updated when SPR-12288 is resolved
@@ -183,42 +190,42 @@ public class SessionRepositoryMessageInterceptorTests {
public void preSendExpiredSession() {
setSessionId("expired");
interceptor.preSend(createMessage(), channel);
this.interceptor.preSend(createMessage(), this.channel);
verify(sessionRepository,times(0)).save(any(ExpiringSession.class));
verify(this.sessionRepository, times(0)).save(any(ExpiringSession.class));
}
@Test
public void preSendNullSessionId() {
setSessionId(null);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
@Test
public void preSendNullSessionAttributes() {
headers.setSessionAttributes(null);
this.headers.setSessionAttributes(null);
assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage);
assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage);
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
@Test
public void beforeHandshakeNotServletServerHttpRequest() throws Exception {
assertThat(interceptor.beforeHandshake(null,null,null,null)).isTrue();
assertThat(this.interceptor.beforeHandshake(null, null, null, null)).isTrue();
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
@Test
public void beforeHandshakeNullSession() throws Exception {
ServletServerHttpRequest request = new ServletServerHttpRequest(new MockHttpServletRequest());
assertThat(interceptor.beforeHandshake(request,null,null,null)).isTrue();
assertThat(this.interceptor.beforeHandshake(request, null, null, null)).isTrue();
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
@Test
@@ -226,9 +233,9 @@ public class SessionRepositoryMessageInterceptorTests {
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
HttpSession httpSession = httpRequest.getSession();
ServletServerHttpRequest request = new ServletServerHttpRequest(httpRequest);
Map<String,Object> attributes = new HashMap<String,Object>();
Map<String, Object> attributes = new HashMap<String, Object>();
assertThat(interceptor.beforeHandshake(request,null,null,attributes)).isTrue();
assertThat(this.interceptor.beforeHandshake(request, null, null, attributes)).isTrue();
assertThat(attributes.size()).isEqualTo(1);
assertThat(SessionRepositoryMessageInterceptor.getSessionId(attributes)).isEqualTo(httpSession.getId());
@@ -239,22 +246,22 @@ public class SessionRepositoryMessageInterceptorTests {
*/
@Test
public void afterHandshakeDoesNothing() {
interceptor.afterHandshake(null,null,null,null);
this.interceptor.afterHandshake(null, null, null, null);
verifyZeroInteractions(sessionRepository);
verifyZeroInteractions(this.sessionRepository);
}
private void setSessionId(String id) {
SessionRepositoryMessageInterceptor.setSessionId(headers.getSessionAttributes(), id);
SessionRepositoryMessageInterceptor.setSessionId(this.headers.getSessionAttributes(), id);
}
private Message<?> createMessage() {
createMessage = MessageBuilder.createMessage("", headers.getMessageHeaders());
return createMessage;
this.createMessage = MessageBuilder.createMessage("", this.headers.getMessageHeaders());
return this.createMessage;
}
private void setMessageType(SimpMessageType type) {
headers.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, type);
this.headers.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, type);
}
static AlmostNowMatcher isAlmostNow() {