Convert DCL tests to use DTCL
[controller.git] / opendaylight / md-sal / sal-inmemory-datastore / src / test / java / org / opendaylight / controller / md / sal / dom / store / impl / DatastoreTestTask.java
1 /*
2  * Copyright (c) 2014 Cisco 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.md.sal.dom.store.impl;
9
10 import static org.junit.Assert.assertTrue;
11 import static org.junit.Assert.fail;
12
13 import com.google.common.base.Preconditions;
14 import com.google.common.util.concurrent.SettableFuture;
15 import com.google.common.util.concurrent.Uninterruptibles;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Iterator;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.TimeoutException;
22 import java.util.function.Function;
23 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
24 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
25 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
26 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
27 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTreeChangePublisher;
29 import org.opendaylight.yangtools.concepts.ListenerRegistration;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
33 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
34
35 public class DatastoreTestTask {
36
37     private final DOMStore store;
38
39     private WriteTransactionCustomizer setup;
40     private WriteTransactionCustomizer write;
41     private ReadTransactionVerifier read;
42     private WriteTransactionCustomizer cleanup;
43     private YangInstanceIdentifier changePath;
44     private DOMStoreTreeChangePublisher storeTreeChangePublisher;
45     private ChangeEventListener internalListener;
46     private final TestDCLExecutorService dclExecutorService;
47
48     public DatastoreTestTask(final DOMStore datastore, final TestDCLExecutorService dclExecutorService) {
49         this.store = datastore;
50         this.dclExecutorService = dclExecutorService;
51     }
52
53     @SafeVarargs
54     public final DatastoreTestTask changeListener(final YangInstanceIdentifier path,
55             Function<DataTreeCandidate, Boolean>... matchers) {
56         assertTrue(store instanceof DOMStoreTreeChangePublisher);
57         this.storeTreeChangePublisher = (DOMStoreTreeChangePublisher)store;
58         this.changePath = path;
59         this.internalListener = new ChangeEventListener(matchers);
60         return this;
61     }
62
63     public static Function<DataTreeCandidate, Boolean> added(YangInstanceIdentifier path) {
64         return candidate -> candidate.getRootNode().getModificationType() == ModificationType.WRITE
65                 && path.equals(candidate.getRootPath()) && !candidate.getRootNode().getDataBefore().isPresent()
66                 && candidate.getRootNode().getDataAfter().isPresent();
67     }
68
69     public static Function<DataTreeCandidate, Boolean> replaced(YangInstanceIdentifier path) {
70         return candidate -> candidate.getRootNode().getModificationType() == ModificationType.WRITE
71                 && path.equals(candidate.getRootPath()) && candidate.getRootNode().getDataBefore().isPresent()
72                 && candidate.getRootNode().getDataAfter().isPresent();
73     }
74
75     public static Function<DataTreeCandidate, Boolean> deleted(YangInstanceIdentifier path) {
76         return candidate -> candidate.getRootNode().getModificationType() == ModificationType.DELETE
77                 && path.equals(candidate.getRootPath()) && candidate.getRootNode().getDataBefore().isPresent()
78                 && !candidate.getRootNode().getDataAfter().isPresent();
79     }
80
81     public static Function<DataTreeCandidate, Boolean> subtreeModified(YangInstanceIdentifier path) {
82         return candidate -> candidate.getRootNode().getModificationType() == ModificationType.SUBTREE_MODIFIED
83                 && path.equals(candidate.getRootPath()) && candidate.getRootNode().getDataBefore().isPresent()
84                 && candidate.getRootNode().getDataAfter().isPresent();
85     }
86
87     public DatastoreTestTask setup(final WriteTransactionCustomizer customizer) {
88         this.setup = customizer;
89         return this;
90     }
91
92     public DatastoreTestTask test(final WriteTransactionCustomizer customizer) {
93         this.write = customizer;
94         return this;
95     }
96
97     public DatastoreTestTask read(final ReadTransactionVerifier customizer) {
98         this.read = customizer;
99         return this;
100     }
101
102     public DatastoreTestTask cleanup(final WriteTransactionCustomizer customizer) {
103         this.cleanup = customizer;
104         return this;
105     }
106
107     public void run() throws Exception {
108         if (setup != null) {
109             execute(setup);
110         }
111         ListenerRegistration<ChangeEventListener> registration = null;
112         if (changePath != null) {
113             registration = storeTreeChangePublisher.registerTreeChangeListener(changePath, internalListener);
114         }
115
116         Preconditions.checkState(write != null, "Write Transaction must be set.");
117
118         dclExecutorService.afterTestSetup();
119
120         execute(write);
121         if (registration != null) {
122             registration.close();
123         }
124
125         if (read != null) {
126             read.verify(store.newReadOnlyTransaction());
127         }
128         if (cleanup != null) {
129             execute(cleanup);
130         }
131     }
132
133     public void verifyChangeEvents() {
134         internalListener.verifyChangeEvents();
135     }
136
137     public void verifyNoChangeEvent() {
138         internalListener.verifyNoChangeEvent();
139     }
140
141     private void execute(final WriteTransactionCustomizer writeCustomizer) throws InterruptedException,
142             ExecutionException {
143         DOMStoreReadWriteTransaction tx = store.newReadWriteTransaction();
144         writeCustomizer.customize(tx);
145         DOMStoreThreePhaseCommitCohort cohort = tx.ready();
146         assertTrue(cohort.canCommit().get());
147         cohort.preCommit().get();
148         cohort.commit().get();
149     }
150
151     public interface WriteTransactionCustomizer {
152         void customize(DOMStoreReadWriteTransaction tx);
153     }
154
155     public interface ReadTransactionVerifier {
156         void verify(DOMStoreReadTransaction tx);
157     }
158
159     private final class ChangeEventListener implements DOMDataTreeChangeListener {
160
161         final SettableFuture<Collection<DataTreeCandidate>> future = SettableFuture.create();
162         final Collection<DataTreeCandidate> accumulatedChanges = new ArrayList<>();
163         final Function<DataTreeCandidate, Boolean>[] matchers;
164         final int expChangeCount;
165
166         ChangeEventListener(Function<DataTreeCandidate, Boolean>[] matchers) {
167             this.expChangeCount = matchers.length;
168             this.matchers = matchers;
169         }
170
171         Collection<DataTreeCandidate> changes() {
172             try {
173                 Collection<DataTreeCandidate> changes = internalListener.future.get(10, TimeUnit.SECONDS);
174                 Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
175                 return changes;
176             } catch (TimeoutException e) {
177                 throw new AssertionError(String.format(
178                         "Data tree change notifications not received. Expected: %s. Actual: %s - %s",
179                         expChangeCount, accumulatedChanges.size(), accumulatedChanges), e);
180             } catch (InterruptedException | ExecutionException e) {
181                 throw new AssertionError("Data tree change notifications failed", e);
182             }
183         }
184
185         void verifyChangeEvents() {
186             Collection<DataTreeCandidate> changes = new ArrayList<>(changes());
187             Iterator<DataTreeCandidate> iter = changes.iterator();
188             while (iter.hasNext()) {
189                 DataTreeCandidate dataTreeModification = iter.next();
190                 for (Function<DataTreeCandidate, Boolean> matcher: matchers) {
191                     if (matcher.apply(dataTreeModification)) {
192                         iter.remove();
193                         break;
194                     }
195                 }
196             }
197
198             if (!changes.isEmpty()) {
199                 DataTreeCandidate mod = changes.iterator().next();
200                 fail(String.format("Received unexpected notification: type: %s, path: %s, before: %s, after: %s",
201                         mod.getRootNode().getModificationType(), mod.getRootPath(),
202                         mod.getRootNode().getDataBefore(), mod.getRootNode().getDataAfter()));
203             }
204         }
205
206         void verifyNoChangeEvent() {
207             try {
208                 Object unexpected = internalListener.future.get(500, TimeUnit.MILLISECONDS);
209                 fail("Got unexpected Data tree change notifications: " + unexpected);
210             } catch (TimeoutException e) {
211                 // Expected
212             } catch (InterruptedException | ExecutionException e) {
213                 throw new AssertionError("Data tree change notifications failed", e);
214             }
215         }
216
217         @Override
218         public void onDataTreeChanged(Collection<DataTreeCandidate> changes) {
219             synchronized (accumulatedChanges) {
220                 accumulatedChanges.addAll(changes);
221                 if (expChangeCount == accumulatedChanges.size()) {
222                     future.set(new ArrayList<>(accumulatedChanges));
223                 }
224             }
225         }
226     }
227
228     public static final WriteTransactionCustomizer simpleWrite(final YangInstanceIdentifier path,
229             final NormalizedNode<?, ?> data) {
230         return tx -> tx.write(path, data);
231     }
232
233     public static final WriteTransactionCustomizer simpleMerge(final YangInstanceIdentifier path,
234             final NormalizedNode<?, ?> data) {
235         return tx -> tx.merge(path, data);
236     }
237
238     public static final WriteTransactionCustomizer simpleDelete(final YangInstanceIdentifier path) {
239         return tx -> tx.delete(path);
240     }
241 }