Project

Profile

Help

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

he / tags / 9.6.0.7 / hen / csource / samples / TestOutcome.cs @ aa733b18

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
135

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

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

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

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

    
167
		public Dictionary<Uri, SingleResultDoc> GetSecondaryResultDocuments() {
168
			return xslResultDocuments;
169
	}
170
    
171
    public SingleResultDoc GetSecondaryResult(Uri uri) {
172
        return xslResultDocuments[uri];
173
    }
174

    
175
	public void SetErrorsReported(IList errors) {
176
        foreach(StaticError err in errors){
177
            if (err.ErrorCode != null)
178
            {
179
                errorsReported.Add(err.ErrorCode);
180
            }
181
        }
182
    }
183

    
184
    public bool HasReportedError(QName errorCode) {
185
        return errorsReported != null && errorsReported.Contains(errorCode);
186
    }
187

    
188
    public string Tostring() {
189
        return (IsException() ? "EXCEPTION " + exception.Message : GetPrincipalResult().ToString());
190
    }
191

    
192
    public void SetPrincipalSerializedResult(string result) {
193
        principalResult.serialization = result;
194
    }
195

    
196
    public string getPrincipalSerializedResult() {
197
        return principalResult.serialization;
198
    }
199

    
200
    public void SetComment(string comment) {
201
        this.comment = comment;
202
    }
203

    
204
    public string GetComment() {
205
        return comment;
206
    }
207

    
208
    public void AddXslMessage(XdmNode message) {
209
        xslMessages.Add(message);
210
    }
211

    
212
    public class MessageListener : IMessageListener
213
    {
214
        TestOutcome outcome1;
215

    
216
        public MessageListener(TestRunner.TestOutcome out1)
217
            : base()
218
        {
219
            outcome1 = out1;
220

    
221
        }
222

    
223
        public void Message(XdmNode content, bool terminate, IXmlLocation location)
224
        {
225
            outcome1.AddXslMessage(content);
226
        }
227
    }
228

    
229

    
230

    
231
    /**
232
     * This method serializes the actual result to produce a serialized result. This is not what is actually
233
     * needed by the serialization tests, which require that the serialization be performed using the parameters
234
     * contained within the query itself.
235
     *
236
     * @param p the processor
237
     * @param uri the URI of the result to serialize; null for the principal result
238
     * @return the result of serialization
239
     */
240

    
241
    public string Serialize(Processor p, Uri uri) {
242
        XdmValue value;
243
        if (uri == null) {
244
            if (principalResult.serialization != null) {
245
                return principalResult.serialization;
246
            } else {
247
                value = principalResult.value;
248
            }
249
        } else {
250
            SingleResultDoc doc = xslResultDocuments[uri];
251
            if (doc == null) {
252
                return "[[[NULL VALUE]]]";
253
            } else if (doc.serialization != null) {
254
                return doc.serialization;
255
            } else {
256
                value = doc.value;
257
            }
258
        }
259
        if (value == null) {
260
            return "[[[NULL VALUE]]]";
261
        }
262
        if (IsException()) {
263
            return "EXCEPTION " + exception.Message;
264
        } else {
265
            StringWriter sw = new StringWriter();
266
            Serializer s = new Serializer();//p.newSerializer(sw);
267
            s.SetOutputProperty(Serializer.METHOD, "xml");
268
            s.SetOutputProperty(Serializer.INDENT, "no");
269
            s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
270
            try {
271
                //s.SerializeXdmValue(value); //TODO
272
            } catch (Exception err) {
273
                return ("SERIALIZATION FAILED: " + err.Message);
274
            }
275
            string str = sw.ToString().Trim();
276
            if (uri == null) {
277
                principalResult.serialization = str;
278
            } else {
279
                xslResultDocuments[uri].serialization = str;
280
            }
281
            return str;
282
        }
283
    }
284

    
285
    /**
286
     * This method serializes the actual result to produce a serialized result. This is not what is actually
287
     * needed by the serialization tests, which require that the serialization be performed using the parameters
288
     * contained within the query itself.
289
     *
290
     * @param p the processor
291
     * @param doc the result to serialize
292
     * @return the result of serialization
293
     */
