Fix various warnings
[netconf.git] / netconf / mdsal-netconf-connector / src / test / java / org / opendaylight / netconf / mdsal / connector / ops / NetconfMDSalMappingTest.java
1 /*
2  * Copyright (c) 2015 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 import static org.mockito.Matchers.any;
16 import static org.mockito.Mockito.doAnswer;
17
18 import com.google.common.io.ByteSource;
19 import com.google.common.util.concurrent.Futures;
20 import java.io.InputStream;
21 import java.io.StringWriter;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.EnumMap;
25 import java.util.List;
26 import java.util.concurrent.ExecutorService;
27 import javax.xml.transform.OutputKeys;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerFactory;
30 import javax.xml.transform.dom.DOMSource;
31 import javax.xml.transform.stream.StreamResult;
32 import org.custommonkey.xmlunit.DetailedDiff;
33 import org.custommonkey.xmlunit.Diff;
34 import org.custommonkey.xmlunit.XMLUnit;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.mockito.Mock;
38 import org.mockito.MockitoAnnotations;
39 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
40 import org.opendaylight.controller.config.util.xml.DocumentedException;
41 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
42 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
43 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
44 import org.opendaylight.controller.config.util.xml.XmlElement;
45 import org.opendaylight.controller.config.util.xml.XmlUtil;
46 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
47 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
48 import org.opendaylight.controller.sal.core.api.model.SchemaService;
49 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
50 import org.opendaylight.netconf.mapping.api.NetconfOperation;
51 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
52 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
53 import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
54 import org.opendaylight.netconf.mdsal.connector.ops.get.Get;
55 import org.opendaylight.netconf.mdsal.connector.ops.get.GetConfig;
56 import org.opendaylight.netconf.util.test.NetconfXmlUnitRecursiveQualifier;
57 import org.opendaylight.netconf.util.test.XmlFileLoader;
58 import org.opendaylight.yangtools.concepts.ListenerRegistration;
59 import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.model.api.Module;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
68 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.w3c.dom.Document;
72 import org.w3c.dom.Node;
73 import org.w3c.dom.NodeList;
74
75 public class NetconfMDSalMappingTest {
76     private static final Logger LOG = LoggerFactory.getLogger(NetconfMDSalMappingTest.class);
77
78     private static final String RPC_REPLY_ELEMENT = "rpc-reply";
79     private static final String DATA_ELEMENT = "data";
80     private static final String FILTER_NODE = "filter";
81     private static final String GET_CONFIG = "get-config";
82     private static final QName TOP = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "top");
83     private static final QName USERS = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "users");
84     private static final QName USER = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "user");
85     private static final QName MODULES = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "modules");
86     private static final QName AUGMENTED_CONTAINER = QName.create("urn:opendaylight:mdsal:mapping:test",
87             "2015-02-26", "augmented-container");
88     private static final QName AUGMENTED_STRING_IN_CONT = QName.create("urn:opendaylight:mdsal:mapping:test",
89             "2015-02-26", "identifier");
90     private static final QName CHOICE_NODE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
91             "choice-node");
92     private static final QName AUGMENTED_CASE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
93             "augmented-case");
94     private static final QName CHOICE_WRAPPER = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
95             "choice-wrapper");
96     private static final QName INNER_CHOICE = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
97             "inner-choice");
98     private static final QName INNER_CHOICE_TEXT = QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26",
99             "text");
100
101     private static final YangInstanceIdentifier AUGMENTED_CONTAINER_IN_MODULES =
102             YangInstanceIdentifier.builder().node(TOP).node(MODULES).build();
103     private static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
104     private static final Document RPC_REPLY_OK = NetconfMDSalMappingTest.getReplyOk();
105
106     private CurrentSchemaContext currentSchemaContext = null;
107     private SchemaContext schemaContext = null;
108     private TransactionProvider transactionProvider = null;
109
110     @Mock
111     private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
112
113     @SuppressWarnings("illegalCatch")
114     private static Document getReplyOk() {
115         Document doc;
116         try {
117             doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpc-reply_ok.xml");
118         } catch (final Exception e) {
119             LOG.debug("unable to load rpc reply ok.", e);
120             doc = XmlUtil.newDocument();
121         }
122         return doc;
123     }
124
125     @Before
126     public void setUp() throws Exception {
127         MockitoAnnotations.initMocks(this);
128
129         XMLUnit.setIgnoreWhitespace(true);
130         XMLUnit.setIgnoreAttributeOrder(true);
131
132         this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
133         schemaContext.getModules();
134         final SchemaService schemaService = createSchemaService();
135
136         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
137         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
138
139         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
140         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
141         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
142
143         final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
144                 16, 16, "CommitFutures");
145
146         final ConcurrentDOMDataBroker cdb = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
147         this.transactionProvider = new TransactionProvider(cdb, SESSION_ID_FOR_REPORTING);
148
149         doAnswer(invocationOnMock -> {
150             final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
151             final YangTextSchemaSource yangTextSchemaSource =
152                     YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
153             return Futures.immediateCheckedFuture(yangTextSchemaSource);
154
155         }).when(sourceProvider).getSource(any(SourceIdentifier.class));
156
157         this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
158     }
159
160     @Test
161     public void testEmptyDatastore() throws Exception {
162         assertEmptyDatastore(get());
163         assertEmptyDatastore(getConfigCandidate());
164         assertEmptyDatastore(getConfigRunning());
165     }
166
167     @Test
168     public void testIncorrectGet() throws Exception {
169         try {
170             executeOperation(new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider),
171                     "messages/mapping/bad_getConfig.xml");
172             fail("Should have failed, this is an incorrect request");
173         } catch (final DocumentedException e) {
174             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
175             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
176             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
177         }
178
179         try {
180             executeOperation(new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider),
181                     "messages/mapping/bad_namespace_getConfig.xml");
182             fail("Should have failed, this is an incorrect request");
183         } catch (final DocumentedException e) {
184             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
185             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
186             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
187         }
188     }
189
190     @Test
191     public void testEditRunning() throws Exception {
192         try {
193             edit("messages/mapping/editConfigs/editConfig_running.xml");
194             fail("Should have failed - edit config on running datastore is not supported");
195         } catch (final DocumentedException e) {
196             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
197             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_NOT_SUPPORTED);
198             assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
199         }
200     }
201
202     @Test
203     public void testCommitWithoutOpenTransaction() throws Exception {
204         verifyResponse(commit(), RPC_REPLY_OK);
205         assertEmptyDatastore(getConfigCandidate());
206     }
207
208     @Test
209     public void testCandidateTransaction() throws Exception {
210         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_n1.xml"), RPC_REPLY_OK);
211         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
212                 "messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
213         assertEmptyDatastore(getConfigRunning());
214
215         verifyResponse(discardChanges(), RPC_REPLY_OK);
216         assertEmptyDatastore(getConfigCandidate());
217     }
218
219     @Test
220     public void testEditWithCommit() throws Exception {
221         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_n1.xml"), RPC_REPLY_OK);
222         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
223                 "messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
224
225         verifyResponse(commit(), RPC_REPLY_OK);
226         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
227                 "messages/mapping/editConfigs/editConfig_merge_n1_control.xml"));
228
229         deleteDatastore();
230     }
231
232     @Test
233     public void testKeyOrder() throws Exception {
234         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_keys_1.xml"), RPC_REPLY_OK);
235         verifyResponse(commit(), RPC_REPLY_OK);
236         final Document configRunning = getConfigRunning();
237         final String responseAsString = XmlUtil.toString(configRunning);
238         verifyResponse(configRunning, XmlFileLoader.xmlFileToDocument(
239                 "messages/mapping/editConfigs/editConfig_merge_multiple_keys_1_control.xml"));
240
241         final int key3 = responseAsString.indexOf("key3");
242         final int key1 = responseAsString.indexOf("key1");
243         final int key2 = responseAsString.indexOf("key2");
244
245         assertTrue(String.format("Key ordering invalid, should be key3(%d) < key1(%d) < key2(%d)", key3, key1, key2),
246                 key3 < key1 && key1 < key2);
247
248         deleteDatastore();
249     }
250
251
252     @Test
253     public void testMultipleEditsWithMerge() throws Exception {
254         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_1.xml"), RPC_REPLY_OK);
255         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
256                 "messages/mapping/editConfigs/editConfig_merge_multiple_control_1.xml"));
257         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_single_1.xml"), RPC_REPLY_OK);
258         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
259                 "messages/mapping/editConfigs/editConfig_merge_multiple_control_2.xml"));
260         assertEmptyDatastore(getConfigRunning());
261
262         verifyResponse(commit(), RPC_REPLY_OK);
263         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
264                 "messages/mapping/editConfigs/editConfig_merge_multiple_control_2.xml"));
265
266         deleteDatastore();
267     }
268
269     @Test
270     public void testMoreComplexEditConfigs() throws Exception {
271         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_1.xml"), RPC_REPLY_OK);
272         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_single_1.xml"), RPC_REPLY_OK);
273
274         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_2.xml"), RPC_REPLY_OK);
275         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
276                 "messages/mapping/editConfigs/editConfig_merge_multiple_after_more_complex_merge.xml"));
277
278         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_3.xml"), RPC_REPLY_OK);
279         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
280                 "messages/mapping/editConfigs/editConfig_merge_multiple_after_more_complex_merge_2.xml"));
281
282         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_4_replace.xml"), RPC_REPLY_OK);
283         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
284                 "messages/mapping/editConfigs/editConfig_merge_multiple_after_replace.xml"));
285         verifyResponse(commit(), RPC_REPLY_OK);
286
287         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
288                 "messages/mapping/editConfigs/editConfig_merge_multiple_after_replace.xml"));
289
290         verifyResponse(edit("messages/mapping/editConfigs/editConfig_replace_default.xml"), RPC_REPLY_OK);
291         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
292                 "messages/mapping/editConfigs/editConfig_replace_default_control.xml"));
293         verifyResponse(commit(), RPC_REPLY_OK);
294
295         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
296                 "messages/mapping/editConfigs/editConfig_replace_default_control.xml"));
297
298         deleteDatastore();
299     }
300
301     @Test
302     public void testLock() throws Exception {
303         verifyResponse(lockCandidate(), RPC_REPLY_OK);
304
305         try {
306             lock();
307             fail("Should have failed - locking of running datastore is not supported");
308         } catch (final DocumentedException e) {
309             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
310             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_NOT_SUPPORTED);
311             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
312         }
313
314         try {
315             lockWithoutTarget();
316             fail("Should have failed, target is missing");
317         } catch (final DocumentedException e) {
318             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
319             assertTrue(e.getErrorTag() == ErrorTag.INVALID_VALUE);
320             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
321         }
322     }
323
324     @Test
325     public void testUnlock() throws Exception {
326         verifyResponse(unlockCandidate(), RPC_REPLY_OK);
327
328         try {
329             unlock();
330             fail("Should have failed - unlocking of running datastore is not supported");
331         } catch (final DocumentedException e) {
332             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
333             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_NOT_SUPPORTED);
334             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
335         }
336
337         try {
338             unlockWithoutTarget();
339             fail("Should have failed, target is missing");
340         } catch (final DocumentedException e) {
341             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
342             assertTrue(e.getErrorTag() == ErrorTag.INVALID_VALUE);
343             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
344         }
345     }
346
347     @Test
348     public void testEditWithCreate() throws Exception {
349         verifyResponse(edit("messages/mapping/editConfigs/editConfig_create.xml"), RPC_REPLY_OK);
350         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
351                 "messages/mapping/editConfig_create_n1_control.xml"));
352
353         try {
354             edit("messages/mapping/editConfigs/editConfig_create.xml");
355             fail("Create should have failed - data already exists");
356         } catch (final DocumentedException e) {
357             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
358             assertTrue(e.getErrorTag() == ErrorTag.DATA_EXISTS);
359             assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
360         }
361
362         verifyResponse(discardChanges(), RPC_REPLY_OK);
363     }
364
365     @Test
366     public void testDeleteNonExisting() throws Exception {
367         assertEmptyDatastore(getConfigCandidate());
368         assertEmptyDatastore(getConfigRunning());
369
370         try {
371             edit("messages/mapping/editConfigs/editConfig_delete-top.xml");
372             fail("Delete should have failed - data is missing");
373         } catch (final DocumentedException e) {
374             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
375             assertTrue(e.getErrorTag() == ErrorTag.DATA_MISSING);
376             assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
377         }
378     }
379
380     @Test
381     public void testEditMissingDefaultOperation() throws Exception {
382         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_missing_default-operation_1.xml"),
383                 RPC_REPLY_OK);
384         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_missing_default-operation_2.xml"),
385                 RPC_REPLY_OK);
386         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
387                 "messages/mapping/editConfigs/editConfig_merge_missing_default-operation_control.xml"));
388
389         verifyResponse(commit(), RPC_REPLY_OK);
390         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument(
391                 "messages/mapping/editConfigs/editConfig_merge_missing_default-operation_control.xml"));
392
393         deleteDatastore();
394     }
395
396     private static void printDocument(final Document doc) throws Exception {
397         final TransformerFactory tf = TransformerFactory.newInstance();
398         final Transformer transformer = tf.newTransformer();
399         transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
400         transformer.setOutputProperty(OutputKeys.METHOD, "xml");
401         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
402         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
403         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
404
405         final StringWriter writer = new StringWriter();
406         transformer.transform(new DOMSource(doc),
407                 new StreamResult(writer));
408         LOG.warn(writer.getBuffer().toString());
409     }
410
411     @Test
412     public void testEditConfigWithMultipleOperations() throws Exception {
413         deleteDatastore();
414
415         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_setup.xml"),
416                 RPC_REPLY_OK);
417         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_1.xml"),
418                 RPC_REPLY_OK);
419
420         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_2.xml"),
421                 RPC_REPLY_OK);
422         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
423                 "messages/mapping/editConfigs/editConfig_merge_multiple_operations_2_control.xml"));
424
425         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_3_leaf_operations.xml"),
426                 RPC_REPLY_OK);
427         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
428                 "messages/mapping/editConfigs/editConfig_merge_multiple_operations_3_control.xml"));
429
430         deleteDatastore();
431
432         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_setup.xml"),
433                 RPC_REPLY_OK);
434         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_default-replace.xml"),
435                 RPC_REPLY_OK);
436
437         try {
438             edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_create_existing.xml");
439             fail();
440         } catch (final DocumentedException e) {
441             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
442             assertTrue(e.getErrorTag() == ErrorTag.DATA_EXISTS);
443             assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
444         }
445
446         verifyResponse(edit(
447                 "messages/mapping/editConfigs/"
448                         + "editConfig_merge_multiple_operations_4_delete_children_operations.xml"),
449                 RPC_REPLY_OK);
450         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
451                 "messages/mapping/editConfigs/"
452                         + "editConfig_merge_multiple_operations_4_delete_children_operations_control.xml"));
453         verifyResponse(edit(
454                 "messages/mapping/editConfigs/"
455                         + "editConfig_merge_multiple_operations_4_remove-non-existing.xml"),
456                 RPC_REPLY_OK);
457         try {
458             edit("messages/mapping/editConfigs/"
459                     + "editConfig_merge_multiple_operations_4_delete-non-existing.xml");
460             fail();
461         } catch (final DocumentedException e) {
462             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
463             assertTrue(e.getErrorTag() == ErrorTag.DATA_MISSING);
464             assertTrue(e.getErrorType() == ErrorType.PROTOCOL);
465         }
466
467         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup.xml"),
468                 RPC_REPLY_OK);
469         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
470                 "messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup-control.xml"));
471
472         // Test files have been modified. RFC6020 requires that at most once case inside a choice is present at any time
473         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup2.xml"),
474                 RPC_REPLY_OK);
475         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
476                 "messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_setup2-control.xml"));
477
478         verifyResponse(edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_5_choice_delete.xml"),
479                 RPC_REPLY_OK);
480         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument(
481                 "messages/mapping/editConfigs"
482                         + "/editConfig_merge_multiple_operations_4_delete_children_operations_control.xml"));
483
484         deleteDatastore();
485     }
486
487     @Test
488     public void testReplaceMapEntry() throws Exception {
489         verifyResponse(edit("messages/mapping/editConfigs/edit-config-replace-map-entry.xml"), RPC_REPLY_OK);
490         verifyResponse(commit(), RPC_REPLY_OK);
491         verifyResponse(getConfigRunning(),
492                 XmlFileLoader.xmlFileToDocument("messages/mapping/get-config-map-entry.xml"));
493     }
494
495     @Test
496     public void testMergeMapEntry() throws Exception {
497         verifyResponse(edit("messages/mapping/editConfigs/edit-config-merge-map-entry.xml"), RPC_REPLY_OK);
498         verifyResponse(commit(), RPC_REPLY_OK);
499         verifyResponse(getConfigRunning(),
500                 XmlFileLoader.xmlFileToDocument("messages/mapping/get-config-map-entry.xml"));
501     }
502
503     @Test
504     public void testFiltering() throws Exception {
505         assertEmptyDatastore(getConfigCandidate());
506         assertEmptyDatastore(getConfigRunning());
507
508         verifyResponse(getConfigWithFilter("messages/mapping/filters/get-config-empty-filter.xml"),
509                 XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response.xml"));
510         verifyResponse(getWithFilter("messages/mapping/filters/get-empty-filter.xml"),
511                 XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response.xml"));
512
513         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response"
514                 + ".xml"));
515         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response.xml"));
516         verifyResponse(getConfigWithFilter("messages/mapping/filters/get-filter-users.xml"),
517                 XmlFileLoader.xmlFileToDocument("messages/mapping/get-empty-response.xml"));
518
519         verifyResponse(edit("messages/mapping/editConfigs/editConfig-filtering-setup.xml"), RPC_REPLY_OK);
520         verifyResponse(commit(), RPC_REPLY_OK);
521
522         verifyFilterIdentifier("messages/mapping/filters/get-filter-alluser.xml",
523                 YangInstanceIdentifier.builder().node(TOP).node(USERS).node(USER).build());
524         verifyFilterIdentifier("messages/mapping/filters/get-filter-company-info.xml",
525                 YangInstanceIdentifier.builder().node(TOP).node(USERS).node(USER).build());
526         verifyFilterIdentifier("messages/mapping/filters/get-filter-modules-and-admin.xml",
527                 YangInstanceIdentifier.builder().node(TOP).build());
528         verifyFilterIdentifier("messages/mapping/filters/get-filter-only-names-types.xml",
529                 YangInstanceIdentifier.builder().node(TOP).node(USERS).node(USER).build());
530         verifyFilterIdentifier("messages/mapping/filters/get-filter-specific-module-type-and-user.xml",
531                 YangInstanceIdentifier.builder().node(TOP).build());
532         verifyFilterIdentifier("messages/mapping/filters/get-filter-superuser.xml",
533                 YangInstanceIdentifier.builder().node(TOP).node(USERS).node(USER).build());
534         verifyFilterIdentifier("messages/mapping/filters/get-filter-users.xml",
535                 YangInstanceIdentifier.builder().node(TOP).node(USERS).build());
536
537         final YangInstanceIdentifier ident = YangInstanceIdentifier
538                 .builder(AUGMENTED_CONTAINER_IN_MODULES)
539                 .node(AUGMENTED_CONTAINER)
540                 .node(AUGMENTED_STRING_IN_CONT).build();
541
542         verifyFilterIdentifier("messages/mapping/filters/get-filter-augmented-string.xml", ident);
543         verifyFilterIdentifier("messages/mapping/filters/get-filter-augmented-case.xml",
544                 YangInstanceIdentifier.builder().node(TOP).node(CHOICE_NODE).node(AUGMENTED_CASE).build());
545
546         verifyResponse(getConfigWithFilter("messages/mapping/filters/get-filter-augmented-case.xml"),
547                 XmlFileLoader.xmlFileToDocument("messages/mapping/filters/response-augmented-case.xml"));
548
549         /*
550          *  RFC6020 requires that at most once case inside a choice is present at any time.
551          *  Therefore
552          *  <augmented-case>augmented case</augmented-case>
553          *  from
554          *  messages/mapping/editConfigs/editConfig-filtering-setup.xml
555          *  cannot exists together with
556          *  <text>augmented nested choice text1</text>
557          *  from
558          *  messages/mapping/editConfigs/editConfig-filtering-setup2.xml
559          */
560         //verifyResponse(edit("messages/mapping/editConfigs/editConfig-filtering-setup2.xml"), RPC_REPLY_OK);
561         //verifyResponse(commit(), RPC_REPLY_OK);
562
563         verifyFilterIdentifier("messages/mapping/filters/get-filter-augmented-case-inner-choice.xml",
564                 YangInstanceIdentifier.builder().node(TOP).node(CHOICE_NODE).node(CHOICE_WRAPPER).build());
565         verifyFilterIdentifier("messages/mapping/filters/get-filter-augmented-case-inner-case.xml",
566                 YangInstanceIdentifier.builder().node(TOP).node(CHOICE_NODE).node(CHOICE_WRAPPER).node(INNER_CHOICE)
567                         .node(INNER_CHOICE_TEXT).build());
568
569 //        verifyResponse(getConfigWithFilter("messages/mapping/filters/get-filter-augmented-string.xml"),
570 //                XmlFileLoader.xmlFileToDocument("messages/mapping/filters/response-augmented-string.xml"));
571 //        verifyResponse(getConfigWithFilter("messages/mapping/filters/get-filter-augmented-case-inner-choice.xml"),
572 //                XmlFileLoader.xmlFileToDocument("messages/mapping/filters/response-augmented-case-inner-choice.xml"));
573 //        verifyResponse(getConfigWithFilter("messages/mapping/filters/get-filter-augmented-case-inner-case.xml"),
574 //                XmlFileLoader.xmlFileToDocument("messages/mapping/filters/response-augmented-case-inner-choice.xml"));
575
576         verifyResponse(edit("messages/mapping/editConfigs/editConfig_delete-top.xml"), RPC_REPLY_OK);
577         verifyResponse(commit(), RPC_REPLY_OK);
578
579     }
580
581     private void verifyFilterIdentifier(final String resource, final YangInstanceIdentifier identifier)
582             throws Exception {
583         final TestingGetConfig getConfig = new TestingGetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext,
584                 transactionProvider);
585         final Document request = XmlFileLoader.xmlFileToDocument(resource);
586         final YangInstanceIdentifier iid = getConfig.getInstanceIdentifierFromDocument(request);
587         assertEquals(identifier, iid);
588     }
589
590     private class TestingGetConfig extends GetConfig {
591         TestingGetConfig(final String sessionId, final CurrentSchemaContext schemaContext,
592                          final TransactionProvider transactionProvider) {
593             super(sessionId, schemaContext, transactionProvider);
594         }
595
596         YangInstanceIdentifier getInstanceIdentifierFromDocument(final Document request) throws DocumentedException {
597             final XmlElement filterElement = XmlElement.fromDomDocument(request).getOnlyChildElement(GET_CONFIG)
598                     .getOnlyChildElement(FILTER_NODE);
599             return getInstanceIdentifierFromFilter(filterElement);
600         }
601     }
602
603     private void deleteDatastore() throws Exception {
604         verifyResponse(edit("messages/mapping/editConfigs/editConfig_delete-root.xml"), RPC_REPLY_OK);
605         assertEmptyDatastore(getConfigCandidate());
606
607         verifyResponse(commit(), RPC_REPLY_OK);
608         assertEmptyDatastore(getConfigRunning());
609     }
610
611     private static void verifyResponse(final Document response, final Document template) throws Exception {
612         final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
613         dd.overrideElementQualifier(new NetconfXmlUnitRecursiveQualifier());
614
615         printDocument(response);
616         printDocument(template);
617
618         assertTrue(dd.toString(), dd.similar());
619     }
620
621     private static void assertEmptyDatastore(final Document response) {
622         final NodeList nodes = response.getChildNodes();
623         assertTrue(nodes.getLength() == 1);
624
625         assertEquals(nodes.item(0).getLocalName(), RPC_REPLY_ELEMENT);
626
627         final NodeList replyNodes = nodes.item(0).getChildNodes();
628         assertTrue(replyNodes.getLength() == 1);
629
630         final Node dataNode = replyNodes.item(0);
631         assertEquals(dataNode.getLocalName(), DATA_ELEMENT);
632         assertFalse(dataNode.hasChildNodes());
633     }
634
635     private Document commit() throws Exception {
636         final Commit commit = new Commit(SESSION_ID_FOR_REPORTING, transactionProvider);
637         return executeOperation(commit, "messages/mapping/commit.xml");
638     }
639
640     private Document discardChanges() throws Exception {
641         final DiscardChanges discardOp = new DiscardChanges(SESSION_ID_FOR_REPORTING, transactionProvider);
642         return executeOperation(discardOp, "messages/mapping/discardChanges.xml");
643     }
644
645     private Document edit(final String resource) throws Exception {
646         final EditConfig editConfig = new EditConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext,
647                 transactionProvider);
648         return executeOperation(editConfig, resource);
649     }
650
651     private Document get() throws Exception {
652         final Get get = new Get(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
653         return executeOperation(get, "messages/mapping/get.xml");
654     }
655
656     private Document getWithFilter(final String resource) throws Exception {
657         final Get get = new Get(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
658         return executeOperation(get, resource);
659     }
660
661     private Document getConfigRunning() throws Exception {
662         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
663         return executeOperation(getConfig, "messages/mapping/getConfig.xml");
664     }
665
666     private Document getConfigCandidate() throws Exception {
667         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
668         return executeOperation(getConfig, "messages/mapping/getConfig_candidate.xml");
669     }
670
671     private Document getConfigWithFilter(final String resource) throws Exception {
672         final GetConfig getConfig = new GetConfig(SESSION_ID_FOR_REPORTING, currentSchemaContext, transactionProvider);
673         return executeOperation(getConfig, resource);
674     }
675
676     private static Document lock() throws Exception {
677         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
678         return executeOperation(lock, "messages/mapping/lock.xml");
679     }
680
681     private static Document unlock() throws Exception {
682         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
683         return executeOperation(unlock, "messages/mapping/unlock.xml");
684     }
685
686     private static Document lockWithoutTarget() throws Exception {
687         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
688         return executeOperation(lock, "messages/mapping/lock_notarget.xml");
689     }
690
691     private static Document unlockWithoutTarget() throws Exception {
692         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
693         return executeOperation(unlock, "messages/mapping/unlock_notarget.xml");
694     }
695
696     private static Document lockCandidate() throws Exception {
697         final Lock lock = new Lock(SESSION_ID_FOR_REPORTING);
698         return executeOperation(lock, "messages/mapping/lock_candidate.xml");
699     }
700
701     private static Document unlockCandidate() throws Exception {
702         final Unlock unlock = new Unlock(SESSION_ID_FOR_REPORTING);
703         return executeOperation(unlock, "messages/mapping/unlock_candidate.xml");
704     }
705
706     private static Document executeOperation(final NetconfOperation op, final String filename) throws Exception {
707         final Document request = XmlFileLoader.xmlFileToDocument(filename);
708         final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
709
710         LOG.debug("Got response {}", response);
711         return response;
712     }
713
714     private List<InputStream> getYangSchemas() {
715         final List<String> schemaPaths = Arrays.asList("/META-INF/yang/config.yang",
716                 "/yang/mdsal-netconf-mapping-test.yang");
717         final List<InputStream> schemas = new ArrayList<>();
718
719         for (final String schemaPath : schemaPaths) {
720             final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
721             schemas.add(resourceAsStream);
722         }
723
724         return schemas;
725     }
726
727     private SchemaService createSchemaService() {
728         return new SchemaService() {
729
730             @Override
731             public void addModule(final Module module) {
732             }
733
734             @Override
735             public void removeModule(final Module module) {
736
737             }
738
739             @Override
740             public SchemaContext getSessionContext() {
741                 return schemaContext;
742             }
743
744             @Override
745             public SchemaContext getGlobalContext() {
746                 return schemaContext;
747             }
748
749             @Override
750             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
751                     final SchemaContextListener listener) {
752                 listener.onGlobalContextUpdated(getGlobalContext());
753                 return new ListenerRegistration<SchemaContextListener>() {
754                     @Override
755                     public void close() {
756
757                     }
758
759                     @Override
760                     public SchemaContextListener getInstance() {
761                         return listener;
762                     }
763                 };
764             }
765         };
766     }
767 }