Project

Profile

Help

How to connect?
Download (42.2 KB) Statistics
| Branch: | Tag: | Revision:

he / latest9.9 / samples / cs / TestRunner9.9 / TestOutcome.cs @ 063bf4dc

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.IO;
6
using Saxon.Api;
7
using System.Collections;
8
using System.Xml;
9
using JWhitespace = net.sf.saxon.value.Whitespace;
10
using JFeatureKeys = net.sf.saxon.lib.FeatureKeys;
11
using JDeepEqual = net.sf.saxon.functions.DeepEqual;
12
using JSequenceIterator = net.sf.saxon.om.SequenceIterator;
13
using JAxisInfo = net.sf.saxon.om.AxisInfo;
14
using JGenericAtomicComparer  = net.sf.saxon.expr.sort.GenericAtomicComparer;
15
using JCodepointCollator = net.sf.saxon.expr.sort.CodepointCollator;
16
using JItemMappingIterator = net.sf.saxon.expr.ItemMappingIterator;
17
using JNodeInfo = net.sf.saxon.om.NodeInfo;
18
using JNamespaceConstant = net.sf.saxon.lib.NamespaceConstant;
19
using JFastStringBuffer = net.sf.saxon.tree.util.FastStringBuffer;
20
using JXPathContext = net.sf.saxon.expr.XPathContext;
21
using JConfiguration = net.sf.saxon.Configuration;
22
using JRegularExpression = net.sf.saxon.regex.RegularExpression;
23
using JLargeStringBuffer = net.sf.saxon.tree.tiny.LargeStringBuffer;
24
using JItemMappingFunction = net.sf.saxon.expr.ItemMappingFunction;
25
using JItem = net.sf.saxon.om.Item;
26
using JGroundedValue = net.sf.saxon.om.GroundedValue;
27

    
28
namespace TestRunner
29
{
30
    public class TestOutcome
31
    {
32
        
33
    /**
34
     * The outcome of a test is either an XDM value or an exception. The object also has the ability to
35
     * hold the serialized result (needed for serialization tests)
36
     */
37
    
38
    public class SingleResultDoc {
39
        public XdmValue value;
40
        public string serialization;
41
        public SingleResultDoc(){}
42
        public SingleResultDoc(XdmValue value, string serialization) {
43
            this.value = value;
44
            this.serialization = serialization;
45
        }
46
    }
47

    
48
    private TestDriver driver;
49
    private SingleResultDoc principalResult = new SingleResultDoc();
50
    private HashSet<QName> errorsReported;
51
    private Exception exception;
52
    private string comment;
53
    private HashSet<XdmNode> xslMessages = new HashSet<XdmNode>();
54
    private Dictionary<Uri, SingleResultDoc> xslResultDocuments = new Dictionary<Uri, SingleResultDoc>();
55
    private string wrongError;
56
	private bool warningsReported;
57

    
58
    public TestOutcome(TestDriver driver) {
59
        this.driver = driver;
60
        errorsReported = new HashSet<QName>();
61
    }
62

    
63
    public void SetException(Exception ex)
64
    {
65
        this.exception = ex;
66

    
67
        if (ex is DynamicError)
68
        {
69
            try
70
            {
71
                errorsReported.Add(((DynamicError)ex).ErrorCode);
72
            }catch(Exception){
73
                errorsReported.Add(new QName("ZZZZZZ999999"));
74
            }
75
        }
76
			else if (ex is StaticError && ((StaticError)ex).ErrorCode != null)
77
        {
78
            try
79
            {
80
                errorsReported.Add(((StaticError)ex).ErrorCode);
81
            }
82
            catch (Exception)
83
            {
84
                errorsReported.Add(new QName("ZZZZZZ999999"));
85
            }
86
        }
87
        else {
88

    
89
            errorsReported.Add(new QName("ZZZZZZ999999"));
90
        }
91
    }
92

    
93
	public bool SetWarningsReported(bool warnings) {
94
		return warningsReported = warnings;
95
	}
96

    
97
	public bool IsWarningsReported() {
98
		return this.warningsReported;
99
	}
100

    
101
    public bool IsException() {
102
        return exception != null;
103
    }
104

    
105
    public Exception GetException()
106
    {
107
        return exception;
108
    }
109

    
110
    public QName GetErrorCode() {
111
        if (exception is DynamicError)
112
        {
113
            return ((DynamicError)exception).ErrorCode;
114
        }
115
        else if (exception is StaticError)
116
        {
117

    
118
            return ((StaticError)exception).ErrorCode;
119
        }
120
        else {
121
			return null;
122
        }
123
    }
124

    
125
    /**
126
     * Get a message giving details about the situation where the actual error code was not one of those
127
     * expected
128
     * @return null if this situation did not occur; otherwise a message showing the actual error code
129
     * and the expected error code
130
     */
131

    
132
    public string GetWrongErrorMessage() {
133
        return wrongError;
134
    }
135

    
136

    
137
    public void SetPrincipalResult(XdmValue value) {
138
        principalResult.value = value;
139
    }
140

    
141
    public XdmValue GetPrincipalResult() {
142
        return principalResult.value;
143
    }
144

    
145
    public SingleResultDoc GetPrincipalResultDoc() {
146
        return principalResult;
147
    }
148

    
149
    public void SetSecondaryResult(Uri uri, XdmNode value, string serialization) {
150
        SingleResultDoc result = null;
151
        try
152
        {
153
            result = xslResultDocuments[uri];
154
        }catch(Exception){}
155
        if (result == null) {
156
            result = new SingleResultDoc(value, serialization);
157
            this.xslResultDocuments.Add(uri,result);
158
        } else {
159
            if (value != null) {
160
                result.value = value;
161
            }
162
            if (serialization != null) {
163
                result.serialization = serialization;
164
            }
165
        }
166
    }
167

    
168
		public Dictionary<Uri, SingleResultDoc> GetSecondaryResultDocuments() {
169
			return xslResultDocuments;
170
	}
171
    
172
    public SingleResultDoc GetSecondaryResult(Uri uri) {
173
            SingleResultDoc doc = xslResultDocuments[uri];
174
            if (doc.serialization.Equals("")) {
175
                Processor proc = new Processor(false);
176
                doc.value = proc.NewXPathCompiler().Compile("doc('"+uri+"')").Load().EvaluateSingle();
177
                
178
            }
179
        return doc;
180
    }
181

    
182
	public void SetErrorsReported(IList<StaticError> errors) {
183
        foreach(StaticError err in errors){
184
            if (err.ErrorCode != null)
185
            {
186
                errorsReported.Add(err.ErrorCode);
187
            }
188
        }
189
    }
190

    
191
        public void SetErrorQNameReported(IList<QName> errors)
192
        {
193
            foreach (QName err in errors)
194
            {
195
                
196
                    errorsReported.Add(err);
197
                
198
            }
199
        }
200

    
201
        public bool HasReportedError(QName errorCode) {
202
        return errorsReported != null && errorsReported.Contains(errorCode);
203
    }
204

    
205
    public string Tostring() {
206
        return (IsException() ? "EXCEPTION " + exception.Message : GetPrincipalResult().ToString());
207
    }
208

    
209
    public void SetPrincipalSerializedResult(string result) {
210
        principalResult.serialization = result;
211
    }
212

    
213
    public string getPrincipalSerializedResult() {
214
        return principalResult.serialization;
215
    }
216

    
217
    public void SetComment(string comment) {
218
        this.comment = comment;
219
    }
220

    
221
    public string GetComment() {
222
        return comment;
223
    }
224

    
225
    public void AddXslMessage(XdmNode message) {
226
        xslMessages.Add(message);
227
    }
228

    
229
    public class MessageListener : IMessageListener
230
    {
231
        TestOutcome outcome1;
232

    
233
        public MessageListener(TestRunner.TestOutcome out1)
234
            : base()
235
        {
236
            outcome1 = out1;
237

    
238
        }
239

    
240
        public void Message(XdmNode content, bool terminate, IXmlLocation location)
241
        {
242
            outcome1.AddXslMessage(content);
243
        }
244
    }
245

    
246

    
247

    
248
    /**
249
     * This method serializes the actual result to produce a serialized result. This is not what is actually
250
     * needed by the serialization tests, which require that the serialization be performed using the parameters
251
     * contained within the query itself.
252
     *
253
     * @param p the processor
254
     * @param uri the URI of the result to serialize; null for the principal result
255
     * @return the result of serialization
256
     */
257

    
258
    public string Serialize(Processor p, Uri uri) {
259
        XdmValue value;
260
        if (uri == null) {
261
            if (principalResult.serialization != null) {
262
                return principalResult.serialization;
263
            } else {
264
                value = principalResult.value;
265
            }
266
        } else {
267
            SingleResultDoc doc = xslResultDocuments[uri];
268
            if (doc == null) {
269
                return "[[[NULL VALUE]]]";
270
            } else if (doc.serialization != null) {
271
                return doc.serialization;
272
            } else {
273
                value = doc.value;
274
            }
275
        }
276
        if (value == null) {
277
            return "[[[NULL VALUE]]]";
278
        }
279
        if (IsException()) {
280
            return "EXCEPTION " + exception.Message;
281
        } else {
282
            StringWriter sw = new StringWriter();
283
            Serializer s = p.NewSerializer();
284
            s.SetOutputProperty(Serializer.METHOD, "xml");
285
            s.SetOutputProperty(Serializer.INDENT, "no");
286
            s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
287
            try {
288
                //s.SerializeXdmValue(value); //TODO
289
            } catch (Exception err) {
290
                return ("SERIALIZATION FAILED: " + err.Message);
291
            }
292
            string str = sw.ToString().Trim();
293
            if (uri == null) {
294
                principalResult.serialization = str;
295
            } else {
296
                xslResultDocuments[uri].serialization = str;
297
            }
298
            return str;
299
        }
300
    }
301

    
302
    /**
303
     * This method serializes the actual result to produce a serialized result. This is not what is actually
304
     * needed by the serialization tests, which require that the serialization be performed using the parameters
305
     * contained within the query itself.
306
     *
307
     * @param p the processor
308
     * @param doc the result to serialize
309
     * @return the result of serialization
310
     */
311

    
312
    public string Serialize(Processor p, SingleResultDoc doc) {
313
        XdmValue value;
314
        if (doc.serialization != null) {
315
            return doc.serialization;
316
        } else {
317
            value = doc.value;
318
        }
319
        if (value == null) {
320
            return "[[[NULL VALUE]]]";
321
        }
322
        if (IsException()) {
323
            return "EXCEPTION " + exception.Message;
324
        } else {
325
            StringWriter sw = new StringWriter();
326

    
327
            Serializer s =  p.NewSerializer(sw); 
328
            s.SetOutputWriter(sw);
329
            s.SetOutputProperty(Serializer.METHOD, "xml");
330
            s.SetOutputProperty(Serializer.INDENT, "no");
331
            s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
332
            try {
333
                p.WriteXdmValue(value, s);
334
                //s.SerializeXdmValue(value);
335
            } catch (Exception err) {
336
                return ("SERIALIZATION FAILED: " + err.Message);
337
            }
338
            string str = sw.ToString().Trim();
339
            doc.serialization = str;
340
            return str;
341
        }
342
    }
343

    
344
    public string Serialize(Processor p, XdmValue value) {
345
        StringWriter sw = new StringWriter();
346
        Serializer s = p.NewSerializer(sw);
347
        s.SetOutputProperty(Serializer.METHOD, "xml");
348
        s.SetOutputProperty(Serializer.INDENT, "no");
349
        s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
350
        try {
351
            //s.serializeXdmValue(value);
352
            p.WriteXdmValue(value, s);
353
        } catch (Exception err) {
354
            return ("SERIALIZATION FAILED: " + err.Message);
355
        }
356
        return sw.ToString().Trim();
357
    }
358

    
359
    public bool TestAssertion(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug)
360
            {
361
        try {
362
            string tag = assertion.NodeName.LocalName;
363
            bool success = TestAssertion2(assertion, result, assertXpc, catalogXpc, debug);
364
            if (debug && !("all-of".Equals(tag)) && !("any-of".Equals(tag))) {
365
                driver.println("Assertion " + tag + " (" + assertion.StringValue + ") " + (success ? " succeeded" : " failed"));
366
                if (tag.Equals("error")) {
367
                    if (IsException()) {
368
                        bool b = compareExpectedError(assertion);
369
                        if (b) {
370
                            driver.println("Returned error as expected");
371
                        } else {
372
                            driver.println(wrongError);
373
                        }
374
//                        QName code = getException().getErrorCode();
375
//                        if (code == null) {
376
//                            actual = "error with no code";
377
//                        } else {
378
//                            actual = code.getLocalName();
379
//                        }
380

    
381
                    } else {
382
                        driver.println("Expected exception " + assertion.GetAttributeValue(new QName("code")) + "; got success");
383
                    }
384
//                    driver.println("Expected exception " + assertion.getAttributeValue(new QName("code")) +
385
//                            ", got " + actual);
386
                }
387
            }
388
            if (!success && wrongError != null) {
389
                // treat getting the wrong error as a pass
390
                success = true;
391
            }
392
            return success;
393
        } catch (Exception e) {
394
            System.Console.WriteLine(e.StackTrace);  //To change body of catch statement use File | Settings | File Templates.
395
            return false;
396
        }
397
    }
398

    
399
    private bool TestAssertion2(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug)  {
400
        string tag = assertion.NodeName.LocalName;
401

    
402
        if (tag.Equals("assert-eq")) {
403
            return assertEq(assertion, result, assertXpc);
404

    
405
        } else if (tag.Equals("assert-deep-eq")) {
406
            return assertDeepEq(assertion, result, assertXpc);
407

    
408
        } else if (tag.Equals("assert-permutation")) {
409
            return assertPermutation(assertion, result, assertXpc);
410

    
411
        } else if (tag.Equals("assert-xml")) {
412
            return assertXml(assertion, result, assertXpc, catalogXpc, debug);
413

    
414
        } else if (tag.Equals("serialization-matches")) {
415
            return AssertSerializationMatches(assertion, result, catalogXpc);
416

    
417
        } else if (tag.Equals("assert-serialization-error")) {
418
            return AssertSerializationError(assertion, result, assertXpc);
419

    
420
        } else if (tag.Equals("assert-empty")) {
421
            return assertEmpty(result.value);
422

    
423
        } else if (tag.Equals("assert-count")) {
424
            return assertCount(assertion, result);
425

    
426
        } else if (tag.Equals("assert")) {
427
            return AssertXPath(assertion, result, assertXpc, debug);
428

    
429
        } else if (tag.Equals("assert-string-value")) {
430
            return AssertstringValue(assertion, result, debug);
431

    
432
        } else if (tag.Equals("assert-serialization")) {
433
            return AssertSerialization(assertion, result, catalogXpc, debug);
434

    
435
        } else if (tag.Equals("assert-type")) {
436
            return AssertType(assertion, result, assertXpc);
437

    
438
        } else if (tag.Equals("assert-true")) {
439
            return AssertTrue(result);
440

    
441
        } else if (tag.Equals("assert-false")) {
442
            return AssertFalse(result);
443

    
444
			} else if(tag.Equals("assert-warning")) {
445
				return AssertWarning ();
446

    
447
			} else if (tag.Equals("assert-message")) {
448
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
449
            foreach (XdmNode message in xslMessages) {
450
                if (TestAssertion2(subAssertion, new SingleResultDoc(message, ""), assertXpc, catalogXpc, debug)) {
451
                    return true;
452
                }
453
            }
454
            return false;
455

    
456
        } else if (tag.Equals("assert-result-document")) {
457
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
458
            XmlUrlResolver res = new XmlUrlResolver();
459
            Uri uri =  new Uri(driver.getResultsDir() + "/results/output.xml");
460
            uri = res.ResolveUri(uri, assertion.GetAttributeValue(new QName("uri")));
461
            SingleResultDoc doc = GetSecondaryResult(uri);
462
            if (doc == null) {
463
                System.Console.WriteLine("**** No output document found for " + uri);
464
                return false;
465
            }
466
            bool ok = TestAssertion2(subAssertion, doc, assertXpc, catalogXpc, debug);
467
            if (!ok) {
468
                System.Console.WriteLine("**** Assertion failed for result-document " + uri);
469
            }
470
            return ok;
471

    
472
        } else if (tag.Equals("error")) {
473
            bool b= false;
474
            try { 
475
                b = IsException() && compareExpectedError(assertion);
476
            } catch(Exception) {
477
                if (GetException() is StaticError) {
478
                    string expectedError = assertion.GetAttributeValue(new QName("code"));
479
                    QName expectedErrorQ;
480
                    if (expectedError.Equals("*"))
481
                    {
482
                        expectedErrorQ = null;
483
                    }
484
                    else if (expectedError.StartsWith("Q{"))
485
                    {
486
                        expectedErrorQ = QName.FromEQName(expectedError);
487
                    }
488
                    else
489
                    {
490
                        expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
491
                    }
492

    
493
                    JFastStringBuffer fsb = new JFastStringBuffer(100);
494
                    fsb.append("Expected ");
495
                    fsb.append(expectedErrorQ.LocalName);
496
                    fsb.append("; got ");
497
                    fsb.append("err:XXX");
498
                    fsb.setLength(fsb.length() - 1);
499
                    wrongError = fsb.ToString();
500
                    return true;
501
                }
502
                if (GetException() is DynamicError)
503
                {
504
                    string expectedError = assertion.GetAttributeValue(new QName("code"));
505
                    QName expectedErrorQ;
506
                    if (expectedError.Equals("*"))
507
                    {
508
                        expectedErrorQ = null;
509
                    }
510
                    else if (expectedError.StartsWith("Q{"))
511
                    {
512
                        expectedErrorQ = QName.FromEQName(expectedError);
513
                    }
514
                    else
515
                    {
516
                        expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
517
                    }
518

    
519
                    JFastStringBuffer fsb = new JFastStringBuffer(100);
520
                    fsb.append("Expected ");
521
                    fsb.append(expectedErrorQ.LocalName);
522
                    fsb.append("; got ");
523
                    fsb.append("err:XXX");
524
                    fsb.setLength(fsb.length() - 1);
525
                    wrongError = fsb.ToString();
526
                    return true;
527
                }
528
            }
529
            return b;
530

    
531
        } else if (tag.Equals("all-of")) {
532
            foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) {
533
                if (!TestAssertion((XdmNode) child, result, assertXpc, catalogXpc, debug)) {
534
                    return false;
535
                }
536
            }
537
            return true;
538

    
539
        } else if (tag.Equals("any-of")) {
540
            bool partialSuccess = false;
541
            foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) {
542
                if (TestAssertion((XdmNode) child, result, assertXpc, catalogXpc, debug)) {
543
                    if (wrongError != null) {
544
                        partialSuccess = true;
545
                        continue;
546
                    }
547
                    return true;
548
                }
549
            }
550
            return partialSuccess;
551

    
552
        } else if (tag.Equals("not")) {
553
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
554
            return !TestAssertion(subAssertion, result, assertXpc, catalogXpc, debug);
555
        }
556
        throw new Exception("Unknown assertion element " + tag);
557
    }
