Project

Profile

Help

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

he / src / samples / cs / TestRunner10.0 / TestOutcome.cs @ be17ef52

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 Processor proc;
42
            public SingleResultDoc() { }
43
            public SingleResultDoc(XdmValue value, string serialization, Processor proci) {
44
                this.value = value;
45
                this.serialization = serialization;
46
                proc = proci;
47
            }
48
        }
49

    
50
        private TestDriver driver;
51
        private SingleResultDoc principalResult = new SingleResultDoc();
52
        private HashSet<QName> errorsReported;
53
        private Exception exception;
54
        private string comment;
55
        private HashSet<XdmNode> xslMessages = new HashSet<XdmNode>();
56
        private Dictionary<Uri, SingleResultDoc> xslResultDocuments = new Dictionary<Uri, SingleResultDoc>();
57
        private string wrongError;
58
        private bool warningsReported;
59
        private Uri baseOutputUri;
60
        private string resultVar = "result";
61

    
62
        public TestOutcome(TestDriver driver) {
63
            this.driver = driver;
64
            errorsReported = new HashSet<QName>();
65
        }
66

    
67
        public void SetException(Exception ex)
68
        {
69
            this.exception = ex;
70

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

    
93
                errorsReported.Add(new QName("ZZZZZZ999999"));
94
            }
95
        }
96

    
97
        public string ResultVar {
98
            set { resultVar = value; }
99
        }
100

    
101
	public bool SetWarningsReported(bool warnings) {
102
		return warningsReported = warnings;
103
	}
104

    
105
	public bool IsWarningsReported() {
106
		return this.warningsReported;
107
	}
108

    
109
    public bool IsException() {
110
        return exception != null;
111
    }
112

    
113
    public Exception GetException()
114
    {
115
        return exception;
116
    }
117

    
118
    public QName GetErrorCode() {
119
        if (exception is DynamicError)
120
        {
121
            return ((DynamicError)exception).ErrorCode;
122
        }
123
        else if (exception is StaticError)
124
        {
125

    
126
            return ((StaticError)exception).ErrorCode;
127
        }
128
        else {
129
			return null;
130
        }
131
    }
132

    
133
    /**
134
     * Get a message giving details about the situation where the actual error code was not one of those
135
     * expected
136
     * @return null if this situation did not occur; otherwise a message showing the actual error code
137
     * and the expected error code
138
     */
139

    
140
    public string GetWrongErrorMessage() {
141
        return wrongError;
142
    }
143

    
144

    
145
    public void SetPrincipalResult(XdmValue value) {
146
        principalResult.value = value;
147
    }
148

    
149
    public XdmValue GetPrincipalResult() {
150
        return principalResult.value;
151
    }
152

    
153
    public SingleResultDoc GetPrincipalResultDoc() {
154
        return principalResult;
155
    }
156

    
157
    public void SetSecondaryResult(Uri uri, XdmNode value, string serialization, Processor proc) {
158
        SingleResultDoc result = null;
159
        try
160
        {
161
            result = xslResultDocuments[uri];
162
        }catch(Exception){}
163
        if (result == null) {
164
            result = new SingleResultDoc(value, serialization, proc);
165
            this.xslResultDocuments.Add(uri,result);
166
        } else {
167
            if (value != null) {
168
                result.value = value;
169
            }
170
            if (serialization != null) {
171
                result.serialization = serialization;
172
            }
173
        }
174
    }
175

    
176
		public Dictionary<Uri, SingleResultDoc> GetSecondaryResultDocuments() {
177
			return xslResultDocuments;
178
	}
179
    
180
    public SingleResultDoc GetSecondaryResult(Uri uri) {
181
            SingleResultDoc doc = xslResultDocuments[uri];
182
            Processor proc = doc.proc;
183
            if (doc.serialization.Equals("")) {
184
           
185
                doc.value = proc.NewXPathCompiler().Compile("doc('"+uri+"')").Load().EvaluateSingle();
186
                
187
            }
188
        return doc;
189
    }
190

    
191
        public void SetErrorsReported(IList<XmlProcessingError> errors)
192
        {
193
            if (errors != null)
194
            {
195
                foreach (StaticError err in errors)
196
                {
197
                    if (err.ErrorCode != null)
198
                    {
199
                        errorsReported.Add(err.ErrorCode);
200
                    }
201
                }
202
            }
203
            else {
204
                Console.WriteLine("seterrorsReported: errors is null");
205

    
206
            }
207
        }
208
    
209

    
210
        public void SetErrorQNameReported(IList<QName> errors)
211
        {
212
            foreach (QName err in errors)
213
            {
214
                
215
                    errorsReported.Add(err);
216
                
217
            }
218
        }
219

    
220
        public bool HasReportedError(QName errorCode) {
221
        return errorsReported != null && errorsReported.Contains(errorCode);
222
    }
223

    
224
    public string Tostring() {
225
        return (IsException() ? "EXCEPTION " + exception.Message : GetPrincipalResult().ToString());
226
    }
227

    
228
    public void SetPrincipalSerializedResult(string result) {
229
        principalResult.serialization = result;
230
    }
231

    
232
    public string getPrincipalSerializedResult() {
233
        return principalResult.serialization;
234
    }
235

    
236
    public void SetComment(string comment) {
237
        this.comment = comment;
238
    }
239

    
240
    public string GetComment() {
241
        return comment;
242
    }
243

    
244
    public void AddXslMessage(XdmNode message) {
245
        xslMessages.Add(message);
246
    }
247

    
248
    public class MessageListener : IMessageListener
249
    {
250
        TestOutcome outcome1;
251

    
252
        public MessageListener(TestRunner.TestOutcome out1)
253
            : base()
254
        {
255
            outcome1 = out1;
256

    
257
        }
258

    
259
        public void Message(XdmNode content, bool terminate, IXmlLocation location)
260
        {
261
            outcome1.AddXslMessage(content);
262
        }
263
    }
264

    
265

    
266

    
267
    /**
268
     * This method serializes the actual result to produce a serialized result. This is not what is actually
269
     * needed by the serialization tests, which require that the serialization be performed using the parameters
270
     * contained within the query itself.
271
     *
272
     * @param p the processor
273
     * @param uri the URI of the result to serialize; null for the principal result
274
     * @return the result of serialization
275
     */
276

    
277
    public string Serialize(Processor p, Uri uri) {
278
        XdmValue value;
279
        if (uri == null) {
280
            if (principalResult.serialization != null) {
281
                return principalResult.serialization;
282
            } else {
283
                value = principalResult.value;
284
            }
285
        } else {
286
            SingleResultDoc doc = xslResultDocuments[uri];
287
            if (doc == null) {
288
                return "[[[NULL VALUE]]]";
289
            } else if (doc.serialization != null) {
290
                return doc.serialization;
291
            } else {
292
                value = doc.value;
293
            }
294
        }
295
        if (value == null) {
296
            return "[[[NULL VALUE]]]";
297
        }
298
        if (IsException()) {
299
            return "EXCEPTION " + exception.Message;
300
        } else {
301
            StringWriter sw = new StringWriter();
302
            Serializer s = p.NewSerializer();
303
            s.SetOutputProperty(Serializer.METHOD, "xml");
304
            s.SetOutputProperty(Serializer.INDENT, "no");
305
            s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
306
            try {
307
                //s.SerializeXdmValue(value); //TODO
308
            } catch (Exception err) {
309
                return ("SERIALIZATION FAILED: " + err.Message);
310
            }
311
            string str = sw.ToString().Trim();
312
            if (uri == null) {
313
                principalResult.serialization = str;
314
            } else {
315
                xslResultDocuments[uri].serialization = str;
316
            }
317
            return str;
318
        }
319
    }
320

    
321
    /**
322
     * This method serializes the actual result to produce a serialized result. This is not what is actually
323
     * needed by the serialization tests, which require that the serialization be performed using the parameters
324
     * contained within the query itself.
325
     *
326
     * @param p the processor
327
     * @param doc the result to serialize
328
     * @return the result of serialization
329
     */
330

    
331
    public string Serialize(Processor p, SingleResultDoc doc) {
332
        XdmValue value;
333
        if (doc.serialization != null) {
334
            return doc.serialization;
335
        } else {
336
            value = doc.value;
337
        }
338
        if (value == null) {
339
            return "[[[NULL VALUE]]]";
340
        }
341
        if (IsException()) {
342
            return "EXCEPTION " + exception.Message;
343
        } else {
344
            StringWriter sw = new StringWriter();
345

    
346
            Serializer s =  p.NewSerializer(sw); 
347
            s.SetOutputWriter(sw);
348
            s.SetOutputProperty(Serializer.METHOD, "xml");
349
            s.SetOutputProperty(Serializer.INDENT, "no");
350
            s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
351
            try {
352
                p.WriteXdmValue(value, s);
353
                //s.SerializeXdmValue(value);
354
            } catch (Exception err) {
355
                return ("SERIALIZATION FAILED: " + err.Message);
356
            }
357
            string str = sw.ToString().Trim();
358
            doc.serialization = str;
359
            return str;
360
        }
361
    }
362

    
363
    public string Serialize(Processor p, XdmValue value) {
364
        StringWriter sw = new StringWriter();
365
        Serializer s = p.NewSerializer(sw);
366
        s.SetOutputProperty(Serializer.METHOD, "xml");
367
        s.SetOutputProperty(Serializer.INDENT, "no");
368
        s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
369
        try {
370
            //s.serializeXdmValue(value);
371
            p.WriteXdmValue(value, s);
372
        } catch (Exception err) {
373
            return ("SERIALIZATION FAILED: " + err.Message);
374
        }
375
        return sw.ToString().Trim();
376
    }