294

    
295
    public string Serialize(Processor p, SingleResultDoc doc) {
296
        XdmValue value;
297
        if (doc.serialization != null) {
298
            return doc.serialization;
299
        } else {
300
            value = doc.value;
301
        }
302
        if (value == null) {
303
            return "[[[NULL VALUE]]]";
304
        }
305
        if (IsException()) {
306
            return "EXCEPTION " + exception.Message;
307
        } else {
308
            StringWriter sw = new StringWriter();
309

    
310
            Serializer s = new Serializer();// p.NewSerializer(sw); // TODO
311
            s.SetOutputWriter(sw);
312
            s.SetOutputProperty(Serializer.METHOD, "xml");
313
            s.SetOutputProperty(Serializer.INDENT, "no");
314
            s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
315
            try {
316
                p.WriteXdmValue(value, s);
317
                //s.SerializeXdmValue(value);
318
            } catch (Exception err) {
319
                return ("SERIALIZATION FAILED: " + err.Message);
320
            }
321
            string str = sw.ToString().Trim();
322
            doc.serialization = str;
323
            return str;
324
        }
325
    }
326

    
327
    public string Serialize(Processor p, XdmValue value) {
328
        StringWriter sw = new StringWriter();
329
        Serializer s = new Serializer();//p.NewSerializer(sw);
330
        s.SetOutputProperty(Serializer.METHOD, "xml");
331
        s.SetOutputProperty(Serializer.INDENT, "no");
332
        s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
333
        try {
334
            //s.serializeXdmValue(value);
335
            p.WriteXdmValue(value, s);
336
        } catch (Exception err) {
337
            return ("SERIALIZATION FAILED: " + err.Message);
338
        }
339
        return sw.ToString().Trim();
340
    }
341

    
342
    public bool TestAssertion(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug)
343
            {
344
        try {
345
            string tag = assertion.NodeName.LocalName;
346
            bool success = TestAssertion2(assertion, result, assertXpc, catalogXpc, debug);
347
            if (debug && !("all-of".Equals(tag)) && !("any-of".Equals(tag))) {
348
                driver.println("Assertion " + tag + " (" + assertion.StringValue + ") " + (success ? " succeeded" : " failed"));
349
                if (tag.Equals("error")) {
350
                    if (IsException()) {
351
                        bool b = compareExpectedError(assertion);
352
                        if (b) {
353
                            driver.println("Returned error as expected");
354
                        } else {
355
                            driver.println(wrongError);
356
                        }
357
//                        QName code = getException().getErrorCode();
358
//                        if (code == null) {
359
//                            actual = "error with no code";
360
//                        } else {
361
//                            actual = code.getLocalName();
362
//                        }
363

    
364
                    } else {
365
                        driver.println("Expected exception " + assertion.GetAttributeValue(new QName("code")) + "; got success");
366
                    }
367
//                    driver.println("Expected exception " + assertion.getAttributeValue(new QName("code")) +
368
//                            ", got " + actual);
369
                }
370
            }
371
            if (!success && wrongError != null) {
372
                // treat getting the wrong error as a pass
373
                success = true;
374
            }
375
            return success;
376
        } catch (Exception e) {
377
            System.Console.WriteLine(e.StackTrace);  //To change body of catch statement use File | Settings | File Templates.
378
            return false;
379
        }
380
    }