558

    
559
    private bool AssertFalse(SingleResultDoc result) {
560
        if (IsException()) {
561
            return false;
562
        } else {
563
            return result.value.Count == 1 &&
564
                    ((XdmAtomicValue)result.value.Simplify).IsAtomic() &&
565
                    ((XdmAtomicValue)result.value.Simplify).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) &&
566
                    !((XdmAtomicValue)result.value.Simplify).GetBooleanValue();
567
        }
568
    }
569

    
570
    private bool AssertTrue(SingleResultDoc result) {
571
        if (IsException()) {
572
            return false;
573
        } else {
574
            return result.value.Count == 1 &&
575
                    ((XdmAtomicValue) result.value.Simplify).IsAtomic() &&
576
                    ((XdmAtomicValue)result.value.Simplify).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) &&
577
                    ((XdmAtomicValue)result.value.Simplify).GetBooleanValue();
578
        }
579
    }
580

    
581
    private bool AssertType(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
582
        if (IsException()) {
583
            return false;
584
        } else {
585
            XPathSelector s = assertXpc.Compile("$result instance of " + assertion.StringValue).Load();
586
            s.SetVariable(new QName("result"), result.value);
587
            return ((XdmAtomicValue) s.EvaluateSingle()).GetBooleanValue();
588
        }
589
    }
