Reuse schemaContext in mdsal-netconf-connector tests
[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 package org.opendaylight.netconf.mdsal.connector.ops;
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.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.AfterClass;
31 import org.junit.Before;
32 import org.junit.BeforeClass;
33 import org.mockito.MockitoAnnotations;
34 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
35 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
36 import org.opendaylight.mdsal.dom.broker.SerializedDOMDataBroker;
37 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
38 import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStoreFactory;
39 import org.opendaylight.netconf.api.xml.XmlUtil;
40 import org.opendaylight.netconf.mapping.api.NetconfOperation;
41 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
42 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
43 import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
44 import org.opendaylight.netconf.mdsal.connector.ops.get.Get;
45 import org.opendaylight.netconf.mdsal.connector.ops.get.GetConfig;
46 import org.opendaylight.netconf.util.test.NetconfXmlUnitRecursiveQualifier;
47 import org.opendaylight.netconf.util.test.XmlFileLoader;
48 import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Node;
55 import org.w3c.dom.NodeList;
56
57 public abstract class AbstractNetconfOperationTest {
58     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfOperationTest.class);
59     protected static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
60     private static final String RPC_REPLY_ELEMENT = "rpc-reply";
61     private static final String DATA_ELEMENT = "data";
62     protected static final Document RPC_REPLY_OK = getReplyOk();
63
64     private static SchemaContext SCHEMA_CONTEXT;
65
66     private CurrentSchemaContext currentSchemaContext;
67     private TransactionProvider transactionProvider;
68
69     @BeforeClass
70     public static void beforeClass() {
71         SCHEMA_CONTEXT = parseYangResources(AbstractNetconfOperationTest.class,
72             "/yang/mdsal-netconf-mapping-test.yang");
73     }
74
75     @AfterClass
76     public static void afterClass() {
77         SCHEMA_CONTEXT = null;
78     }
79
80     @Before
81     public void setUp() throws Exception {
82         MockitoAnnotations.initMocks(this);
83
84         XMLUnit.setIgnoreWhitespace(true);
85         XMLUnit.setIgnoreAttributeOrder(true);
86
87         final DOMSchemaService schemaService = new SchemaServiceStub(SCHEMA_CONTEXT);
88         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
89         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
90
91         currentSchemaContext = new CurrentSchemaContext(schemaService, sourceIdentifier -> {
92             final YangTextSchemaSource yangTextSchemaSource =
93                 YangTextSchemaSource.delegateForByteSource(sourceIdentifier, ByteSource.wrap("module test".getBytes()));
94             return Futures.immediateFuture(yangTextSchemaSource);
95         });
96
97         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
98         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
99         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
100
101         final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
102             16, 16, "CommitFutures", CopyConfigTest.class);
103
104         final SerializedDOMDataBroker sdb = new SerializedDOMDataBroker(datastores,
105             MoreExecutors.listeningDecorator(listenableFutureExecutor));
106         this.transactionProvider = new TransactionProvider(sdb, SESSION_ID_FOR_REPORTING);
107     }
108
109     protected CurrentSchemaContext getCurrentSchemaContext() {
110         return currentSchemaContext;
111     }
112
113     protected TransactionProvider getTransactionProvider() {
114         return transactionProvider;
115     }
116
117     @SuppressWarnings("illegalCatch")
118     private static Document getReplyOk() {
119         Document doc;
120         try {
121             doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpc-reply_ok.xml");
122         } catch (final Exception 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 }