Skip to content

Instantly share code, notes, and snippets.

@kamatama41
Created November 25, 2012 15:44
Show Gist options
  • Save kamatama41/4144106 to your computer and use it in GitHub Desktop.
Save kamatama41/4144106 to your computer and use it in GitHub Desktop.
package com.kamatama41.sandbox4j;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class DistributedCacheTest {
private DistributedCache cache;
@Before
public void setUp() {
List<String> nodes = Arrays.asList("a", "b", "c", "d", "e", "f");
cache = new DistributedCache(nodes);
// put 0-99
for (int i = 0; i < 100; i++) {
cache.put(i, "value"+i);
}
System.out.println("--------------------");
printNodeCounts(100, "before");
}
@Test
public void testGet() {
distributedCheck();
}
@Test
public void testAddNode() {
cache.addNode("g");
distributedCheck();
}
@Test
public void testAddNode_someNodeKey() {
cache.addNode("a");
distributedCheck();
}
@Test
public void testRemoveNode() {
cache.removeNode("a");
distributedCheck();
}
@Test
public void testRemoveNode_notExistNode() {
cache.removeNode("z");
distributedCheck();
}
private void distributedCheck() {
printNodeCounts(100, "0-99 ");
for (int i = 0; i < 100; i++) {
assertThat((String)cache.get(i), is("value"+i));
}
// put 100-199
for (int i = 100; i < 200; i++) {
cache.put(i, "value"+i);
}
printNodeCounts(200, "0-200 ");
for (int i = 0; i < 200; i++) {
assertThat((String)cache.get(i), is("value"+i));
}
}
private void printNodeCounts(int count, String situation) {
Map<String, Integer> nodeCounts = new HashMap<>();
for (int i = 0; i < count; i++) {
String node = cache.getNode(i);
Integer nodeCount = nodeCounts.get(node);
if(nodeCount == null) {
nodeCount = 0;
}
nodeCounts.put(node, nodeCount+1);
}
System.out.println("[" + situation + "]:" + nodeCounts);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment