Merge "Avoid IllegalArgument on missing source"
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / AbstractTransactionProxyTest.java
1 /*
2  * Copyright (c) 2015 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.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.argThat;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Matchers.isA;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.verify;
21 import akka.actor.ActorRef;
22 import akka.actor.ActorSelection;
23 import akka.actor.ActorSystem;
24 import akka.actor.Props;
25 import akka.dispatch.Futures;
26 import akka.testkit.JavaTestKit;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.util.concurrent.CheckedFuture;
29 import com.typesafe.config.Config;
30 import com.typesafe.config.ConfigFactory;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.concurrent.TimeUnit;
35 import org.junit.AfterClass;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.mockito.ArgumentCaptor;
39 import org.mockito.ArgumentMatcher;
40 import org.mockito.Mock;
41 import org.mockito.Mockito;
42 import org.mockito.MockitoAnnotations;
43 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
44 import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
45 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
46 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
47 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
48 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
50 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
51 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
52 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
53 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
54 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
55 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
56 import org.opendaylight.controller.cluster.datastore.modification.Modification;
57 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
58 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
59 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
60 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
61 import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
62 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
63 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
64 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
65 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import scala.concurrent.Await;
72 import scala.concurrent.Future;
73 import scala.concurrent.duration.Duration;
74
75 /**
76  * Abstract base class for TransactionProxy unit tests.
77  *
78  * @author Thomas Pantelis
79  */
80 public abstract class AbstractTransactionProxyTest {
81     protected final Logger log = LoggerFactory.getLogger(getClass());
82
83     private static ActorSystem system;
84
85     private final Configuration configuration = new MockConfiguration();
86
87     @Mock
88     protected ActorContext mockActorContext;
89
90     private SchemaContext schemaContext;
91
92     @Mock
93     private ClusterWrapper mockClusterWrapper;
94
95     protected final String memberName = "mock-member";
96
97     protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
98
99     @BeforeClass
100     public static void setUpClass() throws IOException {
101
102         Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
103                 put("akka.actor.default-dispatcher.type",
104                         "akka.testkit.CallingThreadDispatcherConfigurator").build()).
105                 withFallback(ConfigFactory.load());
106         system = ActorSystem.create("test", config);
107     }
108
109     @AfterClass
110     public static void tearDownClass() throws IOException {
111         JavaTestKit.shutdownActorSystem(system);
112         system = null;
113     }
114
115     @Before
116     public void setUp(){
117         MockitoAnnotations.initMocks(this);
118
119         schemaContext = TestModel.createTestContext();
120
121         doReturn(getSystem()).when(mockActorContext).getActorSystem();
122         doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
123         doReturn(memberName).when(mockActorContext).getCurrentMemberName();
124         doReturn(schemaContext).when(mockActorContext).getSchemaContext();
125         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
126         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
127         doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
128         doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
129
130         ShardStrategyFactory.setConfiguration(configuration);
131     }
132
133     protected ActorSystem getSystem() {
134         return system;
135     }
136
137     protected CreateTransaction eqCreateTransaction(final String memberName,
138             final TransactionType type) {
139         ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
140             @Override
141             public boolean matches(Object argument) {
142                 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
143                     CreateTransaction obj = CreateTransaction.fromSerializable(argument);
144                     return obj.getTransactionId().startsWith(memberName) &&
145                             obj.getTransactionType() == type.ordinal();
146                 }
147
148                 return false;
149             }
150         };
151
152         return argThat(matcher);
153     }
154
155     protected DataExists eqSerializedDataExists() {
156         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
157             @Override
158             public boolean matches(Object argument) {
159                 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
160                        DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
161             }
162         };
163
164         return argThat(matcher);
165     }
166
167     protected DataExists eqDataExists() {
168         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
169             @Override
170             public boolean matches(Object argument) {
171                 return (argument instanceof DataExists) &&
172                     ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
173             }
174         };
175
176         return argThat(matcher);
177     }
178
179     protected ReadData eqSerializedReadData() {
180         return eqSerializedReadData(TestModel.TEST_PATH);
181     }
182
183     protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
184         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
185             @Override
186             public boolean matches(Object argument) {
187                 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
188                        ReadData.fromSerializable(argument).getPath().equals(path);
189             }
190         };
191
192         return argThat(matcher);
193     }
194
195     protected ReadData eqReadData() {
196         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
197             @Override
198             public boolean matches(Object argument) {
199                 return (argument instanceof ReadData) &&
200                     ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
201             }
202         };
203
204         return argThat(matcher);
205     }
206
207     protected Future<Object> readySerializedTxReply(String path) {
208         return Futures.successful((Object)new ReadyTransactionReply(path).toSerializable());
209     }
210
211     protected Future<Object> readyTxReply(String path) {
212         return Futures.successful((Object)new ReadyTransactionReply(path));
213     }
214
215     protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
216             short transactionVersion) {
217         return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
218     }
219
220     protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
221         return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
222     }
223
224     protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
225         return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
226     }
227
228     protected Future<Object> dataExistsSerializedReply(boolean exists) {
229         return Futures.successful(new DataExistsReply(exists).toSerializable());
230     }
231
232     protected Future<DataExistsReply> dataExistsReply(boolean exists) {
233         return Futures.successful(new DataExistsReply(exists));
234     }
235
236     protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
237         return Futures.successful(new BatchedModificationsReply(count));
238     }
239
240     protected Future<Object> incompleteFuture(){
241         return mock(Future.class);
242     }
243
244     protected ActorSelection actorSelection(ActorRef actorRef) {
245         return getSystem().actorSelection(actorRef.path());
246     }
247
248     protected void expectBatchedModifications(ActorRef actorRef, int count) {
249         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
250                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
251     }
252
253     protected void expectBatchedModificationsReady(ActorRef actorRef, int count) {
254         Future<BatchedModificationsReply> replyFuture = Futures.successful(
255                 new BatchedModificationsReply(count, actorRef.path().toString()));
256         doReturn(replyFuture).when(mockActorContext).executeOperationAsync(
257                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
258     }
259
260     protected void expectBatchedModifications(int count) {
261         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
262                 any(ActorSelection.class), isA(BatchedModifications.class));
263     }
264
265     protected void expectIncompleteBatchedModifications() {
266         doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
267                 any(ActorSelection.class), isA(BatchedModifications.class));
268     }
269
270     protected void expectReadyTransaction(ActorRef actorRef) {
271         doReturn(readySerializedTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
272                 eq(actorSelection(actorRef)), isA(ReadyTransaction.SERIALIZABLE_CLASS));
273     }
274
275     protected void expectFailedBatchedModifications(ActorRef actorRef) {
276         doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
277                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
278     }
279
280     protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
281         return CreateTransactionReply.newBuilder()
282             .setTransactionActorPath(actorRef.path().toString())
283             .setTransactionId("txn-1")
284             .setMessageVersion(transactionVersion)
285             .build();
286     }
287
288     protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
289         ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
290         log.info("Created mock shard actor {}", actorRef);
291
292         doReturn(actorSystem.actorSelection(actorRef.path())).
293                 when(mockActorContext).actorSelection(actorRef.path().toString());
294
295         doReturn(Futures.successful(actorSystem.actorSelection(actorRef.path()))).
296                 when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
297
298         doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
299
300         doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
301
302         return actorRef;
303     }
304
305     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
306             TransactionType type, int transactionVersion) {
307         ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem);
308
309         return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
310                 memberName, shardActorRef);
311     }
312
313     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
314             TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
315
316         ActorRef txActorRef;
317         if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
318                 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
319             txActorRef = shardActorRef;
320         } else {
321             txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
322             log.info("Created mock shard Tx actor {}", txActorRef);
323
324             doReturn(actorSystem.actorSelection(txActorRef.path())).
325             when(mockActorContext).actorSelection(txActorRef.path().toString());
326
327             doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
328             executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
329                     eqCreateTransaction(prefix, type));
330         }
331
332         return txActorRef;
333     }
334
335     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
336         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION);
337     }
338
339
340     protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
341             throws Throwable {
342
343         try {
344             future.checkedGet(5, TimeUnit.SECONDS);
345             fail("Expected ReadFailedException");
346         } catch(ReadFailedException e) {
347             throw e.getCause();
348         }
349     }
350
351     protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
352         ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
353                 ArgumentCaptor.forClass(BatchedModifications.class);
354         verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
355                 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
356
357         List<BatchedModifications> batchedModifications = filterCaptured(
358                 batchedModificationsCaptor, BatchedModifications.class);
359         return batchedModifications;
360     }
361
362     protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
363         List<T> captured = new ArrayList<>();
364         for(T c: captor.getAllValues()) {
365             if(type.isInstance(c)) {
366                 captured.add(c);
367             }
368         }
369
370         return captured;
371     }
372
373     protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
374         List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
375         assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
376
377         verifyBatchedModifications(batchedModifications.get(0), expIsReady, expected);
378     }
379
380     protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
381         assertEquals("Message type", BatchedModifications.class, message.getClass());
382         BatchedModifications batchedModifications = (BatchedModifications)message;
383         assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
384         assertEquals("isReady", expIsReady, batchedModifications.isReady());
385         for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
386             Modification actual = batchedModifications.getModifications().get(i);
387             assertEquals("Modification type", expected[i].getClass(), actual.getClass());
388             assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
389                     ((AbstractModification)actual).getPath());
390             if(actual instanceof WriteModification) {
391                 assertEquals("getData", ((WriteModification)expected[i]).getData(),
392                         ((WriteModification)actual).getData());
393             }
394         }
395     }
396
397     protected void verifyCohortFutures(ThreePhaseCommitCohortProxy proxy,
398             Object... expReplies) throws Exception {
399             assertEquals("getReadyOperationFutures size", expReplies.length,
400                     proxy.getCohortFutures().size());
401
402             int i = 0;
403             for( Future<ActorSelection> future: proxy.getCohortFutures()) {
404                 assertNotNull("Ready operation Future is null", future);
405
406                 Object expReply = expReplies[i++];
407                 if(expReply instanceof ActorSelection) {
408                     ActorSelection actual = Await.result(future, Duration.create(5, TimeUnit.SECONDS));
409                     assertEquals("Cohort actor path", expReply, actual);
410                 } else {
411                     try {
412                         Await.result(future, Duration.create(5, TimeUnit.SECONDS));
413                         fail("Expected exception from ready operation Future");
414                     } catch(Exception e) {
415                         assertTrue(String.format("Expected exception type %s. Actual %s",
416                                 expReply, e.getClass()), ((Class<?>)expReply).isInstance(e));
417                     }
418                 }
419             }
420         }
421 }