2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore;
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;
76 * Abstract base class for TransactionProxy unit tests.
78 * @author Thomas Pantelis
80 public abstract class AbstractTransactionProxyTest {
81 protected final Logger log = LoggerFactory.getLogger(getClass());
83 private static ActorSystem system;
85 private final Configuration configuration = new MockConfiguration();
88 protected ActorContext mockActorContext;
90 private SchemaContext schemaContext;
93 private ClusterWrapper mockClusterWrapper;
95 protected final String memberName = "mock-member";
97 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
100 public static void setUpClass() throws IOException {
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);
110 public static void tearDownClass() throws IOException {
111 JavaTestKit.shutdownActorSystem(system);
117 MockitoAnnotations.initMocks(this);
119 schemaContext = TestModel.createTestContext();
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();
130 ShardStrategyFactory.setConfiguration(configuration);
133 protected ActorSystem getSystem() {
137 protected CreateTransaction eqCreateTransaction(final String memberName,
138 final TransactionType type) {
139 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
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();
152 return argThat(matcher);
155 protected DataExists eqSerializedDataExists() {
156 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
158 public boolean matches(Object argument) {
159 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
160 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
164 return argThat(matcher);
167 protected DataExists eqDataExists() {
168 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
170 public boolean matches(Object argument) {
171 return (argument instanceof DataExists) &&
172 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
176 return argThat(matcher);
179 protected ReadData eqSerializedReadData() {
180 return eqSerializedReadData(TestModel.TEST_PATH);
183 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
184 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
186 public boolean matches(Object argument) {
187 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
188 ReadData.fromSerializable(argument).getPath().equals(path);
192 return argThat(matcher);
195 protected ReadData eqReadData() {
196 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
198 public boolean matches(Object argument) {
199 return (argument instanceof ReadData) &&
200 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
204 return argThat(matcher);
207 protected Future<Object> readySerializedTxReply(String path) {
208 return Futures.successful((Object)new ReadyTransactionReply(path).toSerializable());
211 protected Future<Object> readyTxReply(String path) {
212 return Futures.successful((Object)new ReadyTransactionReply(path));
215 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
216 short transactionVersion) {
217 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
220 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
221 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
224 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
225 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
228 protected Future<Object> dataExistsSerializedReply(boolean exists) {
229 return Futures.successful(new DataExistsReply(exists).toSerializable());
232 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
233 return Futures.successful(new DataExistsReply(exists));
236 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
237 return Futures.successful(new BatchedModificationsReply(count));
240 protected Future<Object> incompleteFuture(){
241 return mock(Future.class);
244 protected ActorSelection actorSelection(ActorRef actorRef) {
245 return getSystem().actorSelection(actorRef.path());
248 protected void expectBatchedModifications(ActorRef actorRef, int count) {
249 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
250 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
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));
260 protected void expectBatchedModifications(int count) {
261 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
262 any(ActorSelection.class), isA(BatchedModifications.class));
265 protected void expectIncompleteBatchedModifications() {
266 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
267 any(ActorSelection.class), isA(BatchedModifications.class));
270 protected void expectReadyTransaction(ActorRef actorRef) {
271 doReturn(readySerializedTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
272 eq(actorSelection(actorRef)), isA(ReadyTransaction.SERIALIZABLE_CLASS));
275 protected void expectFailedBatchedModifications(ActorRef actorRef) {
276 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
277 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
280 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
281 return CreateTransactionReply.newBuilder()
282 .setTransactionActorPath(actorRef.path().toString())
283 .setTransactionId("txn-1")
284 .setMessageVersion(transactionVersion)
288 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
289 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
290 log.info("Created mock shard actor {}", actorRef);
292 doReturn(actorSystem.actorSelection(actorRef.path())).
293 when(mockActorContext).actorSelection(actorRef.path().toString());
295 doReturn(Futures.successful(actorSystem.actorSelection(actorRef.path()))).
296 when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
298 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
300 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
305 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
306 TransactionType type, int transactionVersion) {
307 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem);
309 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
310 memberName, shardActorRef);
313 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
314 TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
317 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
318 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
319 txActorRef = shardActorRef;
321 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
322 log.info("Created mock shard Tx actor {}", txActorRef);
324 doReturn(actorSystem.actorSelection(txActorRef.path())).
325 when(mockActorContext).actorSelection(txActorRef.path().toString());
327 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
328 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
329 eqCreateTransaction(prefix, type));
335 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
336 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION);
340 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
344 future.checkedGet(5, TimeUnit.SECONDS);
345 fail("Expected ReadFailedException");
346 } catch(ReadFailedException e) {
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());
357 List<BatchedModifications> batchedModifications = filterCaptured(
358 batchedModificationsCaptor, BatchedModifications.class);
359 return batchedModifications;
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)) {
373 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
374 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
375 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
377 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expected);
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());
397 protected void verifyCohortFutures(ThreePhaseCommitCohortProxy proxy,
398 Object... expReplies) throws Exception {
399 assertEquals("getReadyOperationFutures size", expReplies.length,
400 proxy.getCohortFutures().size());
403 for( Future<ActorSelection> future: proxy.getCohortFutures()) {
404 assertNotNull("Ready operation Future is null", future);
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);
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));