5a9a6a60a60258388b5724e664f18d13ec00ac07
[netconf.git] / netconf / mdsal-netconf-connector / src / test / java / org / opendaylight / netconf / mdsal / connector / ops / AbstractNetconfOperationTest.java
1 /*
2  * Copyright (c) 2018 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
9 package org.opendaylight.netconf.mdsal.connector.ops;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15
16 import com.google.common.io.ByteSource;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.io.StringWriter;
20 import java.util.EnumMap;
21 import java.util.concurrent.ExecutorService;
22 import javax.xml.transform.OutputKeys;
23 import javax.xml.transform.Transformer;
24 import javax.xml.transform.TransformerFactory;
25 import javax.xml.transform.dom.DOMSource;
26 import javax.xml.transform.stream.StreamResult;
27 import org.custommonkey.xmlunit.DetailedDiff;
28 import org.custommonkey.xmlunit.Diff;
29 import org.custommonkey.xmlunit.XMLUnit;
30 import org.junit.Before;
31 import org.mockito.MockitoAnnotations;
32 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
33 import org.opendaylight.controller.md.sal.dom.broker.impl.SerializedDOMDataBroker;
34 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
35 import org.opendaylight.controller.sal.core.api.model.SchemaService;
36 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
37 import org.opendaylight.netconf.api.xml.XmlUtil;
38 import org.opendaylight.netconf.mapping.api.NetconfOperation;
39 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
40 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
41 import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
42 import org.opendaylight.netconf.mdsal.connector.ops.get.Get;
43 import org.opendaylight.netconf.mdsal.connector.ops.get.GetConfig;
44 import org.opendaylight.netconf.util.test.NetconfXmlUnitRecursiveQualifier;
45 import org.opendaylight.netconf.util.test.XmlFileLoader;
46 import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Node;
53 import org.w3c.dom.NodeList;
54
55 abstract class AbstractNetconfOperationTest {
56     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfOperationTest.class);
57     protected static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
58     private static final String RPC_REPLY_ELEMENT = "rpc-reply";
59     private static final String DATA_ELEMENT = "data";
60     protected static final Document RPC_REPLY_OK = getReplyOk();
61
62     private CurrentSchemaContext currentSchemaContext;
63     private TransactionProvider transactionProvider;
64
65     @Before
66     public void setUp() throws Exception {
67         MockitoAnnotations.initMocks(this);
68
69         XMLUnit.setIgnoreWhitespace(true);
70         XMLUnit.setIgnoreAttributeOrder(true);
71
72         final SchemaContext schemaContext = getSchemaContext();
73         final SchemaService schemaService = new SchemaServiceStub(schemaContext);
74         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
75         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
76
77         currentSchemaContext = new CurrentSchemaContext(schemaService, sourceIdentifier -> {
78             final YangTextSchemaSource yangTextSchemaSource =
79                 YangTextSchemaSource.delegateForByteSource(sourceIdentifier, ByteSource.wrap("module test".getBytes()));
80             return Futures.immediateCheckedFuture(yangTextSchemaSource);
81         });
82
83         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
84         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
85         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
86
87         final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
88             16, 16, "CommitFutures", CopyConfigTest.class);
89
90         final SerializedDOMDataBroker sdb = new SerializedDOMDataBroker(datastores,
91             MoreExecutors.listeningDecorator(listenableFutureExecutor));
92         this.transactionProvider = new TransactionProvider(sdb, SESSION_ID_FOR_REPORTING);
93     }
94
95     protected abstract SchemaContext getSchemaContext();
96
97     protected CurrentSchemaContext getCurrentSchemaContext() {
98         return currentSchemaContext;
99     }
100
101     protected TransactionProvider getTransactionProvider() {
102         return transactionProvider;
103     }
104
105     @SuppressWarnings("illegalCatch")
106     private static Document getReplyOk() {
107         Document doc;
108         try {
109             doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpc-reply_ok.xml");
110         } catch (final Exception e) {
111             LOG.debug("unable to load rpc reply ok.", e);
112             doc = XmlUtil.newDocument();
113         }
114         return doc;
115     }
116
117     protected Document commit() throws Exception {
118         final Commit commit = new Commit(SESSION_ID_FOR_REPORTING, transactionProvider);
119         return executeOperation(commit, "messages/mapping/commit.xml");
120     }
121
122     protected Document discardChanges() throws Exception {
123         final DiscardChanges discardOp = new DiscardChanges(SESSION_ID_FOR_REPORTING, transactionProvider);
124         return executeOperation(discardOp, "messages/mapping/discardChanges.xml");
125     }
126
127     protected Document edit(final String resource) throws Exception {
128         final EditConfig editConfig = new EditConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext,
129             transactionProvider);
130         return executeOperation(editConfig, resource);
131     }
132
133     protected Document get() throws Exception {
134         final Get get = new Get(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
135         return executeOperation(get, "messages/mapping/get.xml");
136     }
137
138     protected Document getWithFilter(final String resource) throws Exception {
139         final Get get = new Get(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
140         return executeOperation(get, resource);
141     }
142
143     protected Document getConfigRunning() throws Exception {
144         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
145         return executeOperation(getConfig, "messages/mapping/getConfig.xml");
146     }
147
148     protected Document getConfigCandidate() throws Exception {
149         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
150         return executeOperation(getConfig, "messages/mapping/getConfig_candidate.xml");
151     }
152
153     protected Document getConfigWithFilter(final String resource) throws Exception {
154         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
155         return executeOperation(getConfig, resource);
156     }
157
158     protected static Document lock() throws Exception {
159         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
160         return executeOperation(lock, "messages/mapping/lock.xml");
161     }
162
163     protected static Document unlock() throws Exception {
164         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
165         return executeOperation(unlock, "messages/mapping/unlock.xml");
166     }
167
168     protected static Document lockWithoutTarget() throws Exception {
169         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
170         return executeOperation(lock, "messages/mapping/lock_notarget.xml");
171     }
172
173     protected static Document unlockWithoutTarget() throws Exception {
174         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
175         return executeOperation(unlock, "messages/mapping/unlock_notarget.xml");
176     }
177
178     protected static Document lockCandidate() throws Exception {
179         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
180         return executeOperation(lock, "messages/mapping/lock_candidate.xml");
181     }
182
183     protected static Document unlockCandidate() throws Exception {
184         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
185         return executeOperation(unlock, "messages/mapping/unlock_candidate.xml");
186     }
187
188     protected static Document executeOperation(final NetconfOperation op, final String filename) throws Exception {
189         final Document request = XmlFileLoader.xmlFileToDocument(filename);
190         final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
191
192         LOG.debug("Got response {}", response);
193         return response;
194     }
195
196     protected static void assertEmptyDatastore(final Document response) {
197         final NodeList nodes = response.getChildNodes();
198         assertTrue(nodes.getLength() == 1);
199
200         assertEquals(nodes.item(0).getLocalName(), RPC_REPLY_ELEMENT);
201
202         final NodeList replyNodes = nodes.item(0).getChildNodes();
203         assertTrue(replyNodes.getLength() == 1);
204
205         final Node dataNode = replyNodes.item(0);
206         assertEquals(dataNode.getLocalName(), DATA_ELEMENT);
207         assertFalse(dataNode.hasChildNodes());
208     }
209
210     protected static void verifyResponse(final Document response, final Document template) throws Exception {
211         final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
212         dd.overrideElementQualifier(new NetconfXmlUnitRecursiveQualifier());
213         if (!dd.similar()) {
214             LOG.warn("Actual response:");
215             printDocument(response);
216             LOG.warn("Expected response:");
217             printDocument(template);
218             fail("Differences found: " + dd.toString());
219         }
220     }
221
222     private static void printDocument(final Document doc) throws Exception {
223         final TransformerFactory tf = TransformerFactory.newInstance();
224         final Transformer transformer = tf.newTransformer();
225         transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
226         transformer.setOutputProperty(OutputKeys.METHOD, "xml");
227         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
228         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
229         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
230
231         final StringWriter writer = new StringWriter();
232         transformer.transform(new DOMSource(doc),
233             new StreamResult(writer));
234         LOG.warn(writer.getBuffer().toString());
235     }
236 }