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).
98 shardBatchedModificationCount(1);
101 public static void setUpClass() throws IOException {
103 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
104 put("akka.actor.default-dispatcher.type",
105 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
106 withFallback(ConfigFactory.load());
107 system = ActorSystem.create("test", config);
111 public static void tearDownClass() throws IOException {
112 JavaTestKit.shutdownActorSystem(system);
118 MockitoAnnotations.initMocks(this);
120 schemaContext = TestModel.createTestContext();
122 doReturn(getSystem()).when(mockActorContext).getActorSystem();
123 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
124 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
125 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
126 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
127 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
128 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
129 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
131 ShardStrategyFactory.setConfiguration(configuration);
134 protected ActorSystem getSystem() {
138 protected CreateTransaction eqCreateTransaction(final String memberName,
139 final TransactionType type) {
140 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
142 public boolean matches(Object argument) {
143 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
144 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
145 return obj.getTransactionId().startsWith(memberName) &&
146 obj.getTransactionType() == type.ordinal();
153 return argThat(matcher);
156 protected DataExists eqSerializedDataExists() {
157 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
159 public boolean matches(Object argument) {
160 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
161 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
165 return argThat(matcher);
168 protected DataExists eqDataExists() {
169 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
171 public boolean matches(Object argument) {
172 return (argument instanceof DataExists) &&
173 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
177 return argThat(matcher);
180 protected ReadData eqSerializedReadData() {
181 return eqSerializedReadData(TestModel.TEST_PATH);
184 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
185 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
187 public boolean matches(Object argument) {
188 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
189 ReadData.fromSerializable(argument).getPath().equals(path);
193 return argThat(matcher);
196 protected ReadData eqReadData() {
197 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
199 public boolean matches(Object argument) {
200 return (argument instanceof ReadData) &&
201 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
205 return argThat(matcher);
208 protected Future<Object> readySerializedTxReply(String path) {
209 return Futures.successful((Object)new ReadyTransactionReply(path).toSerializable());
212 protected Future<Object> readyTxReply(String path) {
213 return Futures.successful((Object)new ReadyTransactionReply(path));
216 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
217 short transactionVersion) {
218 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
221 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
222 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
225 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
226 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
229 protected Future<Object> dataExistsSerializedReply(boolean exists) {
230 return Futures.successful(new DataExistsReply(exists).toSerializable());
233 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
234 return Futures.successful(new DataExistsReply(exists));
237 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
238 return Futures.successful(new BatchedModificationsReply(count));
241 protected Future<Object> incompleteFuture(){
242 return mock(Future.class);
245 protected ActorSelection actorSelection(ActorRef actorRef) {
246 return getSystem().actorSelection(actorRef.path());
249 protected void expectBatchedModifications(ActorRef actorRef, int count) {
250 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
251 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
254 protected void expectBatchedModifications(int count) {
255 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
256 any(ActorSelection.class), isA(BatchedModifications.class));
259 protected void expectIncompleteBatchedModifications() {
260 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
261 any(ActorSelection.class), isA(BatchedModifications.class));
264 protected void expectReadyTransaction(ActorRef actorRef) {
265 doReturn(readySerializedTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
266 eq(actorSelection(actorRef)), isA(ReadyTransaction.SERIALIZABLE_CLASS));
269 protected void expectFailedBatchedModifications(ActorRef actorRef) {
270 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
271 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
274 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
275 return CreateTransactionReply.newBuilder()
276 .setTransactionActorPath(actorRef.path().toString())
277 .setTransactionId("txn-1")
278 .setMessageVersion(transactionVersion)
282 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
283 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
284 log.info("Created mock shard actor {}", actorRef);
286 doReturn(actorSystem.actorSelection(actorRef.path())).
287 when(mockActorContext).actorSelection(actorRef.path().toString());
289 doReturn(Futures.successful(actorSystem.actorSelection(actorRef.path()))).
290 when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
292 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
294 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
299 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
300 TransactionType type, int transactionVersion) {
301 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem);
303 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
304 memberName, shardActorRef);
307 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
308 TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
310 ActorRef txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
311 log.info("Created mock shard Tx actor {}", txActorRef);
313 doReturn(actorSystem.actorSelection(txActorRef.path())).when(mockActorContext).actorSelection(
314 txActorRef.path().toString());
316 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
317 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
318 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) {
362 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
363 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
365 verifyBatchedModifications(batchedModifications.get(0), expected);
368 protected void verifyBatchedModifications(Object message, 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 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
373 Modification actual = batchedModifications.getModifications().get(i);
374 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
375 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
376 ((AbstractModification)actual).getPath());
377 if(actual instanceof WriteModification) {
378 assertEquals("getData", ((WriteModification)expected[i]).getData(),
379 ((WriteModification)actual).getData());
384 protected void verifyCohortFutures(ThreePhaseCommitCohortProxy proxy,
385 Object... expReplies) throws Exception {
386 assertEquals("getReadyOperationFutures size", expReplies.length,
387 proxy.getCohortFutures().size());
390 for( Future<ActorSelection> future: proxy.getCohortFutures()) {
391 assertNotNull("Ready operation Future is null", future);
393 Object expReply = expReplies[i++];
394 if(expReply instanceof ActorSelection) {
395 ActorSelection actual = Await.result(future, Duration.create(5, TimeUnit.SECONDS));
396 assertEquals("Cohort actor path", expReply, actual);
399 Await.result(future, Duration.create(5, TimeUnit.SECONDS));
400 fail("Expected exception from ready operation Future");
401 } catch(Exception e) {
402 assertTrue(String.format("Expected exception type %s. Actual %s",
403 expReply, e.getClass()), ((Class<?>)expReply).isInstance(e));