377

    
378
    public bool TestAssertion(TestOutcome outcome, XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug)
379
            {
380
        try {
381
            string tag = assertion.NodeName.LocalName;
382
            bool success = TestAssertion2(outcome, assertion, result, assertXpc, catalogXpc, debug);
383
            if (debug && !("all-of".Equals(tag)) && !("any-of".Equals(tag))) {
384
                driver.println("Assertion " + tag + " (" + assertion.StringValue + ") " + (success ? " succeeded" : " failed"));
385
                if (tag.Equals("error")) {
386
                    if (IsException()) {
387
                        bool b = compareExpectedError(assertion);
388
                        if (b) {
389
                            driver.println("Returned error as expected");
390
                        } else {
391
                            driver.println(wrongError);
392
                        }
393
//                        QName code = getException().getErrorCode();
394
//                        if (code == null) {
395
//                            actual = "error with no code";
396
//                        } else {
397
//                            actual = code.getLocalName();
398
//                        }
399

    
400
                    } else {
401
                        driver.println("Expected exception " + assertion.GetAttributeValue(new QName("code")) + "; got success");
402
                    }
403
//                    driver.println("Expected exception " + assertion.getAttributeValue(new QName("code")) +
404
//                            ", got " + actual);
405
                }
406
            }
407
            if (!success && wrongError != null) {
408
                // treat getting the wrong error as a pass
409
                success = true;
410
            }
411
            return success;
412
        } catch (Exception e) {
413
            System.Console.WriteLine(e.StackTrace);  //To change body of catch statement use File | Settings | File Templates.
414
            return false;
415
        }
416
    }
417

    
418
    private bool TestAssertion2(TestOutcome outcome, XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug)  {
419
        string tag = assertion.NodeName.LocalName;
420

    
421
        if (tag.Equals("assert-eq")) {
422
            return assertEq(assertion, result, assertXpc);
423

    
424
        } else if (tag.Equals("assert-deep-eq")) {
425
            return assertDeepEq(assertion, result, assertXpc);
426

    
427
        } else if (tag.Equals("assert-permutation")) {
428
            return assertPermutation(assertion, result, assertXpc);
429

    
430
        } else if (tag.Equals("assert-xml")) {
431
            return assertXml(assertion, result, assertXpc, catalogXpc, debug);
432

    
433
        } else if (tag.Equals("serialization-matches")) {
434
            return AssertSerializationMatches(assertion, result, catalogXpc);
435

    
436
        } else if (tag.Equals("assert-serialization-error")) {
437
            return AssertSerializationError(assertion, result, assertXpc);
438

    
439
        } else if (tag.Equals("assert-empty")) {
440
            return assertEmpty(result.value);
441

    
442
        } else if (tag.Equals("assert-count")) {
443
            return assertCount(assertion, result);
444

    
445
        } else if (tag.Equals("assert")) {
446
            return AssertXPath(assertion, result, assertXpc, debug);
447

    
448
        } else if (tag.Equals("assert-string-value")) {
449
            return AssertStringValue(assertion, result, debug);
450

    
451
        } else if (tag.Equals("assert-serialization")) {
452
            return AssertSerialization(assertion, result, catalogXpc, debug);
453

    
454
        } else if (tag.Equals("assert-type")) {
455
            return AssertType(assertion, result, assertXpc);
456

    
457
        } else if (tag.Equals("assert-true")) {
458
            return AssertTrue(result);
459

    
460
        } else if (tag.Equals("assert-false")) {
461
            return AssertFalse(result);
462

    
463
			} else if(tag.Equals("assert-warning")) {
464
				return AssertWarning ();
465

    
466
			} else if (tag.Equals("assert-message")) {
467
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
468
            foreach (XdmNode message in xslMessages) {
469
                if (TestAssertion2(outcome, subAssertion, new SingleResultDoc(message, "", assertXpc.Processor), assertXpc, catalogXpc, debug)) {
470
                    return true;
471
                }
472
            }
473
            return false;
474

    
475
        } else if (tag.Equals("assert-result-document")) {
476
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
477
            XmlUrlResolver res = new XmlUrlResolver();
478
                // Uri uri =  new Uri(outcome.BaseOutputUri + "/results/output.xml");
479
                Uri uri = null;
480
                try
481
                {
482
                    uri = res.ResolveUri(outcome.BaseOutputUri, assertion.GetAttributeValue(new QName("uri")));
483
                }
484
                catch (Exception ex) {
485
                    System.Console.WriteLine("**** Invalid output uri " + outcome.BaseOutputUri.AbsolutePath);
486
                    return false;
487
                }
488
            SingleResultDoc doc = GetSecondaryResult(uri);
489
            if (doc == null) {
490
                System.Console.WriteLine("**** No output document found for " + uri);
491
                return false;
492
            }
493
            bool ok = TestAssertion2(outcome, subAssertion, doc, assertXpc, catalogXpc, debug);
494
            if (!ok) {
495
                System.Console.WriteLine("**** Assertion failed for result-document " + uri);
496
            }
497
            return ok;
498

    
499
        } else if (tag.Equals("error")) {
500
            bool b= false;
501
            try { 
502
                b = IsException() && compareExpectedError(assertion);
503
            } catch(Exception) {
504
                if (GetException() is StaticError) {
505
                    string expectedError = assertion.GetAttributeValue(new QName("code"));
506
                    QName expectedErrorQ;
507
                    if (expectedError.Equals("*"))
508
                    {
509
                        expectedErrorQ = null;
510
                    }
511
                    else if (expectedError.StartsWith("Q{"))
512
                    {
513
                        expectedErrorQ = QName.FromEQName(expectedError);
514
                    }
515
                    else
516
                    {
517
                        expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
518
                    }
519

    
520
                    JFastStringBuffer fsb = new JFastStringBuffer(100);
521
                    fsb.append("Expected ");
522
                    fsb.append(expectedErrorQ.LocalName);
523
                    fsb.append("; got ");
524
                    fsb.append("err:XXX");
525
                    fsb.setLength(fsb.length() - 1);
526
                    wrongError = fsb.ToString();
527
                    return true;
528
                }
529
                if (GetException() is DynamicError)
530
                {
531
                    string expectedError = assertion.GetAttributeValue(new QName("code"));
532
                    QName expectedErrorQ;
533
                    if (expectedError.Equals("*"))
534
                    {
535
                        expectedErrorQ = null;
536
                    }
537
                    else if (expectedError.StartsWith("Q{"))
538
                    {
539
                        expectedErrorQ = QName.FromEQName(expectedError);
540
                    }
541
                    else
542
                    {
543
                        expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
544
                    }
545

    
546
                    JFastStringBuffer fsb = new JFastStringBuffer(100);
547
                    fsb.append("Expected ");
548
                    fsb.append(expectedErrorQ.LocalName);
549
                    fsb.append("; got ");
550
                    fsb.append("err:XXX");
551
                    fsb.setLength(fsb.length() - 1);
552
                    wrongError = fsb.ToString();
553
                    return true;
554
                }
555
            }
556
            return b;
557

    
558
        } else if (tag.Equals("all-of")) {
559
            foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) {
560
                if (!TestAssertion(outcome, (XdmNode) child, result, assertXpc, catalogXpc, debug)) {
561
                    return false;
562
                }
563
            }
564
            return true;
565

    
566
        } else if (tag.Equals("any-of")) {
567
            bool partialSuccess = false;
568
            foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) {
569
                if (TestAssertion(outcome, (XdmNode) child, result, assertXpc, catalogXpc, debug)) {
570
                    if (wrongError != null) {
571
                        partialSuccess = true;
572
                        continue;
573
                    }
574
                    return true;
575
                }
576
            }
