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