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