577
            return partialSuccess;
578

    
579
        } else if (tag.Equals("not")) {
580
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
581
            return !TestAssertion(outcome, subAssertion, result, assertXpc, catalogXpc, debug);
582
        }
583
        throw new Exception("Unknown assertion element " + tag);
584
    }
585

    
586
        internal Uri BaseOutputUri
587
        {
588
            set { baseOutputUri = value; }
589
            get { return baseOutputUri; }
590
            
591
        }
592

    
593
        private bool AssertFalse(SingleResultDoc result) {
594
        if (IsException()) {
595
            return false;
596
        } else {
597
            return result.value.Count == 1 &&
598
                    ((XdmAtomicValue)result.value.Simplify).IsAtomic() &&
599
                    ((XdmAtomicValue)result.value.Simplify).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) &&
600
                    !((XdmAtomicValue)result.value.Simplify).GetBooleanValue();
601
        }
602
    }
603

    
604
    private bool AssertTrue(SingleResultDoc result) {
605
        if (IsException()) {
606
            return false;
607
        } else {
608
            return result.value.Count == 1 &&
609
                    ((XdmAtomicValue) result.value.Simplify).IsAtomic() &&
610
                    ((XdmAtomicValue)result.value.Simplify).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) &&
611
                    ((XdmAtomicValue)result.value.Simplify).GetBooleanValue();
612
        }
613
    }
614

    
615
    private bool AssertType(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
616
        if (IsException()) {
617
            return false;
618
        } else {
619
            XPathSelector s = assertXpc.Compile("$result instance of " + assertion.StringValue).Load();
620
            s.SetVariable(new QName("result"), result.value);
621
            return ((XdmAtomicValue) s.EvaluateSingle()).GetBooleanValue();
622
        }
623
    }