590

    
591
    private bool AssertstringValue(XdmNode assertion, SingleResultDoc result,bool debug) {
592
        if (IsException()) {
593
            return false;
594
        } else {
595
            string resultstring;
596
            string assertionstring = assertion.StringValue;
597
            if (result.value is XdmItem) {
598
                resultstring = ((XdmItem) result.value).GetStringValue();
599
            } else {
600
                bool first = true;
601
                net.sf.saxon.tree.util.FastStringBuffer fsb = new net.sf.saxon.tree.util.FastStringBuffer(256);
602
                foreach (XdmItem item in result.value) {
603
                    if (first) {
604
                        first = false;
605
                    } else {
606
                        fsb.append(' ');
607
                    }
608
                    fsb.append(item.Simplify.ToString());
609
                }
610
                resultstring = fsb.ToString();
611
            }
612
            string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
613
                if (normalizeAtt == null && driver.catalogNamespace().Equals("http://www.w3.org/2012/10/xslt-test-catalog")) {
614
                    normalizeAtt = "true";
615
                }
616
            if (normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1"))) {
617
                assertionstring = JWhitespace.collapseWhitespace(assertionstring).ToString();
618
                resultstring = JWhitespace.collapseWhitespace(resultstring).ToString();
619
            }
620
            if (resultstring.Equals(assertionstring)) {
621
                return true;
622
            } else {
623
                if (debug) {
624
                    if (resultstring.Length != assertionstring.Length) {
625
                        driver.println("Result length " + resultstring.Length + "; expected length " + assertionstring.Length);
626
                    }
627
                    int len = Math.Min(resultstring.Length, assertionstring.Length);
628
                    for (int i = 0; i < len; i++) {
629
                        if (resultstring[i] != assertionstring[i]) {
630
                            driver.println("Results differ at index " + i +
631
                                    "(\"" + resultstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" +
632
                                    assertionstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\")");
633
                            break;
634
                        }
635
                    }
636
                }
637
                return false;
638
            }
639
        }
640
    }
