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