624

    
625
    private bool AssertStringValue(XdmNode assertion, SingleResultDoc result,bool debug) {
626
        if (IsException()) {
627
            return false;
628
        } else {
629
            string resultstring;
630
            string assertionstring = assertion.StringValue;
631
            if (result.value is XdmItem) {
632
                resultstring = ((XdmItem) result.value).GetStringValue();
633
            } else {
634
                bool first = true;
635
                //net.sf.saxon.tree.util.FastStringBuffer fsb = new net.sf.saxon.tree.util.FastStringBuffer(256);
636
                    StringBuilder fsb = new StringBuilder(256);
637
                foreach (XdmItem item in result.value) {
638
                    if (first) {
639
                        first = false;
640
                    } else {
641
                        fsb.Append(' ');
642
                    }
643
                    fsb.Append(item.GetStringValue());
644
                }
645
                resultstring = fsb.ToString();
646
            }
647
            string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
648
                if (normalizeAtt == null && driver.catalogNamespace().Equals("http://www.w3.org/2012/10/xslt-test-catalog")) {
649
                    normalizeAtt = "true";
650
                }
651
            if (normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1"))) {
652
                assertionstring = JWhitespace.collapseWhitespace(assertionstring).ToString();
653
                resultstring = JWhitespace.collapseWhitespace(resultstring).ToString();
654
            }
655
            if (resultstring.Equals(assertionstring)) {
656
                return true;
657
            } else {
658
                if (debug) {
659
                    if (resultstring.Length != assertionstring.Length) {
660
                        driver.println("Result length " + resultstring.Length + "; expected length " + assertionstring.Length);
661
                    }
662
                    int len = Math.Min(resultstring.Length, assertionstring.Length);
663
                    for (int i = 0; i < len; i++) {
664
                        if (resultstring[i] != assertionstring[i]) {
665
                            driver.println("Results differ at index " + i +
666
                                    "(\"" + resultstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" +
667
                                    assertionstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\")");
668
                            break;
669
                        }
670
                    }
671
                }
672
                return false;
673
            }
674
        }
675
    }
676

    
677
    private bool AssertSerialization(XdmNode assertion, SingleResultDoc result, XPathCompiler xpath, bool debug) {
678
        if (IsException()) {
679
            return false;
680
        } else {
681
            String method = assertion.GetAttributeValue(new QName("method"));
682
            if (method == null) {
683
                method = "xml";
684
            }
685
            String resultString = result.serialization;
686
            String comparand = xpath.Evaluate(
687
                    "if (@file) then " +
688
                            "if (@encoding) " +
689
                            "then unparsed-text(resolve-uri(@file, base-uri(.)), @encoding) " +
690
                            "else unparsed-text(resolve-uri(@file, base-uri(.))) " +
691
                            "else string(.)", assertion).ToString();
692
            comparand = comparand.Replace("\r\n", "\n");
693
            if (comparand.EndsWith("\n")) {
694
                comparand = comparand.Substring(0, comparand.Length-1);
695
            }
696

    
697
            if (resultString == null) {
698
                if (result.value is XdmItem) {
699
                    resultString = ((XdmItem) result.value).Simplify.ToString();
700
                } else {
701
                    if (debug) {
702
                        driver.println("Assert serialization fails: result is a sequence");
703
                    }
704
                    return false;
705
                }
706
            }
707
            bool isHtml = method.Equals("html") || method.Equals("xhtml");
708
            bool normalize = isHtml;
709
            if (!normalize) {
710
                String normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
711
                normalize = normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1"));
712
            }
713
            if (normalize) {
714
                comparand = JWhitespace.collapseWhitespace(comparand).toString();
715
                resultString = JWhitespace.collapseWhitespace(resultString).toString();
716
            } else if (resultString.EndsWith("\n")) {
717
                resultString = resultString.Substring(0, resultString.Length-1);
718
            }
719
            if (isHtml) {
720
                // should really do this only for block-level elements
721
                comparand = comparand.Replace(" <", "<");
722
                comparand = comparand.Replace("> ", ">");
723
                resultString = resultString.Replace(" <", "<");
724
                resultString = resultString.Replace("> ", ">");
725
            }
726
            if (resultString.Equals(comparand)) {
727
                return true;
728
            } else {
729
                if (debug) {
730
                    if (resultString.Length != comparand.Length) {
731
                        driver.println("Result length " + resultString.Length + "; expected length " + comparand.Length);
732
                    }
733
                    int len = Math.Min(resultString.Length, comparand.Length);
734
                    for (int i = 0; i < len; i++) {
735
                        if (resultString[1] != comparand[i]) {
736
                            driver.println("Results differ at index " + i +
737
                                    "(\"" + resultString.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" +
738
                                    comparand.Substring(i, (i + 10 > len ? len : i + 10)) + "\")");
739
                            break;
740
                        }
741
                    }
742
                }
743
                driver.println("Serialized results differ");
744
                return false;
745
            }
746
        }
747
    }