381

    
382
    private bool TestAssertion2(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug)  {
383
        string tag = assertion.NodeName.LocalName;
384

    
385
        if (tag.Equals("assert-eq")) {
386
            return assertEq(assertion, result, assertXpc);
387

    
388
        } else if (tag.Equals("assert-deep-eq")) {
389
            return assertDeepEq(assertion, result, assertXpc);
390

    
391
        } else if (tag.Equals("assert-permutation")) {
392
            return assertPermutation(assertion, result, assertXpc);
393

    
394
        } else if (tag.Equals("assert-xml")) {
395
            return assertXml(assertion, result, assertXpc, catalogXpc, debug);
396

    
397
        } else if (tag.Equals("serialization-matches")) {
398
            return AssertSerializationMatches(assertion, result, catalogXpc);
399

    
400
        } else if (tag.Equals("assert-serialization-error")) {
401
            return AssertSerializationError(assertion, result, assertXpc);
402

    
403
        } else if (tag.Equals("assert-empty")) {
404
            return assertEmpty(result.value);
405

    
406
        } else if (tag.Equals("assert-count")) {
407
            return assertCount(assertion, result);
408

    
409
        } else if (tag.Equals("assert")) {
410
            return AssertXPath(assertion, result, assertXpc, debug);
411

    
412
        } else if (tag.Equals("assert-string-value")) {
413
            return AssertstringValue(assertion, result, debug);
414

    
415
        } else if (tag.Equals("assert-serialization")) {
416
            return AssertSerialization(assertion, result, catalogXpc, debug);
417

    
418
        } else if (tag.Equals("assert-type")) {
419
            return AssertType(assertion, result, assertXpc);
420

    
421
        } else if (tag.Equals("assert-true")) {
422
            return AssertTrue(result);
423

    
424
        } else if (tag.Equals("assert-false")) {
425
            return AssertFalse(result);
426

    
427
			} else if(tag.Equals("assert-warning")) {
428
				return AssertWarning ();
429

    
430
			} else if (tag.Equals("assert-message")) {
431
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
432
            foreach (XdmNode message in xslMessages) {
433
                if (TestAssertion2(subAssertion, new SingleResultDoc(message, ""), assertXpc, catalogXpc, debug)) {
434
                    return true;
435
                }
436
            }
437
            return false;
438

    
439
        } else if (tag.Equals("assert-result-document")) {
440
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
441
            XmlUrlResolver res = new XmlUrlResolver();
442
            Uri uri =  new Uri(driver.getResultsDir() + "/results/output.xml");
443
            uri = res.ResolveUri(uri, assertion.GetAttributeValue(new QName("uri")));
444
            SingleResultDoc doc = GetSecondaryResult(uri);
445
            if (doc == null) {
446
                System.Console.WriteLine("**** No output document found for " + uri);
447
                return false;
448
            }
449
            bool ok = TestAssertion2(subAssertion, doc, assertXpc, catalogXpc, debug);
450
            if (!ok) {
451
                System.Console.WriteLine("**** Assertion failed for result-document " + uri);
452
            }
453
            return ok;
454

    
455
        } else if (tag.Equals("error")) {
456
            bool b= false;
457
            try { 
458
                b = IsException() && compareExpectedError(assertion);
459
            } catch(Exception) {
460
                if (GetException() is StaticError) {
461
                    string expectedError = assertion.GetAttributeValue(new QName("code"));
462
                    QName expectedErrorQ;
463
                    if (expectedError.Equals("*"))
464
                    {
465
                        expectedErrorQ = null;
466
                    }
467
                    else if (expectedError.StartsWith("Q{"))
468
                    {
469
                        expectedErrorQ = QName.FromEQName(expectedError);
470
                    }
471
                    else
472
                    {
473
                        expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
474
                    }
475

    
476
                    JFastStringBuffer fsb = new JFastStringBuffer(100);
477
                    fsb.append("Expected ");
478
                    fsb.append(expectedErrorQ.LocalName);
479
                    fsb.append("; got ");
480
                    fsb.append("err:XXX");
481
                    fsb.setLength(fsb.length() - 1);
482
                    wrongError = fsb.ToString();
483
                    return true;
484
                }
485
                if (GetException() is DynamicError)
486
                {
487
                    string expectedError = assertion.GetAttributeValue(new QName("code"));
488
                    QName expectedErrorQ;
489
                    if (expectedError.Equals("*"))
490
                    {
491
                        expectedErrorQ = null;
492
                    }
493
                    else if (expectedError.StartsWith("Q{"))
494
                    {
495
                        expectedErrorQ = QName.FromEQName(expectedError);
496
                    }
497
                    else
498
                    {
499
                        expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
500
                    }
501

    
502
                    JFastStringBuffer fsb = new JFastStringBuffer(100);
503
                    fsb.append("Expected ");
504
                    fsb.append(expectedErrorQ.LocalName);
505
                    fsb.append("; got ");
506
                    fsb.append("err:XXX");
507
                    fsb.setLength(fsb.length() - 1);
508
                    wrongError = fsb.ToString();
509
                    return true;
510
                }
511
            }
512
            return b;
513

    
514
        } else if (tag.Equals("all-of")) {
515
            foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) {
516
                if (!TestAssertion((XdmNode) child, result, assertXpc, catalogXpc, debug)) {
517
                    return false;
518
                }
519
            }
520
            return true;
521

    
522
        } else if (tag.Equals("any-of")) {
523
            bool partialSuccess = false;
524
            foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) {
525
                if (TestAssertion((XdmNode) child, result, assertXpc, catalogXpc, debug)) {
526
                    if (wrongError != null) {
527
                        partialSuccess = true;
528
                        continue;
529
                    }
530
                    return true;
531
                }
532
            }
