refactor: Introduced `AbstractStorageStrategyIT` as base for more tests
[demos/kafka/chat] / src / test / java / de / juplo / kafka / chat / backend / persistence / LocalJsonFilesStorageStrategyIT.java
1 package de.juplo.kafka.chat.backend.persistence;
2
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import com.fasterxml.jackson.databind.SerializationFeature;
5 import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
6 import de.juplo.kafka.chat.backend.domain.ChatHomeService;
7 import lombok.extern.slf4j.Slf4j;
8 import org.junit.jupiter.api.BeforeEach;
9
10 import java.io.IOException;
11 import java.nio.file.Files;
12 import java.nio.file.Path;
13 import java.nio.file.Paths;
14 import java.time.Clock;
15 import java.util.function.Supplier;
16
17
18 @Slf4j
19 public class LocalJsonFilesStorageStrategyIT extends AbstractStorageStrategyIT
20 {
21   final static Path path = Paths.get("target","local-json-files");
22
23   final Clock clock;
24   final ObjectMapper mapper;
25   final LocalJsonFilesStorageStrategy storageStrategy;
26
27
28   public LocalJsonFilesStorageStrategyIT()
29   {
30     clock = Clock.systemDefaultZone();
31     mapper = new ObjectMapper();
32     mapper.registerModule(new JavaTimeModule());
33     mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
34     storageStrategy = new LocalJsonFilesStorageStrategy(path, clock, 8, mapper);
35
36   }
37
38
39   @Override
40   StorageStrategy getStorageStrategy()
41   {
42     return storageStrategy;
43   }
44
45   @Override
46   Supplier<ChatHomeService> chatHomeServiceSupplier()
47   {
48     return () -> new InMemoryChatHomeService(getStorageStrategy().readChatrooms(), clock, 8);
49   }
50
51   @BeforeEach
52   void reset() throws Exception
53   {
54     if (Files.exists(path))
55     {
56       Files
57           .walk(path)
58           .forEach(file ->
59           {
60             try
61             {
62               if (!file.equals(path))
63               {
64                 log.debug("Deleting file {}", file);
65                 Files.delete(file);
66               }
67             }
68             catch (IOException e)
69             {
70               throw new RuntimeException(e);
71             }
72           });
73       log.debug("Deleting data-directory {}", path);
74       Files.delete(path);
75     }
76   }
77 }