Tests for CDS DataTreeChangedListener
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / utils / MockDataTreeChangeListener.java
1 /*
2  * Copyright (c) 2015 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.cluster.datastore.utils;
9
10 import com.google.common.collect.Lists;
11 import com.google.common.util.concurrent.Uninterruptibles;
12 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
13 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
14
15 import javax.annotation.Nonnull;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.List;
19 import java.util.concurrent.CountDownLatch;
20 import java.util.concurrent.TimeUnit;
21
22 import static org.junit.Assert.assertEquals;
23 import static org.junit.Assert.fail;
24
25 public class MockDataTreeChangeListener implements DOMDataTreeChangeListener {
26
27     private final List<Collection<DataTreeCandidate>> changeList =
28             Collections.synchronizedList(Lists.<Collection<DataTreeCandidate>>newArrayList());
29
30     private volatile CountDownLatch changeLatch;
31     private int expChangeEventCount;
32
33     public MockDataTreeChangeListener(int expChangeEventCount) {
34         reset(expChangeEventCount);
35     }
36
37     public void reset(int expChangeEventCount) {
38         changeLatch = new CountDownLatch(expChangeEventCount);
39         this.expChangeEventCount = expChangeEventCount;
40         changeList.clear();
41     }
42
43     @Override
44     public void onDataTreeChanged(@Nonnull final Collection<DataTreeCandidate> changes) {
45         changeList.add(changes);
46         changeLatch.countDown();
47     }
48
49     public void waitForChangeEvents() {
50         boolean done = Uninterruptibles.awaitUninterruptibly(changeLatch, 5, TimeUnit.SECONDS);
51         if(!done) {
52             fail(String.format("Missing change notifications. Expected: %d. Actual: %d",
53                     expChangeEventCount, (expChangeEventCount - changeLatch.getCount())));
54         }
55     }
56
57     public void expectNoMoreChanges(String assertMsg) {
58         Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
59         assertEquals(assertMsg, expChangeEventCount, changeList.size());
60     }
61 }