748
    private bool AssertXPath(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, bool debug) {
749
        if (IsException()) {
750
            return false;
751
        } else {
752
            IEnumerator iter = assertion.EnumerateAxis(XdmAxis.Namespace);
753
            while (iter.MoveNext()) {
754
                XdmNode namespace1 = (XdmNode)iter.Current;
755
                if (namespace1.NodeName != null) {
756
                    assertXpc.DeclareNamespace(namespace1.NodeName.LocalName, namespace1.StringValue);
757
                }
758
            }
759

    
760
            QName resultVarName = new QName(resultVar);
761
                assertXpc.DeclareVariable(resultVarName);
762
            XPathExecutable exp = assertXpc.Compile(assertion.StringValue);
763
            XPathSelector s = exp.Load();
764

    
765
                s.SetVariable(resultVarName, result.value);
766
                if (result.value is XdmItem) { // this path used in XSLT tests
767
                    s.ContextItem = (XdmItem)result.value;
768
                }
769
            
770
            
771
            bool b = s.EffectiveBooleanValue();
772
            if (!b && debug) {
773
                driver.println("XPath assertion " + assertion.StringValue + " failed");
774
                try {
775
                    string ass = assertion.StringValue;
776
                    int eq = ass.IndexOf("=");
777
                    if (eq > 0) {
778
                        ass = ass.Substring(0, eq);
779
                        exp = assertXpc.Compile(ass);
780
                        s = exp.Load();
781
                        if (exp.GetRequiredCardinalityForVariable(resultVarName) == null) {
782
                            if (result.value is XdmItem) { // this path used in XSLT tests
783
                                s.ContextItem = ((XdmItem)result.value);
784
                            }
785
                        } else {
786
                            s.SetVariable(resultVarName, result.value);
787
                        }
788
                        XdmValue val = s.Evaluate();
789
                        driver.println("Actual result of " + ass + ": " + val.ToString());
790
                    }
791
                } catch (Exception err) {}
792
                driver.println("Actual results: " + result.value);
793
            }
794
            return b;
795
        }
796
    }
797

    
798
    private bool assertCount(XdmNode assertion, SingleResultDoc result) {
799
        return !IsException() && result.value.Count == int.Parse(assertion.StringValue);
800
    }
801

    
802
    private bool assertEmpty(XdmValue result) {
803
        return !IsException() && result.Count == 0;
804
    }
805

    
806
    private bool AssertSerializationError(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
807
        if (IsException()) {
808
            return compareExpectedError(assertion);
809
        } else {
810
            string expectedError = assertion.GetAttributeValue(new QName("code"));
811
            StringWriter sw = new StringWriter();
812
            Serializer serializer = assertXpc.Processor.NewSerializer();
813
            serializer.SetOutputProperty(Serializer.METHOD, "xml");
814
            serializer.SetOutputProperty(Serializer.INDENT, "no");
815
            serializer.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
816
            try {
817
                assertXpc.Processor.WriteXdmValue(result.value, serializer);
818
                //serializer.serializeXdmValue(result.value);
819
                return false;
820
            } catch (DynamicError err) {
821
                bool b = expectedError.Equals(err.ErrorCode.LocalName);
822
                if (!b) {
823
                    driver.println("Expected " + expectedError + ", got " + err.ErrorCode.LocalName);
824
                }
825
                return true;
826
            }
827
        }
828
    }
829

    
830
    private bool AssertSerializationMatches(XdmNode assertion, SingleResultDoc result,XPathCompiler catalogXpc) {
831
        if (IsException()) {
832
            return false;
833
        } else {
834
            //string testSet = catalogXpc.Evaluate("string(/*/@name)", assertion).ToString();
835
            string flagsAtt = assertion.GetAttributeValue(new QName("flags"));
836
            if (flagsAtt == null) {
837
                flagsAtt = "";
838
            }
839
            string regex = assertion.StringValue;
840
            //IList warnings = new ArrayList();
841
            try {
842
                JRegularExpression re = net.sf.saxon.Version.platform.compileRegularExpression(catalogXpc.Processor.Implementation,regex, flagsAtt, "XP30", new java.util.ArrayList());
843
                if (re.containsMatch(getPrincipalSerializedResult())) {
844
                    return true;
845
                } else {
846
                    driver.println("Serialized result:");
847
                    driver.println(getPrincipalSerializedResult());
848
                    return false;
849
                }
850
                
851
                
852
            } catch (DynamicError e) {
853
                throw e;
854
            }
855
        }
856
    }
