Fix the problem jsonToCacheWrapper crashes when cache value is not JSON format (#1695)

* fix: json to cache wrapper convertor when other exception

* feat: Add test case for level cache
pull/1697/head^2
guqing 2022-03-02 18:06:54 +08:00 committed by GitHub
parent 4354991a9e
commit 52b3e4f605
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 2 deletions

View File

@ -1,6 +1,7 @@
package run.halo.app.cache;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@ -22,8 +23,8 @@ public abstract class AbstractStringCacheStore extends AbstractCacheStore<String
Assert.hasText(json, "json value must not be null");
CacheWrapper<String> cacheWrapper = null;
try {
cacheWrapper = JsonUtils.jsonToObject(json, CacheWrapper.class);
} catch (IOException e) {
cacheWrapper = JsonUtils.jsonToObject(json, new TypeReference<>() {});
} catch (Exception e) {
log.debug("Failed to convert json to wrapper value bytes: [{}]", json, e);
}
return Optional.ofNullable(cacheWrapper);

View File

@ -0,0 +1,55 @@
package run.halo.app.cache;
import static org.assertj.core.api.Assertions.assertThat;
import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import org.iq80.leveldb.DB;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import run.halo.app.config.properties.HaloProperties;
import run.halo.app.utils.FileUtils;
/**
* @author guqing
* @date 2022-03-02
*/
public class LevelCacheStoreTest {
LevelCacheStore cacheStore;
HaloProperties haloProperties = new HaloProperties();
@BeforeEach
void setUp() throws IOException {
String testDir = FileUtils.createTempDirectory().toString();
System.out.println(testDir);
haloProperties.setWorkDir(testDir + FILE_SEPARATOR);
cacheStore = new LevelCacheStore(haloProperties);
cacheStore.init();
}
@Test
public void corruptCacheStructureTest() {
cacheStore.put("A", "B");
// Simulate corrupt cache structure
DB levelDb = (DB) ReflectionTestUtils.getField(cacheStore, "LEVEL_DB");
levelDb.put("B".getBytes(StandardCharsets.UTF_8),
"NOT_JSON".getBytes(StandardCharsets.UTF_8));
Optional<CacheWrapper> bOpt = cacheStore.getAny("B", CacheWrapper.class);
assertThat(bOpt).isNotNull();
assertThat(bOpt.isEmpty()).isTrue();
assertThat(cacheStore.toMap().toString()).isEqualTo("{A=B, B=null}");
}
@AfterEach
public void cleanUp() {
cacheStore.delete("A");
cacheStore.delete("B");
}
}