533
            return partialSuccess;
534

    
535
        } else if (tag.Equals("not")) {
536
            XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
537
            return !TestAssertion(subAssertion, result, assertXpc, catalogXpc, debug);
538
        }
539
        throw new Exception("Unknown assertion element " + tag);
540
    }
541

    
542
    private bool AssertFalse(SingleResultDoc result) {
543
        if (IsException()) {
544
            return false;
545
        } else {
546
            return result.value.Count == 1 &&
547
                    ((XdmAtomicValue)result.value.Simplify).IsAtomic() &&
548
                    ((XdmAtomicValue)result.value.Simplify).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) &&
549
                    !((XdmAtomicValue)result.value.Simplify).GetBooleanValue();
550
        }
551
    }
552

    
553
    private bool AssertTrue(SingleResultDoc result) {
554
        if (IsException()) {
555
            return false;
556
        } else {
557
            return result.value.Count == 1 &&
558
                    ((XdmAtomicValue) result.value.Simplify).IsAtomic() &&
559
                    ((XdmAtomicValue)result.value.Simplify).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) &&
560
                    ((XdmAtomicValue)result.value.Simplify).GetBooleanValue();
561
        }
562
    }
563

    
564
    private bool AssertType(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
565
        if (IsException()) {
566
            return false;
567
        } else {
568
            XPathSelector s = assertXpc.Compile("$result instance of " + assertion.StringValue).Load();
569
            s.SetVariable(new QName("result"), result.value);
570
            return ((XdmAtomicValue) s.EvaluateSingle()).GetBooleanValue();
571
        }
572
    }
573

    
574
    private bool AssertstringValue(XdmNode assertion, SingleResultDoc result,bool debug) {
575
        if (IsException()) {
576
            return false;
577
        } else {
578
            string resultstring;
579
            string assertionstring = assertion.StringValue;
580
            if (result.value is XdmItem) {
581
                resultstring = ((XdmItem) result.value).Simplify.ToString();
582
            } else {
583
                bool first = true;
584
                net.sf.saxon.tree.util.FastStringBuffer fsb = new net.sf.saxon.tree.util.FastStringBuffer(256);
585
                foreach (XdmItem item in result.value) {
586
                    if (first) {
587
                        first = false;
588
                    } else {
589
                        fsb.append(' ');
590
                    }
591
                    fsb.append(item.Simplify.ToString());
592
                }
593
                resultstring = fsb.ToString();
594
            }
595
            string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
596
            if (normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1"))) {
597
                assertionstring = JWhitespace.collapseWhitespace(assertionstring).ToString();
598
                resultstring = JWhitespace.collapseWhitespace(resultstring).ToString();
599
            }
600
            if (resultstring.Equals(assertionstring)) {
601
                return true;
602
            } else {
603
                if (debug) {
604
                    if (resultstring.Length != assertionstring.Length) {
605
                        driver.println("Result length " + resultstring.Length + "; expected length " + assertionstring.Length);
606
                    }
607
                    int len = Math.Min(resultstring.Length, assertionstring.Length);
608
                    for (int i = 0; i < len; i++) {
609
                        if (resultstring[i] != assertionstring[i]) {
610
                            driver.println("Results differ at index " + i +
611
                                    "(\"" + resultstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" +
612
                                    assertionstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\")");
613
                            break;
614
                        }
615
                    }
616
                }
617
                return false;
618
            }
619
        }
620
    }