641

    
642
    private bool AssertSerialization(XdmNode assertion, SingleResultDoc result, XPathCompiler xpath, bool debug) {
643
        if (IsException()) {
644
            return false;
645
        } else {
646
            String method = assertion.GetAttributeValue(new QName("method"));
647
            if (method == null) {
648
                method = "xml";
649
            }
650
            String resultString = result.serialization;
651
            String comparand = xpath.Evaluate(
652
                    "if (@file) then " +
653
                            "if (@encoding) " +
654
                            "then unparsed-text(resolve-uri(@file, base-uri(.)), @encoding) " +
655
                            "else unparsed-text(resolve-uri(@file, base-uri(.))) " +
656
                            "else string(.)", assertion).ToString();
657
            comparand = comparand.Replace("\r\n", "\n");
658
            if (comparand.EndsWith("\n")) {
659
                comparand = comparand.Substring(0, comparand.Length-1);
660
            }
661

    
662
            if (resultString == null) {
663
                if (result.value is XdmItem) {
664
                    resultString = ((XdmItem) result.value).Simplify.ToString();
665
                } else {
666
                    if (debug) {
667
                        driver.println("Assert serialization fails: result is a sequence");
668
                    }
669
                    return false;
670
                }
671
            }
672
            bool isHtml = method.Equals("html") || method.Equals("xhtml");
673
            bool normalize = isHtml;
674
            if (!normalize) {
675
                String normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
676
                normalize = normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1"));
677
            }
678
            if (normalize) {
679
                comparand = JWhitespace.collapseWhitespace(comparand).toString();
680
                resultString = JWhitespace.collapseWhitespace(resultString).toString();
681
            } else if (resultString.EndsWith("\n")) {
682
                resultString = resultString.Substring(0, resultString.Length-1);
683
            }
684
            if (isHtml) {
685
                // should really do this only for block-level elements
686
                comparand = comparand.Replace(" <", "<");
687
                comparand = comparand.Replace("> ", ">");
688
                resultString = resultString.Replace(" <", "<");
689
                resultString = resultString.Replace("> ", ">");
690
            }
691
            if (resultString.Equals(comparand)) {
692
                return true;
693
            } else {
694
                if (debug) {
695
                    if (resultString.Length != comparand.Length) {
696
                        driver.println("Result length " + resultString.Length + "; expected length " + comparand.Length);
697
                    }
698
                    int len = Math.Min(resultString.Length, comparand.Length);
699
                    for (int i = 0; i < len; i++) {
700
                        if (resultString[1] != comparand[i]) {
701
                            driver.println("Results differ at index " + i +
702
                                    "(\"" + resultString.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" +
703
                                    comparand.Substring(i, (i + 10 > len ? len : i + 10)) + "\")");
704
                            break;
705
                        }
706
                    }
707
                }
708
                driver.println("Serialized results differ");
709
                return false;
710
            }
711
        }
712
    }
