MCPcopy Create free account
hub / github.com/InterviewReady/Low-Level-Design / TestCache

Class TestCache

distributed-cache/src/test/java/TestCache.java:20–366  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

18import java.util.stream.Collectors;
19
20public class TestCache {
21
22 private static final String PROFILE_MUMBAI_ENGINEER = "profile_mumbai_engineer", PROFILE_HYDERABAD_ENGINEER = "profile_hyderabad_engineer";
23 private final Map<String, String> dataMap = new ConcurrentHashMap<>();
24 private final Queue<CompletableFuture<Void>> writeOperations = new LinkedList<>();
25 private DataSource<String, String> dataSource;
26 private DataSource<String, String> writeBackDataSource;
27
28 @Before
29 public void setUp() {
30 dataMap.clear();
31 writeOperations.clear();
32 dataMap.put(PROFILE_MUMBAI_ENGINEER, "violet");
33 dataMap.put(PROFILE_HYDERABAD_ENGINEER, "blue");
34 dataSource = new DataSource<>() {
35 @Override
36 public CompletionStage<String> load(String key) {
37 if (dataMap.containsKey(key)) {
38 return CompletableFuture.completedFuture(dataMap.get(key));
39 } else {
40 return CompletableFuture.failedStage(new NullPointerException());
41 }
42 }
43
44 @Override
45 public CompletionStage<Void> persist(String key, String value, long timestamp) {
46 dataMap.put(key, value);
47 return CompletableFuture.completedFuture(null);
48 }
49 };
50
51 writeBackDataSource = new DataSource<>() {
52 @Override
53 public CompletionStage<String> load(String key) {
54 if (dataMap.containsKey(key)) {
55 return CompletableFuture.completedFuture(dataMap.get(key));
56 } else {
57 return CompletableFuture.failedStage(new NullPointerException());
58 }
59 }
60
61 @Override
62 public CompletionStage<Void> persist(String key, String value, long timestamp) {
63 final CompletableFuture<Void> hold = new CompletableFuture<>();
64 writeOperations.add(hold);
65 return hold.thenAccept(__ -> dataMap.put(key, value));
66 }
67 };
68 }
69
70 private void acceptWrite() {
71 final CompletableFuture<Void> write = writeOperations.poll();
72 if (write != null) {
73 write.complete(null);
74 }
75 }
76
77 @Test(expected = IllegalArgumentException.class)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected