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