2 * Copyright 2015 Open Networking Laboratory
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.onosproject.store.ecmap;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
24 import java.util.Objects;
25 import java.util.Optional;
27 import java.util.concurrent.CompletableFuture;
28 import java.util.concurrent.CountDownLatch;
29 import java.util.concurrent.Executor;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.atomic.AtomicLong;
32 import java.util.function.Consumer;
33 import java.util.function.Function;
35 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Test;
38 import org.onlab.packet.IpAddress;
39 import org.onlab.util.KryoNamespace;
40 import org.onosproject.cluster.ClusterService;
41 import org.onosproject.cluster.ControllerNode;
42 import org.onosproject.cluster.DefaultControllerNode;
43 import org.onosproject.cluster.NodeId;
44 import org.onosproject.event.AbstractEvent;
45 import org.onosproject.persistence.impl.PersistenceManager;
46 import org.onosproject.store.Timestamp;
47 import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
48 import org.onosproject.store.cluster.messaging.ClusterCommunicationServiceAdapter;
49 import org.onosproject.store.cluster.messaging.MessageSubject;
50 import org.onosproject.store.impl.LogicalTimestamp;
51 import org.onosproject.store.serializers.KryoNamespaces;
52 import org.onosproject.store.serializers.KryoSerializer;
53 import org.onosproject.store.service.EventuallyConsistentMap;
54 import org.onosproject.store.service.EventuallyConsistentMapEvent;
55 import org.onosproject.store.service.EventuallyConsistentMapListener;
56 import org.onosproject.store.service.WallClockTimestamp;
58 import com.google.common.collect.ComparisonChain;
59 import com.google.common.collect.ImmutableList;
60 import com.google.common.collect.ImmutableSet;
61 import com.google.common.util.concurrent.MoreExecutors;
63 import static com.google.common.base.Preconditions.checkArgument;
64 import static junit.framework.TestCase.assertFalse;
65 import static org.easymock.EasyMock.anyObject;
66 import static org.easymock.EasyMock.createMock;
67 import static org.easymock.EasyMock.eq;
68 import static org.easymock.EasyMock.expect;
69 import static org.easymock.EasyMock.expectLastCall;
70 import static org.easymock.EasyMock.replay;
71 import static org.easymock.EasyMock.reset;
72 import static org.easymock.EasyMock.verify;
73 import static org.junit.Assert.assertEquals;
74 import static org.junit.Assert.assertNull;
75 import static org.junit.Assert.assertTrue;
76 import static org.junit.Assert.fail;
79 * Unit tests for EventuallyConsistentMapImpl.
81 public class EventuallyConsistentMapImplTest {
83 private EventuallyConsistentMap<String, String> ecMap;
85 private PersistenceManager persistenceService;
86 private ClusterService clusterService;
87 private ClusterCommunicationService clusterCommunicator;
88 private SequentialClockService<String, String> clockService;
90 private static final String MAP_NAME = "test";
91 private static final MessageSubject UPDATE_MESSAGE_SUBJECT
92 = new MessageSubject("ecm-" + MAP_NAME + "-update");
93 private static final MessageSubject ANTI_ENTROPY_MESSAGE_SUBJECT
94 = new MessageSubject("ecm-" + MAP_NAME + "-anti-entropy");
96 private static final String KEY1 = "one";
97 private static final String KEY2 = "two";
98 private static final String VALUE1 = "oneValue";
99 private static final String VALUE2 = "twoValue";
101 private final ControllerNode self =
102 new DefaultControllerNode(new NodeId("local"), IpAddress.valueOf(1));
104 private Consumer<Collection<UpdateEntry<String, String>>> updateHandler;
105 private Consumer<AntiEntropyAdvertisement<String>> antiEntropyHandler;
108 * Serialization is a bit tricky here. We need to serialize in the tests
109 * to set the expectations, which will use this serializer here, but the
110 * EventuallyConsistentMap will use its own internal serializer. This means
111 * this serializer must be set up exactly the same as map's internal
114 private static final KryoSerializer SERIALIZER = new KryoSerializer() {
116 protected void setupKryoPool() {
117 serializerPool = KryoNamespace.newBuilder()
118 // Classes we give to the map
119 .register(KryoNamespaces.API)
120 .register(TestTimestamp.class)
121 // Below is the classes that the map internally registers
122 .register(LogicalTimestamp.class)
123 .register(WallClockTimestamp.class)
124 .register(ArrayList.class)
125 .register(AntiEntropyAdvertisement.class)
126 .register(HashMap.class)
127 .register(Optional.class)
133 public void setUp() throws Exception {
134 clusterService = createMock(ClusterService.class);
135 expect(clusterService.getLocalNode()).andReturn(self).anyTimes();
136 expect(clusterService.getNodes()).andReturn(ImmutableSet.of(self)).anyTimes();
137 replay(clusterService);
139 clusterCommunicator = createMock(ClusterCommunicationService.class);
141 persistenceService = new PersistenceManager();
142 persistenceService.activate();
143 // Add expectation for adding cluster message subscribers which
144 // delegate to our ClusterCommunicationService implementation. This
145 // allows us to get a reference to the map's internal cluster message
146 // handlers so we can induce events coming in from a peer.
147 clusterCommunicator.<String>addSubscriber(anyObject(MessageSubject.class),
148 anyObject(Function.class), anyObject(Consumer.class), anyObject(Executor.class));
149 expectLastCall().andDelegateTo(new TestClusterCommunicationService()).times(2);
151 replay(clusterCommunicator);
153 clockService = new SequentialClockService<>();
155 KryoNamespace.Builder serializer = KryoNamespace.newBuilder()
156 .register(KryoNamespaces.API)
157 .register(TestTimestamp.class);
159 ecMap = new EventuallyConsistentMapBuilderImpl<String, String>(
160 clusterService, clusterCommunicator, persistenceService)
162 .withSerializer(serializer)
163 .withTimestampProvider((k, v) -> clockService.getTimestamp(k, v))
164 .withCommunicationExecutor(MoreExecutors.newDirectExecutorService())
168 // Reset ready for tests to add their own expectations
169 reset(clusterCommunicator);
173 public void tearDown() {
174 reset(clusterCommunicator);
178 @SuppressWarnings("unchecked")
179 private EventuallyConsistentMapListener<String, String> getListener() {
180 return createMock(EventuallyConsistentMapListener.class);
184 public void testSize() throws Exception {
185 expectPeerMessage(clusterCommunicator);
187 assertEquals(0, ecMap.size());
188 ecMap.put(KEY1, VALUE1);
189 assertEquals(1, ecMap.size());
190 ecMap.put(KEY1, VALUE2);
191 assertEquals(1, ecMap.size());
192 ecMap.put(KEY2, VALUE2);
193 assertEquals(2, ecMap.size());
194 for (int i = 0; i < 10; i++) {
195 ecMap.put("" + i, "" + i);
197 assertEquals(12, ecMap.size());
199 assertEquals(11, ecMap.size());
201 assertEquals(11, ecMap.size());
205 public void testIsEmpty() throws Exception {
206 expectPeerMessage(clusterCommunicator);
208 assertTrue(ecMap.isEmpty());
209 ecMap.put(KEY1, VALUE1);
210 assertFalse(ecMap.isEmpty());
212 assertTrue(ecMap.isEmpty());
216 public void testContainsKey() throws Exception {
217 expectPeerMessage(clusterCommunicator);
219 assertFalse(ecMap.containsKey(KEY1));
220 ecMap.put(KEY1, VALUE1);
221 assertTrue(ecMap.containsKey(KEY1));
222 assertFalse(ecMap.containsKey(KEY2));
224 assertFalse(ecMap.containsKey(KEY1));
228 public void testContainsValue() throws Exception {
229 expectPeerMessage(clusterCommunicator);
231 assertFalse(ecMap.containsValue(VALUE1));
232 ecMap.put(KEY1, VALUE1);
233 assertTrue(ecMap.containsValue(VALUE1));
234 assertFalse(ecMap.containsValue(VALUE2));
235 ecMap.put(KEY1, VALUE2);
236 assertFalse(ecMap.containsValue(VALUE1));
237 assertTrue(ecMap.containsValue(VALUE2));
239 assertFalse(ecMap.containsValue(VALUE2));
243 public void testGet() throws Exception {
244 expectPeerMessage(clusterCommunicator);
246 CountDownLatch latch;
249 assertNull(ecMap.get(KEY1));
250 ecMap.put(KEY1, VALUE1);
251 assertEquals(VALUE1, ecMap.get(KEY1));
254 List<UpdateEntry<String, String>> message
255 = ImmutableList.of(generatePutMessage(KEY2, VALUE2, clockService.getTimestamp(KEY2, VALUE2)));
257 // Create a latch so we know when the put operation has finished
258 latch = new CountDownLatch(1);
259 ecMap.addListener(new TestListener(latch));
261 assertNull(ecMap.get(KEY2));
262 updateHandler.accept(message);
263 assertTrue("External listener never got notified of internal event",
264 latch.await(100, TimeUnit.MILLISECONDS));
265 assertEquals(VALUE2, ecMap.get(KEY2));
269 assertNull(ecMap.get(KEY2));
272 message = ImmutableList.of(generateRemoveMessage(KEY1, clockService.getTimestamp(KEY1, VALUE1)));
274 // Create a latch so we know when the remove operation has finished
275 latch = new CountDownLatch(1);
276 ecMap.addListener(new TestListener(latch));
278 updateHandler.accept(message);
279 assertTrue("External listener never got notified of internal event",
280 latch.await(100, TimeUnit.MILLISECONDS));
281 assertNull(ecMap.get(KEY1));
285 public void testPut() throws Exception {
286 // Set up expectations of external events to be sent to listeners during
287 // the test. These don't use timestamps so we can set them all up at once.
288 EventuallyConsistentMapListener<String, String> listener
290 listener.event(new EventuallyConsistentMapEvent<>(
291 MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1));
292 listener.event(new EventuallyConsistentMapEvent<>(
293 MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE2));
296 ecMap.addListener(listener);
298 // Set up expected internal message to be broadcast to peers on first put
299 expectSpecificMulticastMessage(generatePutMessage(KEY1, VALUE1, clockService
300 .peekAtNextTimestamp()), UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
303 assertNull(ecMap.get(KEY1));
304 ecMap.put(KEY1, VALUE1);
305 assertEquals(VALUE1, ecMap.get(KEY1));
307 verify(clusterCommunicator);
309 // Set up expected internal message to be broadcast to peers on second put
310 expectSpecificMulticastMessage(generatePutMessage(
311 KEY1, VALUE2, clockService.peekAtNextTimestamp()), UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
313 // Update same key to a new value
314 ecMap.put(KEY1, VALUE2);
315 assertEquals(VALUE2, ecMap.get(KEY1));
317 verify(clusterCommunicator);
319 // Do a put with a older timestamp than the value already there.
320 // The map data should not be changed and no notifications should be sent.
321 reset(clusterCommunicator);
322 replay(clusterCommunicator);
324 clockService.turnBackTime();
325 ecMap.put(KEY1, VALUE1);
326 // Value should not have changed.
327 assertEquals(VALUE2, ecMap.get(KEY1));
329 verify(clusterCommunicator);
331 // Check that our listener received the correct events during the test
336 public void testRemove() throws Exception {
337 // Set up expectations of external events to be sent to listeners during
338 // the test. These don't use timestamps so we can set them all up at once.
339 EventuallyConsistentMapListener<String, String> listener
341 listener.event(new EventuallyConsistentMapEvent<>(
342 MAP_NAME, EventuallyConsistentMapEvent.Type.REMOVE, KEY1, VALUE1));
343 listener.event(new EventuallyConsistentMapEvent<>(
344 MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1));
345 listener.event(new EventuallyConsistentMapEvent<>(
346 MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY2, VALUE2));
349 ecMap.addListener(listener);
351 // Put in an initial value
352 expectPeerMessage(clusterCommunicator);
353 ecMap.put(KEY1, VALUE1);
354 assertEquals(VALUE1, ecMap.get(KEY1));
356 // Remove the value and check the correct internal cluster messages
358 expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()),
359 UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
362 assertNull(ecMap.get(KEY1));
364 verify(clusterCommunicator);
366 // Remove the same value again. Even though the value is no longer in
367 // the map, we expect that the tombstone is updated and another remove
368 // event is sent to the cluster and external listeners.
369 expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()),
370 UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
373 assertNull(ecMap.get(KEY1));
375 verify(clusterCommunicator);
378 // Put in a new value for us to try and remove
379 expectPeerMessage(clusterCommunicator);
381 ecMap.put(KEY2, VALUE2);
383 clockService.turnBackTime();
385 // Remove should have no effect, since it has an older timestamp than
386 // the put. Expect no notifications to be sent out
387 reset(clusterCommunicator);
388 replay(clusterCommunicator);
392 verify(clusterCommunicator);
394 // Check that our listener received the correct events during the test
399 public void testCompute() throws Exception {
400 // Set up expectations of external events to be sent to listeners during
401 // the test. These don't use timestamps so we can set them all up at once.
402 EventuallyConsistentMapListener<String, String> listener
404 listener.event(new EventuallyConsistentMapEvent<>(
405 MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1));
406 listener.event(new EventuallyConsistentMapEvent<>(
407 MAP_NAME, EventuallyConsistentMapEvent.Type.REMOVE, KEY1, VALUE1));
408 listener.event(new EventuallyConsistentMapEvent<>(
409 MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY2, VALUE2));
412 ecMap.addListener(listener);
414 // Put in an initial value
415 expectPeerMessage(clusterCommunicator);
416 ecMap.compute(KEY1, (k, v) -> VALUE1);
417 assertEquals(VALUE1, ecMap.get(KEY1));
419 // Remove the value and check the correct internal cluster messages
421 expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()),
422 UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
424 ecMap.compute(KEY1, (k, v) -> null);
425 assertNull(ecMap.get(KEY1));
427 verify(clusterCommunicator);
429 // Remove the same value again. Even though the value is no longer in
430 // the map, we expect that the tombstone is updated and another remove
431 // event is sent to the cluster and external listeners.
432 expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()),
433 UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
435 ecMap.compute(KEY1, (k, v) -> null);
436 assertNull(ecMap.get(KEY1));
438 verify(clusterCommunicator);
440 // Put in a new value for us to try and remove
441 expectPeerMessage(clusterCommunicator);
443 ecMap.compute(KEY2, (k, v) -> VALUE2);
445 clockService.turnBackTime();
447 // Remove should have no effect, since it has an older timestamp than
448 // the put. Expect no notifications to be sent out
449 reset(clusterCommunicator);
450 replay(clusterCommunicator);
452 ecMap.compute(KEY2, (k, v) -> null);
454 verify(clusterCommunicator);
456 // Check that our listener received the correct events during the test
461 public void testPutAll() throws Exception {
462 // putAll() with an empty map is a no-op - no messages will be sent
463 reset(clusterCommunicator);
464 replay(clusterCommunicator);
466 ecMap.putAll(new HashMap<>());
468 verify(clusterCommunicator);
470 // Set up the listener with our expected events
471 EventuallyConsistentMapListener<String, String> listener
473 listener.event(new EventuallyConsistentMapEvent<>(
474 MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1));
475 listener.event(new EventuallyConsistentMapEvent<>(
476 MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY2, VALUE2));
479 ecMap.addListener(listener);
481 // Expect a multi-update inter-instance message
482 expectSpecificBroadcastMessage(generatePutMessage(KEY1, VALUE1, KEY2, VALUE2), UPDATE_MESSAGE_SUBJECT,
483 clusterCommunicator);
485 Map<String, String> putAllValues = new HashMap<>();
486 putAllValues.put(KEY1, VALUE1);
487 putAllValues.put(KEY2, VALUE2);
489 // Put the values in the map
490 ecMap.putAll(putAllValues);
492 // Check the correct messages and events were sent
493 verify(clusterCommunicator);
498 public void testClear() throws Exception {
499 EventuallyConsistentMapListener<String, String> listener
501 listener.event(new EventuallyConsistentMapEvent<>(
502 MAP_NAME, EventuallyConsistentMapEvent.Type.REMOVE, KEY1, VALUE1));
503 listener.event(new EventuallyConsistentMapEvent<>(
504 MAP_NAME, EventuallyConsistentMapEvent.Type.REMOVE, KEY2, VALUE2));
507 // clear() on an empty map is a no-op - no messages will be sent
508 reset(clusterCommunicator);
509 replay(clusterCommunicator);
511 assertTrue(ecMap.isEmpty());
513 verify(clusterCommunicator);
515 // Put some items in the map
516 expectPeerMessage(clusterCommunicator);
517 ecMap.put(KEY1, VALUE1);
518 ecMap.put(KEY2, VALUE2);
520 ecMap.addListener(listener);
521 expectSpecificBroadcastMessage(generateRemoveMessage(KEY1, KEY2), UPDATE_MESSAGE_SUBJECT, clusterCommunicator);
525 verify(clusterCommunicator);
530 public void testKeySet() throws Exception {
531 expectPeerMessage(clusterCommunicator);
533 assertTrue(ecMap.keySet().isEmpty());
535 // Generate some keys
536 Set<String> keys = new HashSet<>();
537 for (int i = 1; i <= 10; i++) {
541 // Put each key in the map
542 keys.forEach(k -> ecMap.put(k, "value" + k));
544 // Check keySet() returns the correct value
545 assertEquals(keys, ecMap.keySet());
547 // Update the value for one of the keys
548 ecMap.put(keys.iterator().next(), "new-value");
550 // Check the key set is still the same
551 assertEquals(keys, ecMap.keySet());
554 String removeKey = keys.iterator().next();
555 keys.remove(removeKey);
556 ecMap.remove(removeKey);
558 // Check the key set is still correct
559 assertEquals(keys, ecMap.keySet());
563 public void testValues() throws Exception {
564 expectPeerMessage(clusterCommunicator);
566 assertTrue(ecMap.values().isEmpty());
568 // Generate some values
569 Map<String, String> expectedValues = new HashMap<>();
570 for (int i = 1; i <= 10; i++) {
571 expectedValues.put("" + i, "value" + i);
574 // Add them into the map
575 expectedValues.entrySet().forEach(e -> ecMap.put(e.getKey(), e.getValue()));
577 // Check the values collection is correct
578 assertEquals(expectedValues.values().size(), ecMap.values().size());
579 expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v)));
581 // Update the value for one of the keys
582 Map.Entry<String, String> first = expectedValues.entrySet().iterator().next();
583 expectedValues.put(first.getKey(), "new-value");
584 ecMap.put(first.getKey(), "new-value");
586 // Check the values collection is still correct
587 assertEquals(expectedValues.values().size(), ecMap.values().size());
588 expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v)));
591 String removeKey = expectedValues.keySet().iterator().next();
592 expectedValues.remove(removeKey);
593 ecMap.remove(removeKey);
595 // Check the values collection is still correct
596 assertEquals(expectedValues.values().size(), ecMap.values().size());
597 expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v)));
601 public void testEntrySet() throws Exception {
602 expectPeerMessage(clusterCommunicator);
604 assertTrue(ecMap.entrySet().isEmpty());
606 // Generate some values
607 Map<String, String> expectedValues = new HashMap<>();
608 for (int i = 1; i <= 10; i++) {
609 expectedValues.put("" + i, "value" + i);
612 // Add them into the map
613 expectedValues.entrySet().forEach(e -> ecMap.put(e.getKey(), e.getValue()));
615 // Check the entry set is correct
616 assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet()));
618 // Update the value for one of the keys
619 Map.Entry<String, String> first = expectedValues.entrySet().iterator().next();
620 expectedValues.put(first.getKey(), "new-value");
621 ecMap.put(first.getKey(), "new-value");
623 // Check the entry set is still correct
624 assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet()));
627 String removeKey = expectedValues.keySet().iterator().next();
628 expectedValues.remove(removeKey);
629 ecMap.remove(removeKey);
631 // Check the entry set is still correct
632 assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet()));
635 private static boolean entrySetsAreEqual(Map<String, String> expectedMap, Set<Map.Entry<String, String>> actual) {
636 if (expectedMap.entrySet().size() != actual.size()) {
640 for (Map.Entry<String, String> e : actual) {
641 if (!expectedMap.containsKey(e.getKey())) {
644 if (!Objects.equals(expectedMap.get(e.getKey()), e.getValue())) {
652 public void testDestroy() throws Exception {
653 clusterCommunicator.removeSubscriber(UPDATE_MESSAGE_SUBJECT);
654 clusterCommunicator.removeSubscriber(ANTI_ENTROPY_MESSAGE_SUBJECT);
656 replay(clusterCommunicator);
660 verify(clusterCommunicator);
664 fail("get after destroy should throw exception");
665 } catch (IllegalStateException e) {
670 ecMap.put(KEY1, VALUE1);
671 fail("put after destroy should throw exception");
672 } catch (IllegalStateException e) {
677 private UpdateEntry<String, String> generatePutMessage(String key, String value, Timestamp timestamp) {
678 return new UpdateEntry<>(key, new MapValue<>(value, timestamp));
681 private List<UpdateEntry<String, String>> generatePutMessage(
682 String key1, String value1, String key2, String value2) {
683 List<UpdateEntry<String, String>> list = new ArrayList<>();
685 Timestamp timestamp1 = clockService.peek(1);
686 Timestamp timestamp2 = clockService.peek(2);
688 list.add(generatePutMessage(key1, value1, timestamp1));
689 list.add(generatePutMessage(key2, value2, timestamp2));
694 private UpdateEntry<String, String> generateRemoveMessage(String key, Timestamp timestamp) {
695 return new UpdateEntry<>(key, new MapValue<>(null, timestamp));
698 private List<UpdateEntry<String, String>> generateRemoveMessage(String key1, String key2) {
699 List<UpdateEntry<String, String>> list = new ArrayList<>();
701 Timestamp timestamp1 = clockService.peek(1);
702 Timestamp timestamp2 = clockService.peek(2);
704 list.add(generateRemoveMessage(key1, timestamp1));
705 list.add(generateRemoveMessage(key2, timestamp2));
711 * Sets up a mock ClusterCommunicationService to expect a specific cluster
712 * message to be broadcast to the cluster.
714 * @param message message we expect to be sent
715 * @param clusterCommunicator a mock ClusterCommunicationService to set up
718 private static <T> void expectSpecificBroadcastMessage(
720 MessageSubject subject,
721 ClusterCommunicationService clusterCommunicator) {
722 reset(clusterCommunicator);
723 clusterCommunicator.<T>multicast(eq(message), eq(subject), anyObject(Function.class), anyObject(Set.class));
724 expectLastCall().anyTimes();
725 replay(clusterCommunicator);
729 * Sets up a mock ClusterCommunicationService to expect a specific cluster
730 * message to be multicast to the cluster.
732 * @param message message we expect to be sent
733 * @param subject subject we expect to be sent to
734 * @param clusterCommunicator a mock ClusterCommunicationService to set up
737 private static <T> void expectSpecificMulticastMessage(T message, MessageSubject subject,
738 ClusterCommunicationService clusterCommunicator) {
739 reset(clusterCommunicator);
740 clusterCommunicator.<T>multicast(eq(message), eq(subject), anyObject(Function.class), anyObject(Set.class));
741 expectLastCall().anyTimes();
742 replay(clusterCommunicator);
747 * Sets up a mock ClusterCommunicationService to expect a multicast cluster message
748 * that is sent to it. This is useful for unit tests where we aren't
749 * interested in testing the messaging component.
751 * @param clusterCommunicator a mock ClusterCommunicationService to set up
754 private <T> void expectPeerMessage(ClusterCommunicationService clusterCommunicator) {
755 reset(clusterCommunicator);
756 // expect(clusterCommunicator.multicast(anyObject(ClusterMessage.class),
757 // anyObject(Iterable.class)))
758 expect(clusterCommunicator.<T>unicast(
760 anyObject(MessageSubject.class),
761 anyObject(Function.class),
762 anyObject(NodeId.class)))
763 .andReturn(CompletableFuture.completedFuture(null))
765 replay(clusterCommunicator);
769 * Sets up a mock ClusterCommunicationService to expect a broadcast cluster message
770 * that is sent to it. This is useful for unit tests where we aren't
771 * interested in testing the messaging component.
773 * @param clusterCommunicator a mock ClusterCommunicationService to set up
775 private void expectBroadcastMessage(ClusterCommunicationService clusterCommunicator) {
776 reset(clusterCommunicator);
777 clusterCommunicator.<AbstractEvent>multicast(
778 anyObject(AbstractEvent.class),
779 anyObject(MessageSubject.class),
780 anyObject(Function.class),
781 anyObject(Set.class));
782 expectLastCall().anyTimes();
783 replay(clusterCommunicator);
787 * ClusterCommunicationService implementation that the map's addSubscriber
788 * call will delegate to. This means we can get a reference to the
789 * internal cluster message handler used by the map, so that we can simulate
790 * events coming in from other instances.
792 private final class TestClusterCommunicationService
793 extends ClusterCommunicationServiceAdapter {
796 public <M> void addSubscriber(MessageSubject subject,
797 Function<byte[], M> decoder, Consumer<M> handler,
799 if (subject.equals(UPDATE_MESSAGE_SUBJECT)) {
800 updateHandler = (Consumer<Collection<UpdateEntry<String, String>>>) handler;
801 } else if (subject.equals(ANTI_ENTROPY_MESSAGE_SUBJECT)) {
802 antiEntropyHandler = (Consumer<AntiEntropyAdvertisement<String>>) handler;
804 throw new RuntimeException("Unexpected message subject " + subject.toString());
810 * ClockService implementation that gives out timestamps based on a
811 * sequential counter. This clock service enables more control over the
812 * timestamps that are given out, including being able to "turn back time"
813 * to give out timestamps from the past.
815 * @param <T> Type that the clock service will give out timestamps for
816 * @param <U> Second type that the clock service will give out values for
818 private class SequentialClockService<T, U> {
820 private static final long INITIAL_VALUE = 1;
821 private final AtomicLong counter = new AtomicLong(INITIAL_VALUE);
823 public Timestamp getTimestamp(T object, U object2) {
824 return new TestTimestamp(counter.getAndIncrement());
828 * Returns what the next timestamp will be without consuming the
829 * timestamp. This allows test code to set expectations correctly while
830 * still allowing the CUT to get the same timestamp.
832 * @return timestamp equal to the timestamp that will be returned by the
833 * next call to {@link #getTimestamp(T, U)}.
835 public Timestamp peekAtNextTimestamp() {
840 * Returns the ith timestamp to be given out in the future without
841 * consuming the timestamp. For example, i=1 returns the next timestamp,
842 * i=2 returns the timestamp after that, and so on.
844 * @param i number of the timestamp to peek at
845 * @return the ith timestamp that will be given out
847 public Timestamp peek(int i) {
848 checkArgument(i > 0, "i must be a positive integer");
850 return new TestTimestamp(counter.get() + i - 1);
854 * Turns the clock back two ticks, so the next call to getTimestamp will
855 * return an older timestamp than the previous call to getTimestamp.
857 public void turnBackTime() {
858 // Not atomic, but should be OK for these tests.
859 counter.decrementAndGet();
860 counter.decrementAndGet();
866 * Timestamp implementation where the value of the timestamp can be
867 * specified explicitly at creation time.
869 private class TestTimestamp implements Timestamp {
871 private final long timestamp;
874 * Creates a new timestamp that has the specified value.
876 * @param timestamp value of the timestamp
878 public TestTimestamp(long timestamp) {
879 this.timestamp = timestamp;
883 public int compareTo(Timestamp o) {
884 checkArgument(o instanceof TestTimestamp);
885 TestTimestamp otherTimestamp = (TestTimestamp) o;
886 return ComparisonChain.start()
887 .compare(this.timestamp, otherTimestamp.timestamp)
893 * EventuallyConsistentMapListener implementation which triggers a latch
894 * when it receives an event.
896 private class TestListener implements EventuallyConsistentMapListener<String, String> {
897 private CountDownLatch latch;
900 * Creates a new listener that will trigger the specified latch when it
901 * receives and event.
903 * @param latch the latch to trigger on events
905 public TestListener(CountDownLatch latch) {
910 public void event(EventuallyConsistentMapEvent<String, String> event) {