Migrate from JavaTestKit to javadsl.TestKit
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / DataChangeListenerRegistrationProxyTest.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
10 import static org.mockito.Matchers.any;
11 import static org.mockito.Matchers.eq;
12 import static org.mockito.Mockito.doAnswer;
13 import static org.mockito.Mockito.doReturn;
14 import static org.mockito.Mockito.mock;
15
16 import akka.actor.ActorRef;
17 import akka.actor.ActorSystem;
18 import akka.actor.Props;
19 import akka.actor.Terminated;
20 import akka.dispatch.ExecutionContexts;
21 import akka.dispatch.Futures;
22 import akka.testkit.javadsl.TestKit;
23 import akka.util.Timeout;
24 import com.google.common.util.concurrent.MoreExecutors;
25 import com.google.common.util.concurrent.Uninterruptibles;
26 import java.util.concurrent.TimeUnit;
27 import org.junit.Assert;
28 import org.junit.Test;
29 import org.mockito.Mockito;
30 import org.mockito.stubbing.Answer;
31 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
32 import org.opendaylight.controller.cluster.datastore.config.Configuration;
33 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
34 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistration;
35 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
36 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
37 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
38 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
39 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply;
40 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
41 import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
42 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
43 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
44 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
45 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
46 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataChangeListener;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import scala.concurrent.ExecutionContextExecutor;
50 import scala.concurrent.Future;
51 import scala.concurrent.duration.FiniteDuration;
52
53 /**
54  * Unit tests for DataChangeListenerRegistrationProxy.
55  *
56  * @author Thomas Pantelis
57  */
58 public class DataChangeListenerRegistrationProxyTest extends AbstractActorTest {
59
60     @SuppressWarnings("unchecked")
61     private final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> mockListener =
62             Mockito.mock(AsyncDataChangeListener.class);
63
64     @Test
65     public void testGetInstance() throws Exception {
66         try (DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
67                 "shard", Mockito.mock(ActorContext.class), mockListener)) {
68             Assert.assertEquals(mockListener, proxy.getInstance());
69         }
70     }
71
72     @Test(timeout = 10000)
73     public void testSuccessfulRegistration() {
74         new TestKit(getSystem()) {
75             {
76                 ActorContext actorContext = new ActorContext(getSystem(), getRef(),
77                         mock(ClusterWrapper.class), mock(Configuration.class));
78
79                 final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
80                         "shard-1", actorContext, mockListener);
81
82                 final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
83                 final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
84                 new Thread(() -> proxy.init(path, scope)).start();
85
86                 FiniteDuration timeout = duration("5 seconds");
87                 FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
88                 Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
89
90                 reply(new LocalShardFound(getRef()));
91
92                 RegisterChangeListener registerMsg = expectMsgClass(timeout, RegisterChangeListener.class);
93                 Assert.assertEquals("getPath", path, registerMsg.getPath());
94                 Assert.assertEquals("getScope", scope, registerMsg.getScope());
95                 Assert.assertEquals("isRegisterOnAllInstances", false, registerMsg.isRegisterOnAllInstances());
96
97                 reply(new RegisterDataTreeNotificationListenerReply(getRef()));
98
99                 for (int i = 0; i < 20 * 5 && proxy.getListenerRegistrationActor() == null; i++) {
100                     Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
101                 }
102
103                 Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()),
104                         proxy.getListenerRegistrationActor());
105
106                 watch(proxy.getDataChangeListenerActor());
107
108                 proxy.close();
109
110                 // The listener registration actor should get a Close message
111                 expectMsgClass(timeout, CloseDataTreeNotificationListenerRegistration.class);
112
113                 // The DataChangeListener actor should be terminated
114                 expectMsgClass(timeout, Terminated.class);
115
116                 proxy.close();
117
118                 expectNoMsg();
119             }
120         };
121     }
122
123     @Test(timeout = 10000)
124     public void testSuccessfulRegistrationForClusteredListener() {
125         new TestKit(getSystem()) {
126             {
127                 ActorContext actorContext = new ActorContext(getSystem(), getRef(),
128                     mock(ClusterWrapper.class), mock(Configuration.class));
129
130                 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> mockClusteredListener =
131                         Mockito.mock(ClusteredDOMDataChangeListener.class);
132
133                 final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
134                         "shard-1", actorContext, mockClusteredListener);
135
136                 final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
137                 final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
138                 new Thread(() -> proxy.init(path, scope)).start();
139
140                 FiniteDuration timeout = duration("5 seconds");
141                 FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
142                 Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
143
144                 reply(new LocalShardFound(getRef()));
145
146                 RegisterChangeListener registerMsg = expectMsgClass(timeout, RegisterChangeListener.class);
147                 Assert.assertEquals("getPath", path, registerMsg.getPath());
148                 Assert.assertEquals("getScope", scope, registerMsg.getScope());
149                 Assert.assertEquals("isRegisterOnAllInstances", true, registerMsg.isRegisterOnAllInstances());
150
151                 reply(new RegisterDataTreeNotificationListenerReply(getRef()));
152
153                 for (int i = 0; i < 20 * 5 && proxy.getListenerRegistrationActor() == null; i++) {
154                     Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
155                 }
156
157                 Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()),
158                         proxy.getListenerRegistrationActor());
159
160                 watch(proxy.getDataChangeListenerActor());
161
162                 proxy.close();
163
164                 // The listener registration actor should get a Close message
165                 expectMsgClass(timeout, CloseDataTreeNotificationListenerRegistration.class);
166
167                 // The DataChangeListener actor should be terminated
168                 expectMsgClass(timeout, Terminated.class);
169
170                 proxy.close();
171
172                 expectNoMsg();
173             }
174         };
175     }
176
177     @Test(timeout = 10000)
178     public void testLocalShardNotFound() {
179         new TestKit(getSystem()) {
180             {
181                 ActorContext actorContext = new ActorContext(getSystem(), getRef(),
182                         mock(ClusterWrapper.class), mock(Configuration.class));
183
184                 final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
185                         "shard-1", actorContext, mockListener);
186
187                 final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
188                 final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
189                 new Thread(() -> proxy.init(path, scope)).start();
190
191                 FiniteDuration timeout = duration("5 seconds");
192                 FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
193                 Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
194
195                 reply(new LocalShardNotFound("shard-1"));
196
197                 expectNoMsg(duration("1 seconds"));
198
199                 proxy.close();
200             }
201         };
202     }
203
204     @Test(timeout = 10000)
205     public void testLocalShardNotInitialized() {
206         new TestKit(getSystem()) {
207             {
208                 ActorContext actorContext = new ActorContext(getSystem(), getRef(),
209                         mock(ClusterWrapper.class), mock(Configuration.class));
210
211                 final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
212                         "shard-1", actorContext, mockListener);
213
214                 final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
215                 final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
216                 new Thread(() -> proxy.init(path, scope)).start();
217
218                 FiniteDuration timeout = duration("5 seconds");
219                 FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
220                 Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
221
222                 reply(new NotInitializedException("not initialized"));
223
224                 expectNoMsg(duration("1 seconds"));
225                 proxy.close();
226             }
227         };
228     }
229
230     @Test
231     public void testFailedRegistration() {
232         new TestKit(getSystem()) {
233             {
234                 ActorSystem mockActorSystem = mock(ActorSystem.class);
235
236                 ActorRef mockActor = getSystem().actorOf(Props.create(DoNothingActor.class),
237                         "testFailedRegistration");
238                 doReturn(mockActor).when(mockActorSystem).actorOf(any(Props.class));
239                 ExecutionContextExecutor executor = ExecutionContexts.fromExecutor(
240                         MoreExecutors.directExecutor());
241
242
243                 ActorContext actorContext = mock(ActorContext.class);
244
245                 doReturn(executor).when(actorContext).getClientDispatcher();
246
247                 String shardName = "shard-1";
248                 final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
249                         shardName, actorContext, mockListener);
250
251                 doReturn(mockActorSystem).when(actorContext).getActorSystem();
252                 doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
253                 doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
254                 doReturn(Futures.failed(new RuntimeException("mock")))
255                     .when(actorContext).executeOperationAsync(any(ActorRef.class),
256                         any(Object.class), any(Timeout.class));
257                 doReturn(mock(DatastoreContext.class)).when(actorContext).getDatastoreContext();
258
259                 proxy.init(YangInstanceIdentifier.of(TestModel.TEST_QNAME),
260                         AsyncDataBroker.DataChangeScope.ONE);
261
262                 Assert.assertEquals("getListenerRegistrationActor", null, proxy.getListenerRegistrationActor());
263
264                 proxy.close();
265             }
266         };
267     }
268
269     @Test
270     public void testCloseBeforeRegistration() {
271         new TestKit(getSystem()) {
272             {
273                 ActorContext actorContext = mock(ActorContext.class);
274
275                 String shardName = "shard-1";
276                 final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
277                         shardName, actorContext, mockListener);
278
279                 doReturn(DatastoreContext.newBuilder().build()).when(actorContext).getDatastoreContext();
280                 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(actorContext).getClientDispatcher();
281                 doReturn(getSystem()).when(actorContext).getActorSystem();
282                 doReturn(Dispatchers.DEFAULT_DISPATCHER_PATH).when(actorContext).getNotificationDispatcherPath();
283                 doReturn(getSystem().actorSelection(getRef().path()))
284                     .when(actorContext).actorSelection(getRef().path());
285                 doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
286                 doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
287
288                 Answer<Future<Object>> answer = invocation -> {
289                     proxy.close();
290                     return Futures.successful((Object)new RegisterDataTreeNotificationListenerReply(getRef()));
291                 };
292
293                 doAnswer(answer).when(actorContext).executeOperationAsync(any(ActorRef.class),
294                         any(Object.class), any(Timeout.class));
295
296                 proxy.init(YangInstanceIdentifier.of(TestModel.TEST_QNAME),
297                         AsyncDataBroker.DataChangeScope.ONE);
298
299                 expectMsgClass(duration("5 seconds"), CloseDataTreeNotificationListenerRegistration.class);
300
301                 Assert.assertEquals("getListenerRegistrationActor", null, proxy.getListenerRegistrationActor());
302                 proxy.close();
303             }
304         };
305     }
306 }