summaryrefslogtreecommitdiff
path: root/test/java/src/org/apache/qetest/xalanj2/TestXPathAPI.java
blob: f5481236b22ef8c5ce469d219e2077ad511892ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the  "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * $Id$
 */
// This file uses 2 space indents, no tabs.

/*
 *
 * TestXPathAPI.java
 *
 */
package org.apache.qetest.xalanj2;

import android.platform.test.annotations.FlakyTest;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.qetest.FileBasedTest;
import org.apache.qetest.OutputNameManager;
import org.apache.qetest.xsl.XSLTestfileInfo;
import org.apache.test.android.AndroidFileUtils;
import org.apache.xml.dtm.DTM;
import org.apache.xml.dtm.DTMIterator;
import org.apache.xml.dtm.DTMManager;
import org.apache.xml.utils.PrefixResolverDefault;
import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.XObject;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.InputSource;

/**
 * Basic functionality test of the public XPathAPI methods.
 * 
 * Very basic coverage/smoketest level test.
 * Applies a number of XPaths to some sample documents 
 * and checks output from the various public XPathAPI mehods.
 * @see XPathAPI
 * @author myriam_midy@lotus.com
 * @author shane_curcuru@lotus.com
 */
public class TestXPathAPI extends FileBasedTest
{
  /** Array of sample XPaths to test.  */
  protected String[] xpath;
  
  /** Base path/name of all output files.  */
  protected String baseOutName = null;

  protected XSLTestfileInfo testFileInfo1 = new XSLTestfileInfo();
  protected XSLTestfileInfo testFileInfo2 = new XSLTestfileInfo();
  protected XSLTestfileInfo testFileInfo3 = new XSLTestfileInfo();
  protected XSLTestfileInfo testFileInfo4 = new XSLTestfileInfo();
  protected XSLTestfileInfo testFileInfo5 = new XSLTestfileInfo();
  protected XSLTestfileInfo testFileInfo6 = new XSLTestfileInfo();
  protected XSLTestfileInfo testFileInfo7 = new XSLTestfileInfo();


  /** Provides nextName(), currentName() functionality.  */
  protected OutputNameManager outNames; 

  /** Subdirectory under test\tests\api for our xsl/xml files.  */
    public static final String X2J_SUBDIR = "xalanj2";

    /** Just initialize test name, comment, numTestCases. */
    public TestXPathAPI()
    {
        numTestCases = 7;  // REPLACE_num
        testName = "TestXPathAPI";
        testComment = "API coverage testing of XPathAPI";
    }
    
