Bump upstreams
[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.CharSource;
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,
95             sourceIdentifier -> Futures.immediateFuture(YangTextSchemaSource.delegateForCharSource(sourceIdentifier,
96                 CharSource.wrap("module test"))));
97
98         final var datastores = new EnumMap<LogicalDatastoreType, DOMStore>(LogicalDatastoreType.class);
99         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
100         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
101
102         final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
103             16, 16, "CommitFutures", CopyConfigTest.class);
104
105         final SerializedDOMDataBroker sdb = new SerializedDOMDataBroker(datastores,
106             MoreExecutors.listeningDecorator(listenableFutureExecutor));
107         transactionProvider = new TransactionProvider(sdb, SESSION_ID_FOR_REPORTING);
108     }
109
110     protected CurrentSchemaContext getCurrentSchemaContext() {
111         return currentSchemaContext;
112     }
113
114     protected TransactionProvider getTransactionProvider() {
115         return transactionProvider;
116     }
117
118     private static Document getReplyOk() {
119         Document doc;
120         try {
121             doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpc-reply_ok.xml");
122         } catch (final IOException | SAXException | ParserConfigurationException e) {
123             LOG.debug("unable to load rpc reply ok.", e);
124             doc = XmlUtil.newDocument();
125         }
126         return doc;
127     }
128
129     protected Document commit() throws Exception {
130         final Commit commit = new Commit(SESSION_ID_FOR_REPORTING, transactionProvider);
131         return executeOperation(commit, "messages/mapping/commit.xml");
132     }
133
134     protected Document discardChanges() throws Exception {
135         final DiscardChanges discardOp = new DiscardChanges(SESSION_ID_FOR_REPORTING, transactionProvider);
136         return executeOperation(discardOp, "messages/mapping/discardChanges.xml");
137     }
138
139     protected Document edit(final String resource) throws Exception {
140         final EditConfig editConfig = new EditConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext,
141             transactionProvider);
142         return executeOperation(editConfig, resource);
143     }
144
145     protected Document edit(final Document request) throws Exception {
146         final EditConfig editConfig = new EditConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext,
147             transactionProvider);
148         return executeOperation(editConfig, request);
149     }
150
151     protected Document get() throws Exception {
152         final Get get = new Get(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
153         return executeOperation(get, "messages/mapping/get.xml");
154     }
155
156     protected Document getWithFilter(final String resource) throws Exception {
157         final Get get = new Get(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
158         return executeOperation(get, resource);
159     }
160
161     protected Document getConfigRunning() throws Exception {
162         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
163         return executeOperation(getConfig, "messages/mapping/getConfig.xml");
164     }
165
166     protected Document getConfigCandidate() throws Exception {
167         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
168         return executeOperation(getConfig, "messages/mapping/getConfig_candidate.xml");
169     }
170
171     protected Document getConfigWithFilter(final String resource) throws Exception {
172         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
173         return executeOperation(getConfig, resource);
174     }
175
176     protected static Document lock() throws Exception {
177         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
178         return executeOperation(lock, "messages/mapping/lock.xml");
179     }
180
181     protected static Document unlock() throws Exception {
182         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
183         return executeOperation(unlock, "messages/mapping/unlock.xml");
184     }
185
186     protected static Document lockWithoutTarget() throws Exception {
187         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
188         return executeOperation(lock, "messages/mapping/lock_notarget.xml");
189     }
190
191     protected static Document unlockWithoutTarget() throws Exception {
192         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
193         return executeOperation(unlock, "messages/mapping/unlock_notarget.xml");
194     }
195
196     protected static Document lockCandidate() throws Exception {
197         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
198         return executeOperation(lock, "messages/mapping/lock_candidate.xml");
199     }
200
201     protected static Document unlockCandidate() throws Exception {
202         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
203         return executeOperation(unlock, "messages/mapping/unlock_candidate.xml");
204     }
205
206     protected static Document executeOperation(final NetconfOperation op, final String filename) throws Exception {
207         final Document request = XmlFileLoader.xmlFileToDocument(filename);
208         return executeOperation(op, request);
209     }
210
211     protected static Document executeOperation(final NetconfOperation op, final Document request) throws Exception {
212         final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
213         LOG.debug("Got response {}", response);
214         return response;
215     }
216
217     protected static void assertEmptyDatastore(final Document response) {
218         final NodeList nodes = response.getChildNodes();
219         assertTrue(nodes.getLength() == 1);
220
221         assertEquals(nodes.item(0).getLocalName(), RPC_REPLY_ELEMENT);
222
223         final NodeList replyNodes = nodes.item(0).getChildNodes();
224         assertTrue(replyNodes.getLength() == 1);
225
226         final Node dataNode = replyNodes.item(0);
227         assertEquals(dataNode.getLocalName(), DATA_ELEMENT);
228         assertFalse(dataNode.hasChildNodes());
229     }
230
231     protected static void verifyResponse(final Document response, final Document template) throws Exception {
232         final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
233         dd.overrideElementQualifier(new NetconfXmlUnitRecursiveQualifier());
234         if (!dd.similar()) {
235             LOG.warn("Actual response:");
236             printDocument(response);
237             LOG.warn("Expected response:");
238             printDocument(template);
239             fail("Differences found: " + dd.toString());
240         }
241     }
242
243     private static void printDocument(final Document doc) throws Exception {
244         final TransformerFactory tf = TransformerFactory.newInstance();
245         final Transformer transformer = tf.newTransformer();
246         transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
247         transformer.setOutputProperty(OutputKeys.METHOD, "xml");
248         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
249         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
250         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
251
252         final StringWriter writer = new StringWriter();
253         transformer.transform(new DOMSource(doc),
254             new StreamResult(writer));
255         LOG.warn(writer.getBuffer().toString());
256     }
257 }