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.ReadyTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
55 import org.opendaylight.controller.cluster.datastore.modification.Modification;
56 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
57 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
58 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
59 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
60 import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
61 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
62 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
63 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
64 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import scala.concurrent.Await;
71 import scala.concurrent.Future;
72 import scala.concurrent.duration.Duration;
75 * Abstract base class for TransactionProxy unit tests.
77 * @author Thomas Pantelis
79 public abstract class AbstractTransactionProxyTest {
80 protected final Logger log = LoggerFactory.getLogger(getClass());
82 private static ActorSystem system;
84 private final Configuration configuration = new MockConfiguration();
87 protected ActorContext mockActorContext;
89 private SchemaContext schemaContext;
92 private ClusterWrapper mockClusterWrapper;
94 protected final String memberName = "mock-member";
96 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
99 public static void setUpClass() throws IOException {
101 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
102 put("akka.actor.default-dispatcher.type",
103 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
104 withFallback(ConfigFactory.load());
105 system = ActorSystem.create("test", config);
109 public static void tearDownClass() throws IOException {
110 JavaTestKit.shutdownActorSystem(system);
116 MockitoAnnotations.initMocks(this);
118 schemaContext = TestModel.createTestContext();
120 doReturn(getSystem()).when(mockActorContext).getActorSystem();
121 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
122 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
123 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
124 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
125 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
126 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
127 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
129 ShardStrategyFactory.setConfiguration(configuration);
132 protected ActorSystem getSystem() {
136 protected CreateTransaction eqCreateTransaction(final String memberName,
137 final TransactionType type) {
138 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
140 public boolean matches(Object argument) {
141 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
142 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
143 return obj.getTransactionId().startsWith(memberName) &&
144 obj.getTransactionType() == type.ordinal();
151 return argThat(matcher);
154 protected DataExists eqSerializedDataExists() {
155 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
157 public boolean matches(Object argument) {
158 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
159 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
163 return argThat(matcher);
166 protected DataExists eqDataExists() {
167 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
169 public boolean matches(Object argument) {
170 return (argument instanceof DataExists) &&
171 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
175 return argThat(matcher);
178 protected ReadData eqSerializedReadData() {
179 return eqSerializedReadData(TestModel.TEST_PATH);
182 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
183 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
185 public boolean matches(Object argument) {
186 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
187 ReadData.fromSerializable(argument).getPath().equals(path);
191 return argThat(matcher);
194 protected ReadData eqReadData() {
195 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
197 public boolean matches(Object argument) {
198 return (argument instanceof ReadData) &&
199 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
203 return argThat(matcher);
206 protected Future<Object> readyTxReply(String path) {
207 return Futures.successful((Object)new ReadyTransactionReply(path));
210 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
211 short transactionVersion) {
212 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
215 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
216 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
219 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
220 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
223 protected Future<Object> dataExistsSerializedReply(boolean exists) {
224 return Futures.successful(new DataExistsReply(exists).toSerializable());
227 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
228 return Futures.successful(new DataExistsReply(exists));
231 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
232 return Futures.successful(new BatchedModificationsReply(count));
235 protected Future<Object> incompleteFuture(){
236 return mock(Future.class);
239 protected ActorSelection actorSelection(ActorRef actorRef) {
240 return getSystem().actorSelection(actorRef.path());
243 protected void expectBatchedModifications(ActorRef actorRef, int count) {
244 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
245 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
248 protected void expectBatchedModificationsReady(ActorRef actorRef) {
249 doReturn(readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
250 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
253 protected void expectBatchedModifications(int count) {
254 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
255 any(ActorSelection.class), isA(BatchedModifications.class));
258 protected void expectIncompleteBatchedModifications() {
259 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
260 any(ActorSelection.class), isA(BatchedModifications.class));
263 protected void expectFailedBatchedModifications(ActorRef actorRef) {
264 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
265 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
268 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
269 return CreateTransactionReply.newBuilder()
270 .setTransactionActorPath(actorRef.path().toString())
271 .setTransactionId("txn-1")
272 .setMessageVersion(transactionVersion)
276 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
277 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
278 log.info("Created mock shard actor {}", actorRef);
280 doReturn(actorSystem.actorSelection(actorRef.path())).
281 when(mockActorContext).actorSelection(actorRef.path().toString());
283 doReturn(Futures.successful(actorSystem.actorSelection(actorRef.path()))).
284 when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
286 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
288 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
293 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
294 TransactionType type, int transactionVersion) {
295 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem);
297 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
298 memberName, shardActorRef);
301 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
302 TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
305 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
306 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
307 txActorRef = shardActorRef;
309 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
310 log.info("Created mock shard Tx actor {}", txActorRef);
312 doReturn(actorSystem.actorSelection(txActorRef.path())).
313 when(mockActorContext).actorSelection(txActorRef.path().toString());
315 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
316 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
317 eqCreateTransaction(prefix, type));
323 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
324 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION);
328 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
332 future.checkedGet(5, TimeUnit.SECONDS);
333 fail("Expected ReadFailedException");
334 } catch(ReadFailedException e) {
339 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
340 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
341 ArgumentCaptor.forClass(BatchedModifications.class);
342 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
343 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
345 List<BatchedModifications> batchedModifications = filterCaptured(
346 batchedModificationsCaptor, BatchedModifications.class);
347 return batchedModifications;
350 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
351 List<T> captured = new ArrayList<>();
352 for(T c: captor.getAllValues()) {
353 if(type.isInstance(c)) {
361 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
362 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
363 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
365 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expected);
368 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
369 assertEquals("Message type", BatchedModifications.class, message.getClass());
370 BatchedModifications batchedModifications = (BatchedModifications)message;
371 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
372 assertEquals("isReady", expIsReady, batchedModifications.isReady());
373 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
374 Modification actual = batchedModifications.getModifications().get(i);
375 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
376 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
377 ((AbstractModification)actual).getPath());
378 if(actual instanceof WriteModification) {
379 assertEquals("getData", ((WriteModification)expected[i]).getData(),
380 ((WriteModification)actual).getData());
385 protected void verifyCohortFutures(ThreePhaseCommitCohortProxy proxy,
386 Object... expReplies) throws Exception {
387 assertEquals("getReadyOperationFutures size", expReplies.length,
388 proxy.getCohortFutures().size());
391 for( Future<ActorSelection> future: proxy.getCohortFutures()) {
392 assertNotNull("Ready operation Future is null", future);
394 Object expReply = expReplies[i++];
395 if(expReply instanceof ActorSelection) {
396 ActorSelection actual = Await.result(future, Duration.create(5, TimeUnit.SECONDS));
397 assertEquals("Cohort actor path", expReply, actual);
400 Await.result(future, Duration.create(5, TimeUnit.SECONDS));
401 fail("Expected exception from ready operation Future");
402 } catch(Exception e) {
403 assertTrue(String.format("Expected exception type %s. Actual %s",
404 expReply, e.getClass()), ((Class<?>)expReply).isInstance(e));