857

    
858
    private bool assertXml(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) {
859
        if (IsException()) {
860
            return false;
861
        } else {
862
            string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
863
            bool normalize = normalizeAtt != null && ("true".Equals(normalizeAtt.Trim()) || "1".Equals(normalizeAtt.Trim()));
864
            string ignoreAtt = assertion.GetAttributeValue(new QName("ignore-prefixes"));
865
            bool ignorePrefixes = ignoreAtt != null && ("true".Equals(ignoreAtt.Trim()) || "1".Equals(ignoreAtt.Trim()));
866
            string xmlVersion = assertion.GetAttributeValue(new QName("xml-version"));
867
            bool xml11 = "1.1".Equals(xmlVersion);
868

    
869
            string comparand = catalogXpc.Evaluate("if (@file) then unparsed-text(resolve-uri(@file, base-uri(.))) else string(.)", assertion).ToString();
870
            if (comparand.StartsWith("<?xml")) {
871
                int index = comparand.IndexOf("?>");
872
                comparand = comparand.Substring(index+2);
873
            }
874
            comparand = comparand.Trim();
875
            comparand = comparand.Replace("\r\n", "\n");
876
            if (normalize) {
877
                comparand = JWhitespace.collapseWhitespace(comparand).ToString();
878
            }
879

    
880
            if (comparand.Equals(Serialize(assertXpc.Processor, result))) {
881
                return true;
882
            }
883

    
884
            DocumentBuilder builder = assertXpc.Processor.NewDocumentBuilder();
885
            if (xml11) {
886
                assertXpc.Processor.SetProperty(JFeatureKeys.XML_VERSION, "1.1");
887
            }
888
            StringReader reader = new StringReader((xml11 ? "<?xml version='1.1'?>" : "") + "<z>" + comparand + "</z>");
889
            builder.BaseUri = assertion.BaseUri;
890
            XdmNode expected = builder.Build(reader);
891

    
892
            int flag = 0;
893

    
894
            flag |= JDeepEqual.INCLUDE_COMMENTS;
895
            flag |= JDeepEqual.INCLUDE_PROCESSING_INSTRUCTIONS;
896
            flag |= JDeepEqual.EXCLUDE_VARIETY;
897
            if (!ignorePrefixes) {
898
                flag |= JDeepEqual.INCLUDE_NAMESPACES;
899
                flag |= JDeepEqual.INCLUDE_PREFIXES;
900
            }
901
            flag |= JDeepEqual.COMPARE_STRING_VALUES;
902
            if (debug) {
903
                flag |= JDeepEqual.WARNING_IF_FALSE;
904
            }
905
            try {
906
                JSequenceIterator iter0;
907
                if (result == null) {
908
                    System.Console.WriteLine("Result value is null");
909
                    return false;
910
                }
911
                XdmValue value = result.value;
912
                
913
                if (value == null) {
914
                    System.Console.WriteLine("Result value is null (perhaps serialized?)");
915
                    return false;
916
                }
917
                if (value.Count == 1 && value.Simplify is XdmNode && ((XdmNode) value.Simplify).NodeKind == System.Xml.XmlNodeType.Document) {
918
                    iter0 = ((XdmNode) value.Simplify).Implementation.iterateAxis(JAxisInfo.CHILD);
919
                } else {
920
                    iter0 = value.Unwrap().iterate();
921
                }
922
                JGroundedValue val0 = net.sf.saxon.value.SequenceExtent.makeSequenceExtent(iter0);
923
                JSequenceIterator iter1 = expected.Implementation.iterateAxis(JAxisInfo.CHILD).next().iterateAxis(JAxisInfo.CHILD);
924
                JGroundedValue val1 = net.sf.saxon.value.SequenceExtent.makeSequenceExtent(iter1);
925
                    bool success = JDeepEqual.deepEqual(
926
                        iter0, iter1,
927
                        new JGenericAtomicComparer(JCodepointCollator.getInstance(), null),
928
                        assertXpc.Processor.Implementation.getConversionContext(), flag);
929
                // if necessary try again ignoring whitespace nodes
930
                if (!success) {
931
                    iter0 = val0.iterate();
932
                    iter1 = val1.iterate();
933
                    // deep-equals with the EXCLUDE_WHITESPACE flag doesn't ignore top-level whitespace, so we
934
                    // need to filter that out ourselves
935
                    iter0 = new JItemMappingIterator(iter0, new RemoveWhitespace());
936
                    iter1 = new JItemMappingIterator(iter1, new RemoveWhitespace());
937
                    success = JDeepEqual.deepEqual(
938
                        iter0, iter1,
939
                        new JGenericAtomicComparer(JCodepointCollator.getInstance(), null),
940
                        assertXpc.Processor.Implementation.getConversionContext(),
941
                            flag | JDeepEqual.EXCLUDE_WHITESPACE_TEXT_NODES);
942
                    if (success) {
943
                        comment = "OK after ignoring whitespace text";
944
                    }
945
                }
946
                if (!success) {
947
                   System.Console.WriteLine("assert-xml comparison failed");
948
                   if (debug) {
949
                        System.Console.WriteLine("assert-xml comparison failed");
950
                        System.Console.WriteLine("Reference results:");
951
                        System.Console.WriteLine(expected.ToString());
952
                        System.Console.WriteLine("Actual results:");
953
                        //System.Console.WriteLine(result.serialization);
954
                        System.Console.WriteLine(value.ToString());
955
                    }
956
                }
957
                return success;
958
            } catch (DynamicError e) {
959
                Console.WriteLine(e.StackTrace);
960
                return false;
961
            }
962
        }
963
    }
