package com.ruoyi.framework.web.service;
|
|
import com.ruoyi.common.core.domain.model.LoginUser;
|
import com.ruoyi.common.core.redis.RedisCache;
|
import com.ruoyi.common.constant.CacheConstants;
|
|
import java.lang.reflect.Field;
|
import java.lang.reflect.Method;
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.concurrent.TimeUnit;
|
|
/**
|
* 中台 Token 独立 Redis 登录态回归测试。
|
*/
|
public class TokenServiceMiddlePlatformTokenTest
|
{
|
private static final String LOGIN_TOKEN = "login-token";
|
private static final String MIDDLE_PLATFORM_TOKEN = "middle-token";
|
|
public static void main(String[] args) throws Exception
|
{
|
MemoryRedisCache redisCache = new MemoryRedisCache();
|
TokenService tokenService = new TokenService();
|
setField(tokenService, "redisCache", redisCache);
|
setField(tokenService, "expireTime", 30);
|
|
LoginUser loginUser = new LoginUser();
|
loginUser.setToken(LOGIN_TOKEN);
|
loginUser.setMiddlePlatformToken(MIDDLE_PLATFORM_TOKEN);
|
invoke(tokenService, "cacheMiddlePlatformToken",
|
new Class<?>[] { LoginUser.class }, loginUser);
|
|
LoginUser restored = new LoginUser();
|
invoke(tokenService, "restoreMiddlePlatformToken",
|
new Class<?>[] { LoginUser.class, String.class }, restored, LOGIN_TOKEN);
|
require(MIDDLE_PLATFORM_TOKEN.equals(restored.getMiddlePlatformToken()),
|
"未从独立 Redis 键恢复中台 Token");
|
|
tokenService.delLoginUser(LOGIN_TOKEN);
|
require(!redisCache.values.containsKey(CacheConstants.MIDDLE_PLATFORM_TOKEN_KEY + LOGIN_TOKEN),
|
"退出登录时未删除中台 Token");
|
}
|
|
private static void setField(Object target, String name, Object value) throws Exception
|
{
|
Field field = target.getClass().getDeclaredField(name);
|
field.setAccessible(true);
|
field.set(target, value);
|
}
|
|
private static void invoke(Object target, String name, Class<?>[] parameterTypes,
|
Object... arguments) throws Exception
|
{
|
Method method = target.getClass().getDeclaredMethod(name, parameterTypes);
|
method.setAccessible(true);
|
method.invoke(target, arguments);
|
}
|
|
private static void require(boolean condition, String message)
|
{
|
if (!condition)
|
{
|
throw new AssertionError(message);
|
}
|
}
|
|
private static final class MemoryRedisCache extends RedisCache
|
{
|
private final Map<String, Object> values = new HashMap<>();
|
|
@Override
|
public <T> void setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit)
|
{
|
values.put(key, value);
|
}
|
|
@SuppressWarnings("unchecked")
|
@Override
|
public <T> T getCacheObject(String key)
|
{
|
return (T) values.get(key);
|
}
|
|
@Override
|
public boolean deleteObject(String key)
|
{
|
return values.remove(key) != null;
|
}
|
}
|
}
|