621

    
622
    private bool AssertSerialization(XdmNode assertion, SingleResultDoc result, XPathCompiler xpath, bool debug) {
623
        if (IsException()) {
624
            return false;
625
        } else {
626
            String method = assertion.GetAttributeValue(new QName("method"));
627
            if (method == null) {
628
                method = "xml";
629
            }
630
            String resultString = result.serialization;
631
            String comparand = xpath.Evaluate(
632
                    "if (@file) then " +
633
                            "if (@encoding) " +
634
                            "then unparsed-text(resolve-uri(@file, base-uri(.)), @encoding) " +
635
                            "else unparsed-text(resolve-uri(@file, base-uri(.))) " +
636
                            "else string(.)", assertion).ToString();
637
            comparand = comparand.Replace("\r\n", "\n");
638
            if (comparand.EndsWith("\n")) {
639
                comparand = comparand.Substring(0, comparand.Length-1);
640
            }
641

    
642
            if (resultString == null) {
643
                if (result.value is XdmItem) {
644
                    resultString = ((XdmItem) result.value).Simplify.ToString();
645
                } else {
646
                    if (debug) {
647
                        driver.println("Assert serialization fails: result is a sequence");
648
                    }
649
                    return false;
650
                }
651
            }
652
            bool isHtml = method.Equals("html") || method.Equals("xhtml");
653
            bool normalize = isHtml;
654
            if (!normalize) {
655
                String normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
656
                normalize = normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1"));
657
            }
658
            if (normalize) {
659
                comparand = JWhitespace.collapseWhitespace(comparand).toString();
660
                resultString = JWhitespace.collapseWhitespace(resultString).toString();
661
            } else if (resultString.EndsWith("\n")) {
662
                resultString = resultString.Substring(0, resultString.Length-1);
663
            }
664
            if (isHtml) {
665
                // should really do this only for block-level elements
666
                comparand = comparand.Replace(" <", "<");
667
                comparand = comparand.Replace("> ", ">");
668
                resultString = resultString.Replace(" <", "<");
669
                resultString = resultString.Replace("> ", ">");
670
            }
671
            if (resultString.Equals(comparand)) {
672
                return true;
673
            } else {
674
                if (debug) {
675
                    if (resultString.Length != comparand.Length) {
676
                        driver.println("Result length " + resultString.Length + "; expected length " + comparand.Length);
677
                    }
678
                    int len = Math.Min(resultString.Length, comparand.Length);
679
                    for (int i = 0; i < len; i++) {
680
                        if (resultString[1] != comparand[i]) {
681
                            driver.println("Results differ at index " + i +
682
                                    "(\"" + resultString.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" +
683
                                    comparand.Substring(i, (i + 10 > len ? len : i + 10)) + "\")");
684
                            break;
685
                        }
686
                    }
687
                }
688
                driver.println("Serialized results differ");
689
                return false;
690
            }
691
        }
692
    }
693
    private bool AssertXPath(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, bool debug) {
694
        if (IsException()) {
695
            return false;
696
        } else {
697
            IEnumerator iter = assertion.EnumerateAxis(XdmAxis.Namespace);
698
            while (iter.MoveNext()) {
699
                XdmNode namespace1 = (XdmNode)iter.Current;
700
                if (namespace1.NodeName != null) {
701
                    assertXpc.DeclareNamespace(namespace1.NodeName.LocalName, namespace1.StringValue);
702
                }
703
            }
704

    
705
            XPathExecutable exp = assertXpc.Compile(assertion.StringValue);
706
            XPathSelector s = exp.Load();
707
            QName resultVar = new QName("result");
708
            
709
             if (exp.GetRequiredCardinalityForVariable(resultVar) == '0') {
710
                if (result.value is XdmItem) { // this path used in XSLT tests
711
                    s.ContextItem = ((XdmItem)result.value);
712
                }
713
            } else {
714
                s.SetVariable(resultVar, result.value);
715
            }
716
            
717
            bool b = s.EffectiveBooleanValue();
718
            if (!b && debug) {
719
                driver.println("XPath assertion " + assertion.StringValue + " failed");
720
                try {
721
                    string ass = assertion.StringValue;
722
                    int eq = ass.IndexOf("=");
723
                    if (eq > 0) {
724
                        ass = ass.Substring(0, eq);
725
                        exp = assertXpc.Compile(ass);
726
                        s = exp.Load();
727
                        if (exp.GetRequiredCardinalityForVariable(resultVar) == null) {
728
                            if (result.value is XdmItem) { // this path used in XSLT tests
729
                                s.ContextItem = ((XdmItem)result.value);
730
                            }
731
                        } else {
732
                            s.SetVariable(resultVar, result.value);
733
                        }
734
                        XdmValue val = s.Evaluate();
735
                        driver.println("Actual result of " + ass + ": " + val.ToString());
736
                    }
737
                } catch (Exception err) {}
738
                driver.println("Actual results: " + result.value);
739
            }
740
            return b;
741
        }
742
    }