713
    private bool AssertXPath(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, bool debug) {
714
        if (IsException()) {
715
            return false;
716
        } else {
717
            IEnumerator iter = assertion.EnumerateAxis(XdmAxis.Namespace);
718
            while (iter.MoveNext()) {
719
                XdmNode namespace1 = (XdmNode)iter.Current;
720
                if (namespace1.NodeName != null) {
721
                    assertXpc.DeclareNamespace(namespace1.NodeName.LocalName, namespace1.StringValue);
722
                }
723
            }
724

    
725
            XPathExecutable exp = assertXpc.Compile(assertion.StringValue);
726
            XPathSelector s = exp.Load();
727
            QName resultVar = new QName("result");
728
            
729
             if (exp.GetRequiredCardinalityForVariable(resultVar) == '0') {
730
                if (result.value is XdmItem) { // this path used in XSLT tests
731
                    s.ContextItem = ((XdmItem)result.value);
732
                }
733
            } else {
734
                s.SetVariable(resultVar, result.value);
735
            }
736
            
737
            bool b = s.EffectiveBooleanValue();
738
            if (!b && debug) {
739
                driver.println("XPath assertion " + assertion.StringValue + " failed");
740
                try {
741
                    string ass = assertion.StringValue;
742
                    int eq = ass.IndexOf("=");
743
                    if (eq > 0) {
744
                        ass = ass.Substring(0, eq);
745
                        exp = assertXpc.Compile(ass);
746
                        s = exp.Load();
747
                        if (exp.GetRequiredCardinalityForVariable(resultVar) == null) {
748
                            if (result.value is XdmItem) { // this path used in XSLT tests
749
                                s.ContextItem = ((XdmItem)result.value);
750
                            }
751
                        } else {
752
                            s.SetVariable(resultVar, result.value);
753
                        }
754
                        XdmValue val = s.Evaluate();
755
                        driver.println("Actual result of " + ass + ": " + val.ToString());
756
                    }
757
                } catch (Exception err) {}
758
                driver.println("Actual results: " + result.value);
759
            }
760
            return b;
761
        }
762
    }
