YANGTOOLS-813: add parent schemapath to error report
[yangtools.git] / yang / yang-data-codec-xml / src / test / java / org / opendaylight / yangtools / yang / data / codec / xml / NormalizedNodeXmlTranslationTest.java
1 /*
2  * Copyright (c) 2016 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.yangtools.yang.data.codec.xml;
10
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13 import static org.junit.Assert.assertNotNull;
14 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.augmentationBuilder;
15 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.choiceBuilder;
16 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.containerBuilder;
17 import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.leafNode;
18
19 import com.google.common.collect.ImmutableSet;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.StringWriter;
23 import java.net.URI;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Map;
29 import java.util.Set;
30 import javax.xml.stream.XMLInputFactory;
31 import javax.xml.stream.XMLOutputFactory;
32 import javax.xml.stream.XMLStreamReader;
33 import javax.xml.stream.XMLStreamWriter;
34 import javax.xml.transform.OutputKeys;
35 import javax.xml.transform.Transformer;
36 import javax.xml.transform.TransformerException;
37 import javax.xml.transform.TransformerFactory;
38 import javax.xml.transform.TransformerFactoryConfigurationError;
39 import javax.xml.transform.dom.DOMResult;
40 import javax.xml.transform.dom.DOMSource;
41 import javax.xml.transform.stream.StreamResult;
42 import org.custommonkey.xmlunit.Diff;
43 import org.custommonkey.xmlunit.ElementNameAndTextQualifier;
44 import org.custommonkey.xmlunit.IgnoreTextAndAttributeValuesDifferenceListener;
45 import org.custommonkey.xmlunit.XMLUnit;
46 import org.junit.Test;
47 import org.junit.runner.RunWith;
48 import org.junit.runners.Parameterized;
49 import org.opendaylight.yangtools.util.xml.UntrustedXML;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.common.Revision;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
63 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
64 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
65 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
66 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
67 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
68 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
71 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
72 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
75 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.Module;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
79 import org.w3c.dom.Document;
80 import org.w3c.dom.Node;
81 import org.xml.sax.SAXException;
82
83 @RunWith(Parameterized.class)
84 public class NormalizedNodeXmlTranslationTest {
85     private final SchemaContext schema;
86
87     @Parameterized.Parameters()
88     public static Collection<Object[]> data() {
89         return Arrays.asList(new Object[][] {
90                 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok.xml", augmentChoiceHell() },
91                 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok2.xml", null },
92                 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok3.xml", augmentChoiceHell2() },
93                 { "/schema/test.yang", "/schema/simple.xml", null },
94                 { "/schema/test.yang", "/schema/simple2.xml", null },
95                 // TODO check attributes
96                 { "/schema/test.yang", "/schema/simple_xml_with_attributes.xml", withAttributes() }
97         });
98     }
99
100     private static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
101     private static final Revision REVISION = Revision.of("2014-03-13");
102
103     static final XMLOutputFactory XML_FACTORY;
104
105     static {
106         XML_FACTORY = XMLOutputFactory.newFactory();
107         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
108     }
109
110     private static ContainerNode augmentChoiceHell2() {
111         final NodeIdentifier container = getNodeIdentifier("container");
112         final QName augmentChoice1QName = QName.create(container.getNodeType(), "augment-choice1");
113         final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
114         final QName containerQName = QName.create(augmentChoice1QName, "case11-choice-case-container");
115         final QName leafQName = QName.create(augmentChoice1QName, "case11-choice-case-leaf");
116
117         final AugmentationIdentifier aug1Id = new AugmentationIdentifier(ImmutableSet.of(augmentChoice1QName));
118         final AugmentationIdentifier aug2Id = new AugmentationIdentifier(ImmutableSet.of(augmentChoice2QName));
119         final NodeIdentifier augmentChoice1Id = new NodeIdentifier(augmentChoice1QName);
120         final NodeIdentifier augmentChoice2Id = new NodeIdentifier(augmentChoice2QName);
121         final NodeIdentifier containerId = new NodeIdentifier(containerQName);
122
123         return containerBuilder().withNodeIdentifier(container)
124                 .withChild(augmentationBuilder().withNodeIdentifier(aug1Id)
125                         .withChild(choiceBuilder().withNodeIdentifier(augmentChoice1Id)
126                                 .withChild(augmentationBuilder().withNodeIdentifier(aug2Id)
127                                         .withChild(choiceBuilder().withNodeIdentifier(augmentChoice2Id)
128                                                 .withChild(containerBuilder().withNodeIdentifier(containerId)
129                                                         .withChild(leafNode(leafQName, "leaf-value"))
130                                                         .build())
131                                                 .build())
132                                         .build())
133                                 .build())
134                         .build()).build();
135     }
136
137     private static ContainerNode withAttributes() {
138         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> b = containerBuilder();
139         b.withNodeIdentifier(getNodeIdentifier("container"));
140
141         final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
142                 getNodeIdentifier("list"));
143
144         final Map<QName, Object> predicates = new HashMap<>();
145         predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
146
147         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
148                 .mapEntryBuilder().withNodeIdentifier(
149                         new NodeIdentifierWithPredicates(
150                                 getNodeIdentifier("list").getNodeType(), predicates));
151         final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> uint32InListBuilder = Builders
152                 .leafBuilder().withNodeIdentifier(getNodeIdentifier("uint32InList"));
153
154         list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
155
156         listBuilder.withChild(list1Builder.build());
157         b.withChild(listBuilder.build());
158
159         final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> booleanBuilder = Builders
160                 .leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
161         booleanBuilder.withValue(Boolean.FALSE);
162         b.withChild(booleanBuilder.build());
163
164         final ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder = Builders.leafSetBuilder()
165                 .withNodeIdentifier(getNodeIdentifier("leafList"));
166
167         final NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder = Builders
168                 .leafSetEntryBuilder().withNodeIdentifier(
169                         new NodeWithValue(getNodeIdentifier("leafList").getNodeType(), "a"));
170
171         leafList1Builder.withValue("a");
172
173         leafListBuilder.withChild(leafList1Builder.build());
174         b.withChild(leafListBuilder.build());
175
176         return b.build();
177     }
178
179     private static ContainerNode augmentChoiceHell() {
180
181         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> b = containerBuilder();
182         b.withNodeIdentifier(getNodeIdentifier("container"));
183
184         b.withChild(choiceBuilder()
185                 .withNodeIdentifier(getNodeIdentifier("ch2"))
186                 .withChild(
187                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2").build())
188                 .withChild(
189                         choiceBuilder()
190                                 .withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
191                                 .withChild(
192                                         Builders.leafBuilder()
193                                                 .withNodeIdentifier(getNodeIdentifier("c2DeepChoiceCase1Leaf2"))
194                                                 .withValue("2").build()).build()).build());
195
196         b.withChild(choiceBuilder()
197                 .withNodeIdentifier(getNodeIdentifier("ch3"))
198                 .withChild(
199                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3").build())
200                 .build());
201
202         b.withChild(augmentationBuilder()
203                 .withNodeIdentifier(getAugmentIdentifier("augLeaf"))
204                 .withChild(
205                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("augLeaf")).withValue("augment")
206                                 .build()).build());
207
208         b.withChild(augmentationBuilder()
209                 .withNodeIdentifier(getAugmentIdentifier("ch"))
210                 .withChild(
211                         choiceBuilder()
212                                 .withNodeIdentifier(getNodeIdentifier("ch"))
213                                 .withChild(
214                                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf"))
215                                                 .withValue("1").build())
216                                 .withChild(
217                                         augmentationBuilder()
218                                                 .withNodeIdentifier(
219                                                         getAugmentIdentifier("c1Leaf_AnotherAugment", "deepChoice"))
220                                                 .withChild(
221                                                         Builders.leafBuilder()
222                                                                 .withNodeIdentifier(
223                                                                         getNodeIdentifier("c1Leaf_AnotherAugment"))
224                                                                 .withValue("1").build())
225                                                 .withChild(
226                                                         choiceBuilder()
227                                                                 .withNodeIdentifier(getNodeIdentifier("deepChoice"))
228                                                                 .withChild(
229                                                                         Builders.leafBuilder()
230                                                                                 .withNodeIdentifier(
231                                                                                         getNodeIdentifier("deepLeafc1"))
232                                                                                 .withValue("1").build()).build())
233                                                 .build()).build()).build());
234
235         return b.build();
236     }
237
238     private static NodeIdentifier getNodeIdentifier(final String localName) {
239         return new NodeIdentifier(QName.create(URI.create(NAMESPACE), REVISION, localName));
240     }
241
242     private static AugmentationIdentifier getAugmentIdentifier(final String... childNames) {
243         final Set<QName> qn = new HashSet<>();
244
245         for (final String childName : childNames) {
246             qn.add(getNodeIdentifier(childName).getNodeType());
247         }
248
249         return new AugmentationIdentifier(qn);
250     }
251
252     public NormalizedNodeXmlTranslationTest(final String yangPath, final String xmlPath,
253             final ContainerNode expectedNode) {
254         this.schema = YangParserTestUtils.parseYangResource(yangPath);
255         this.xmlPath = xmlPath;
256         this.containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
257         this.expectedNode = expectedNode;
258     }
259
260     private final ContainerNode expectedNode;
261     private final ContainerSchemaNode containerNode;
262     private final String xmlPath;
263
264     @Test
265     public void testTranslation() throws Exception {
266         final InputStream resourceAsStream = XmlToNormalizedNodesTest.class.getResourceAsStream(xmlPath);
267
268         final XMLInputFactory factory = XMLInputFactory.newInstance();
269         final XMLStreamReader reader = factory.createXMLStreamReader(resourceAsStream);
270
271         final NormalizedNodeResult result = new NormalizedNodeResult();
272         final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
273
274         final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, schema, containerNode);
275         xmlParser.parse(reader);
276
277         final NormalizedNode<?, ?> built = result.getResult();
278         assertNotNull(built);
279
280         if (expectedNode != null) {
281             org.junit.Assert.assertEquals(expectedNode, built);
282         }
283
284         final Document document = UntrustedXML.newDocumentBuilder().newDocument();
285         final DOMResult domResult = new DOMResult(document);
286
287         final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
288         outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
289
290         final XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(domResult);
291
292         final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter
293                 .create(xmlStreamWriter, schema);
294
295         final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
296                 xmlNormalizedNodeStreamWriter);
297
298         normalizedNodeWriter.write(built);
299
300         final Document doc = loadDocument(xmlPath);
301
302         XMLUnit.setIgnoreWhitespace(true);
303         XMLUnit.setIgnoreComments(true);
304         XMLUnit.setIgnoreAttributeOrder(true);
305         XMLUnit.setNormalize(true);
306
307         final String expectedXml = toString(doc.getDocumentElement());
308         final String serializedXml = toString(domResult.getNode());
309
310         final Diff diff = new Diff(expectedXml, serializedXml);
311         diff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
312         diff.overrideElementQualifier(new ElementNameAndTextQualifier());
313
314         // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in
315         // this case
316         // We need to implement custom qualifier so that the element ordering does not mess the DIFF
317         // dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
318         // assertTrue(dd.toString(), dd.similar());
319
320         //new XMLTestCase() {}.assertXMLEqual(diff, true);
321     }
322
323     private static Document loadDocument(final String xmlPath) throws IOException, SAXException {
324         final InputStream resourceAsStream = NormalizedNodeXmlTranslationTest.class.getResourceAsStream(xmlPath);
325         return requireNonNull(readXmlToDocument(resourceAsStream));
326     }
327
328     private static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
329         final Document doc = UntrustedXML.newDocumentBuilder().parse(xmlContent);
330         doc.getDocumentElement().normalize();
331         return doc;
332     }
333
334     private static String toString(final Node xml) {
335         try {
336             final Transformer transformer = TransformerFactory.newInstance().newTransformer();
337             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
338             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
339
340             final StreamResult result = new StreamResult(new StringWriter());
341             final DOMSource source = new DOMSource(xml);
342             transformer.transform(source, result);
343
344             return result.getWriter().toString();
345         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
346             throw new RuntimeException("Unable to serialize xml element " + xml, e);
347         }
348     }
349
350     private static DataSchemaNode getSchemaNode(final SchemaContext context, final String moduleName,
351                                                final String childNodeName) {
352         for (Module module : context.getModules()) {
353             if (module.getName().equals(moduleName)) {
354                 DataSchemaNode found = findChildNode(module, childNodeName);
355                 checkState(found != null, "Unable to find %s", childNodeName);
356                 return found;
357             }
358         }
359         throw new IllegalStateException("Unable to find child node " + childNodeName);
360     }
361
362     // FIXME: duplicate of NormalizedDataBuilderTest.findChildNode()
363     private static DataSchemaNode findChildNode(final DataNodeContainer container, final String name) {
364         for (DataSchemaNode dataSchemaNode : container.getChildNodes()) {
365             if (dataSchemaNode.getQName().getLocalName().equals(name)) {
366                 return dataSchemaNode;
367             }
368             if (dataSchemaNode instanceof DataNodeContainer) {
369                 DataSchemaNode retVal = findChildNode((DataNodeContainer) dataSchemaNode, name);
370                 if (retVal != null) {
371                     return retVal;
372                 }
373             } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
374                 for (ChoiceCaseNode caseNode : ((ChoiceSchemaNode) dataSchemaNode).getCases().values()) {
375                     DataSchemaNode retVal = findChildNode(caseNode, name);
376                     if (retVal != null) {
377                         return retVal;
378                     }
379                 }
380             }
381         }
382         return null;
383     }
384
385 }