    /**
     * Initialize this test - Set names of xml/xsl test files etc.  
     * Also initializes an array of sample xpaths to test.
     *
     * @param p Properties to initialize from (if needed)
     * @return false if we should abort the test; true otherwise
     */
    public boolean doTestFileInit(Properties p)
    {
        // Used for all tests; just dump files in trax subdir
        File outSubDir = new File(outputDir + File.separator + X2J_SUBDIR);
        if (!outSubDir.mkdirs())
            reporter.logWarningMsg("Could not create output dir: " + outSubDir);
        // Output name manager initialized in each testCase
        baseOutName = outputDir + File.separator + X2J_SUBDIR + File.separator + testName;
       
        String testBasePath = inputDir 
                              + File.separator 
                              + X2J_SUBDIR
                              + File.separator;
        String goldBasePath = goldDir 
                              + File.separator 
                              + X2J_SUBDIR
                              + File.separator;

        // Gold names are appended onto for each test
        testFileInfo1.xmlName = testBasePath + "testXPath.xml";
        testFileInfo1.goldName = goldBasePath;

        testFileInfo2.xmlName = testBasePath + "testXPath.xml";
        testFileInfo2.goldName = goldBasePath;

        testFileInfo3.xmlName = testBasePath + "testXPath.xml";
        testFileInfo3.goldName = goldBasePath;

        testFileInfo4.xmlName = testBasePath + "testXPath.xml";
        testFileInfo4.goldName = goldBasePath;
        
        testFileInfo5.xmlName = testBasePath + "testXPath.xml";
        testFileInfo5.goldName = goldBasePath;
        
        testFileInfo6.xmlName = testBasePath + "testXPath2.xml";
        testFileInfo6.goldName = goldBasePath;
        
        testFileInfo7.xmlName = testBasePath + "testXPath3.xml";
        testFileInfo7.goldName = goldBasePath;
        
        // Initialize xpath test data
        // Note: when adding new xpaths, update array ctor and 
        //  also need to update each testCase's gold files
        xpath = new String[25];
        xpath[0] = "/doc/a/@test";
        xpath[1] = "//."; 
        xpath[2] = "/doc"; 
        xpath[3] = "/doc/a"; 
        xpath[4] = "//@*";
        xpath[5] = ".";
        xpath[6] = "//ancestor-or-self::*";
        xpath[7] = "./child::*[1]";
        xpath[8] = "//descendant-or-self::*/@*[1]";
        xpath[9] = "//@* | * | node()";
        xpath[10] = "//*";
        xpath[11] = "/doc/namespace::*";
        xpath[12] = "//descendant::comment()";        
        xpath[13] = "//*[local-name()='a']";
        xpath[14] = "//*[current()]/@*";
        xpath[15] = "//*[last()]";
        xpath[16] = "doc/*[last()]";
        xpath[17] = "/doc/a/*[current()]/@*";
        xpath[18] = "doc/descendant::node()";
        xpath[19] = "doc/a/@*";
        xpath[20] = "doc/b/a/ancestor-or-self::*";
        xpath[21] = "doc/b/a/preceding::*";
        xpath[22] = "doc/a/following::*";
        xpath[23] = "/doc/b/preceding-sibling::*";
        xpath[24] = "/doc/a/following-sibling::*";
               
        return true;
    }


  
  /** Quick test of XPathAPI.selectNodeIterator().  */
  public boolean testCase1()
    throws Exception
  {        
    reporter.testCaseInit("Quick test of XPathAPI.selectNodeIterator()");
    outNames = new OutputNameManager(baseOutName + reporter.getCurrentCaseNum(), ".out");
    
    Document doc = parseToDOM(testFileInfo1.xmlName);
    Transformer serializer = getSerializer();
    
    for (int i=0;i<xpath.length; i++) 
    {
      // Use the simple XPath API to select a nodeIterator.
      NodeIterator nl = XPathAPI.selectNodeIterator(doc, xpath[i]);
      
      Node n;
      while ((n = nl.nextNode())!= null)
      { 
        serializer.transform(new DOMSource(n), new StreamResult(outNames.nextName()));
        File f = new File(outNames.currentName()); 
        fileChecker.check(reporter, 
                           f, 
                           new File(testFileInfo1.goldName + f.getName()), 
                          "selectNodeIterator() of "+xpath[i] + " into " + outNames.currentName());
      }
    } // of for...
    reporter.testCaseClose();
    return true;
  }
  
  /** Quick test of XPathAPI.selectNodeList().  */
  public boolean testCase2()
    throws Exception
  {        
    reporter.testCaseInit("Quick test of XPathAPI.selectNodeList()");
    outNames = new OutputNameManager(baseOutName + reporter.getCurrentCaseNum(), ".out");

    // Note: parsed file and gold file don't match - why? 10-Oct-01 -sc
    Document doc = parseToDOM(testFileInfo1.xmlName);
    Transformer serializer = getSerializer();

    for (int i=0;i<xpath.length; i++) 
    {
      NodeList nl = XPathAPI.selectNodeList(doc, xpath[i]);
      
      Node n;
      int j = 0;
      while (j < nl.getLength())
      {        
        n = nl.item(j++);
        serializer.transform(new DOMSource(n), new StreamResult(outNames.nextName()));
        File f = new File(outNames.currentName()); 
        fileChecker.check(reporter, 
                          f, 
                          new File(testFileInfo2.goldName + f.getName()), 
                          "selectNodeList() of "+xpath[i] + " into " + outNames.currentName());
      }
    } // of for...
    reporter.testCaseClose();
    return true;
  }
  