743

    
744
    private bool assertCount(XdmNode assertion, SingleResultDoc result) {
745
        return !IsException() && result.value.Count == int.Parse(assertion.StringValue);
746
    }
747

    
748
    private bool assertEmpty(XdmValue result) {
749
        return !IsException() && result.Count == 0;
750
    }
751

    
752
    private bool AssertSerializationError(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
753
        if (IsException()) {
754
            return compareExpectedError(assertion);
755
        } else {
756
            string expectedError = assertion.GetAttributeValue(new QName("code"));
757
            StringWriter sw = new StringWriter();
758
            Serializer serializer = assertXpc.Processor.NewSerializer();
759
            serializer.SetOutputProperty(Serializer.METHOD, "xml");
760
            serializer.SetOutputProperty(Serializer.INDENT, "no");
761
            serializer.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
762
            try {
763
                assertXpc.Processor.WriteXdmValue(result.value, serializer);
764
                //serializer.serializeXdmValue(result.value);
765
                return false;
766
            } catch (DynamicError err) {
767
                bool b = expectedError.Equals(err.ErrorCode.LocalName);
768
                if (!b) {
769
                    driver.println("Expected " + expectedError + ", got " + err.ErrorCode.LocalName);
770
                }
771
                return true;
772
            }
773
        }
774
    }
775

    
776
    private bool AssertSerializationMatches(XdmNode assertion, SingleResultDoc result,XPathCompiler catalogXpc) {
777
        if (IsException()) {
778
            return false;
779
        } else {
780
            //string testSet = catalogXpc.Evaluate("string(/*/@name)", assertion).ToString();
781
            string flagsAtt = assertion.GetAttributeValue(new QName("flags"));
782
            if (flagsAtt == null) {
783
                flagsAtt = "";
784
            }
785
            string regex = assertion.StringValue;
786
            //IList warnings = new ArrayList();
787
            try {
788
                JRegularExpression re = JConfiguration.getPlatform().compileRegularExpression(regex, flagsAtt, "XP30", new java.util.ArrayList());
789
                if (re.containsMatch(getPrincipalSerializedResult())) {
790
                    return true;
791
                } else {
792
                    driver.println("Serialized result:");
793
                    driver.println(getPrincipalSerializedResult());
794
                    return false;
795
                }
796
                
797
                
798
            } catch (DynamicError e) {
799
                throw e;
800
            }
801
        }
802
    }