763

    
764
    private bool assertCount(XdmNode assertion, SingleResultDoc result) {
765
        return !IsException() && result.value.Count == int.Parse(assertion.StringValue);
766
    }
767

    
768
    private bool assertEmpty(XdmValue result) {
769
        return !IsException() && result.Count == 0;
770
    }
771

    
772
    private bool AssertSerializationError(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
773
        if (IsException()) {
774
            return compareExpectedError(assertion);
775
        } else {
776
            string expectedError = assertion.GetAttributeValue(new QName("code"));
777
            StringWriter sw = new StringWriter();
778
            Serializer serializer = assertXpc.Processor.NewSerializer();
779
            serializer.SetOutputProperty(Serializer.METHOD, "xml");
780
            serializer.SetOutputProperty(Serializer.INDENT, "no");
781
            serializer.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
782
            try {
783
                assertXpc.Processor.WriteXdmValue(result.value, serializer);
784
                //serializer.serializeXdmValue(result.value);
785
                return false;
786
            } catch (DynamicError err) {
787
                bool b = expectedError.Equals(err.ErrorCode.LocalName);
788
                if (!b) {
789
                    driver.println("Expected " + expectedError + ", got " + err.ErrorCode.LocalName);
790
                }
791
                return true;
792
            }
793
        }
794
    }
795

    
796
    private bool AssertSerializationMatches(XdmNode assertion, SingleResultDoc result,XPathCompiler catalogXpc) {
797
        if (IsException()) {
798
            return false;
799
        } else {
800
            //string testSet = catalogXpc.Evaluate("string(/*/@name)", assertion).ToString();
801
            string flagsAtt = assertion.GetAttributeValue(new QName("flags"));
802
            if (flagsAtt == null) {
803
                flagsAtt = "";
804
            }
805
            string regex = assertion.StringValue;
806
            //IList warnings = new ArrayList();
807
            try {
808
                JRegularExpression re = net.sf.saxon.Version.platform.compileRegularExpression(catalogXpc.Processor.Implementation,regex, flagsAtt, "XP30", new java.util.ArrayList());
809
                if (re.containsMatch(getPrincipalSerializedResult())) {
810
                    return true;
811
                } else {
812
                    driver.println("Serialized result:");
813
                    driver.println(getPrincipalSerializedResult());
814
                    return false;
815
                }
816
                
817
                
818
            } catch (DynamicError e) {
819
                throw e;
820
            }
821
        }
822
    }