  /** Quick test of XPathAPI.selectSingleNode().  */
  public boolean testCase3()
    throws Exception
  {        
    reporter.testCaseInit("Quick test of XPathAPI.selectSingleNode()");
    outNames = new OutputNameManager(baseOutName + reporter.getCurrentCaseNum(), ".out");

    // Note: parsed file and gold file don't match - why? 10-Oct-01 -sc
    Document doc = parseToDOM(testFileInfo1.xmlName);
    Transformer serializer = getSerializer();
    
    for (int i=0;i<xpath.length; i++) 
    {
      Node n = XPathAPI.selectSingleNode(doc, xpath[i]);
      
      if (n != null)
      {
        serializer.transform(new DOMSource(n), new StreamResult(outNames.nextName()));
        File f = new File(outNames.currentName()); 
        fileChecker.check(reporter, 
                           f, 
                           new File(testFileInfo3.goldName + f.getName()), 
                          "selectSingleNode() of "+xpath[i] + " into " + outNames.currentName());
      }
      else
      {
        reporter.logWarningMsg("No node found with selectSingleNode() of "+xpath[i]);
      }
    } // of for...
    reporter.testCaseClose();
    return true;
  }
  
  
  /** Quick test of XPathAPI.eval().  */
  public boolean testCase4()
    throws Exception
  {        
    reporter.testCaseInit("Quick test of XPathAPI.eval()");
    outNames = new OutputNameManager(baseOutName + reporter.getCurrentCaseNum(), ".out");

    // Note: parsed file and gold file don't match - why? 10-Oct-01 -sc
    Document doc = parseToDOM(testFileInfo1.xmlName);
    Transformer serializer = getSerializer();
    
    //Document d1 =(Document) doc.getDocumentElement();
    // Node d = (doc.getNodeType() == Node.DOCUMENT_NODE)
    // ? (Document) doc.getDocumentElement() : doc;
    reporter.logInfoMsg("Creating a PrefixResolverDefault(...)");
    PrefixResolverDefault prefixResolver = 
               new PrefixResolverDefault(doc.getDocumentElement());

    for (int i=0;i<xpath.length; i++) 
    {
      XObject list = XPathAPI.eval(doc, xpath[i], prefixResolver);
      
      int n;
      DTMIterator nl = list.iter();
      DTMManager dtmManager = nl.getDTMManager();
      while ((n = nl.nextNode())!= DTM.NULL)
      { 
        Node node = dtmManager.getDTM(n).getNode(n);
        serializer.transform(new DOMSource(node), new StreamResult(outNames.nextName()));
        File f = new File(outNames.currentName()); 
        fileChecker.check(reporter, 
                           f, 
                           new File(testFileInfo4.goldName + f.getName()), 
                          "eval() of "+xpath[i] + " into " + outNames.currentName());
      }
    } // of for...
    reporter.testCaseClose();
    return true;
  }
  
  /** Quick test of XPathAPI.selectNodeList() and doc.getFirstChild().  */
  public boolean testCase5()
    throws Exception
  {        
    reporter.testCaseInit("Quick test of XPathAPI.selectNodeList() and doc.getFirstChild()");
    outNames = new OutputNameManager(baseOutName + reporter.getCurrentCaseNum(), ".out");

    Document doc = parseToDOM(testFileInfo5.xmlName);
    Transformer serializer = getSerializer();
    
    // Use the simple XPath API to select a nodeIterator.
    reporter.logStatusMsg("Querying DOM using selectNodeList(doc.getFirstChild(), 'a')");
    NodeList nl = XPathAPI.selectNodeList(doc.getFirstChild(), "a");
    
    Node n;
    int j = 0;
    while (j < nl.getLength())
    {        
      n = nl.item(j++);
      serializer.transform(new DOMSource(n), new StreamResult(outNames.nextName()));
      File f = new File(outNames.currentName()); 
      fileChecker.check(reporter, 
                        f, 
                        new File(testFileInfo5.goldName + f.getName()), 
                        "selectNodeList(doc.getFirstChild(), 'a') into " + outNames.currentName());
    }
    reporter.testCaseClose();
    return true;
  }
  
