Use spring-javaformat to format and check code

Resolves: #1450
This commit is contained in:
Vedran Pavic
2019-06-17 23:44:55 +02:00
parent 0eaeb98b0c
commit 822db7fbbf
241 changed files with 2961 additions and 4660 deletions

View File

@@ -49,28 +49,24 @@ import static org.mockito.Mockito.verifyZeroInteractions;
*
* @author Vedran Pavic
*/
public class ReactiveRedisOperationsSessionRepositoryTests {
class ReactiveRedisOperationsSessionRepositoryTests {
@SuppressWarnings("unchecked")
private ReactiveRedisOperations<String, Object> redisOperations = mock(
ReactiveRedisOperations.class);
private ReactiveRedisOperations<String, Object> redisOperations = mock(ReactiveRedisOperations.class);
@SuppressWarnings("unchecked")
private ReactiveHashOperations<String, Object, Object> hashOperations = mock(
ReactiveHashOperations.class);
private ReactiveHashOperations<String, Object, Object> hashOperations = mock(ReactiveHashOperations.class);
@SuppressWarnings("unchecked")
private ArgumentCaptor<Map<String, Object>> delta = ArgumentCaptor
.forClass(Map.class);
private ArgumentCaptor<Map<String, Object>> delta = ArgumentCaptor.forClass(Map.class);
private ReactiveRedisOperationsSessionRepository repository;
private MapSession cached;
@BeforeEach
public void setUp() {
this.repository = new ReactiveRedisOperationsSessionRepository(
this.redisOperations);
void setUp() {
this.repository = new ReactiveRedisOperationsSessionRepository(this.redisOperations);
this.cached = new MapSession();
this.cached.setId("session-id");
@@ -79,82 +75,73 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
}
@Test
public void constructorWithNullReactiveRedisOperations() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ReactiveRedisOperationsSessionRepository(null))
void constructorWithNullReactiveRedisOperations() {
assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveRedisOperationsSessionRepository(null))
.withMessageContaining("sessionRedisOperations cannot be null");
}
@Test
public void customRedisKeyNamespace() {
void customRedisKeyNamespace() {
this.repository.setRedisKeyNamespace("test");
assertThat(ReflectionTestUtils.getField(this.repository, "namespace"))
.isEqualTo("test:");
assertThat(ReflectionTestUtils.getField(this.repository, "namespace")).isEqualTo("test:");
}
@Test
public void nullRedisKeyNamespace() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.repository.setRedisKeyNamespace(null))
void nullRedisKeyNamespace() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisKeyNamespace(null))
.withMessage("namespace cannot be null or empty");
}
@Test
public void emptyRedisKeyNamespace() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.repository.setRedisKeyNamespace(""))
void emptyRedisKeyNamespace() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisKeyNamespace(""))
.withMessage("namespace cannot be null or empty");
}
@Test
public void customMaxInactiveInterval() {
void customMaxInactiveInterval() {
this.repository.setDefaultMaxInactiveInterval(600);
assertThat(ReflectionTestUtils.getField(this.repository,
"defaultMaxInactiveInterval")).isEqualTo(600);
assertThat(ReflectionTestUtils.getField(this.repository, "defaultMaxInactiveInterval")).isEqualTo(600);
}
@Test
public void customRedisFlushMode() {
void customRedisFlushMode() {
this.repository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
assertThat(ReflectionTestUtils.getField(this.repository, "redisFlushMode"))
.isEqualTo(RedisFlushMode.IMMEDIATE);
assertThat(ReflectionTestUtils.getField(this.repository, "redisFlushMode")).isEqualTo(RedisFlushMode.IMMEDIATE);
}
@Test
public void nullRedisFlushMode() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.repository.setRedisFlushMode(null))
void nullRedisFlushMode() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisFlushMode(null))
.withMessage("redisFlushMode cannot be null");
}
@Test
public void createSessionDefaultMaxInactiveInterval() {
void createSessionDefaultMaxInactiveInterval() {
StepVerifier.create(this.repository.createSession())
.consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)))
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)))
.verifyComplete();
}
@Test
public void createSessionCustomMaxInactiveInterval() {
void createSessionCustomMaxInactiveInterval() {
this.repository.setDefaultMaxInactiveInterval(600);
StepVerifier.create(this.repository.createSession())
.consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(600)))
.consumeNextWith(
(session) -> assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(600)))
.verifyComplete();
}
@Test
public void saveNewSession() {
void saveNewSession() {
given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any()))
.willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true));
RedisSession newSession = this.repository.new RedisSession();
StepVerifier.create(this.repository.save(newSession)).verifyComplete();
@@ -176,13 +163,11 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
}
@Test
public void saveSessionNothingChanged() {
void saveSessionNothingChanged() {
given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any()))
.willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true));
RedisSession session = this.repository.new RedisSession(
new MapSession(this.cached));
RedisSession session = this.repository.new RedisSession(new MapSession(this.cached));
StepVerifier.create(this.repository.save(session)).verifyComplete();
@@ -192,12 +177,11 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
}
@Test
public void saveLastAccessChanged() {
void saveLastAccessChanged() {
given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true));
given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any()))
.willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true));
RedisSession session = this.repository.new RedisSession(this.cached);
session.setLastAccessedTime(Instant.ofEpochMilli(12345678L));
@@ -210,18 +194,16 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
verifyZeroInteractions(this.redisOperations);
verifyZeroInteractions(this.hashOperations);
assertThat(this.delta.getAllValues().get(0))
.isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
session.getLastAccessedTime().toEpochMilli()));
assertThat(this.delta.getAllValues().get(0)).isEqualTo(
map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
}
@Test
public void saveSetAttribute() {
void saveSetAttribute() {
given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true));
given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any()))
.willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true));
String attrName = "attrName";
RedisSession session = this.repository.new RedisSession(this.cached);
@@ -236,17 +218,15 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
verifyZeroInteractions(this.hashOperations);
assertThat(this.delta.getAllValues().get(0)).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
@Test
public void saveRemoveAttribute() {
void saveRemoveAttribute() {
given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true));
given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any()))
.willReturn(Mono.just(true));
given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true));
String attrName = "attrName";
RedisSession session = this.repository.new RedisSession(new MapSession());
@@ -260,12 +240,12 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
verifyZeroInteractions(this.redisOperations);
verifyZeroInteractions(this.hashOperations);
assertThat(this.delta.getAllValues().get(0)).isEqualTo(map(
RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null));
assertThat(this.delta.getAllValues().get(0))
.isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null));
}
@Test
public void redisSessionGetAttributes() {
void redisSessionGetAttributes() {
String attrName = "attrName";
RedisSession session = this.repository.new RedisSession(this.cached);
assertThat(session.getAttributeNames()).isEmpty();
@@ -278,7 +258,7 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
}
@Test
public void delete() {
void delete() {
given(this.redisOperations.delete(anyString())).willReturn(Mono.just(1L));
StepVerifier.create(this.repository.deleteById("test")).verifyComplete();
@@ -289,7 +269,7 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
}
@Test
public void getSessionNotFound() {
void getSessionNotFound() {
given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
given(this.hashOperations.entries(anyString())).willReturn(Flux.empty());
given(this.redisOperations.delete(anyString())).willReturn(Mono.just(0L));
@@ -305,7 +285,7 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
@Test
@SuppressWarnings("unchecked")
public void getSessionFound() {
void getSessionFound() {
given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
String attribute1 = "attribute1";
String attribute2 = "attribute2";
@@ -313,54 +293,38 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
expected.setLastAccessedTime(Instant.now().minusSeconds(60));
expected.setAttribute(attribute1, "test");
expected.setAttribute(attribute2, null);
Map map = map(RedisSessionMapper.ATTRIBUTE_PREFIX + attribute1,
expected.getAttribute(attribute1),
RedisSessionMapper.ATTRIBUTE_PREFIX + attribute2,
expected.getAttribute(attribute2), RedisSessionMapper.CREATION_TIME_KEY,
expected.getCreationTime().toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY,
(int) expected.getMaxInactiveInterval().getSeconds(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
expected.getLastAccessedTime().toEpochMilli());
given(this.hashOperations.entries(anyString()))
.willReturn(Flux.fromIterable(map.entrySet()));
Map map = map(RedisSessionMapper.ATTRIBUTE_PREFIX + attribute1, expected.getAttribute(attribute1),
RedisSessionMapper.ATTRIBUTE_PREFIX + attribute2, expected.getAttribute(attribute2),
RedisSessionMapper.CREATION_TIME_KEY, expected.getCreationTime().toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) expected.getMaxInactiveInterval().getSeconds(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, expected.getLastAccessedTime().toEpochMilli());
given(this.hashOperations.entries(anyString())).willReturn(Flux.fromIterable(map.entrySet()));
StepVerifier.create(this.repository.findById("test"))
.consumeNextWith((session) -> {
verify(this.redisOperations).opsForHash();
verify(this.hashOperations).entries(anyString());
verifyZeroInteractions(this.redisOperations);
verifyZeroInteractions(this.hashOperations);
StepVerifier.create(this.repository.findById("test")).consumeNextWith((session) -> {
verify(this.redisOperations).opsForHash();
verify(this.hashOperations).entries(anyString());
verifyZeroInteractions(this.redisOperations);
verifyZeroInteractions(this.hashOperations);
assertThat(session.getId()).isEqualTo(expected.getId());
assertThat(session.getAttributeNames())
.isEqualTo(expected.getAttributeNames());
assertThat(session.<String>getAttribute(attribute1))
.isEqualTo(expected.getAttribute(attribute1));
assertThat(session.<String>getAttribute(attribute2))
.isEqualTo(expected.getAttribute(attribute2));
assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getCreationTime()
.truncatedTo(ChronoUnit.MILLIS));
assertThat(session.getMaxInactiveInterval())
.isEqualTo(expected.getMaxInactiveInterval());
assertThat(
session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getLastAccessedTime()
.truncatedTo(ChronoUnit.MILLIS));
}).verifyComplete();
assertThat(session.getId()).isEqualTo(expected.getId());
assertThat(session.getAttributeNames()).isEqualTo(expected.getAttributeNames());
assertThat(session.<String>getAttribute(attribute1)).isEqualTo(expected.getAttribute(attribute1));
assertThat(session.<String>getAttribute(attribute2)).isEqualTo(expected.getAttribute(attribute2));
assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
assertThat(session.getMaxInactiveInterval()).isEqualTo(expected.getMaxInactiveInterval());
assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS));
}).verifyComplete();
}
@Test
@SuppressWarnings("unchecked")
public void getSessionExpired() {
void getSessionExpired() {
given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
Map map = map(RedisSessionMapper.CREATION_TIME_KEY, 0L,
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1,
RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
given(this.hashOperations.entries(anyString()))
.willReturn(Flux.fromIterable(map.entrySet()));
Map map = map(RedisSessionMapper.CREATION_TIME_KEY, 0L, RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1,
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
given(this.hashOperations.entries(anyString())).willReturn(Flux.fromIterable(map.entrySet()));
given(this.redisOperations.delete(anyString())).willReturn(Mono.just(0L));
StepVerifier.create(this.repository.findById("test")).verifyComplete();
@@ -373,7 +337,7 @@ public class ReactiveRedisOperationsSessionRepositoryTests {
}
@Test // gh-1120
public void getAttributeNamesAndRemove() {
void getAttributeNamesAndRemove() {
RedisSession session = this.repository.new RedisSession(this.cached);
session.setAttribute("attribute1", "value1");
session.setAttribute("attribute2", "value2");

View File

@@ -72,27 +72,37 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class RedisOperationsSessionRepositoryTests {
static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";
class RedisOperationsSessionRepositoryTests {
private static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";
@Mock
RedisConnectionFactory factory;
@Mock
RedisConnection connection;
@Mock
RedisOperations<Object, Object> redisOperations;
@Mock
BoundValueOperations<Object, Object> boundValueOperations;
@Mock
BoundHashOperations<Object, Object, Object> boundHashOperations;
@Mock
BoundSetOperations<Object, Object> boundSetOperations;
@Mock
ApplicationEventPublisher publisher;
@Mock
RedisSerializer<Object> defaultSerializer;
@Captor
ArgumentCaptor<AbstractSessionEvent> event;
@Captor
ArgumentCaptor<Map<String, Object>> delta;
@@ -101,7 +111,7 @@ public class RedisOperationsSessionRepositoryTests {
private RedisOperationsSessionRepository redisRepository;
@BeforeEach
public void setup() {
void setup() {
MockitoAnnotations.initMocks(this);
this.redisRepository = new RedisOperationsSessionRepository(this.redisOperations);
this.redisRepository.setDefaultSerializer(this.defaultSerializer);
@@ -113,20 +123,16 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void setApplicationEventPublisherNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.redisRepository.setApplicationEventPublisher(null))
void setApplicationEventPublisherNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setApplicationEventPublisher(null))
.withMessage("applicationEventPublisher cannot be null");
}
@Test
public void changeSessionIdWhenNotSaved() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
void changeSessionIdWhenNotSaved() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
RedisSession createSession = this.redisRepository.createSession();
String originalId = createSession.getId();
@@ -140,13 +146,10 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void changeSessionIdWhenSaved() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
void changeSessionIdWhenSaved() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
RedisSession session = this.redisRepository.new RedisSession(this.cached);
session.setLastAccessedTime(session.getLastAccessedTime());
@@ -161,30 +164,25 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void createSessionDefaultMaxInactiveInterval() throws Exception {
void createSessionDefaultMaxInactiveInterval() throws Exception {
Session session = this.redisRepository.createSession();
assertThat(session.getMaxInactiveInterval())
.isEqualTo(new MapSession().getMaxInactiveInterval());
assertThat(session.getMaxInactiveInterval()).isEqualTo(new MapSession().getMaxInactiveInterval());
}
@Test
public void createSessionCustomMaxInactiveInterval() throws Exception {
void createSessionCustomMaxInactiveInterval() throws Exception {
int interval = 1;
this.redisRepository.setDefaultMaxInactiveInterval(interval);
Session session = this.redisRepository.createSession();
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(interval));
assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(interval));
}
@Test
public void saveNewSession() {
void saveNewSession() {
RedisSession session = this.redisRepository.createSession();
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.save(session);
@@ -192,16 +190,15 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta.get(RedisSessionMapper.CREATION_TIME_KEY);
assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli());
assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)).isEqualTo(
(int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)
.getSeconds());
assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY))
.isEqualTo(session.getCreationTime().toEpochMilli());
}
// gh-467
@Test
public void saveSessionNothingChanged() {
void saveSessionNothingChanged() {
RedisSession session = this.redisRepository.new RedisSession(this.cached);
this.redisRepository.save(session);
@@ -210,21 +207,17 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void saveJavadocSummary() {
void saveJavadocSummary() {
RedisSession session = this.redisRepository.createSession();
String sessionKey = "spring:session:sessions:" + session.getId();
String backgroundExpireKey = "spring:session:expirations:"
+ RedisSessionExpirationPolicy.roundUpToNextMinute(
RedisSessionExpirationPolicy.expiresInMillis(session));
String backgroundExpireKey = "spring:session:expirations:" + RedisSessionExpirationPolicy
.roundUpToNextMinute(RedisSessionExpirationPolicy.expiresInMillis(session));
String destroyedTriggerKey = "spring:session:sessions:expires:" + session.getId();
given(this.redisOperations.boundHashOps(sessionKey))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(backgroundExpireKey))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(destroyedTriggerKey))
.willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(sessionKey)).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(backgroundExpireKey)).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(destroyedTriggerKey)).willReturn(this.boundValueOperations);
this.redisRepository.save(session);
@@ -232,10 +225,8 @@ public class RedisOperationsSessionRepositoryTests {
// can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since
// findById checks if it is expired
long fiveMinutesAfterExpires = session.getMaxInactiveInterval().plusMinutes(5)
.getSeconds();
verify(this.boundHashOperations).expire(fiveMinutesAfterExpires,
TimeUnit.SECONDS);
long fiveMinutesAfterExpires = session.getMaxInactiveInterval().plusMinutes(5).getSeconds();
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);
@@ -243,18 +234,16 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void saveJavadoc() {
void saveJavadoc() {
RedisSession session = this.redisRepository.new RedisSession(this.cached);
session.setLastAccessedTime(session.getLastAccessedTime());
given(this.redisOperations.boundHashOps("spring:session:sessions:session-id"))
.willReturn(this.boundHashOperations);
given(this.redisOperations
.boundSetOps("spring:session:expirations:1404361860000"))
.willReturn(this.boundSetOperations);
given(this.redisOperations
.boundValueOps("spring:session:sessions:expires:session-id"))
.willReturn(this.boundValueOperations);
given(this.redisOperations.boundSetOps("spring:session:expirations:1404361860000"))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps("spring:session:sessions:expires:session-id"))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
@@ -262,74 +251,59 @@ public class RedisOperationsSessionRepositoryTests {
// can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since
// findById checks if it is expired
verify(this.boundHashOperations).expire(
session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
verify(this.boundHashOperations).expire(session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
TimeUnit.SECONDS);
}
@Test
public void saveLastAccessChanged() {
RedisSession session = this.redisRepository.new RedisSession(
new MapSession(this.cached));
void saveLastAccessChanged() {
RedisSession session = this.redisRepository.new RedisSession(new MapSession(this.cached));
session.setLastAccessedTime(Instant.ofEpochMilli(12345678L));
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
session.getLastAccessedTime().toEpochMilli()));
}
@Test
public void saveSetAttribute() {
String attrName = "attrName";
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.setAttribute(attrName, "attrValue");
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
}
@Test
public void saveRemoveAttribute() {
void saveSetAttribute() {
String attrName = "attrName";
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.removeAttribute(attrName);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
session.setAttribute(attrName, "attrValue");
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(
RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null));
assertThat(getDelta()).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
@Test
public void saveExpired() {
void saveRemoveAttribute() {
String attrName = "attrName";
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.removeAttribute(attrName);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null));
}
@Test
void saveExpired() {
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.setMaxInactiveInterval(Duration.ZERO);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
this.redisRepository.save(session);
@@ -339,7 +313,7 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void redisSessionGetAttributes() {
void redisSessionGetAttributes() {
String attrName = "attrName";
RedisSession session = this.redisRepository.new RedisSession(
Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
@@ -351,39 +325,31 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void delete() {
void delete() {
String attrName = "attrName";
MapSession expected = new MapSession();
expected.setLastAccessedTime(Instant.now().minusSeconds(60));
expected.setAttribute(attrName, "attrValue");
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
expected.getAttribute(attrName), RedisSessionMapper.CREATION_TIME_KEY,
expected.getCreationTime().toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY,
(int) expected.getMaxInactiveInterval().getSeconds(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
expected.getLastAccessedTime().toEpochMilli());
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
RedisSessionMapper.CREATION_TIME_KEY, expected.getCreationTime().toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) expected.getMaxInactiveInterval().getSeconds(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, expected.getLastAccessedTime().toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
String id = expected.getId();
this.redisRepository.deleteById(id);
assertThat(getDelta().get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
.isEqualTo(0);
assertThat(getDelta().get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)).isEqualTo(0);
verify(this.redisOperations, atLeastOnce()).delete(getKey("expires:" + id));
verify(this.redisOperations, never()).boundValueOps(getKey("expires:" + id));
}
@Test
public void deleteNullSession() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
void deleteNullSession() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
String id = "abc";
this.redisRepository.deleteById(id);
@@ -392,58 +358,48 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void getSessionNotFound() {
void getSessionNotFound() {
String id = "abc";
given(this.redisOperations.boundHashOps(getKey(id)))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundHashOps(getKey(id))).willReturn(this.boundHashOperations);
given(this.boundHashOperations.entries()).willReturn(map());
assertThat(this.redisRepository.findById(id)).isNull();
}
@Test
public void getSessionFound() {
void getSessionFound() {
String attribute1 = "attribute1";
String attribute2 = "attribute2";
MapSession expected = new MapSession();
expected.setLastAccessedTime(Instant.now().minusSeconds(60));
expected.setAttribute(attribute1, "test");
expected.setAttribute(attribute2, null);
given(this.redisOperations.boundHashOps(getKey(expected.getId())))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundHashOps(getKey(expected.getId()))).willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attribute1),
expected.getAttribute(attribute1),
RedisOperationsSessionRepository.getSessionAttrNameKey(attribute2),
expected.getAttribute(attribute1), RedisOperationsSessionRepository.getSessionAttrNameKey(attribute2),
expected.getAttribute(attribute2), RedisSessionMapper.CREATION_TIME_KEY,
expected.getCreationTime().toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY,
(int) expected.getMaxInactiveInterval().getSeconds(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
expected.getCreationTime().toEpochMilli(), RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY,
(int) expected.getMaxInactiveInterval().getSeconds(), RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
expected.getLastAccessedTime().toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
RedisSession session = this.redisRepository.findById(expected.getId());
assertThat(session.getId()).isEqualTo(expected.getId());
assertThat(session.getAttributeNames()).isEqualTo(expected.getAttributeNames());
assertThat(session.<String>getAttribute(attribute1))
.isEqualTo(expected.getAttribute(attribute1));
assertThat(session.<String>getAttribute(attribute2))
.isEqualTo(expected.getAttribute(attribute2));
assertThat(session.<String>getAttribute(attribute1)).isEqualTo(expected.getAttribute(attribute1));
assertThat(session.<String>getAttribute(attribute2)).isEqualTo(expected.getAttribute(attribute2));
assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
assertThat(session.getMaxInactiveInterval())
.isEqualTo(expected.getMaxInactiveInterval());
assertThat(session.getMaxInactiveInterval()).isEqualTo(expected.getMaxInactiveInterval());
assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS));
}
@Test
public void getSessionExpired() {
void getSessionExpired() {
String expiredId = "expired-id";
given(this.redisOperations.boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1,
RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
@@ -451,46 +407,36 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void findByPrincipalNameExpired() {
void findByPrincipalNameExpired() {
String expiredId = "expired-id";
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.boundSetOperations.members())
.willReturn(Collections.singleton(expiredId));
given(this.redisOperations.boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1,
RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.singleton(expiredId));
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
assertThat(this.redisRepository.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"))
assertThat(this.redisRepository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"))
.isEmpty();
}
@Test
public void findByPrincipalName() {
void findByPrincipalName() {
Instant lastAccessed = Instant.now().minusMillis(10);
Instant createdTime = lastAccessed.minusMillis(10);
Duration maxInactive = Duration.ofHours(1);
String sessionId = "some-id";
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.boundSetOperations.members())
.willReturn(Collections.singleton(sessionId));
given(this.redisOperations.boundHashOps(getKey(sessionId)))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.singleton(sessionId));
given(this.redisOperations.boundHashOps(getKey(sessionId))).willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.CREATION_TIME_KEY, createdTime.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY,
(int) maxInactive.getSeconds(), RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
lastAccessed.toEpochMilli());
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) maxInactive.getSeconds(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, lastAccessed.toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
Map<String, RedisSession> sessionIdToSessions = this.redisRepository
.findByIndexNameAndIndexValue(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
"principal");
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal");
assertThat(sessionIdToSessions).hasSize(1);
RedisSession session = sessionIdToSessions.get(sessionId);
@@ -504,13 +450,11 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void cleanupExpiredSessions() {
void cleanupExpiredSessions() {
String expiredId = "expired-id";
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
Set<Object> expiredIds = new HashSet<>(
Arrays.asList("expired-key1", "expired-key2"));
Set<Object> expiredIds = new HashSet<>(Arrays.asList("expired-key1", "expired-key2"));
given(this.boundSetOperations.members()).willReturn(expiredIds);
this.redisRepository.cleanupExpiredSessions();
@@ -523,15 +467,14 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void onMessageCreated() {
void onMessageCreated() {
MapSession session = this.cached;
byte[] pattern = "".getBytes(StandardCharsets.UTF_8);
String channel = "spring:session:event:0:created:" + session.getId();
JdkSerializationRedisSerializer defaultSerailizer = new JdkSerializationRedisSerializer();
this.redisRepository.setDefaultSerializer(defaultSerailizer);
byte[] body = defaultSerailizer.serialize(new HashMap());
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8), body);
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body);
this.redisRepository.setApplicationEventPublisher(this.publisher);
@@ -542,15 +485,13 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test // gh-309
public void onMessageCreatedCustomSerializer() {
void onMessageCreatedCustomSerializer() {
MapSession session = this.cached;
byte[] pattern = "".getBytes(StandardCharsets.UTF_8);
byte[] body = new byte[0];
String channel = "spring:session:event:0:created:" + session.getId();
given(this.defaultSerializer.deserialize(body))
.willReturn(new HashMap<String, Object>());
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8), body);
given(this.defaultSerializer.deserialize(body)).willReturn(new HashMap<String, Object>());
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body);
this.redisRepository.setApplicationEventPublisher(this.publisher);
this.redisRepository.onMessage(message, pattern);
@@ -561,19 +502,16 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void onMessageDeletedSessionFound() {
void onMessageDeletedSessionFound() {
String deletedId = "deleted-id";
given(this.redisOperations.boundHashOps(getKey(deletedId)))
.willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 0,
RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
given(this.redisOperations.boundHashOps(getKey(deletedId))).willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 0, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
given(this.boundHashOperations.entries()).willReturn(map);
String channel = "__keyevent@0__:del";
String body = "spring:session:sessions:expires:" + deletedId;
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8),
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8),
body.getBytes(StandardCharsets.UTF_8));
this.redisRepository.setApplicationEventPublisher(this.publisher);
@@ -590,16 +528,14 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void onMessageDeletedSessionNotFound() {
void onMessageDeletedSessionNotFound() {
String deletedId = "deleted-id";
given(this.redisOperations.boundHashOps(getKey(deletedId)))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundHashOps(getKey(deletedId))).willReturn(this.boundHashOperations);
given(this.boundHashOperations.entries()).willReturn(map());
String channel = "__keyevent@0__:del";
String body = "spring:session:sessions:expires:" + deletedId;
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8),
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8),
body.getBytes(StandardCharsets.UTF_8));
this.redisRepository.setApplicationEventPublisher(this.publisher);
@@ -614,19 +550,16 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void onMessageExpiredSessionFound() {
void onMessageExpiredSessionFound() {
String expiredId = "expired-id";
given(this.redisOperations.boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1,
RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
given(this.boundHashOperations.entries()).willReturn(map);
String channel = "__keyevent@0__:expired";
String body = "spring:session:sessions:expires:" + expiredId;
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8),
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8),
body.getBytes(StandardCharsets.UTF_8));
this.redisRepository.setApplicationEventPublisher(this.publisher);
@@ -643,16 +576,14 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void onMessageExpiredSessionNotFound() {
void onMessageExpiredSessionNotFound() {
String expiredId = "expired-id";
given(this.redisOperations.boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
given(this.boundHashOperations.entries()).willReturn(map());
String channel = "__keyevent@0__:expired";
String body = "spring:session:sessions:expires:" + expiredId;
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8),
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8),
body.getBytes(StandardCharsets.UTF_8));
this.redisRepository.setApplicationEventPublisher(this.publisher);
@@ -667,21 +598,20 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void resolvePrincipalIndex() {
void resolvePrincipalIndex() {
PrincipalNameResolver resolver = RedisOperationsSessionRepository.PRINCIPAL_NAME_RESOLVER;
String username = "username";
RedisSession session = this.redisRepository.createSession();
session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
username);
session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);
assertThat(resolver.resolvePrincipal(session)).isEqualTo(username);
}
@Test
public void resolveIndexOnSecurityContext() {
void resolveIndexOnSecurityContext() {
String principal = "resolveIndexOnSecurityContext";
Authentication authentication = new UsernamePasswordAuthenticationToken(principal,
"notused", AuthorityUtils.createAuthorityList("ROLE_USER"));
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused",
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContext context = new SecurityContextImpl();
context.setAuthentication(authentication);
@@ -694,14 +624,14 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void flushModeOnSaveCreate() {
void flushModeOnSaveCreate() {
this.redisRepository.createSession();
verifyZeroInteractions(this.boundHashOperations);
}
@Test
public void flushModeOnSaveSetAttribute() {
void flushModeOnSaveSetAttribute() {
RedisSession session = this.redisRepository.createSession();
session.setAttribute("something", "here");
@@ -709,7 +639,7 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void flushModeOnSaveRemoveAttribute() {
void flushModeOnSaveRemoveAttribute() {
RedisSession session = this.redisRepository.createSession();
session.removeAttribute("remove");
@@ -717,7 +647,7 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void flushModeOnSaveSetLastAccessedTime() {
void flushModeOnSaveSetLastAccessedTime() {
RedisSession session = this.redisRepository.createSession();
session.setLastAccessedTime(Instant.ofEpochMilli(1L));
@@ -725,7 +655,7 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void flushModeOnSaveSetMaxInactiveIntervalInSeconds() {
void flushModeOnSaveSetMaxInactiveIntervalInSeconds() {
RedisSession session = this.redisRepository.createSession();
session.setMaxInactiveInterval(Duration.ofSeconds(1));
@@ -733,13 +663,10 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void flushModeImmediateCreate() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
void flushModeImmediateCreate() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -748,21 +675,17 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta.get(RedisSessionMapper.CREATION_TIME_KEY);
assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli());
assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)).isEqualTo(
(int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)
.getSeconds());
assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY))
.isEqualTo(session.getCreationTime().toEpochMilli());
}
@Test // gh-1409
public void flushModeImmediateCreateWithCustomMaxInactiveInterval() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
void flushModeImmediateCreateWithCustomMaxInactiveInterval() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.setDefaultMaxInactiveInterval(60);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
this.redisRepository.createSession();
@@ -772,13 +695,10 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void flushModeImmediateSetAttribute() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
void flushModeImmediateSetAttribute() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -788,18 +708,14 @@ public class RedisOperationsSessionRepositoryTests {
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
@Test
public void flushModeImmediateRemoveAttribute() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
void flushModeImmediateRemoveAttribute() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -809,18 +725,14 @@ public class RedisOperationsSessionRepositoryTests {
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName)));
}
@Test
public void flushModeSetMaxInactiveIntervalInSeconds() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
void flushModeSetMaxInactiveIntervalInSeconds() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -833,13 +745,10 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void flushModeSetLastAccessedTime() {
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString()))
.willReturn(this.boundValueOperations);
void flushModeSetLastAccessedTime() {
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
@@ -848,53 +757,46 @@ public class RedisOperationsSessionRepositoryTests {
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
session.getLastAccessedTime().toEpochMilli()));
assertThat(delta).isEqualTo(
map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
}
@Test
public void setRedisFlushModeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.redisRepository.setRedisFlushMode(null))
void setRedisFlushModeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setRedisFlushMode(null))
.withMessage("redisFlushMode cannot be null");
}
@Test
public void changeRedisNamespace() {
void changeRedisNamespace() {
String namespace = "foo:bar";
this.redisRepository.setRedisKeyNamespace(namespace);
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.setMaxInactiveInterval(Duration.ZERO);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
this.redisRepository.save(session);
String id = session.getId();
verify(this.redisOperations, atLeastOnce())
.delete(namespace + ":sessions:expires:" + id);
verify(this.redisOperations, never())
.boundValueOps(namespace + ":sessions:expires:" + id);
verify(this.redisOperations, atLeastOnce()).delete(namespace + ":sessions:expires:" + id);
verify(this.redisOperations, never()).boundValueOps(namespace + ":sessions:expires:" + id);
}
@Test
public void setRedisKeyNamespaceNullNamespace() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(null))
void setRedisKeyNamespaceNullNamespace() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(null))
.withMessage("namespace cannot be null or empty");
}
@Test
public void setRedisKeyNamespaceEmptyNamespace() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(" "))
void setRedisKeyNamespaceEmptyNamespace() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(" "))
.withMessage("namespace cannot be null or empty");
}
@Test // gh-1120
public void getAttributeNamesAndRemove() {
void getAttributeNamesAndRemove() {
RedisSession session = this.redisRepository.new RedisSession(this.cached);
session.setAttribute("attribute1", "value1");
session.setAttribute("attribute2", "value2");
@@ -907,7 +809,7 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void onMessageCreatedInOtherDatabase() {
void onMessageCreatedInOtherDatabase() {
JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
this.redisRepository.setApplicationEventPublisher(this.publisher);
this.redisRepository.setDefaultSerializer(serializer);
@@ -915,8 +817,7 @@ public class RedisOperationsSessionRepositoryTests {
MapSession session = this.cached;
String channel = "spring:session:event:created:1:" + session.getId();
byte[] body = serializer.serialize(new HashMap());
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8), body);
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body);
this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8));
@@ -925,7 +826,7 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void onMessageDeletedInOtherDatabase() {
void onMessageDeletedInOtherDatabase() {
JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
this.redisRepository.setApplicationEventPublisher(this.publisher);
this.redisRepository.setDefaultSerializer(serializer);
@@ -933,8 +834,7 @@ public class RedisOperationsSessionRepositoryTests {
MapSession session = this.cached;
String channel = "__keyevent@1__:del";
String body = "spring:session:sessions:expires:" + session.getId();
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8),
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8),
body.getBytes(StandardCharsets.UTF_8));
this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8));
@@ -944,7 +844,7 @@ public class RedisOperationsSessionRepositoryTests {
}
@Test
public void onMessageExpiredInOtherDatabase() {
void onMessageExpiredInOtherDatabase() {
JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
this.redisRepository.setApplicationEventPublisher(this.publisher);
this.redisRepository.setDefaultSerializer(serializer);
@@ -952,8 +852,7 @@ public class RedisOperationsSessionRepositoryTests {
MapSession session = this.cached;
String channel = "__keyevent@1__:expired";
String body = "spring:session:sessions:expires:" + session.getId();
DefaultMessage message = new DefaultMessage(
channel.getBytes(StandardCharsets.UTF_8),
DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8),
body.getBytes(StandardCharsets.UTF_8));
this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8));
@@ -985,4 +884,5 @@ public class RedisOperationsSessionRepositoryTests {
verify(this.boundHashOperations, times(times)).putAll(this.delta.capture());
return this.delta.getAllValues().get(times - 1);
}
}

View File

@@ -39,54 +39,52 @@ import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*/
public class RedisSessionExpirationPolicyTests {
class RedisSessionExpirationPolicyTests {
// Wed Apr 15 10:28:32 CDT 2015
static final Long NOW = 1429111712346L;
// Wed Apr 15 10:27:32 CDT 2015
static final Long ONE_MINUTE_AGO = 1429111652346L;
private static final Long ONE_MINUTE_AGO = 1429111652346L;
@Mock
RedisOperations<Object, Object> sessionRedisOperations;
@Mock
BoundSetOperations<Object, Object> setOperations;
@Mock
BoundHashOperations<Object, Object, Object> hashOperations;
@Mock
BoundValueOperations<Object, Object> valueOperations;
RedisSessionExpirationPolicy policy;
private RedisSessionExpirationPolicy policy;
private MapSession session;
@BeforeEach
public void setup() {
void setup() {
MockitoAnnotations.initMocks(this);
RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(
this.sessionRedisOperations);
this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations,
repository::getExpirationsKey, repository::getSessionKey);
RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(this.sessionRedisOperations);
this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations, repository::getExpirationsKey,
repository::getSessionKey);
this.session = new MapSession();
this.session.setLastAccessedTime(Instant.ofEpochMilli(1429116694675L));
this.session.setId("12345");
given(this.sessionRedisOperations.boundSetOps(anyString()))
.willReturn(this.setOperations);
given(this.sessionRedisOperations.boundHashOps(anyString()))
.willReturn(this.hashOperations);
given(this.sessionRedisOperations.boundValueOps(anyString()))
.willReturn(this.valueOperations);
given(this.sessionRedisOperations.boundSetOps(anyString())).willReturn(this.setOperations);
given(this.sessionRedisOperations.boundHashOps(anyString())).willReturn(this.hashOperations);
given(this.sessionRedisOperations.boundValueOps(anyString())).willReturn(this.valueOperations);
}
// gh-169
@Test
public void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp()
throws Exception {
void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp() throws Exception {
long originalExpirationTimeInMs = ONE_MINUTE_AGO;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy
.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = this.policy
.getExpirationKey(originalRoundedToNextMinInMs);
String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);
@@ -96,14 +94,11 @@ public class RedisSessionExpirationPolicyTests {
}
@Test
public void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange()
throws Exception {
long originalExpirationTimeInMs = RedisSessionExpirationPolicy
.expiresInMillis(this.session) - 10;
void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange() throws Exception {
long originalExpirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session) - 10;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy
.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = this.policy
.getExpirationKey(originalRoundedToNextMinInMs);
String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);
@@ -113,36 +108,32 @@ public class RedisSessionExpirationPolicyTests {
}
@Test
public void onExpirationUpdatedAddsExpirationTimeRoundedUp() throws Exception {
long expirationTimeInMs = RedisSessionExpirationPolicy
.expiresInMillis(this.session);
long expirationRoundedUpInMs = RedisSessionExpirationPolicy
.roundUpToNextMinute(expirationTimeInMs);
void onExpirationUpdatedAddsExpirationTimeRoundedUp() throws Exception {
long expirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session);
long expirationRoundedUpInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(expirationTimeInMs);
String expectedExpireKey = this.policy.getExpirationKey(expirationRoundedUpInMs);
this.policy.onExpirationUpdated(null, this.session);
verify(this.sessionRedisOperations).boundSetOps(expectedExpireKey);
verify(this.setOperations).add("expires:" + this.session.getId());
verify(this.setOperations).expire(
this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
verify(this.setOperations).expire(this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
TimeUnit.SECONDS);
}
@Test
public void onExpirationUpdatedSetExpireSession() throws Exception {
void onExpirationUpdatedSetExpireSession() throws Exception {
String sessionKey = this.policy.getSessionKey(this.session.getId());
this.policy.onExpirationUpdated(null, this.session);
verify(this.sessionRedisOperations).boundHashOps(sessionKey);
verify(this.hashOperations).expire(
this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
verify(this.hashOperations).expire(this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
TimeUnit.SECONDS);
}
@Test
public void onExpirationUpdatedDeleteOnZero() throws Exception {
void onExpirationUpdatedDeleteOnZero() throws Exception {
String sessionKey = this.policy.getSessionKey("expires:" + this.session.getId());
long originalExpirationTimeInMs = ONE_MINUTE_AGO;
@@ -155,13 +146,12 @@ public class RedisSessionExpirationPolicyTests {
verify(this.setOperations).remove("expires:" + this.session.getId());
verify(this.setOperations).add("expires:" + this.session.getId());
verify(this.sessionRedisOperations).delete(sessionKey);
verify(this.setOperations).expire(
this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
verify(this.setOperations).expire(this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
TimeUnit.SECONDS);
}
@Test
public void onExpirationUpdatedPersistOnNegativeExpiration() throws Exception {
void onExpirationUpdatedPersistOnNegativeExpiration() throws Exception {
long originalExpirationTimeInMs = ONE_MINUTE_AGO;
this.session.setMaxInactiveInterval(Duration.ofSeconds(-1));
@@ -173,4 +163,5 @@ public class RedisSessionExpirationPolicyTests {
verify(this.valueOperations).persist();
verify(this.hashOperations).persist();
}
}

View File

@@ -47,8 +47,7 @@ class RedisSessionMapperTests {
@Test
void constructor_NullId_ShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new RedisSessionMapper(null))
assertThatIllegalArgumentException().isThrownBy(() -> new RedisSessionMapper(null))
.withMessage("sessionId must not be empty");
}
@@ -66,8 +65,7 @@ class RedisSessionMapperTests {
@Test
void apply_EmptyMap_ShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.mapper.apply(Collections.emptyMap()))
assertThatIllegalArgumentException().isThrownBy(() -> this.mapper.apply(Collections.emptyMap()))
.withMessage("map must not be empty");
}
@@ -77,8 +75,7 @@ class RedisSessionMapperTests {
sessionMap.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, 0L);
sessionMap.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1800);
assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap))
.withMessage(
RedisSessionMapper.CREATION_TIME_KEY + " key must not be null");
.withMessage(RedisSessionMapper.CREATION_TIME_KEY + " key must not be null");
}
@Test
@@ -87,8 +84,7 @@ class RedisSessionMapperTests {
sessionMap.put(RedisSessionMapper.CREATION_TIME_KEY, 0L);
sessionMap.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1800);
assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap))
.withMessage(RedisSessionMapper.LAST_ACCESSED_TIME_KEY
+ " key must not be null");
.withMessage(RedisSessionMapper.LAST_ACCESSED_TIME_KEY + " key must not be null");
}
@Test
@@ -97,8 +93,7 @@ class RedisSessionMapperTests {
sessionMap.put(RedisSessionMapper.CREATION_TIME_KEY, 0L);
sessionMap.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, 0L);
assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap))
.withMessage(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY
+ " key must not be null");
.withMessage(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY + " key must not be null");
}
@Test