964

    
965
    private class RemoveWhitespace : JItemMappingFunction 
966
    {
967
        public JItem mapItem(JItem itemi){
968
            JNodeInfo item = (JNodeInfo)itemi;
969
            bool isWhite = item.getNodeKind() ==  net.sf.saxon.type.Type.TEXT && JWhitespace.isWhite(item.getStringValueCS());
970
            return (isWhite ? null : item);
971
        }
972
    }
973

    
974
	private bool AssertWarning() {
975
			/*byte[] data = new byte[]{31, 32, 33};
976
			String.valueOf(data);*/
977
			return true;//IsWarningsReported();
978
	}
979

    
980
    private bool assertPermutation(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc) {
981
        // TODO: extend this to handle nodes (if required)
982
        if (IsException()) {
983
            return false;
984
        } else {
985
				return true;
986
            try {
987
                int expectedItems = 0;
988
                HashSet<string> expected = new HashSet<string>();
989
                XPathSelector s = assertXpc.Compile("(" + assertion.StringValue + ")").Load();
990
                s.SetVariable(new QName("result"), result.value); // not used, but we declared it
991
                JCodepointCollator collator = JCodepointCollator.getInstance();
992
                //JXPathContext context =  new JXPathContextMajor(stringValue.EMPTY_string, assertXpc.getUnderlyingStaticContext().getConfiguration());
993
                foreach (XdmItem item in s) {
994
                    expectedItems++;
995
                    XdmValue value = (XdmValue) item.Simplify;
996
                   // value.Simplify.
997
                  /*  Object comparable = value.isNaN() ?
998
                            AtomicSortComparer.COLLATION_KEY_NaN :
999
                            value.getXPathComparable(false, collator, context);
1000
                    expected.Add(comparable);*/
1001
                    
1002
                }
1003
                int actualItems = 0;
1004
                foreach (XdmItem item in GetPrincipalResult()) {
1005
                    actualItems++;
1006
                    XdmValue value = (XdmValue)item.Simplify;
1007
                    /*Object comparable = value.isNaN() ?
1008
                            AtomicSortComparer.COLLATION_KEY_NaN :
1009
                            value.getXPathComparable(false, collator, context); */
1010
                 //   if (!expected.Contains(comparable)) {
1011
                        return false;
1012
                   // }
1013
                }
1014
                return actualItems == expectedItems;
1015
            } catch (DynamicError) {
1016
                return false;
1017
            } 
1018
        } 
1019
    }
1020

    
1021
    private bool assertDeepEq(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
1022
        if (IsException()) {
1023
            return false;
1024
        } else {
1025
            XPathSelector s = assertXpc.Compile("deep-equal($result , (" + assertion.StringValue + "))").Load();
1026
            s.SetVariable(new QName("result"), result.value);
1027
            return ((XdmAtomicValue) s.Evaluate()).GetBooleanValue();
1028
        }
1029
    }
1030

    
1031
    private bool assertEq(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc) {
1032
        if (IsException()) {
1033
            return false;
1034
        } else {
1035
            XPathSelector s = assertXpc.Compile("$result eq " + assertion.StringValue).Load();
1036
            s.SetVariable(new QName("result"), result.value);
1037
            XdmAtomicValue item = (XdmAtomicValue) s.EvaluateSingle();
1038
            return item != null && item.GetBooleanValue();
1039
        }
1040
    }
1041

    
1042
    public bool compareExpectedError(XdmNode assertion) {
1043
        string expectedError = assertion.GetAttributeValue(new QName("code"));
1044
        QName expectedErrorQ;
1045
        if (expectedError.Equals("*")) {
1046
            expectedErrorQ = null;
1047
        } else if (expectedError.StartsWith("Q{")) {
1048
            expectedErrorQ = QName.FromEQName(expectedError);
1049
        } else {
1050
            expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
1051
        }
1052
        //noinspection ThrowableResultOfMethodCallIgnored
1053
        bool ok = (expectedError.Equals("*") ||
1054
				(GetErrorCode() != null &&
1055
					GetErrorCode().LocalName.Equals(expectedErrorQ.LocalName)) ||
1056
                (HasReportedError(new QName(expectedError))));
1057
        if (ok) {
1058
            wrongError = null;
1059
        } else if (expectedErrorQ != null && errorsReported!= null && errorsReported.Count!=0) {
1060
             JFastStringBuffer fsb = new JFastStringBuffer(100);
1061
            fsb.append("Expected ");
1062
            fsb.append(expectedErrorQ.LocalName);
1063
            fsb.append("; got ");
1064
            foreach (QName e in errorsReported) {
1065
                fsb.append(e.LocalName);
1066
                fsb.append("|");
1067
            }
1068
            fsb.setLength(fsb.length() - 1);
1069
            wrongError = fsb.ToString();
1070
        }
1071
        return ok;
1072
    }
1073

    
1074

    
1075

    
1076
    }
1077
}
(11-11/19)