  /** Quick test of XPathAPI.selectNodeIterator() and non-document node.  */
  public boolean testCase6()
    throws Exception
  {        
    reporter.testCaseInit("Quick test of XPathAPI.selectNodeIterator() and non-document node");
    outNames = new OutputNameManager(baseOutName + reporter.getCurrentCaseNum(), ".out");
    String filename = testFileInfo6.xmlName;
    String xpathStr = "*[local-name()='sitemap' and namespace-uri()='http://apache.org/xalan/test/sitemap']"; 

    // Set up a DOM tree to query.
    reporter.logInfoMsg("Parsing input file "+filename);
    // Android-added: Look up the file in the java resources.
    // InputSource in = new InputSource(new FileInputStream(filename));
    InputSource in = new InputSource(AndroidFileUtils.getInputFileUrl(filename).openStream());
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setNamespaceAware(true);
    Document doc = dfactory.newDocumentBuilder().parse(in);

    Transformer serializer = getSerializer();
    
    // Create DocumentFragment
    DocumentFragment frag = doc.createDocumentFragment();
    frag.appendChild(doc.getFirstChild());
    
    // Use the simple XPath API to select a nodeIterator.
    reporter.logStatusMsg("selectNodeIterator(" + xpathStr + ") and a non document node");
    NodeIterator nl = XPathAPI.selectNodeIterator(frag, xpathStr);
    
    Node n;
    while ((n = nl.nextNode())!= null)
    {        
      serializer.transform(new DOMSource(n), new StreamResult(outNames.nextName()));
      File f = new File(outNames.currentName()); 
      fileChecker.check(reporter, 
                        f, 
                        new File(testFileInfo6.goldName + f.getName()), 
                        "selectNodeIterator(...) into " + outNames.currentName());
    }
    reporter.testCaseClose();
    return true;
  }
  
  /** Quick test of XPathAPI.selectNodeList using 'id(a)'.  */
  public boolean testCase7()
    throws Exception
  {        
    reporter.testCaseInit("Quick test of XPathAPI.selectNodeList using 'id(a)'");
    outNames = new OutputNameManager(baseOutName + reporter.getCurrentCaseNum(), ".out");

    // Note: parsed file and gold file don't match - why? 10-Oct-01 -sc
    Document doc = parseToDOM(testFileInfo7.xmlName);
    Transformer serializer = getSerializer();
    
    // Use the simple XPath API to select a nodeIterator.
    reporter.logStatusMsg("selectNodeList using 'id(a)' ");
    NodeList nl = XPathAPI.selectNodeList(doc, "id('a')");
    
    Node n;
    int j = 0;
    while (j < nl.getLength())
    {        
      n = nl.item(j++);
      serializer.transform(new DOMSource(n), new StreamResult(outNames.nextName()));
      File f = new File(outNames.currentName()); 
      fileChecker.check(reporter, 
                        f, 
                        new File(testFileInfo5.goldName + f.getName()), 
                        "selectNodeList using 'id(a)' into " + outNames.currentName());
    }
    reporter.testCaseClose();
    return true;
  }

  /** Worker method to return a transformer for serializing.  */
  protected Transformer getSerializer() throws TransformerException
  {
    // Set up an identity transformer to use as serializer.
    Transformer serializer = TransformerFactory.newInstance().newTransformer();
    serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    return serializer;
  }
  
  /** Worker method to parse file into a DOM.  */
  protected Document parseToDOM(String filename) throws Exception
  {
    reporter.logInfoMsg("Parsing input file "+filename);
    
    // Set up a DOM tree to query.
    // Android-added: Look up the file in the java resources.
    // InputSource in = new InputSource(new FileInputStream(filename));
    InputSource in = new InputSource(AndroidFileUtils.getInputFileUrl(filename).openStream());
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    Document doc = dfactory.newDocumentBuilder().parse(in);
    return doc;
  }

  //-----------------------------------------------------------
  //---- Basic XSLProcessorTestBase utility methods
  //-----------------------------------------------------------
  /**
   * Convenience method to print out usage information - update if needed.  
   * @return String denoting usage of this test class
   */
  public String usage()
  {
    return ("Common [optional] options supported by TestXPathAPI:\n"
            + "(Note: assumes inputDir=.\\tests\\api)\n"
            + super.usage());   // Grab our parent classes usage as well
  }
  
  
  /** Main method to run from the command line.    */
  public static void main (String[] args)
  {
    TestXPathAPI app = new TestXPathAPI();
    app.doMain(args);
  }

  // Android-added: Run main method as a JUnit test case.
  @FlakyTest(bugId = 292520220)
  @Test
  public void main() {
    main(new String[0]);
  }
} // end of class ApplyXPath