View File

@@ -70,52 +70,45 @@ class SimpleRedisOperationsSessionRepositoryTests {
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
given(this.sessionRedisOperations.<String, Object>opsForHash())
.willReturn(this.sessionHashOperations);
this.sessionRepository = new SimpleRedisOperationsSessionRepository(
this.sessionRedisOperations);
given(this.sessionRedisOperations.<String, Object>opsForHash()).willReturn(this.sessionHashOperations);
this.sessionRepository = new SimpleRedisOperationsSessionRepository(this.sessionRedisOperations);
}
@Test
void constructor_NullRedisOperations_ShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ReactiveRedisOperationsSessionRepository(null))
assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveRedisOperationsSessionRepository(null))
.withMessageContaining("sessionRedisOperations cannot be null");
}
@Test
void setDefaultMaxInactiveInterval_ValidInterval_ShouldSetInterval() {
this.sessionRepository.setDefaultMaxInactiveInterval(Duration.ofMinutes(10));
assertThat(ReflectionTestUtils.getField(this.sessionRepository,
"defaultMaxInactiveInterval")).isEqualTo(Duration.ofMinutes(10));
assertThat(ReflectionTestUtils.getField(this.sessionRepository, "defaultMaxInactiveInterval"))
.isEqualTo(Duration.ofMinutes(10));
}
@Test
void setDefaultMaxInactiveInterval_NullInterval_ShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(
() -> this.sessionRepository.setDefaultMaxInactiveInterval(null))
.isThrownBy(() -> this.sessionRepository.setDefaultMaxInactiveInterval(null))
.withMessage("defaultMaxInactiveInterval must not be null");
}
@Test
void setKeyNamespace_ValidNamespace_ShouldSetNamespace() {
this.sessionRepository.setKeyNamespace("test:");
assertThat(ReflectionTestUtils.getField(this.sessionRepository, "keyNamespace"))
.isEqualTo("test:");
assertThat(ReflectionTestUtils.getField(this.sessionRepository, "keyNamespace")).isEqualTo("test:");
}
@Test
void setKeyNamespace_NullNamespace_ShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.sessionRepository.setKeyNamespace(null))
assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setKeyNamespace(null))
.withMessage("keyNamespace must not be empty");
}
@Test
void setKeyNamespace_EmptyNamespace_ShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.sessionRepository.setKeyNamespace(" "))
assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setKeyNamespace(" "))
.withMessage("keyNamespace must not be empty");
}
@@ -128,16 +121,15 @@ class SimpleRedisOperationsSessionRepositoryTests {
@Test
void setFlushMode_NullFlushMode_ShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.sessionRepository.setFlushMode(null))
assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setFlushMode(null))
.withMessage("flushMode must not be null");
}
@Test
void createSession_DefaultMaxInactiveInterval_ShouldCreateSession() {
RedisSession redisSession = this.sessionRepository.createSession();
assertThat(redisSession.getMaxInactiveInterval()).isEqualTo(
Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
assertThat(redisSession.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
verifyNoMoreInteractions(this.sessionRedisOperations);
verifyNoMoreInteractions(this.sessionHashOperations);
}
@@ -146,8 +138,7 @@ class SimpleRedisOperationsSessionRepositoryTests {
void createSession_CustomMaxInactiveInterval_ShouldCreateSession() {
this.sessionRepository.setDefaultMaxInactiveInterval(Duration.ofMinutes(10));
RedisSession redisSession = this.sessionRepository.createSession();
assertThat(redisSession.getMaxInactiveInterval())
.isEqualTo(Duration.ofMinutes(10));
assertThat(redisSession.getMaxInactiveInterval()).isEqualTo(Duration.ofMinutes(10));
verifyNoMoreInteractions(this.sessionRedisOperations);
verifyNoMoreInteractions(this.sessionHashOperations);
}
@@ -215,10 +206,8 @@ class SimpleRedisOperationsSessionRepositoryTests {
this.sessionRepository.save(session);
verify(this.sessionRedisOperations).hasKey(eq(TEST_SESSION_KEY));
verify(this.sessionRedisOperations).opsForHash();
verify(this.sessionRedisOperations).expireAt(eq(TEST_SESSION_KEY),
eq(getExpiry(session)));
verify(this.sessionHashOperations).putAll(eq(TEST_SESSION_KEY),
this.delta.capture());
verify(this.sessionRedisOperations).expireAt(eq(TEST_SESSION_KEY), eq(getExpiry(session)));
verify(this.sessionHashOperations).putAll(eq(TEST_SESSION_KEY), this.delta.capture());
assertThat(this.delta.getValue()).hasSize(2);
verifyNoMoreInteractions(this.sessionRedisOperations);
verifyNoMoreInteractions(this.sessionHashOperations);
@@ -237,8 +226,7 @@ class SimpleRedisOperationsSessionRepositoryTests {
@Test
void save_SessionNotExists_ShouldThrowException() {
RedisSession session = createTestSession();
assertThatIllegalStateException()
.isThrownBy(() -> this.sessionRepository.save(session))
assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(session))
.withMessage("Session was invalidated");
verify(this.sessionRedisOperations).hasKey(eq(TEST_SESSION_KEY));
verifyNoMoreInteractions(this.sessionRedisOperations);
@@ -249,20 +237,18 @@ class SimpleRedisOperationsSessionRepositoryTests {
@SuppressWarnings("unchecked")
void findById_SessionExists_ShouldReturnSession() {
Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY))).willReturn(
mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY)))
.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, now.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY,
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
RedisSession session = this.sessionRepository.findById(TEST_SESSION_ID);
assertThat(session.getId()).isEqualTo(TEST_SESSION_ID);
assertThat(session.getCreationTime()).isEqualTo(Instant.EPOCH);
assertThat(session.getLastAccessedTime()).isEqualTo(now);
assertThat(session.getMaxInactiveInterval()).isEqualTo(
Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
assertThat(session.getAttributeNames())
.isEqualTo(Collections.singleton("attribute1"));
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
assertThat(session.getAttributeNames()).isEqualTo(Collections.singleton("attribute1"));
assertThat(session.<String>getAttribute("attribute1")).isEqualTo("value1");
verify(this.sessionRedisOperations).opsForHash();
verify(this.sessionHashOperations).entries(eq(TEST_SESSION_KEY));
@@ -273,12 +259,11 @@ class SimpleRedisOperationsSessionRepositoryTests {
@Test
@SuppressWarnings("unchecked")
void findById_SessionExistsAndIsExpired_ShouldReturnNull() {
given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY))).willReturn(mapOf(
RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY,
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY)))
.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
assertThat(this.sessionRepository.findById(TEST_SESSION_ID)).isNull();
verify(this.sessionRedisOperations).opsForHash();
verify(this.sessionHashOperations).entries(eq(TEST_SESSION_KEY));
@@ -306,8 +291,7 @@ class SimpleRedisOperationsSessionRepositoryTests {
@Test
void getSessionRedisOperations__ShouldReturnRedisOperations() {
assertThat(this.sessionRepository.getSessionRedisOperations())
.isEqualTo(this.sessionRedisOperations);
assertThat(this.sessionRepository.getSessionRedisOperations()).isEqualTo(this.sessionRedisOperations);
verifyNoMoreInteractions(this.sessionRedisOperations);
verifyNoMoreInteractions(this.sessionHashOperations);
}
@@ -317,9 +301,8 @@ class SimpleRedisOperationsSessionRepositoryTests {
}
private static Date getExpiry(RedisSession session) {
return Date
.from(Instant.ofEpochMilli(session.getLastAccessedTime().toEpochMilli())
.plusSeconds(session.getMaxInactiveInterval().getSeconds()));
return Date.from(Instant.ofEpochMilli(session.getLastAccessedTime().toEpochMilli())
.plusSeconds(session.getMaxInactiveInterval().getSeconds()));
}
private static Map mapOf(Object... objects) {

View File

@@ -36,20 +36,23 @@ import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
public class EnableRedisKeyspaceNotificationsInitializerTests {
static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events";
class EnableRedisKeyspaceNotificationsInitializerTests {
private static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events";
@Mock
RedisConnectionFactory connectionFactory;
@Mock
RedisConnection connection;
@Captor
ArgumentCaptor<String> options;
RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer initializer;
private RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer initializer;
@BeforeEach
public void setup() {
void setup() {
MockitoAnnotations.initMocks(this);
given(this.connectionFactory.getConnection()).willReturn(this.connection);
@@ -58,7 +61,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetUnset() throws Exception {
void afterPropertiesSetUnset() throws Exception {
setConfigNotification("");
this.initializer.afterPropertiesSet();
@@ -67,7 +70,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetA() throws Exception {
void afterPropertiesSetA() throws Exception {
setConfigNotification("A");
this.initializer.afterPropertiesSet();
@@ -76,7 +79,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetE() throws Exception {
void afterPropertiesSetE() throws Exception {
setConfigNotification("E");
this.initializer.afterPropertiesSet();
@@ -85,7 +88,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetK() throws Exception {
void afterPropertiesSetK() throws Exception {
setConfigNotification("K");
this.initializer.afterPropertiesSet();
@@ -94,7 +97,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetAE() throws Exception {
void afterPropertiesSetAE() throws Exception {
setConfigNotification("AE");
this.initializer.afterPropertiesSet();
@@ -103,7 +106,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetAK() throws Exception {
void afterPropertiesSetAK() throws Exception {
setConfigNotification("AK");
this.initializer.afterPropertiesSet();
@@ -112,7 +115,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetEK() throws Exception {
void afterPropertiesSetEK() throws Exception {
setConfigNotification("EK");
this.initializer.afterPropertiesSet();
@@ -121,7 +124,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetEg() throws Exception {
void afterPropertiesSetEg() throws Exception {
setConfigNotification("Eg");
this.initializer.afterPropertiesSet();
@@ -130,7 +133,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetE$() throws Exception {
void afterPropertiesSetE$() throws Exception {
setConfigNotification("E$");
this.initializer.afterPropertiesSet();
@@ -139,7 +142,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetKg() throws Exception {
void afterPropertiesSetKg() throws Exception {
setConfigNotification("Kg");
this.initializer.afterPropertiesSet();
@@ -148,7 +151,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
@Test
public void afterPropertiesSetAEK() throws Exception {
void afterPropertiesSetAEK() throws Exception {
setConfigNotification("AEK");
this.initializer.afterPropertiesSet();
@@ -157,8 +160,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
}
private void assertOptionsContains(String... expectedValues) {
verify(this.connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS),
this.options.capture());
verify(this.connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), this.options.capture());
for (String expectedValue : expectedValues) {
assertThat(this.options.getValue()).contains(expectedValue);
}
@@ -168,7 +170,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests {
private void setConfigNotification(String value) {
Properties properties = new Properties();
properties.setProperty(CONFIG_NOTIFY_KEYSPACE_EVENTS, value);
given(this.connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS))
.willReturn(properties);
given(this.connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)).willReturn(properties);
}
}

View File

@@ -41,7 +41,7 @@ public class RedisHttpSessionConfigurationClassPathXmlApplicationContextTests {
// gh-318
@Test
public void contextLoads() {
void contextLoads() {
}
static RedisConnectionFactory connectionFactory() {
@@ -52,4 +52,5 @@ public class RedisHttpSessionConfigurationClassPathXmlApplicationContextTests {
return factory;
}
}

View File

@@ -32,23 +32,25 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
public class RedisHttpSessionConfigurationMockTests {
class RedisHttpSessionConfigurationMockTests {
@Mock
RedisConnectionFactory factory;
@Mock
RedisConnection connection;
@BeforeEach
public void setup() {
void setup() {
MockitoAnnotations.initMocks(this);
given(this.factory.getConnection()).willReturn(this.connection);
}
@Test
public void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenNoOpThenNoInteractionWithConnectionFactory()
void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenNoOpThenNoInteractionWithConnectionFactory()
throws Exception {
EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(
this.factory, ConfigureRedisAction.NO_OP);
EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(this.factory,
ConfigureRedisAction.NO_OP);
init.afterPropertiesSet();
@@ -56,13 +58,13 @@ public class RedisHttpSessionConfigurationMockTests {
}
@Test
public void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenExceptionThenCloseConnection()
void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenExceptionThenCloseConnection()
throws Exception {
ConfigureRedisAction action = mock(ConfigureRedisAction.class);
willThrow(new RuntimeException()).given(action).configure(this.connection);
EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(
this.factory, action);
EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(this.factory,
action);
try {
init.afterPropertiesSet();
@@ -75,15 +77,16 @@ public class RedisHttpSessionConfigurationMockTests {
}
@Test
public void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenNoExceptionThenCloseConnection()
void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenNoExceptionThenCloseConnection()
throws Exception {
ConfigureRedisAction action = mock(ConfigureRedisAction.class);
EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(
this.factory, action);
EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(this.factory,
action);
init.afterPropertiesSet();
verify(this.connection).close();
}
}

View File

@@ -35,10 +35,10 @@ import static org.mockito.Mockito.mock;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests {
class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests {
@Test
public void redisConnectionFactoryNotUsedSinceNoValidation() {
void redisConnectionFactoryNotUsedSinceNoValidation() {
}
@EnableRedisHttpSession
@@ -54,5 +54,7 @@ public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests {
public RedisConnectionFactory redisConnectionFactory() {
return mock(RedisConnectionFactory.class);
}
}
}

View File

@@ -46,7 +46,7 @@ import static org.mockito.Mockito.mock;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests {
class RedisHttpSessionConfigurationOverrideDefaultSerializerTests {
@SpringSessionRedisOperations
RedisTemplate<Object, Object> template;
@@ -55,14 +55,14 @@ public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests {
RedisSerializer<Object> defaultRedisSerializer;
@Test
public void overrideDefaultRedisTemplate() {
assertThat(this.template.getDefaultSerializer())
.isSameAs(this.defaultRedisSerializer);
void overrideDefaultRedisTemplate() {
assertThat(this.template.getDefaultSerializer()).isSameAs(this.defaultRedisSerializer);
}
@EnableRedisHttpSession
@Configuration
static class Config {
@Bean
@SuppressWarnings("unchecked")
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
@@ -78,5 +78,7 @@ public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests {
return factory;
}
}
}

View File

@@ -47,7 +47,7 @@ import static org.mockito.Mockito.verify;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor {
class RedisHttpSessionConfigurationOverrideSessionTaskExecutor {
@Autowired
RedisMessageListenerContainer redisMessageListenerContainer;
@@ -56,14 +56,14 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor {
Executor springSessionRedisTaskExecutor;
@Test
public void overrideSessionTaskExecutor() {
verify(this.springSessionRedisTaskExecutor, times(1))
.execute(any(SchedulingAwareRunnable.class));
void overrideSessionTaskExecutor() {
verify(this.springSessionRedisTaskExecutor, times(1)).execute(any(SchedulingAwareRunnable.class));
}
@EnableRedisHttpSession
@Configuration
static class Config {
@Bean
public Executor springSessionRedisTaskExecutor() {
return mock(Executor.class);
@@ -78,5 +78,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor {
return factory;
}
}
}

View File

@@ -49,7 +49,7 @@ import static org.mockito.Mockito.verify;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors {
class RedisHttpSessionConfigurationOverrideSessionTaskExecutors {
@Autowired
RedisMessageListenerContainer redisMessageListenerContainer;
@@ -61,15 +61,15 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors {
Executor springSessionRedisSubscriptionExecutor;
@Test
public void overrideSessionTaskExecutors() {
verify(this.springSessionRedisSubscriptionExecutor, times(1))
.execute(any(SchedulingAwareRunnable.class));
void overrideSessionTaskExecutors() {
verify(this.springSessionRedisSubscriptionExecutor, times(1)).execute(any(SchedulingAwareRunnable.class));
verify(this.springSessionRedisTaskExecutor, never()).execute(any(Runnable.class));
}
@EnableRedisHttpSession
@Configuration
static class Config {
@Bean
public Executor springSessionRedisTaskExecutor() {
return mock(Executor.class);
@@ -89,5 +89,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors {
return factory;
}
}
}

View File

@@ -51,156 +51,137 @@ import static org.mockito.Mockito.mock;
* @author Mark Paluch
* @author Vedran Pavic
*/
public class RedisHttpSessionConfigurationTests {
class RedisHttpSessionConfigurationTests {
private static final String CLEANUP_CRON_EXPRESSION = "0 0 * * * *";
private AnnotationConfigApplicationContext context;
@BeforeEach
public void before() {
void before() {
this.context = new AnnotationConfigApplicationContext();
}
@AfterEach
public void after() {
void after() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void resolveValue() {
void resolveValue() {
registerAndRefresh(RedisConfig.class, CustomRedisHttpSessionConfiguration.class);
RedisHttpSessionConfiguration configuration = this.context
.getBean(RedisHttpSessionConfiguration.class);
assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace"))
.isEqualTo("myRedisNamespace");
RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class);
assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace")).isEqualTo("myRedisNamespace");
}
@Test
public void resolveValueByPlaceholder() {
this.context.setEnvironment(new MockEnvironment()
.withProperty("session.redis.namespace", "customRedisNamespace"));
void resolveValueByPlaceholder() {
this.context
.setEnvironment(new MockEnvironment().withProperty("session.redis.namespace", "customRedisNamespace"));
registerAndRefresh(RedisConfig.class, PropertySourceConfiguration.class,
CustomRedisHttpSessionConfiguration2.class);
RedisHttpSessionConfiguration configuration = this.context
.getBean(RedisHttpSessionConfiguration.class);
assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace"))
.isEqualTo("customRedisNamespace");
RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class);
assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace")).isEqualTo("customRedisNamespace");
}
@Test
public void customCleanupCronAnnotation() {
registerAndRefresh(RedisConfig.class,
CustomCleanupCronExpressionAnnotationConfiguration.class);
void customCleanupCronAnnotation() {
registerAndRefresh(RedisConfig.class, CustomCleanupCronExpressionAnnotationConfiguration.class);
RedisHttpSessionConfiguration configuration = this.context
.getBean(RedisHttpSessionConfiguration.class);
RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class);
assertThat(configuration).isNotNull();
assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron"))
.isEqualTo(CLEANUP_CRON_EXPRESSION);
assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")).isEqualTo(CLEANUP_CRON_EXPRESSION);
}
@Test
public void customCleanupCronSetter() {
registerAndRefresh(RedisConfig.class,
CustomCleanupCronExpressionSetterConfiguration.class);
void customCleanupCronSetter() {
registerAndRefresh(RedisConfig.class, CustomCleanupCronExpressionSetterConfiguration.class);
RedisHttpSessionConfiguration configuration = this.context
.getBean(RedisHttpSessionConfiguration.class);
RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class);
assertThat(configuration).isNotNull();
assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron"))
.isEqualTo(CLEANUP_CRON_EXPRESSION);
assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")).isEqualTo(CLEANUP_CRON_EXPRESSION);
}
@Test
public void qualifiedConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class,
QualifiedConnectionFactoryRedisConfig.class);
void qualifiedConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class, QualifiedConnectionFactoryRedisConfig.class);
RedisOperationsSessionRepository repository = this.context
.getBean(RedisOperationsSessionRepository.class);
RedisConnectionFactory redisConnectionFactory = this.context
.getBean("qualifiedRedisConnectionFactory", RedisConnectionFactory.class);
RedisOperationsSessionRepository repository = this.context.getBean(RedisOperationsSessionRepository.class);
RedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory",
RedisConnectionFactory.class);
assertThat(repository).isNotNull();
assertThat(redisConnectionFactory).isNotNull();
RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
}
@Test
public void primaryConnectionFactoryRedisConfig() {
void primaryConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class, PrimaryConnectionFactoryRedisConfig.class);
RedisOperationsSessionRepository repository = this.context
.getBean(RedisOperationsSessionRepository.class);
RedisConnectionFactory redisConnectionFactory = this.context
.getBean("primaryRedisConnectionFactory", RedisConnectionFactory.class);
RedisOperationsSessionRepository repository = this.context.getBean(RedisOperationsSessionRepository.class);
RedisConnectionFactory redisConnectionFactory = this.context.getBean("primaryRedisConnectionFactory",
RedisConnectionFactory.class);
assertThat(repository).isNotNull();
assertThat(redisConnectionFactory).isNotNull();
RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
}
@Test
public void qualifiedAndPrimaryConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class,
QualifiedAndPrimaryConnectionFactoryRedisConfig.class);
void qualifiedAndPrimaryConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class, QualifiedAndPrimaryConnectionFactoryRedisConfig.class);
RedisOperationsSessionRepository repository = this.context
.getBean(RedisOperationsSessionRepository.class);
RedisConnectionFactory redisConnectionFactory = this.context
.getBean("qualifiedRedisConnectionFactory", RedisConnectionFactory.class);
RedisOperationsSessionRepository repository = this.context.getBean(RedisOperationsSessionRepository.class);
RedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory",
RedisConnectionFactory.class);
assertThat(repository).isNotNull();
assertThat(redisConnectionFactory).isNotNull();
RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
}
@Test
public void namedConnectionFactoryRedisConfig() {
void namedConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class, NamedConnectionFactoryRedisConfig.class);
RedisOperationsSessionRepository repository = this.context
.getBean(RedisOperationsSessionRepository.class);
RedisConnectionFactory redisConnectionFactory = this.context
.getBean("redisConnectionFactory", RedisConnectionFactory.class);
RedisOperationsSessionRepository repository = this.context.getBean(RedisOperationsSessionRepository.class);
RedisConnectionFactory redisConnectionFactory = this.context.getBean("redisConnectionFactory",
RedisConnectionFactory.class);
assertThat(repository).isNotNull();
assertThat(redisConnectionFactory).isNotNull();
RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
}
@Test
public void multipleConnectionFactoryRedisConfig() {
void multipleConnectionFactoryRedisConfig() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> registerAndRefresh(RedisConfig.class,
MultipleConnectionFactoryRedisConfig.class))
.isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class))
.withMessageContaining("expected single matching bean but found 2");
}
@Test // gh-1252
public void customRedisMessageListenerContainerConfig() {
registerAndRefresh(RedisConfig.class,
CustomRedisMessageListenerContainerConfig.class);
void customRedisMessageListenerContainerConfig() {
registerAndRefresh(RedisConfig.class, CustomRedisMessageListenerContainerConfig.class);
Map<String, RedisMessageListenerContainer> beans = this.context
.getBeansOfType(RedisMessageListenerContainer.class);
assertThat(beans).hasSize(2);
assertThat(beans).containsKeys("springSessionRedisMessageListenerContainer",
"redisMessageListenerContainer");
assertThat(beans).containsKeys("springSessionRedisMessageListenerContainer", "redisMessageListenerContainer");
}
private void registerAndRefresh(Class<?>... annotatedClasses) {
@@ -242,8 +223,7 @@ public class RedisHttpSessionConfigurationTests {
}
@Configuration
static class CustomCleanupCronExpressionSetterConfiguration
extends RedisHttpSessionConfiguration {
static class CustomCleanupCronExpressionSetterConfiguration extends RedisHttpSessionConfiguration {
CustomCleanupCronExpressionSetterConfiguration() {
setCleanupCron(CLEANUP_CRON_EXPRESSION);

View File

@@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock;
public class RedisHttpSessionConfigurationXmlCustomExpireTests {
@Test
public void contextLoads() {
void contextLoads() {
}
static RedisConnectionFactory connectionFactory() {
@@ -48,4 +48,5 @@ public class RedisHttpSessionConfigurationXmlCustomExpireTests {
return factory;
}
}

View File

@@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock;
public class RedisHttpSessionConfigurationXmlTests {
@Test
public void contextLoads() {
void contextLoads() {
}
static RedisConnectionFactory connectionFactory() {
@@ -48,4 +48,5 @@ public class RedisHttpSessionConfigurationXmlTests {
return factory;
}
}

View File

@@ -47,10 +47,10 @@ import static org.mockito.Mockito.mock;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class Gh109Tests {
class Gh109Tests {
@Test
public void loads() {
void loads() {
}
@@ -63,8 +63,7 @@ public class Gh109Tests {
* override sessionRepository construction to set the custom session-timeout
*/
@Bean
public RedisOperationsSessionRepository sessionRepository(
RedisOperations<Object, Object> sessionRedisTemplate,
public RedisOperationsSessionRepository sessionRepository(RedisOperations<Object, Object> sessionRedisTemplate,
ApplicationEventPublisher applicationEventPublisher) {
RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(
sessionRedisTemplate);
@@ -80,5 +79,7 @@ public class Gh109Tests {
given(connection.getConfig(anyString())).willReturn(new Properties());
return factory;
}
}
}

View File

@@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock;
*
* @author Vedran Pavic
*/
public class RedisWebSessionConfigurationTests {
class RedisWebSessionConfigurationTests {
private static final String REDIS_NAMESPACE = "testNamespace";
@@ -53,19 +53,19 @@ public class RedisWebSessionConfigurationTests {
private AnnotationConfigApplicationContext context;
@BeforeEach
public void before() {
void before() {
this.context = new AnnotationConfigApplicationContext();
}
@AfterEach
public void after() {
void after() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void defaultConfiguration() {
void defaultConfiguration() {
registerAndRefresh(RedisConfig.class, DefaultConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
@@ -74,34 +74,31 @@ public class RedisWebSessionConfigurationTests {
}
@Test
public void springSessionRedisOperationsResolvingConfiguration() {
registerAndRefresh(RedisConfig.class,
SpringSessionRedisOperationsResolvingConfig.class);
void springSessionRedisOperationsResolvingConfiguration() {
registerAndRefresh(RedisConfig.class, SpringSessionRedisOperationsResolvingConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
.getBean(ReactiveRedisOperationsSessionRepository.class);
assertThat(repository).isNotNull();
ReactiveRedisOperations<String, Object> springSessionRedisOperations = this.context
.getBean(SpringSessionRedisOperationsResolvingConfig.class)
.getSpringSessionRedisOperations();
.getBean(SpringSessionRedisOperationsResolvingConfig.class).getSpringSessionRedisOperations();
assertThat(springSessionRedisOperations).isNotNull();
assertThat((ReactiveRedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations")).isEqualTo(springSessionRedisOperations);
assertThat((ReactiveRedisOperations) ReflectionTestUtils.getField(repository, "sessionRedisOperations"))
.isEqualTo(springSessionRedisOperations);
}
@Test
public void customNamespace() {
void customNamespace() {
registerAndRefresh(RedisConfig.class, CustomNamespaceConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
.getBean(ReactiveRedisOperationsSessionRepository.class);
assertThat(repository).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "namespace"))
.isEqualTo(REDIS_NAMESPACE + ":");
assertThat(ReflectionTestUtils.getField(repository, "namespace")).isEqualTo(REDIS_NAMESPACE + ":");
}
@Test
public void customMaxInactiveInterval() {
void customMaxInactiveInterval() {
registerAndRefresh(RedisConfig.class, CustomMaxInactiveIntervalConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
@@ -112,121 +109,112 @@ public class RedisWebSessionConfigurationTests {
}
@Test
public void customFlushMode() {
void customFlushMode() {
registerAndRefresh(RedisConfig.class, CustomFlushModeConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
.getBean(ReactiveRedisOperationsSessionRepository.class);
assertThat(repository).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "redisFlushMode"))
.isEqualTo(RedisFlushMode.IMMEDIATE);
assertThat(ReflectionTestUtils.getField(repository, "redisFlushMode")).isEqualTo(RedisFlushMode.IMMEDIATE);
}
@Test
public void qualifiedConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class,
QualifiedConnectionFactoryRedisConfig.class);
void qualifiedConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class, QualifiedConnectionFactoryRedisConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
.getBean(ReactiveRedisOperationsSessionRepository.class);
ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean(
"qualifiedRedisConnectionFactory", ReactiveRedisConnectionFactory.class);
ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory",
ReactiveRedisConnectionFactory.class);
assertThat(repository).isNotNull();
assertThat(redisConnectionFactory).isNotNull();
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
}
@Test
public void primaryConnectionFactoryRedisConfig() {
void primaryConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class, PrimaryConnectionFactoryRedisConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
.getBean(ReactiveRedisOperationsSessionRepository.class);
ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean(
"primaryRedisConnectionFactory", ReactiveRedisConnectionFactory.class);
ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean("primaryRedisConnectionFactory",
ReactiveRedisConnectionFactory.class);
assertThat(repository).isNotNull();
assertThat(redisConnectionFactory).isNotNull();
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
}
@Test
public void qualifiedAndPrimaryConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class,
QualifiedAndPrimaryConnectionFactoryRedisConfig.class);
void qualifiedAndPrimaryConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class, QualifiedAndPrimaryConnectionFactoryRedisConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
.getBean(ReactiveRedisOperationsSessionRepository.class);
ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean(
"qualifiedRedisConnectionFactory", ReactiveRedisConnectionFactory.class);
ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory",
ReactiveRedisConnectionFactory.class);
assertThat(repository).isNotNull();
assertThat(redisConnectionFactory).isNotNull();
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
}
@Test
public void namedConnectionFactoryRedisConfig() {
void namedConnectionFactoryRedisConfig() {
registerAndRefresh(RedisConfig.class, NamedConnectionFactoryRedisConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
.getBean(ReactiveRedisOperationsSessionRepository.class);
ReactiveRedisConnectionFactory redisConnectionFactory = this.context
.getBean("redisConnectionFactory", ReactiveRedisConnectionFactory.class);
ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean("redisConnectionFactory",
ReactiveRedisConnectionFactory.class);
assertThat(repository).isNotNull();
assertThat(redisConnectionFactory).isNotNull();
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
}
@Test
public void multipleConnectionFactoryRedisConfig() {
void multipleConnectionFactoryRedisConfig() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> registerAndRefresh(RedisConfig.class,
MultipleConnectionFactoryRedisConfig.class))
.isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class))
.withMessageContaining("expected single matching bean but found 2");
}
@Test
@SuppressWarnings("unchecked")
public void customRedisSerializerConfig() {
void customRedisSerializerConfig() {
registerAndRefresh(RedisConfig.class, CustomRedisSerializerConfig.class);
ReactiveRedisOperationsSessionRepository repository = this.context
.getBean(ReactiveRedisOperationsSessionRepository.class);
RedisSerializer<Object> redisSerializer = this.context
.getBean("springSessionDefaultRedisSerializer", RedisSerializer.class);
RedisSerializer<Object> redisSerializer = this.context.getBean("springSessionDefaultRedisSerializer",
RedisSerializer.class);
assertThat(repository).isNotNull();
assertThat(redisSerializer).isNotNull();
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository,
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
RedisSerializationContext serializationContext = redisOperations
.getSerializationContext();
assertThat(ReflectionTestUtils.getField(
serializationContext.getValueSerializationPair().getReader(),
RedisSerializationContext serializationContext = redisOperations.getSerializationContext();
assertThat(ReflectionTestUtils.getField(serializationContext.getValueSerializationPair().getReader(),
"serializer")).isEqualTo(redisSerializer);
assertThat(ReflectionTestUtils.getField(
serializationContext.getValueSerializationPair().getWriter(),
assertThat(ReflectionTestUtils.getField(serializationContext.getValueSerializationPair().getWriter(),
"serializer")).isEqualTo(redisSerializer);
assertThat(ReflectionTestUtils.getField(
serializationContext.getHashValueSerializationPair().getReader(),
assertThat(ReflectionTestUtils.getField(serializationContext.getHashValueSerializationPair().getReader(),
"serializer")).isEqualTo(redisSerializer);
assertThat(ReflectionTestUtils.getField(
serializationContext.getHashValueSerializationPair().getWriter(),
assertThat(ReflectionTestUtils.getField(serializationContext.getHashValueSerializationPair().getWriter(),
"serializer")).isEqualTo(redisSerializer);
}
@@ -256,7 +244,7 @@ public class RedisWebSessionConfigurationTests {
@SpringSessionRedisOperations
private ReactiveRedisOperations<String, Object> springSessionRedisOperations;
public ReactiveRedisOperations<String, Object> getSpringSessionRedisOperations() {
ReactiveRedisOperations<String, Object> getSpringSessionRedisOperations() {
return this.springSessionRedisOperations;
}