803

    
804
    private bool assertXml(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) {
805
        if (IsException()) {
806
            return false;
807
        } else {
808
            string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space"));
809
            bool normalize = normalizeAtt != null && ("true".Equals(normalizeAtt.Trim()) || "1".Equals(normalizeAtt.Trim()));
810
            string ignoreAtt = assertion.GetAttributeValue(new QName("ignore-prefixes"));
811
            bool ignorePrefixes = ignoreAtt != null && ("true".Equals(ignoreAtt.Trim()) || "1".Equals(ignoreAtt.Trim()));
812
            string xmlVersion = assertion.GetAttributeValue(new QName("xml-version"));
813
            bool xml11 = "1.1".Equals(xmlVersion);
814

    
815
            string comparand = catalogXpc.Evaluate("if (@file) then unparsed-text(resolve-uri(@file, base-uri(.))) else string(.)", assertion).ToString();
816
            if (comparand.StartsWith("<?xml")) {
817
                int index = comparand.IndexOf("?>");
818
                comparand = comparand.Substring(index+2);
819
            }
820
            comparand = comparand.Trim();
821
            comparand = comparand.Replace("\r\n", "\n");
822
            if (normalize) {
823
                comparand = JWhitespace.collapseWhitespace(comparand).ToString();
824
            }
825

    
826
            if (comparand.Equals(Serialize(assertXpc.Processor, result))) {
827
                return true;
828
            }
829

    
830
            DocumentBuilder builder = assertXpc.Processor.NewDocumentBuilder();
831
            if (xml11) {
832
                assertXpc.Processor.SetProperty(JFeatureKeys.XML_VERSION, "1.1");
833
            }
834
            StringReader reader = new StringReader((xml11 ? "<?xml version='1.1'?>" : "") + "<z>" + comparand + "</z>");
835
            builder.BaseUri = assertion.BaseUri;
836
            XdmNode expected = builder.Build(reader);
837

    
838
            int flag = 0;
839

    
840
            flag |= JDeepEqual.INCLUDE_COMMENTS;
841
            flag |= JDeepEqual.INCLUDE_PROCESSING_INSTRUCTIONS;
842
            flag |= JDeepEqual.EXCLUDE_VARIETY;
843
            if (!ignorePrefixes) {
844
                flag |= JDeepEqual.INCLUDE_NAMESPACES;
845
                flag |= JDeepEqual.INCLUDE_PREFIXES;
846
            }
847
            flag |= JDeepEqual.COMPARE_STRING_VALUES;
848
            if (debug) {
849
                flag |= JDeepEqual.WARNING_IF_FALSE;
850
            }
851
            try {
852
                JSequenceIterator iter0;
853
                if (result == null) {
854
                    System.Console.WriteLine("Result value is null");
855
                    return false;
856
                }
857
                XdmValue value = result.value;
858
                
859
                if (value == null) {
860
                    System.Console.WriteLine("Result value is null (perhaps serialized?)");
861
                    return false;
862
                }
863
                if (value.Count == 1 && value.Simplify is XdmNode && ((XdmNode) value.Simplify).NodeKind == System.Xml.XmlNodeType.Document) {
864
                    iter0 = ((XdmNode) value.Simplify).Implementation.iterateAxis(JAxisInfo.CHILD);
865
                } else {
866
                    iter0 = value.Unwrap().iterate();
867
                }
868
                JSequenceIterator iter1 = expected.Implementation.iterateAxis(JAxisInfo.CHILD).next().iterateAxis(JAxisInfo.CHILD);
869
                bool success = JDeepEqual.deepEquals(
870
                        iter0, iter1,
871
                        new JGenericAtomicComparer(JCodepointCollator.getInstance(), null),
872
                        assertXpc.Processor.Implementation.getConversionContext(), flag);
873
                // if necessary try again ignoring whitespace nodes
874
                if (!success) {
875
                    iter0 = iter0.getAnother();
876
                    iter1 = iter1.getAnother();
877
                    // deep-equals with the EXCLUDE_WHITESPACE flag doesn't ignore top-level whitespace, so we
878
                    // need to filter that out ourselves
879
                    iter0 = new JItemMappingIterator(iter0, new RemoveWhitespace());
880
                    iter1 = new JItemMappingIterator(iter1, new RemoveWhitespace());
881
                    success = JDeepEqual.deepEquals(
882
                        iter0, iter1,
883
                        new JGenericAtomicComparer(JCodepointCollator.getInstance(), null),
884
                        assertXpc.Processor.Implementation.getConversionContext(),
885
                            flag | JDeepEqual.EXCLUDE_WHITESPACE_TEXT_NODES);
886
                    if (success) {
887
                        comment = "OK after ignoring whitespace text";
888
                    }
889
                }
890
                if (!success) {
891
                   System.Console.WriteLine("assert-xml comparison failed");
892
                   if (debug) {
893
                        System.Console.WriteLine("assert-xml comparison failed");
894
                        System.Console.WriteLine("Reference results:");
895
                        System.Console.WriteLine(expected.ToString());
896
                        System.Console.WriteLine("Actual results:");
897
                        //System.Console.WriteLine(result.serialization);
898
                        System.Console.WriteLine(value.ToString());
899
                    }
900
                }
901
                return success;
902
            } catch (DynamicError e) {
903
                Console.WriteLine(e.StackTrace);
904
                return false;
905
            }
906
        }
907
    }
908

    
909
    private class RemoveWhitespace : JItemMappingFunction 
910
    {
911
        public JItem mapItem(JItem itemi){
912
            JNodeInfo item = (JNodeInfo)itemi;
913
            bool isWhite = item.getNodeKind() ==  net.sf.saxon.type.Type.TEXT && JWhitespace.isWhite(item.getStringValueCS());
914
            return (isWhite ? null : item);
915
        }
916
    }
917

    
918
	private bool AssertWarning() {
919
			/*byte[] data = new byte[]{31, 32, 33};
920
			String.valueOf(data);*/
921
			return true;//IsWarningsReported();
922
	}