823

    
824
    private bool assertXml(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) {
825
        if (IsException()) {
826
            return false;
827
        } else {
828
            string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
829
            bool normalize = normalizeAtt != null && ("true".Equals(normalizeAtt.Trim()) || "1".Equals(normalizeAtt.Trim()));
830
            string ignoreAtt = assertion.GetAttributeValue(new QName("ignore-prefixes"));
831
            bool ignorePrefixes = ignoreAtt != null && ("true".Equals(ignoreAtt.Trim()) || "1".Equals(ignoreAtt.Trim()));
832
            string xmlVersion = assertion.GetAttributeValue(new QName("xml-version"));
833
            bool xml11 = "1.1".Equals(xmlVersion);
834

    
835
            string comparand = catalogXpc.Evaluate("if (@file) then unparsed-text(resolve-uri(@file, base-uri(.))) else string(.)", assertion).ToString();
836
            if (comparand.StartsWith("<?xml")) {
837
                int index = comparand.IndexOf("?>");
838
                comparand = comparand.Substring(index+2);
839
            }
840
            comparand = comparand.Trim();
841
            comparand = comparand.Replace("\r\n", "\n");
842
            if (normalize) {
843
                comparand = JWhitespace.collapseWhitespace(comparand).ToString();
844
            }
845

    
846
            if (comparand.Equals(Serialize(assertXpc.Processor, result))) {
847
                return true;
848
            }
849

    
850
            DocumentBuilder builder = assertXpc.Processor.NewDocumentBuilder();
851
            if (xml11) {
852
                assertXpc.Processor.SetProperty(JFeatureKeys.XML_VERSION, "1.1");
853
            }
854
            StringReader reader = new StringReader((xml11 ? "<?xml version='1.1'?>" : "") + "<z>" + comparand + "</z>");
855
            builder.BaseUri = assertion.BaseUri;
856
            XdmNode expected = builder.Build(reader);
857

    
858
            int flag = 0;
859

    
860
            flag |= JDeepEqual.INCLUDE_COMMENTS;
861
            flag |= JDeepEqual.INCLUDE_PROCESSING_INSTRUCTIONS;
862
            flag |= JDeepEqual.EXCLUDE_VARIETY;
863
            if (!ignorePrefixes) {
864
                flag |= JDeepEqual.INCLUDE_NAMESPACES;
865
                flag |= JDeepEqual.INCLUDE_PREFIXES;
866
            }
867
            flag |= JDeepEqual.COMPARE_STRING_VALUES;
868
            if (debug) {
869
                flag |= JDeepEqual.WARNING_IF_FALSE;
870
            }
871
            try {
872
                JSequenceIterator iter0;
873
                if (result == null) {
874
                    System.Console.WriteLine("Result value is null");
875
                    return false;
876
                }
877
                XdmValue value = result.value;
878
                
879
                if (value == null) {
880
                    System.Console.WriteLine("Result value is null (perhaps serialized?)");
881
                    return false;
882
                }
883
                if (value.Count == 1 && value.Simplify is XdmNode && ((XdmNode) value.Simplify).NodeKind == System.Xml.XmlNodeType.Document) {
884
                    iter0 = ((XdmNode) value.Simplify).Implementation.iterateAxis(JAxisInfo.CHILD);
885
                } else {
886
                    iter0 = value.Unwrap().iterate();
887
                }
888
                JGroundedValue val0 = net.sf.saxon.value.SequenceExtent.makeSequenceExtent(iter0);
889
                JSequenceIterator iter1 = expected.Implementation.iterateAxis(JAxisInfo.CHILD).next().iterateAxis(JAxisInfo.CHILD);
890
                JGroundedValue val1 = net.sf.saxon.value.SequenceExtent.makeSequenceExtent(iter1);
891
                    bool success = JDeepEqual.deepEqual(
892
                        iter0, iter1,
893
                        new JGenericAtomicComparer(JCodepointCollator.getInstance(), null),
894
                        assertXpc.Processor.Implementation.getConversionContext(), flag);
895
                // if necessary try again ignoring whitespace nodes
896
                if (!success) {
897
                    iter0 = val0.iterate();
898
                    iter1 = val1.iterate();
899
                    // deep-equals with the EXCLUDE_WHITESPACE flag doesn't ignore top-level whitespace, so we
900
                    // need to filter that out ourselves
901
                    iter0 = new JItemMappingIterator(iter0, new RemoveWhitespace());
902
                    iter1 = new JItemMappingIterator(iter1, new RemoveWhitespace());
903
                    success = JDeepEqual.deepEqual(
904
                        iter0, iter1,
905
                        new JGenericAtomicComparer(JCodepointCollator.getInstance(), null),
906
                        assertXpc.Processor.Implementation.getConversionContext(),
907
                            flag | JDeepEqual.EXCLUDE_WHITESPACE_TEXT_NODES);
908
                    if (success) {
909
                        comment = "OK after ignoring whitespace text";
910
                    }
911
                }
912
                if (!success) {
913
                   System.Console.WriteLine("assert-xml comparison failed");
914
                   if (debug) {
915
                        System.Console.WriteLine("assert-xml comparison failed");
916
                        System.Console.WriteLine("Reference results:");
917
                        System.Console.WriteLine(expected.ToString());
918
                        System.Console.WriteLine("Actual results:");
919
                        //System.Console.WriteLine(result.serialization);
920
                        System.Console.WriteLine(value.ToString());
921
                    }
922
                }
923
                return success;
924
            } catch (DynamicError e) {
925
                Console.WriteLine(e.StackTrace);
926
                return false;
927
            }
928
        }
929
    }
