Debian Codegraph @

net/sf/saxon/testdriver/TestOutcome.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.testdriver;
9
10 import net.sf.saxon.expr.ItemMappingFunction;
11 import net.sf.saxon.expr.ItemMappingIterator;
12 import net.sf.saxon.expr.XPathContext;
13 import net.sf.saxon.expr.sort.AtomicMatchKey;
14 import net.sf.saxon.expr.sort.AtomicSortComparer;
15 import net.sf.saxon.expr.sort.CodepointCollator;
16 import net.sf.saxon.expr.sort.GenericAtomicComparer;
17 import net.sf.saxon.functions.DeepEqual;
18 import net.sf.saxon.lib.Feature;
19 import net.sf.saxon.lib.NamespaceConstant;
20 import net.sf.saxon.lib.StringCollator;
21 import net.sf.saxon.om.*;
22 import net.sf.saxon.regex.RegularExpression;
23 import net.sf.saxon.s9api.*;
24 import net.sf.saxon.trans.NoDynamicContextException;
25 import net.sf.saxon.trans.XPathException;
26 import net.sf.saxon.tree.util.FastStringBuffer;
27 import net.sf.saxon.type.Type;
28 import net.sf.saxon.value.AtomicValue;
29 import net.sf.saxon.value.StringValue;
30 import net.sf.saxon.value.Whitespace;
31
32 import javax.xml.transform.stream.StreamSource;
33 import java.io.StringReader;
34 import java.io.StringWriter;
35 import java.net.URI;
36 import java.net.URISyntaxException;
37 import java.util.*;
38
39 public class TestOutcome {
40 /**
41 * The outcome of a test is either an XDM value or an exception. The object also has the ability to
42 * hold the serialized result (needed for serialization tests)
43 */
44
45 public static class SingleResultDoc {
46 public XdmValue value;
47 public String serialization;
48 public boolean wellFormed = true;
49
50 public SingleResultDoc() {
51 }
52
53 public SingleResultDoc(XdmValue value, String serialization) {
54 this.value = value;
55 this.serialization = serialization;
56 }
57 }
58
59 private TestDriver driver;
60 private SingleResultDoc principalResult = new SingleResultDoc();
61 private Set<String> errorsReported;
62 private boolean warningsReported;
63 private SaxonApiException exception;
64 private String comment;
65 private Set<XdmNode> xslMessages = new HashSet<>(4);
66 private Map<URI, SingleResultDoc> xslResultDocuments = new HashMap<>(4);
67 private String wrongError;
68 private String resultVar;
69 private String baseOutputUri;
70
71 public TestOutcome(TestDriver driver) {
72 this.driver = driver;
73 }
74
75 public void setException(SaxonApiException exception) {
76 this.exception = exception;
77 }
78
79 public boolean isException() {
80 return exception != null;
81 }
82
83 public void setResultVar(String variableName) {
84 resultVar = variableName;
85 }
86
87 public void setBaseOutputUri(String uri) {
88 baseOutputUri = uri;
89 }
90
91 public String getBaseOutputUri() {
92 return baseOutputUri;
93 }
94
95 public SaxonApiException getException() {
96 return exception;
97 }
98
99 /**
100 * Get a message giving details about the situation where the actual error code was not one of those
101 * expected
102 *
103 * @return null if this situation did not occur; otherwise a message showing the actual error code
104 * and the expected error code
105 */
106
107 public String getWrongErrorMessage() {
108 return wrongError;
109 }
110
111
112 public void setPrincipalResult(XdmValue value) {
113 principalResult.value = value;
114 }
115
116 public void setWarningsReported(boolean warnings) {
117 this.warningsReported = warnings;
118 }
119
120 public boolean isWarningsReported() {
121 return this.warningsReported;
122 }
123
124 public XdmValue getPrincipalResult() {
125 return principalResult.value;
126 }
127
128 public SingleResultDoc getPrincipalResultDoc() {
129 return principalResult;
130 }
131
132 public synchronized void setSecondaryResult(URI uri, XdmValue value, String serialization) {
133 SingleResultDoc result = xslResultDocuments.get(uri);
134 if (result == null) {
135 result = new SingleResultDoc(value, serialization);
136 this.xslResultDocuments.put(uri, result);
137 } else {
138 if (value != null) {
139 result.value = value;
140 }
141 if (serialization != null) {
142 result.serialization = serialization;
143 }
144 }
145 }
146
147 public synchronized SingleResultDoc getSecondaryResult(URI uri) {
148 return xslResultDocuments.get(uri);
149 }
150
151 public Map<URI, SingleResultDoc> getSecondaryResultDocuments() {
152 return xslResultDocuments;
153 }
154
155 public void setErrorsReported(Set<String> errors) {
156 errorsReported = errors;
157 }
158
159 public synchronized void addReportedError(String error) {
160 if (errorsReported == null) {
161 errorsReported = new HashSet<>();
162 }
163 errorsReported.add(error);
164 }
165
166 public synchronized boolean hasReportedError(String errorCode) {
167 return errorsReported != null && errorsReported.contains(errorCode);
168 }
169
170 public String toString() {
171 return isException() ? "EXCEPTION " + exception.getMessage() : getPrincipalResult().toString();
172 }
173
174 public void setPrincipalSerializedResult(String result) {
175 principalResult.serialization = result;
176 }
177
178 public String getPrincipalSerializedResult() {
179 return principalResult.serialization;
180 }
181
182 public void setComment(String comment) {
183 this.comment = comment;
184 }
185
186 public String getComment() {
187 return comment;
188 }
189
190 public synchronized void addXslMessage(XdmNode message) {
191 xslMessages.add(message);
192 }
193
194
195 /**
196 * This method serializes the actual result to produce a serialized result. This is not what is actually
197 * needed by the serialization tests, which require that the serialization be performed using the parameters
198 * contained within the query itself.
199 *
200 * @param p the processor
201 * @param uri the URI of the result to serialize; null for the principal result
202 * @return the result of serialization
203 */
204
205 public String serialize(Processor p, URI uri) {
206 XdmValue value;
207 if (uri == null) {
208 if (principalResult.serialization != null) {
209 return principalResult.serialization;
210 } else {
211 value = principalResult.value;
212 }
213 } else {
214 SingleResultDoc doc = xslResultDocuments.get(uri);
215 if (doc == null) {
216 return "[[[NULL VALUE]]]";
217 } else if (doc.serialization != null) {
218 return doc.serialization;
219 } else {
220 value = doc.value;
221 }
222 }
223 if (value == null) {
224 return "[[[NULL VALUE]]]";
225 }
226 if (isException()) {
227 return "EXCEPTION " + exception.getMessage();
228 } else {
229 StringWriter sw = new StringWriter();
230 Serializer s = p.newSerializer(sw);
231 s.setOutputProperty(Serializer.Property.METHOD, "xml");
232 s.setOutputProperty(Serializer.Property.INDENT, "no");
233 s.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
234 try {
235 s.serializeXdmValue(value);
236 } catch (SaxonApiException err) {
237 return "SERIALIZATION FAILED: " + err.getMessage();
238 }
239 String str = sw.toString().trim();
240 if (uri == null) {
241 principalResult.serialization = str;
242 } else {
243 xslResultDocuments.get(uri).serialization = str;
244 }
245 return str;
246 }
247 }
248
249 /**
250 * This method serializes the actual result to produce a serialized result. This is not what is actually
251 * needed by the serialization tests, which require that the serialization be performed using the parameters
252 * contained within the query itself.
253 *
254 * @param p the processor
255 * @param doc the result to serialize
256 * @return the result of serialization
257 */
258
259 public String serialize(Processor p, SingleResultDoc doc) {
260 XdmValue value;
261 if (doc.serialization != null) {
262 return doc.serialization;
263 } else {
264 value = doc.value;
265 }
266 if (value == null) {
267 return "[[[NULL VALUE]]]";
268 }
269 if (isException()) {
270 return "EXCEPTION " + exception.getMessage();
271 } else {
272 StringWriter sw = new StringWriter();
273 Serializer s = p.newSerializer(sw);
274 s.setOutputProperty(Serializer.Property.METHOD, "adaptive");
275 s.setOutputProperty(Serializer.Property.INDENT, "no");
276 s.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
277 try {
278 s.serializeXdmValue(value);
279 } catch (SaxonApiException err) {
280 return "SERIALIZATION FAILED: " + err.getMessage();
281 }
282 String str = sw.toString().trim();
283 doc.serialization = str;
284 return str;
285 }
286 }
287
288 public String serialize(Processor p, XdmValue value) {
289 StringWriter sw = new StringWriter();
290 Serializer s = p.newSerializer(sw);
291 s.setOutputProperty(Serializer.Property.METHOD, "xml");
292 s.setOutputProperty(Serializer.Property.INDENT, "no");
293 s.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
294 try {
295 s.serializeXdmValue(value);
296 } catch (SaxonApiException err) {
297 return "SERIALIZATION FAILED: " + err.getMessage();
298 }
299 return sw.toString().trim();
300 }
301
302 public boolean testAssertion(XdmNode assertion, TestOutcome outcome, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, boolean debug) {
303 try {
304 String tag = assertion.getNodeName().getLocalName();
305 boolean success = testAssertion2(assertion, outcome, result, assertXpc, catalogXpc, debug);
306 if (debug && !"all-of".equals(tag) && !"any-of".equals(tag) && !"not".equals(tag)) {
307 String parentTag = assertion.getParent().getNodeName().getLocalName();
308 String label = "Assertion " + tag;
309 if (parentTag.equals("not") || parentTag.equals("any-of") || parentTag.equals("all-of")) {
310 label = "(Within " + parentTag + ") " + label;
311 }
312 driver.println(label + " (" + assertion.getStringValue() + ") " + (success ? " succeeded" : " failed"));
313 if (tag.equals("error")) {
314 if (isException()) {
315 boolean b = compareExpectedError(assertion);
316 if (b) {
317 driver.println("Returned error as expected");
318 } else {
319 driver.println(wrongError);
320 }
321 } else {
322 driver.println("Expected error " + assertion.attribute("code") + "; got success");
323 }
324 } else if (!success && isException()) {
325 FastStringBuffer fsb = new FastStringBuffer(32);
326 fsb.append("Expected success, got error ");
327 if (errorsReported != null) {
328 for (String e : errorsReported) {
329 fsb.append(e);
330 fsb.append("|");
331 }
332 }
333 fsb.setLength(fsb.length() - 1);
334 driver.println(fsb.toString());
335 }
336 }
337 if (!success && wrongError != null) {
338 // at this stage getting the wrong error means failure (or at least, !success),
339 // the test drivers later pick up a wrong error and treat it as a pass
340 success = false;
341 }
342 return success;
343 } catch (SaxonApiException e) {
344 e.printStackTrace();
345 return false;
346 }
347 }
348
349 private boolean testAssertion2(XdmNode assertion, TestOutcome outcome, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, boolean debug) throws SaxonApiException {
350 String tag = assertion.getNodeName().getLocalName();
351
352 switch (tag) {
353 case "assert-eq":
354 return assertEq(assertion, result, assertXpc);
355
356 case "assert-deep-eq":
357 return assertDeepEq(assertion, result, assertXpc);
358
359 case "assert-permutation":
360 return assertPermutation(assertion, result, assertXpc);
361
362 case "assert-xml":
363 return assertXml(assertion, result, assertXpc, catalogXpc, debug);
364
365 case "serialization-matches":
366 return assertSerializationMatches(assertion, result, catalogXpc);
367
368 case "assert-serialization-error":
369 return assertSerializationError(assertion, result, assertXpc);
370
371 case "assert-empty":
372 return assertEmpty(result.value);
373
374 case "assert-count":
375 return assertCount(assertion, result);
376
377 case "assert":
378 return assertXPath(assertion, result, assertXpc, debug);
379
380 case "assert-string-value":
381 return assertStringValue(assertion, result, debug);
382
383 case "assert-serialization":
384 return assertSerialization(assertion, result, catalogXpc, debug);
385
386 case "assert-type":
387 return assertType(assertion, result, assertXpc);
388
389 case "assert-true":
390 return assertTrue(result);
391
392 case "assert-false":
393 return assertFalse(result);
394 case "assert-warning":
395 return assertWarning();
396
397 case "assert-message": {
398 XdmNode subAssertion = (XdmNode) catalogXpc.evaluateSingle("*", assertion);
399 for (XdmNode message : xslMessages) {
400 if (message.getNodeKind() == XdmNodeKind.PROCESSING_INSTRUCTION && message.getNodeName().getLocalName().equals("trust") && message.getStringValue().equals("me")) {
401 // In the JS tests, assume message assertions are OK
402 return true;
403 }
404 if (testAssertion2(subAssertion, outcome, new SingleResultDoc(message, ""), assertXpc, catalogXpc, debug)) {
405 return true;
406 }
407 }
408 return false;
409
410 }
411 case "assert-result-document": {
412 XdmNode subAssertion = (XdmNode) catalogXpc.evaluateSingle("*", assertion);
413 //URI uri = new File(driver.resultsDir + "/results/output.xml").toURI().resolve(assertion.attribute("uri"));
414 URI uri;
415 try {
416 uri = new URI(outcome.getBaseOutputUri()).resolve(assertion.attribute("uri"));
417 } catch (URISyntaxException e) {
418 System.err.println("**** Invalid output uri " + outcome.getBaseOutputUri());
419 return false;
420 }
421 SingleResultDoc doc = getSecondaryResult(uri);
422 if (doc == null) {
423 System.err.println("**** No output document found for " + uri);
424 return false;
425 }
426 boolean ok = testAssertion2(subAssertion, outcome, doc, assertXpc, catalogXpc, debug);
427 if (!ok) {
428 System.err.println("**** Assertion failed for result-document " + uri);
429 }
430 return ok;
431
432 }
433 case "error":
434 return isException() && compareExpectedError(assertion);
435
436 case "all-of":
437 for (XdmNode child : assertion.children("*")) {
438 if (!testAssertion((XdmNode) child, outcome, result, assertXpc, catalogXpc, debug)) {
439 return false;
440 }
441 }
442 return true;
443
444 case "any-of":
445 boolean partialSuccess = false;
446 for (XdmItem child : catalogXpc.evaluate("*", assertion)) {
447 if (testAssertion((XdmNode) child, outcome, result, assertXpc, catalogXpc, debug)) {
448 if (wrongError != null) {
449 partialSuccess = true;
450 continue;
451 }
452 return true;
453 }
454 }
455 return partialSuccess;
456
457 case "not": {
458 XdmNode subAssertion = (XdmNode) catalogXpc.evaluateSingle("*", assertion);
459 return !testAssertion(subAssertion, outcome, result, assertXpc, catalogXpc, debug);
460 }
461 }
462 throw new IllegalStateException("Unknown assertion element " + tag);
463 }
464
465 private boolean assertFalse(SingleResultDoc result) throws SaxonApiException {
466 if (isException()) {
467 return false;
468 } else {
469 return result.value.size() == 1 &&
470 result.value.itemAt(0).isAtomicValue() &&
471 ((XdmAtomicValue) result.value.itemAt(0)).getPrimitiveTypeName().equals(QName.XS_BOOLEAN) &&
472 !((XdmAtomicValue) result.value.itemAt(0)).getBooleanValue();
473 }
474 }
475
476 private boolean assertTrue(SingleResultDoc result) throws SaxonApiException {
477 if (isException()) {
478 return false;
479 } else {
480 return result.value.size() == 1 &&
481 result.value.itemAt(0).isAtomicValue() &&
482 ((XdmAtomicValue) result.value.itemAt(0)).getPrimitiveTypeName().equals(QName.XS_BOOLEAN) &&
483 ((XdmAtomicValue) result.value.itemAt(0)).getBooleanValue();
484 }
485 }
486
487 private boolean assertWarning() {
488 return isWarningsReported();
489 }
490
491 private boolean assertType(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) throws SaxonApiException {
492 if (isException()) {
493 return false;
494 } else {
495 assertXpc.declareVariable(new QName("result"));
496 XPathSelector s = assertXpc.compile("$result instance of " + assertion.getStringValue()).load();
497 s.setVariable(new QName("result"), result.value);
498 return ((XdmAtomicValue) s.evaluateSingle()).getBooleanValue();
499 }
500 }
501
502 private boolean assertStringValue(XdmNode assertion, SingleResultDoc result, boolean debug) {
503 if (isException()) {
504 return false;
505 } else {
506 String resultString;
507 String assertionString = assertion.getStringValue();
508 if (result.value instanceof XdmItem) {
509 resultString = ((XdmItem) result.value).getStringValue();
510 } else {
511 boolean first = true;
512 FastStringBuffer fsb = new FastStringBuffer(256);
513 for (XdmItem item : result.value) {
514 if (first) {
515 first = false;
516 } else {
517 fsb.append(' ');
518 }
519 fsb.append(item.getStringValue());
520 }
521 resultString = fsb.toString();
522 }
523 String normalizeAtt = assertion.attribute("normalize-space");
524 if (normalizeAtt == null && driver.catalogNamespace().equals("http://www.w3.org/2012/10/xslt-test-catalog")) {
525 // default in XSLT test suite is "true"
526 normalizeAtt = "true";
527 }
528 if (normalizeAtt != null && (normalizeAtt.trim().equals("true") || normalizeAtt.trim().equals("1"))) {
529 assertionString = Whitespace.collapseWhitespace(assertionString).toString();
530 resultString = Whitespace.collapseWhitespace(resultString).toString();
531 }
532 if (resultString.equals(assertionString)) {
533 return true;
534 } else {
535 if (debug) {
536 if (resultString.length() != assertionString.length()) {
537 driver.println("Result length " + resultString.length() + "; expected length " + assertionString.length());
538 }
539 int len = Math.min(resultString.length(), assertionString.length());
540 for (int i = 0; i < len; i++) {
541 if (resultString.charAt(i) != assertionString.charAt(i)) {
542 driver.println("Actual:'" + StringValue.diagnosticDisplay(resultString) + "'");
543 driver.println("Results differ at index " + i +
544 "(\"" + StringValue.diagnosticDisplay(resultString.substring(i, i + 10 > len ? len : i + 10)) + "\") vs (\"" +
545 StringValue.diagnosticDisplay(assertionString.substring(i, i + 10 > len ? len : i + 10)) + "\")");
546 break;
547 }
548 }
549 }
550 return false;
551 }
552 }
553 }
554
555 private boolean assertSerialization(XdmNode assertion, SingleResultDoc result, XPathCompiler xpath, boolean debug) throws SaxonApiException {
556 if (isException()) {
557 return false;
558 } else {
559 String method = assertion.attribute("method");
560 if (method == null) {
561 method = "xml";
562 }
563 String resultString = result.serialization;
564 String comparand = xpath.evaluate(
565 "if (@file) then " +
566 "if (@encoding) " +
567 "then unparsed-text(resolve-uri(@file, base-uri(.)), @encoding) " +
568 "else unparsed-text(resolve-uri(@file, base-uri(.))) " +
569 "else string(.)", assertion).toString();
570 comparand = comparand.replace("\r\n", "\n");
571 if (comparand.endsWith("\n")) {
572 comparand = comparand.substring(0, comparand.length() - 1);
573 }
574
575 if (resultString == null) {
576 if (result.value instanceof XdmItem) {
577 resultString = ((XdmItem) result.value).getStringValue();
578 } else {
579 if (debug) {
580 driver.println("Assert serialization fails: result is a sequence");
581 }
582 return false;
583 }
584 }
585 boolean isHtml = method.equals("html") || method.equals("xhtml");
586 boolean normalize = isHtml;
587 if (!normalize) {
588 String normalizeAtt = assertion.attribute("normalize-space");
589 normalize = normalizeAtt != null && (normalizeAtt.trim().equals("true") || normalizeAtt.trim().equals("1"));
590 }
591 if (normalize) {
592 comparand = Whitespace.collapseWhitespace(comparand).toString();
593 resultString = Whitespace.collapseWhitespace(resultString).toString();
594 } else if (resultString.endsWith("\n")) {
595 resultString = resultString.substring(0, resultString.length() - 1);
596 }
597 if (isHtml) {
598 // should really do this only for block-level elements
599 comparand = comparand.replace(" <", "<");
600 comparand = comparand.replace("> ", ">");
601 resultString = resultString.replace(" <", "<");
602 resultString = resultString.replace("> ", ">");
603 }
604 if (resultString.equals(comparand)) {
605 return true;
606 } else {
607 if (debug) {
608 if (resultString.length() != comparand.length()) {
609 driver.println("Result length " + resultString.length() + "; expected length " + comparand.length());
610 }
611 int len = Math.min(resultString.length(), comparand.length());
612 for (int i = 0; i < len; i++) {
613 if (resultString.charAt(i) != comparand.charAt(i)) {
614 int start = i < 20 ? 0 : i-20;
615 int end = i + 20 > len ? len : i+20;
616 driver.println("Serialized results differ at index " + i +
617 "(\"" + StringValue.diagnosticDisplay(resultString.substring(start, end)) + "\"), expected (\"" +
618 StringValue.diagnosticDisplay(comparand.substring(start, end)) + "\")");
619 break;
620 }
621 }
622 driver.println("Actual results:");
623 driver.println(resultString);
624 } else {
625 driver.println("Serialized results differ");
626 }
627 return false;
628 }
629 }
630 }
631
632 private boolean assertXPath(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, boolean debug) throws SaxonApiException {
633 if (isException()) {
634 return false;
635 } else {
636 XdmSequenceIterator iter = assertion.axisIterator(Axis.NAMESPACE);
637 while (iter.hasNext()) {
638 XdmNode namespace = (XdmNode) iter.next();
639 if (namespace.getNodeName() != null) {
640 assertXpc.declareNamespace(namespace.getNodeName().getLocalName(), namespace.getStringValue());
641 }
642 }
643 if (resultVar != null) {
644 assertXpc.declareVariable(new QName("result"));
645 }
646 driver.println("Testing " + assertion.getStringValue());
647 XPathExecutable exp = assertXpc.compile(assertion.getStringValue());
648 XPathSelector s = exp.load();
649 QName resultVarName = new QName("result");
650 if (resultVar != null) {
651 s.setVariable(new QName(resultVar), result.value);
652 } else if (exp.getRequiredCardinalityForVariable(resultVarName) == null) {
653 if (result.value instanceof XdmItem) { // this path used in XSLT tests
654 s.setContextItem((XdmItem) result.value);
655 }
656 } else {
657 s.setVariable(resultVarName, result.value);
658 }
659 boolean b = s.effectiveBooleanValue();
660 if (!b && debug) {
661 driver.println("XPath assertion " + assertion.getStringValue() + " failed");
662 try {
663 String ass = assertion.getStringValue();
664 // Try to evaluate the expression on the lhs of an "=" operator in the assertion
665 int eq = ass.indexOf("=");
666 if (eq > 0) {
667 ass = ass.substring(0, eq);
668 exp = assertXpc.compile(ass);
669 s = exp.load();
670 if (exp.getRequiredCardinalityForVariable(resultVarName) == null) {
671 if (result.value instanceof XdmItem) { // this path used in XSLT tests
672 s.setContextItem((XdmItem) result.value);
673 }
674 } else {
675 s.setVariable(resultVarName, result.value);
676 }
677 XdmValue val = s.evaluate();
678 driver.println("Actual result of " + ass + ": " + val.toString());
679 }
680 } catch (Exception err) {
681 // Occurs for example with an assertion like /x[a = 2] where what precedes the '=' is not an expression
682 }
683 driver.println("Actual results: " + result.value);
684 }
685 return b;
686 }
687 }
688
689 private boolean assertCount(XdmNode assertion, SingleResultDoc result) {
690 if (isException()) {
691 return false;
692 } else {
693 int expected = Integer.parseInt(assertion.getStringValue());
694 int actual = result.value.size();
695 if (actual != expected) {
696 driver.println("Expected result size = " + expected + "; actual size = " + actual);
697 }
698 return actual == expected;
699 }
700 }
701
702 private boolean assertEmpty(XdmValue result) {
703 return !isException() && result.size() == 0;
704 }
705
706 private boolean assertSerializationError(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
707 if (isException()) {
708 return compareExpectedError(assertion);
709 } else {
710 String expectedError = assertion.attribute("code");
711 driver.println("Expected serialization error " + expectedError + "; got success");
712 return false;
713 }
714 // } else if (result.value == null) {
715 // driver.println("Expected " );
716 // return false;
717 // } else {
718 // String expectedError = assertion.getAttributeValue(new QName("code"));
719 // StringWriter sw = new StringWriter();
720 // Serializer serializer = assertXpc.getProcessor().newSerializer(sw);
721 // serializer.setOutputProperty(Serializer.Property.METHOD, "xml");
722 // serializer.setOutputProperty(Serializer.Property.INDENT, "no");
723 // serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
724 // try {
725 // serializer.serializeXdmValue(result.value);
726 // return false;
727 // } catch (SaxonApiException err) {
728 // boolean b = expectedError.equals(err.getErrorCode().getLocalName());
729 // if (!b) {
730 // driver.println("Expected " + expectedError + ", got " + err.getErrorCode().getLocalName());
731 // }
732 // return true;
733 // }
734 // }
735 }
736
737 private boolean assertSerializationMatches(XdmNode assertion, SingleResultDoc result, XPathCompiler xpath) {
738 if (isException()) {
739 return false;
740 } else {
741 //String testSet = catalogXpc.evaluate("string(/*/@name)", assertion).toString();
742 String flagsAtt = assertion.attribute("flags");
743 if (flagsAtt == null) {
744 flagsAtt = "";
745 }
746 /* String regex = xpath.evaluate(
747 "if (@file) then " +
748 "if (@encoding) " +
749 "then unparsed-text(resolve-uri(@file, base-uri(.)), @encoding) " +
750 "else unparsed-text(resolve-uri(@file, base-uri(.))) " +
751 "else string(.)", assertion).toString();
752 regex = regex.replace("\r\n", "\n");
753 if (regex.endsWith("\n")) {
754 regex = regex.substring(0, regex.length() - 1);
755 }*/
756 String regex = assertion.getStringValue();
757 List<String> warnings = new ArrayList<>(1);
758 try {
759 String principalSerializedResult = result.serialization;
760 if (principalSerializedResult == null) {
761 driver.println("No serialized result available!");
762 return false;
763 }
764 RegularExpression re = xpath.getProcessor().getUnderlyingConfiguration().compileRegularExpression(
765 regex, flagsAtt, "XP30", warnings);
766 if (re.containsMatch(principalSerializedResult)) {
767 return true;
768 } else {
769 driver.println("Serialized result:");
770 driver.println(principalSerializedResult);
771 return false;
772 }
773 } catch (XPathException e) {
774 throw new AssertionError(e);
775 }
776 }
777 }
778
779 private boolean assertXml(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, boolean debug) throws SaxonApiException {
780 if (isException()) {
781 return false;
782 } else {
783 String normalizeAtt = assertion.attribute("normalize-space");
784 boolean normalize = normalizeAtt != null && ("true".equals(normalizeAtt.trim()) || "1".equals(normalizeAtt.trim()));
785 String ignoreAtt = assertion.attribute("ignore-prefixes");
786 boolean ignorePrefixes = ignoreAtt != null && ("true".equals(ignoreAtt.trim()) || "1".equals(ignoreAtt.trim()));
787 String xmlVersion = assertion.attribute("xml-version");
788 boolean xml11 = "1.1".equals(xmlVersion);
789
790 String comparand = catalogXpc.evaluate("if (@file) then unparsed-text(resolve-uri(@file, base-uri(.))) else string(.)", assertion).toString();
791 if (comparand.startsWith("<?xml")) {
792 int index = comparand.indexOf("?>");
793 comparand = comparand.substring(index + 2);
794 }
795 /* String expectedDoctype = null;
796 if (comparand.startsWith("<!DOCTYPE")) {
797 int index = comparand.indexOf(">");
798 expectedDoctype = comparand.substring(0,index+1);
799 }*/
800 comparand = comparand.trim();
801 comparand = comparand.replace("\r\n", "\n");
802 if (normalize) {
803 comparand = Whitespace.collapseWhitespace(comparand).toString();
804 }
805
806 if (comparand.equals(serialize(assertXpc.getProcessor(), result))) {
807 return true;
808 }
809
810 DocumentBuilder builder = assertXpc.getProcessor().newDocumentBuilder();
811 if (xml11) {
812 assertXpc.getProcessor().setConfigurationProperty(Feature.XML_VERSION, "1.1");
813 }
814 StringReader reader = new StringReader((xml11 ? "<?xml version='1.1'?>" : "") + "<z>" + comparand + "</z>");
815 /*if (expectedDoctype != null) {
816 reader = new StringReader(comparand);
817 }*/
818 XdmNode expected = builder.build(new StreamSource(reader));
819
820 int flag = 0;
821
822 flag |= DeepEqual.INCLUDE_COMMENTS;
823 flag |= DeepEqual.INCLUDE_PROCESSING_INSTRUCTIONS;
824 flag |= DeepEqual.EXCLUDE_VARIETY;
825 if (!ignorePrefixes) {
826 flag |= DeepEqual.INCLUDE_NAMESPACES;
827 flag |= DeepEqual.INCLUDE_PREFIXES;
828 }
829 flag |= DeepEqual.COMPARE_STRING_VALUES;
830 if (debug) {
831 flag |= DeepEqual.WARNING_IF_FALSE;
832 }
833 try {
834 SequenceIterator<?> iter0;
835 if (result == null) {
836 System.err.println("Result value is null");
837 return false;
838 }
839 XdmValue value = result.value;
840 if (value == null) {
841 System.err.println("Result value is null (perhaps serialized?)");
842 return false;
843 }
844 if (value.size() == 1 && value.itemAt(0) instanceof XdmNode && ((XdmNode) value.itemAt(0)).getNodeKind() == XdmNodeKind.DOCUMENT) {
845 iter0 = ((XdmNode) value.itemAt(0)).getUnderlyingNode().iterateAxis(AxisInfo.CHILD);
846 } else {
847 iter0 = value.getUnderlyingValue().iterate();
848 }
849 GroundedValue<?> val0 = iter0.materialize();
850 SequenceIterator<?> iter1 = expected.axisIterator(Axis.CHILD).next()
851 .getUnderlyingValue().iterateAxis(AxisInfo.CHILD);
852 GroundedValue<?> val1 = iter1.materialize();
853 boolean success = DeepEqual.deepEqual(
854 val0.iterate(), val1.iterate(),
855 new GenericAtomicComparer(CodepointCollator.getInstance(), null),
856 assertXpc.getProcessor().getUnderlyingConfiguration().getConversionContext(), flag);
857 // if necessary try again ignoring whitespace nodes
858 if (!success) {
859 iter0 = val0.iterate();
860 iter1 = val1.iterate();
861 // deep-equals with the EXCLUDE_WHITESPACE flag doesn't ignore top-level whitespace, so we
862 // need to filter that out ourselves
863 iter0 = new ItemMappingIterator(iter0, new RemoveWhitespace());
864 iter1 = new ItemMappingIterator(iter1, new RemoveWhitespace());
865 success = DeepEqual.deepEqual(
866 iter0, iter1,
867 new GenericAtomicComparer(CodepointCollator.getInstance(), null),
868 assertXpc.getProcessor().getUnderlyingConfiguration().getConversionContext(),
869 flag | DeepEqual.EXCLUDE_WHITESPACE_TEXT_NODES);
870 if (success) {
871 comment = "OK after ignoring whitespace text";
872 }
873 }
874 if (!success) {
875 driver.println("assert-xml comparison failed");
876 if (debug) {
877 driver.println("assert-xml comparison failed");
878 driver.println("Reference results:");
879 /*if(expectedDoctype != null) {
880 System.err.println(expectedDoctype);
881 }*/
882 driver.println(expected.toString());
883 driver.println("Actual results:");
884 //System.err.println(result.serialization);
885 driver.println(value.toString());
886 }
887 }
888 return success;
889 } catch (XPathException e) {
890 e.printStackTrace();
891 return false;
892 }
893 }
894 }
895
896 private class RemoveWhitespace implements ItemMappingFunction<NodeInfo, NodeInfo> {
897 public NodeInfo mapItem(NodeInfo item) {
898 boolean isWhite = item.getNodeKind() == Type.TEXT && Whitespace.isWhite(item.getStringValueCS());
899 return isWhite ? null : item;
900 }
901 }
902
903 private boolean assertPermutation(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) throws SaxonApiException {
904 // TODO: extend this to handle nodes (if required)
905 if (isException()) {
906 return false;
907 } else {
908 try {
909 int expectedItems = 0;
910 HashSet<AtomicMatchKey> expected = new HashSet<>();
911 XPathSelector s = assertXpc.compile("(" + assertion.getStringValue() + ")").load();
912 s.setVariable(new QName("result"), result.value); // not used, but we declared it
913 StringCollator collator = CodepointCollator.getInstance();
914 XPathContext context = s.getUnderlyingXPathContext().getXPathContextObject();
915 for (XdmItem item : s) {
916 expectedItems++;
917 AtomicValue value = (AtomicValue) item.getUnderlyingValue();
918 AtomicMatchKey comparable = value.isNaN() ?
919 AtomicSortComparer.COLLATION_KEY_NaN :
920 value.getXPathComparable(false, collator, context.getImplicitTimezone());
921 expected.add(comparable);
922 }
923 int actualItems = 0;
924 for (XdmItem item : getPrincipalResult()) {
925 actualItems++;
926 AtomicValue value = (AtomicValue) item.getUnderlyingValue();
927 AtomicMatchKey comparable = value.isNaN() ?
928 AtomicSortComparer.COLLATION_KEY_NaN :
929 value.getXPathComparable(false, collator, context.getImplicitTimezone());
930 if (!expected.contains(comparable)) {
931 return false;
932 }
933 }
934 return actualItems == expectedItems;
935 } catch (NoDynamicContextException e) {
936 System.err.println("Comparison of results failed - no timezone available");
937 return false;
938 }
939 }
940 }
941
942 private boolean assertDeepEq(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) throws SaxonApiException {
943 if (isException()) {
944 return false;
945 } else {
946 assertXpc.declareVariable(new QName("result"));
947 XPathSelector s = assertXpc.compile("deep-equal($result , (" + assertion.getStringValue() + "))").load();
948 s.setVariable(new QName("result"), result.value);
949 return ((XdmAtomicValue) s.evaluate()).getBooleanValue();
950 }
951 }
952
953 private boolean assertEq(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) throws SaxonApiException {
954 if (isException()) {
955 return false;
956 } else {
957 assertXpc.declareVariable(new QName("result"));
958 XPathSelector s = assertXpc.compile("$result eq " + assertion.getStringValue()).load();
959 s.setVariable(new QName("result"), result.value);
960 XdmAtomicValue item;
961 try {
962 item = (XdmAtomicValue) s.evaluateSingle();
963 } catch (SaxonApiException e) {
964 System.err.println("assert-eq failed - " + e.getMessage());
965 return false;
966 }
967 return item != null && item.getBooleanValue();
968 }
969 }
970
971 public boolean compareExpectedError(XdmNode assertion) {
972 String expectedError = assertion.attribute("code");
973 QName expectedErrorQ;
974 if (expectedError.equals("*")) {
975 expectedErrorQ = null;
976 } else if (expectedError.startsWith("Q{")) {
977 expectedErrorQ = QName.fromEQName(expectedError);
978 } else if (expectedError.contains(":")) {
979 try {
980 NamespaceResolver resolver = new InscopeNamespaceResolver(assertion.getUnderlyingNode());
981 StructuredQName sq = StructuredQName.fromLexicalQName(expectedError, false, false, resolver);
982 expectedErrorQ = new QName(sq);
983 } catch (XPathException e) {
984 expectedErrorQ = new QName("", "", "unknown-prefix-in-lexical-QName");
985 }
986 } else {
987 expectedErrorQ = new QName("err", NamespaceConstant.ERR, expectedError);
988 }
989 //noinspection ThrowableResultOfMethodCallIgnored
990 boolean ok = expectedError.equals("*") ||
991 (getException().getErrorCode() != null &&
992 getException().getErrorCode().equals(expectedErrorQ)) ||
993 hasReportedError(expectedError);
994 if (ok) {
995 wrongError = null;
996 } else if (expectedErrorQ != null && errorsReported != null && !errorsReported.isEmpty()) {
997 FastStringBuffer fsb = new FastStringBuffer(100);
998 fsb.append("Expected ");
999 fsb.append(expectedErrorQ.getLocalName());
1000 fsb.append("; got ");
1001 for (String e : errorsReported) {
1002 fsb.append(e);
1003 fsb.append("|");
1004 }
1005 fsb.setLength(fsb.length() - 1);
1006 wrongError = fsb.toString();
1007 }
1008 return ok;
1009 }
1010
1011
1012 }