923

    
924
    private bool assertPermutation(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc) {
925
        // TODO: extend this to handle nodes (if required)
926
        if (IsException()) {
927
            return false;
928
        } else {
929
				return true;
930
            try {
931
                int expectedItems = 0;
932
                HashSet<string> expected = new HashSet<string>();
933
                XPathSelector s = assertXpc.Compile("(" + assertion.StringValue + ")").Load();
934
                s.SetVariable(new QName("result"), result.value); // not used, but we declared it
935
                JCodepointCollator collator = JCodepointCollator.getInstance();
936
                //JXPathContext context =  new JXPathContextMajor(stringValue.EMPTY_string, assertXpc.getUnderlyingStaticContext().getConfiguration());
937
                foreach (XdmItem item in s) {
938
                    expectedItems++;
939
                    XdmValue value = (XdmValue) item.Simplify;
940
                   // value.Simplify.
941
                  /*  Object comparable = value.isNaN() ?
942
                            AtomicSortComparer.COLLATION_KEY_NaN :
943
                            value.getXPathComparable(false, collator, context);
944
                    expected.Add(comparable);*/
945
                    
946
                }
947
                int actualItems = 0;
948
                foreach (XdmItem item in GetPrincipalResult()) {
949
                    actualItems++;
950
                    XdmValue value = (XdmValue)item.Simplify;
951
                    /*Object comparable = value.isNaN() ?
952
                            AtomicSortComparer.COLLATION_KEY_NaN :
953
                            value.getXPathComparable(false, collator, context); */
954
                 //   if (!expected.Contains(comparable)) {
955
                        return false;
956
                   // }
957
                }
958
                return actualItems == expectedItems;
959
            } catch (DynamicError) {
960
                return false;
961
            } 
962
        } 
963
    }
964

    
965
    private bool assertDeepEq(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) {
966
        if (IsException()) {
967
            return false;
968
        } else {
969
            XPathSelector s = assertXpc.Compile("deep-equal($result , (" + assertion.StringValue + "))").Load();
970
            s.SetVariable(new QName("result"), result.value);
971
            return ((XdmAtomicValue) s.Evaluate()).GetBooleanValue();
972
        }
973
    }
974

    
975
    private bool assertEq(XdmNode assertion, SingleResultDoc result,XPathCompiler assertXpc) {
976
        if (IsException()) {
977
            return false;
978
        } else {
979
            XPathSelector s = assertXpc.Compile("$result eq " + assertion.StringValue).Load();
980
            s.SetVariable(new QName("result"), result.value);
981
            XdmAtomicValue item = (XdmAtomicValue) s.EvaluateSingle();
982
            return item != null && item.GetBooleanValue();
983
        }
984
    }
985

    
986
    public bool compareExpectedError(XdmNode assertion) {
987
        string expectedError = assertion.GetAttributeValue(new QName("code"));
988
        QName expectedErrorQ;
989
        if (expectedError.Equals("*")) {
990
            expectedErrorQ = null;
991
        } else if (expectedError.StartsWith("Q{")) {
992
            expectedErrorQ = QName.FromEQName(expectedError);
993
        } else {
994
            expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
995
        }
996
        //noinspection ThrowableResultOfMethodCallIgnored
997
        bool ok = (expectedError.Equals("*") ||
998
				(GetErrorCode() != null &&
999
					GetErrorCode().LocalName.Equals(expectedErrorQ.LocalName)) ||
1000
                (HasReportedError(new QName(expectedError))));
1001
        if (ok) {
1002
            wrongError = null;
1003
        } else if (expectedErrorQ != null && errorsReported!= null && errorsReported.Count!=0) {
1004
             JFastStringBuffer fsb = new JFastStringBuffer(100);
1005
            fsb.append("Expected ");
1006
            fsb.append(expectedErrorQ.LocalName);
1007
            fsb.append("; got ");
1008
            foreach (QName e in errorsReported) {
1009
                fsb.append(e.LocalName);
1010
                fsb.append("|");
1011
            }
1012
            fsb.setLength(fsb.length() - 1);
1013
            wrongError = fsb.ToString();
1014
        }
1015
        return ok;
1016
    }
1017

    
1018

    
1019

    
1020
    }
1021
}
(15-15/24)