930

    
931
    private class RemoveWhitespace : JItemMappingFunction 
932
    {
933
        public JItem mapItem(JItem itemi){
934
            JNodeInfo item = (JNodeInfo)itemi;
935
            bool isWhite = item.getNodeKind() ==  net.sf.saxon.type.Type.TEXT && JWhitespace.isWhite(item.getStringValueCS());
936
            return (isWhite ? null : item);
937
        }
938
    }
939

    
940
	private bool AssertWarning() {
941
			/*byte[] data = new byte[]{31, 32, 33};
942
			String.valueOf(data);*/
943
			return true;//IsWarningsReported();
944
	}
945

    
946
    private bool assertPermutation(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc) {
947
        // TODO: extend this to handle nodes (if required)
948
        if (IsException()) {
949
            return false;
950
        } else {
951
				return true;
952
            try {
953
                int expectedItems = 0;
954
                HashSet<string> expected = new HashSet<string>();
955
                XPathSelector s = assertXpc.Compile("(" + assertion.StringValue + ")").Load();
956
                s.SetVariable(new QName("result"), result.value); // not used, but we declared it
957
                JCodepointCollator collator = JCodepointCollator.getInstance();
958
                //JXPathContext context =  new JXPathContextMajor(stringValue.EMPTY_string, assertXpc.getUnderlyingStaticContext().getConfiguration());
959
                foreach (XdmItem item in s) {
960
                    expectedItems++;
961
                    XdmValue value = (XdmValue) item.Simplify;
962
                   // value.Simplify.
963
                  /*  Object comparable = value.isNaN() ?
964
                            AtomicSortComparer.COLLATION_KEY_NaN :
965
                            value.getXPathComparable(false, collator, context);
966
                    expected.Add(comparable);*/
967
                    
968
                }
969
                int actualItems = 0;
970
                foreach (XdmItem item in GetPrincipalResult()) {
971
                    actualItems++;
972
                    XdmValue value = (XdmValue)item.Simplify;
973
                    /*Object comparable = value.isNaN() ?
974
                            AtomicSortComparer.COLLATION_KEY_NaN :
975
                            value.getXPathComparable(false, collator, context); */
976
                 //   if (!expected.Contains(comparable)) {
977
                        return false;
978
                   // }
979
                }
980
                return actualItems == expectedItems;
981
            } catch (DynamicError) {
982
                return false;
983
            } 
984
        } 
985
    }
986

    
987
    private bool assertDeepEq(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
988
        if (IsException()) {
989
            return false;
990
        } else {
991
            XPathSelector s = assertXpc.Compile("deep-equal($result , (" + assertion.StringValue + "))").Load();
992
            s.SetVariable(new QName("result"), result.value);
993
            return ((XdmAtomicValue) s.Evaluate()).GetBooleanValue();
994
        }
995
    }
996

    
997
    private bool assertEq(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc) {
998
        if (IsException()) {
999
            return false;
1000
        } else {
1001
            XPathSelector s = assertXpc.Compile("$result eq " + assertion.StringValue).Load();
1002
            s.SetVariable(new QName("result"), result.value);
1003
            XdmAtomicValue item = (XdmAtomicValue) s.EvaluateSingle();
1004
            return item != null && item.GetBooleanValue();
1005
        }
1006
    }
1007

    
1008
    public bool compareExpectedError(XdmNode assertion) {
1009
        string expectedError = assertion.GetAttributeValue(new QName("code"));
1010
        QName expectedErrorQ;
1011
        if (expectedError.Equals("*")) {
1012
            expectedErrorQ = null;
1013
        } else if (expectedError.StartsWith("Q{")) {
1014
            expectedErrorQ = QName.FromEQName(expectedError);
1015
        } else {
1016
            expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
1017
        }
1018
        //noinspection ThrowableResultOfMethodCallIgnored
1019
        bool ok = (expectedError.Equals("*") ||
1020
				(GetErrorCode() != null &&
1021
					GetErrorCode().LocalName.Equals(expectedErrorQ.LocalName)) ||
1022
                (HasReportedError(new QName(expectedError))));
1023
        if (ok) {
1024
            wrongError = null;
1025
        } else if (expectedErrorQ != null && errorsReported!= null && errorsReported.Count!=0) {
1026
             JFastStringBuffer fsb = new JFastStringBuffer(100);
1027
            fsb.append("Expected ");
1028
            fsb.append(expectedErrorQ.LocalName);
1029
            fsb.append("; got ");
1030
            foreach (QName e in errorsReported) {
1031
                fsb.append(e.LocalName);
1032
                fsb.append("|");
1033
            }
1034
            fsb.setLength(fsb.length() - 1);
1035
            wrongError = fsb.ToString();
1036
        }
1037
        return ok;
1038
    }
1039

    
1040

    
1041

    
1042
    }
1043
}
(11-11/19)