Project

Profile

Help

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

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

1
using System;
2
using System.Collections;
3
using System.Collections.Generic;
4
using System.Text;
5
using System.Xml;
6
using System.IO;
7
using System.Text.RegularExpressions;
8
using System.Globalization;
9
using Saxon.Api;
10
using TestRunner;
11

    
12

    
13
//using net.sf.saxon.Version;
14
using JFeatureKeys = net.sf.saxon.lib.FeatureKeys;
15
using JConfiguration = net.sf.saxon.Configuration;
16
using JVersion = net.sf.saxon.Version;
17

    
18
namespace TestRunner
19
{
20

    
21

    
22

    
23
    /**
24
     * Test Driver for the QT3 test suite
25
     */
26
    public class FOTestSuiteDriver : TestDriver
27
    {
28

    
29

    
30
        public static string RNS = "http://www.w3.org/2012/08/qt-fots-results";
31
        public static string CNS = "http://www.w3.org/2010/09/qt-fots-catalog";
32

    
33

    
34
        public object getDependencyDictionary()
35
        {
36
            return dependencyDictionary;
37
        }
38

    
39
        private Dictionary<string, Dependency> dependencyDictionary = new Dictionary<string, Dependency>();
40

    
41

    
42
        private Spec spec;
43
        //private FotsResultsDocument resultsDoc;
44

    
45
        public override string catalogNamespace()
46
        {
47
            return CNS;
48
        }
49
			
50

    
51
        public override void processSpec(string specStr)
52
        {
53

    
54
            if (specStr.Equals("XP20"))
55
            {
56
                spec = Spec.XP20;
57
            }
58
            else if (specStr.Equals("XP30"))
59
            {
60
                spec = Spec.XP30;
61
            }
62
            else if (specStr.Equals("XQ10"))
63
            {
64
                spec = Spec.XQ10;
65
            }
66
            else if (specStr.Equals("XQ30"))
67
            {
68
                spec = Spec.XQ30;
69
            }
70
            else
71
            {
72
                System.Console.WriteLine("The specific language must be one of the following: XP20, XP30, XQ10 or XQ30");
73
            }
74
            resultsDoc = new FotsResultsDocument(this.getResultsDir(), spec);
75
        }
76

    
77
        public static void Main(string[] args)
78
        {
79
            if (args.Length == 0 || args[0].Equals("-?"))
80
            {
81
                System.Console.WriteLine("testsuiteDir catalog [-o:resultsdir] [-s:testSetName]" +
82
                        " [-t:testNamePattern] [-unfolded] [-bytecode:on|off|debug] [-tree] [-lang:XP20|XP30|XQ10|XQ30]");
83
            }
84
            System.Console.WriteLine("Testing Saxon " + (new Processor()).ProductVersion);
85
            new FOTestSuiteDriver().go(args);
86
        }
87

    
88

    
89

    
90
        protected override void createGlobalEnvironments(XdmNode catalog, XPathCompiler xpc)
91
        {
92
            Environment environment = null;
93

    
94
            Environment defaultEnv = null;
95
            try
96
            {
97
                defaultEnv = localEnvironments["default"];
98
            }
99
            catch (Exception) { }
100
            foreach (XdmItem env in xpc.Evaluate("//environment", catalog))
101
            {
102
                environment = Environment.processEnvironment(
103
                        this, xpc, env, globalEnvironments, defaultEnv);
104
            }
105
            buildDependencyDictionary(driverProc, environment);
106
        }
107

    
108
        /**
109
         * Decide whether a dependency is satisfied
110
         *
111
         * @param dependency the dependency element in the catalog
112
         * @param env        an environment in the catalog, which can be modified to satisfy the dependency if necessary.
113
         *                   May be null.
114
         * @return true if the environment satisfies the dependency, else false
115
         */
116
        
117
        public override bool dependencyIsSatisfied(XdmNode dependency, Environment env)
118
        {
119
            string type = dependency.GetAttributeValue(new QName("type"));
120
            string value = dependency.GetAttributeValue(new QName("value"));
121
            bool inverse = "false".Equals(dependency.GetAttributeValue(new QName("satisfied")));
122
            if ("xml-version".Equals(type))
123
            {
124
                if (value.Equals("1.0:4-") && !inverse)
125
                {
126
                    // we don't support XML 1.0 4th edition or earlier
127
                    return false;
128
                }
129
                if (value.Contains("1.1") && !inverse)
130
                {
131
                    if (env != null)
132
                    {
133
                        env.processor.SetProperty(JFeatureKeys.XML_VERSION, "1.1");
134
                    }
135
                    else
136
                    {
137
                        return false;
138
                    }
139
                }
140
                else if (value.Contains("1.0") && !inverse)
141
                {
142
                    if (env != null)
143
                    {
144
                        env.processor.SetProperty(JFeatureKeys.XML_VERSION, "1.0");
145
                    }
146
                    else
147
                    {
148
                        return false;
149
                    }
150
                }
151
                return true;
152
            }
153
            else if ("xsd-version".Equals(type))
154
            {
155
                if ("1.1".Equals(value))
156
                {
157
                    if (env != null)
158
                    {
159
                        env.processor.SetProperty(JFeatureKeys.XSD_VERSION, (inverse ? "1.0" : "1.1"));
160
                    }
161
                    else
162
                    {
163
                        return false;
164
                    }
165
                }
166
                else if ("1.0".Equals(value))
167
                {
168
                    if (env != null)
169
                    {
170
                        env.processor.SetProperty(JFeatureKeys.XSD_VERSION, (inverse ? "1.1" : "1.0"));
171
                    }
172
                    else
173
                    {
174
                        return false;
175
                    }
176
                }
177
                return true;
178
            }
179
            else if ("limits".Equals(type))
180
            {
181
                return "year_lt_0".Equals(value) && !inverse;
182
            }
183
            else if ("spec".Equals(type))
184
            {
185
                return true;
186
            }
187
            else if ("collection-stability".Equals(type))
188
            {
189
                // SAXON has a problem here - we don't support stable collections
190
                return ("false".Equals(value) != inverse);
191
            }
192
            else if ("default-language".Equals(type))
193
            {
194
                return ("en".Equals(value) != inverse);
195
            }
196
            else if ("directory-as-collection-uri".Equals(type))
197
            {
198
                return ("true".Equals(value) != inverse);
199
            }
200
            else if ("language".Equals(type))
201
            {
202
                return (("en".Equals(value) || "de".Equals(value) || "fr".Equals(value)) != inverse);
203
            }
204
            else if ("calendar".Equals(type))
205
            {
206
                return (("AD".Equals(value) || "ISO".Equals(value)) != inverse);
207
            }
208
            else if ("format-integer-sequence".Equals(type))
209
            {
210
                return !inverse;
211
            }
212
            else if ("unicode-normalization-form".Equals(type))
213
            {
214
                return value.Equals("FULLY-NORMALIZED", StringComparison.OrdinalIgnoreCase) ? inverse : !inverse;
215
            }
216
            else if ("feature".Equals(type))
217
            {
218
                if ("namespace-axis".Equals(value))
219
                {
220
                    return !inverse;
221
                }
222
                else if ("higherOrderFunctions".Equals(value))
223
                {
224
                    return !inverse;
225
                }
226
                else if ("schemaImport".Equals(value) || "schemaValidation".Equals(value) || "schemaAware".Equals(value))
227
                {
228
                    //if (!treeModel.isSchemaAware()) {//TODO
229
                    //  return false; // cannot use the selected tree model for schema-aware tests
230
                    //}
231
                    // Need to reset these after use for this query??
232
                    if (env != null)
233
                    {
234
                        if (inverse)
235
                        {
236
                            // force use of a non-schema-aware processor by creating a ProfessionalConfiguration
237
                            /* ProfessionalConfiguration pConfig = new ProfessionalConfiguration();
238
                             pConfig.setNamePool(env.processor.getUnderlyingConfiguration().getNamePool());
239
                             final Processor savedProcessor = env.processor;
240
                             final XPathCompiler savedXPathCompiler = env.xpathCompiler;
241
                             final XQueryCompiler savedXQueryCompiler = env.xqueryCompiler;
242
                             final XsltCompiler savedXsltCompiler = env.xsltCompiler;
243
                             env.processor = new Processor(pConfig);
244
                             env.xpathCompiler = env.processor.newXPathCompiler();
245
                             env.xqueryCompiler = env.processor.newXQueryCompiler();
246
                             env.xsltCompiler = env.processor.newXsltCompiler();
247
                             env.xpathCompiler.setSchemaAware(false);
248
                             env.xqueryCompiler.setSchemaAware(false);
249
                             env.xsltCompiler.setSchemaAware(false);
250
                             env.resetAction = new Environment.ResetAction() {
251
                                 public void reset(Environment env) {
252
                                     env.processor = savedProcessor;
253
                                     env.xpathCompiler = savedXPathCompiler;
254
                                     env.xqueryCompiler = savedXQueryCompiler;
255
                                     env.xsltCompiler = savedXsltCompiler;
256
                                 }
257
                             }; */
258
                        }
259
                        else
260
                        {
261
                            env.xpathCompiler.SchemaAware = true;
262
                            env.xqueryCompiler.SchemaAware = true;
263
							if (env.xsltCompiler != null) {
264
								env.xsltCompiler.SchemaAware = true;
265
							}
266
                        }
267
                    }
268
                    return true;
269
                }
270
                else if ("xpath-1.0-compatibility".Equals(value))
271
                {
272
                    if (env != null)
273
                    {
274
                        env.xpathCompiler.BackwardsCompatible = !inverse;
275
                        return true;
276
                    }
277
                    else
278
                    {
279
                        return false;
280
                    }
281
                }
282
                else if ("staticTyping".Equals(value))
283
                {
284
                    return inverse;
285
                }
286
                else if ("moduleImport".Equals(value))
287
                {
288
                    return !inverse;
289
                }
290
                else if ("schema-location-hint".Equals(value))
291
                {
292
                    return !inverse;
293
                }
294
                else
295
                {
296
                    println("**** feature = " + value + "  ????");
297
                    return false;
298
                }
299
            }
300
            else
301
            {
302
                println("**** dependency not recognized: " + type);
303
                return false;
304
            }
305
        }
306

    
307
        /**
308
         * Run a test case
309
         *
310
         *
311
         * @param testCase the test case element in the catalog
312
         * @param xpc      the XPath compiler to be used for compiling XPath expressions against the catalog
313
         * @
314
         */
315

    
316
        protected override void runTestCase(XdmNode testCase, XPathCompiler xpc)
317
        {
318
            bool run = true;
319
            bool xpDependency = false;
320
            string hostLang;
321
            string langVersion;
322
            Spec specOpt = Spec.NULL;
323
            XPathCompiler xpath = driverProc.NewXPathCompiler();
324
            string testCaseName = testCase.GetAttributeValue(new QName("name"));
325
            string testSetName = testCase.Parent.GetAttributeValue(new QName("name"));
326
            bool needSerializedResult = ((XdmAtomicValue)xpc.EvaluateSingle(
327
                    "exists(./result//assert-serialization-error) or exists(./result//serialization-matches)", testCase)).GetBooleanValue();
328
            bool needResultValue = true;
329
            if (needSerializedResult)
330
            {
331
                needResultValue = ((XdmAtomicValue)xpc.EvaluateSingle(
332
                        "exists(./result//*[not(self::serialization-matches or self::assert-serialization-error or self::any-of or self::all-of)])", testCase)).GetBooleanValue();
333
            }
334

    
335
            XdmNode alternativeResult = null;
336
            XdmNode optimization = null;
337

    
338

    
339
            hostLang = ((SpecAttr)spec.GetAttr()).sname;
340
            langVersion = ((SpecAttr)spec.GetAttr()).version;
341

    
342

    
343
            Environment env = getEnvironment(testCase, xpc);
344
            if (env == null)
345
            {
346
                notrun++;
347
                return;
348
            }
349
            env.xpathCompiler.BackwardsCompatible = false;
350
            env.processor.XmlVersion = (decimal)1.0;
351

    
352

    
353
			//test
354
			bool icuColCheck = net.sf.saxon.Configuration.getPlatform ().hasICUCollator ();
355
			bool icuNumCheck = net.sf.saxon.Configuration.getPlatform ().hasICUNumberer();
356
			Console.WriteLine ("ICUCol: " + (icuColCheck ? "true" : "false"));
357
			Console.WriteLine ("ICUNum: " + (icuNumCheck ? "true" : "false"));
358
			//end of test
359
            foreach (XdmItem dependency in xpc.Evaluate("/*/dependency, ./dependency", testCase))
360
            {
361
                string type = ((XdmNode)dependency).GetAttributeValue(new QName("type"));
362
                if (type == null)
363
                {
364
                    // throw new IllegalStateException("dependency/@type is missing"); //TODO
365
                }
366
                string value = ((XdmNode)dependency).GetAttributeValue(new QName("value"));
367
                if (value == null)
368
                {
369
                    //throw new IllegalStateException("dependency/@value is missing"); //TODO
370
                }
371

    
372
                if (type.Equals("spec"))
373
                {
374
                    bool applicable = false;
375
                    if (!value.Contains(((SpecAttr)spec.GetAttr()).sname))
376
                    {
377
                        applicable = false;
378
                    }
379
                    else if (value.Contains(((SpecAttr)spec.GetAttr()).svname))
380
                    {
381
                        applicable = true;
382
                    }
383
                    else if (((SpecAttr)spec.GetAttr()).svname.Equals("XQ30") && value.Contains("XQ10+"))
384
                    {
385
                        applicable = true;
386
                    }
387
                    else if (((SpecAttr)spec.GetAttr()).svname.Equals("XP30") && value.Contains("XP20+"))
388
                    {
389
                        applicable = true;
390
                    }
391
                    if (!applicable)
392
                    {
393
                        writeTestcaseElement(testCaseName, "n/a", "not" + ((SpecAttr)spec.GetAttr()).svname, spec);
394
                        notrun++;
395
                        return;
396
                    }
397
                }
398
                if (langVersion.Equals("3.0"))
399
                {
400
                    /* EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() {
401
                         public Set<string> getAvailableEnvironmentVariables() {
402
                             Set<string> strings = new HashSet<string>();
403
                             strings.add("QTTEST");
404
                             strings.add("QTTEST2");
405
                             strings.add("QTTESTEMPTY");
406
                             return strings;
407
                         }
408

    
409
                         public string getEnvironmentVariable(string name) {
410
                             if (name.Equals("QTTEST")) {
411
                                 return "42";
412
                             } else if (name.Equals("QTTEST2")) {
413
                                 return "other";
414
                             } else if (name.Equals("QTTESTEMPTY")) {
415
                                 return "";
416
                             } else {
417
                                 return null;
418
                             }
419
                         }
420
                     }; */
421
                    //TODO
422
                    //env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver);
423
                }
424
                if (type.Equals("feature") && value.Equals("xpath-1.0-compatibility"))
425
                {
426
                    hostLang = "XP";
427
                    langVersion = "3.0";
428
                    xpDependency = true;
429
                    specOpt = Spec.XP30;
430
                }
431
                if (type.Equals("feature") && value.Equals("namespace-axis"))
432
                {
433
                    hostLang = "XP";
434
                    langVersion = "3.0";
435
                    xpDependency = true;
436
                    specOpt = Spec.XP30;
437
                }
438
                if (!dependencyIsSatisfied((XdmNode)dependency, env))
439
                {
440
                    println("*** Dependency not satisfied: " + ((XdmNode)dependency).GetAttributeValue(new QName("type")));
441
                    writeTestcaseElement(testCaseName, "n/a", "Dependency not satisfied", spec);
442
                    run = false;
443
                    notrun++;
444
                    return;
445
                }
446
            }
447

    
448
            XdmNode exceptionElement;
449
            
450
            try{
451
                exceptionElement = exceptionsMap[testCaseName];
452

    
453
            } catch(Exception) {
454
                exceptionElement = null;
455
            }
456
            if (exceptionElement != null)
457
            {
458
                XdmItem config = xpath.EvaluateSingle("configuration", exceptionElement);
459

    
460
                string runAtt = exceptionElement.GetAttributeValue(new QName("run"));
461
                string reasonMsg = xpath.EvaluateSingle("reason", exceptionElement).ToString();
462
                string reportAtt = exceptionElement.GetAttributeValue(new QName("report"));
463

    
464
                if (config != null)
465
                {
466
                    XdmItem paramValue = xpath.EvaluateSingle("param[@name='not-unfolded' and @value='yes']/@name", config);
467
                    if (unfolded && paramValue != null)
468
                    {
469
                        writeTestcaseElement(testCaseName, "notRun", reasonMsg, spec);
470
                        notrun++;
471
                        return;
472
                    }
473
                }
474

    
475
                if ("false".Equals(runAtt))
476
                {
477
                    writeTestcaseElement(testCaseName, reportAtt, reasonMsg, spec);
478
                    notrun++;
479
                    return;
480
                }
481

    
482
                alternativeResult = (XdmNode)xpc.EvaluateSingle("result", exceptionElement);
483
                optimization = (XdmNode)xpc.EvaluateSingle("optimization", exceptionElement);
484
            }
485

    
486
            if (run && (specOpt == Spec.NULL || specOpt == spec))
487
            {
488

    
489
                TestOutcome outcome = new TestOutcome(this);
490
                string exp = null;
491
                try
492
                {
493
                    exp = xpc.Evaluate("if (test/@file) then unparsed-text(resolve-uri(test/@file, base-uri(.))) else string(test)", testCase).ToString();
494
                }
495
                catch (Exception err)
496
                {
497
                    println("*** Failed to read query: " + err.Message);
498
                    outcome.SetException((DynamicError)err);
499
                }
500

    
501
                //noinspection ThrowableResultOfMethodCallIgnored
502
                if (outcome.GetException() == null)
503
                {
504
                    if (hostLang.Equals("XP") || hostLang.Equals("XT"))
505
                    {
506
                        XPathCompiler testXpc = env.xpathCompiler;
507
                        testXpc.XPathLanguageVersion = langVersion;
508
                        testXpc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions");
509
                        testXpc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema");
510
                        testXpc.DeclareNamespace("map", "http://www.w3.org/2005/xpath-functions/map");
511
                        //testXpc.DeclareNamespace("math", NamespaceConstant.MATH);
512
                        //testXpc.DeclareNamespace("Dictionary", NamespaceConstant.Dictionary_FUNCTIONS);
513

    
514
                        try
515
                        {
516
                            XPathSelector selector = testXpc.Compile(exp).Load();
517
                            foreach (QName varName in env.params1.Keys)
518
                            {
519
                                selector.SetVariable(varName, env.params1[varName]);
520
                            }
521
                            if (env.contextItem != null)
522
                            {
523
                                selector.ContextItem = env.contextItem;
524
                            }
525
                            selector.InputXmlResolver = new TestUriResolver(env);
526

    
527
                            if (env.unparsedTextResolver != null)
528
                            {
529
                                //selector.getUnderlyingXPathContext().setUnparsedTextURIResolver(env.unparsedTextResolver); //TODO
530
                            }
531
                            XdmValue result = selector.Evaluate();
532
                            outcome.SetPrincipalResult(result);
533
                        }
534
                        catch (Exception err)
535
                        {
536
                            println(err.Message);
537
                            
538
                           outcome.SetException(err);
539
                            
540

    
541
                        }
542
                    }
543
                    else if (hostLang.Equals("XQ"))
544
                    {
545
                        XQueryCompiler testXqc = env.xqueryCompiler;
546
                        testXqc.XQueryLanguageVersion = langVersion;
547
                        testXqc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions");
548
                        testXqc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema");
549
                        //testXqc.DeclareNamespace("math", NamespaceConstant.MATH);
550
                        testXqc.DeclareNamespace("map", "http://www.w3.org/2005/xpath-functions/map");
551
                       // ErrorCollector errorCollector = new ErrorCollector();
552
                        testXqc.ErrorList = new ArrayList();
553
                        string decVars = env.paramDecimalDeclarations.ToString();
554
                        if (decVars.Length != 0)
555
                        {
556
                            int x = (exp.IndexOf("(:%DECL%:)"));
557
                            if (x < 0)
558
                            {
559
                                exp = decVars + exp;
560
                            }
561
                            else
562
                            {
563
                                exp = exp.Substring(0, x) + decVars + exp.Substring(x + 13);
564
                            }
565
                        }
566
                        string vars = env.paramDeclarations.ToString();
567
                        if (vars.Length != 0)
568
                        {
569
                            int x = (exp.IndexOf("(:%VARDECL%:)"));
570
                            if (x < 0)
571
                            {
572
                                exp = vars + exp;
573
                            }
574
                            else
575
                            {
576
                                exp = exp.Substring(0, x) + vars + exp.Substring(x + 13);
577
                            }
578
                        }
579
                         ModuleResolver mr = new ModuleResolver(xpc);
580
                         mr.setTestCase(testCase);
581
                        //  testXqc.QueryResolver = mr;// .setModuleURIResolver(mr); //TODO
582
						testXqc.QueryResolver = mr;
583
                        try
584
                        {
585
                            XQueryExecutable q = testXqc.Compile(exp);
586
                            if (optimization != null)
587
                            {
588
                                // Test whether required optimizations have been performed
589
                                XdmDestination expDest = new XdmDestination();
590
                                JConfiguration config = driverProc.Implementation;
591
                                //ExpressionPresenter presenter = new ExpressionPresenter(config, expDest.getReceiver(config));
592
                                //q.getUnderlyingCompiledQuery().explain(presenter);
593
                                //presenter.close();
594
                                XdmNode explanation = expDest.XdmNode;
595
                                XdmItem optResult = xpc.EvaluateSingle(optimization.GetAttributeValue(new QName("assert")), explanation);
596
                                if (((XdmAtomicValue)optResult).GetBooleanValue())
597
                                {
598
                                    println("Optimization result OK");
599
                                }
600
                                else
601
                                {
602
                                    println("Failed optimization test");
603
                                    Serializer ser = new Serializer();
604
                                    ser.SetOutputStream((Stream)System.Console.OpenStandardError());
605
                                    driverProc.WriteXdmValue(explanation, ser);
606
                                    writeTestcaseElement(testCaseName, "fail", "Failed optimization assertions", spec);
607
                                    failures++;
608
                                    return;
609
                                }
610

    
611
                            }
612
                            XQueryEvaluator selector = q.Load();
613
                            foreach (QName varName in env.params1.Keys)
614
                            {
615
                                selector.SetExternalVariable(varName, env.params1[varName]);
616
                            }
617
                            if (env.contextItem != null)
618
                            {
619
                                selector.ContextItem = env.contextItem;
620
                            }
621
							selector.InputXmlResolver = env;
622
                            //selector.InputXmlResolver =  .SetURIResolver(new TestURIResolver(env)); //TODO
623
                            if (env.unparsedTextResolver != null)
624
                            {
625
                                //selector.Implementation.setURIResolver(env.unparsedTextResolver);// TODO
626
                            }
627
                            if (needSerializedResult)
628
                            {
629
                                StringWriter sw = new StringWriter();
630
                                Serializer serializer = new Serializer(); //env.processor.NewSerializer(sw); //TODO
631
                                serializer.SetOutputWriter(sw);
632
                                selector.Run(serializer);
633
                                outcome.SetPrincipalSerializedResult(sw.ToString());
634
                            }
635
                            if (needResultValue)
636
                            {
637
                                XdmValue result = selector.Evaluate();
638
                                outcome.SetPrincipalResult(result);
639
                            }
640
                        }
641
                        catch (Exception err)
642
                        {
643
							println("in TestSet " + testSetName + err.StackTrace);
644
                            println(err.Message);
645
                            outcome.SetException(err);
646
							outcome.SetErrorsReported((IList)testXqc.ErrorList);
647
                        }
648
                    }
649
                    else
650
                    {
651
                        writeTestcaseElement(testCaseName, "notRun", "No processor found", spec);
652
                        notrun++;
653
                        return;
654
                    }
655
                }
656

    
657
                if (env.resetAction != null)
658
                {
659
                    env.resetAction.reset(env);
660
                }
661
                XdmNode assertion;
662
                if (alternativeResult != null)
663
                {
664
                    assertion = (XdmNode)xpc.EvaluateSingle("*[1]", alternativeResult);
665
                }
666
                else
667
                {
668
                    assertion = (XdmNode)xpc.EvaluateSingle("result/*[1]", testCase);
669
                }
670
                if (assertion == null)
671
                {
672
                    println("*** No assertions found for test case " + testCaseName);
673
                    writeTestcaseElement(testCaseName, "disputed", "No assertions in test case", spec);
674
                    feedback.Feedback(successes, failures++, total);
675
                    return;
676
                }
677
                XPathCompiler assertXpc = env.processor.NewXPathCompiler();
678
                assertXpc.XPathLanguageVersion = "3.0";
679
                assertXpc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions");
680
                assertXpc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema");
681
                assertXpc.DeclareNamespace("math", "http://www.w3.org/2005/xpath-functions/math");
682
                assertXpc.DeclareNamespace("MAP_FUNCTIONS", "http://www.w3.org/2005/xpath-functions/map");
683
                assertXpc.DeclareVariable(new QName("result"));
684

    
685
                bool b = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertXpc, xpc, debug);
686
                if (b)
687
                {
688
                    //println("OK");
689
                    writeTestcaseElement(testCaseName, "pass", null, spec);
690
                    feedback.Feedback(successes++, failures, total);
691

    
692
                }
693
                else
694
                {
695

    
696
                    if (outcome.IsException())
697
                    {
698
                        XdmItem expectedError = xpc.EvaluateSingle("result//error/@code", testCase);
699

    
700
                        if (expectedError == null)
701
                        {
702
                            //                        if (debug) {
703
                            //                            outcome.getException().printStackTrace(System.out);
704
                            //                        }
705
                            writeTestcaseElement(testCaseName, "fail", "Expected success, got " + outcome.GetErrorCode().LocalName, spec);
706
                            println("*** fail, result " + outcome.GetException() +
707
                                    " Expected success.");
708
                            feedback.Feedback(successes, failures++, total);
709
                        }
710
                        else
711
                        {
712
                            writeTestcaseElement(testCaseName, "wrongError",
713
                                    "Expected error:" + expectedError.ToString() + ", got " + outcome.GetErrorCode().LocalName, spec);
714
                            println("*** fail, result " + outcome.GetErrorCode().LocalName +
715
                                    " Expected error:" + expectedError.ToString());
716
                            wrongErrorResults++;
717
                            feedback.Feedback(successes++, failures, total);
718
                        }
719

    
720
                    }
721
                    else
722
                    {
723
                        writeTestcaseElement(testCaseName, "fail", "Wrong results, got " +
724
                                truncate(outcome.Serialize(assertXpc.Processor, outcome.GetPrincipalResultDoc())), spec);
725
                        feedback.Feedback(successes, failures++, total);
726
                        if (debug)
727
                        {
728
                            try
729
                            {
730
                                println("Result:");
731
                                driverProc.WriteXdmValue(outcome.GetPrincipalResult(), driverSerializer);
732
                                println("<=======");
733
                            }
734
                            catch (Exception err)
735
                            {
736
                            }
737
                            //println(outcome.getResult());
738
                        }
739
                        else
740
                        {
741
                            println("*** fail (use -debug to show actual result)");
742
                            //failures++;
743
                        }
744
                    }
745
                }
746
            }
747
        }
748

    
749
        private string truncate(string in1)
750
        {
751
            if (in1.Length > 80)
752
            {
753
                return in1.Substring(0, 80) + "...";
754
            }
755
            else
756
            {
757
                return in1;
758
            }
759
        }
760

    
761

    
762

    
763
        public void writeResultFilePreamble(Processor processor, XdmNode catalog)
764
        {
765
            resultsDoc.writeResultFilePreamble(processor, catalog);
766
        }
767

    
768
        public void writeResultFilePostamble()
769
        {
770
            resultsDoc.writeResultFilePostamble();
771
        }
772

    
773

    
774
        public void startTestSetElement(XdmNode testSetNode)
775
        {
776
            resultsDoc.startTestSetElement(testSetNode);
777
        }
778

    
779

    
780
        protected void writeTestSetEndElement()
781
        {
782
            resultsDoc.endElement();
783
        }
784

    
785
        private void writeTestcaseElement(string name, string result, string comment, Spec specOpt)
786
        {
787
            resultsDoc.writeTestcaseElement(name, result, comment);
788
        }
789

    
790
		public class ModuleResolver : IQueryResolver {
791

    
792
            XPathCompiler catXPC;
793
            XdmNode testCase;
794

    
795
            public ModuleResolver(XPathCompiler xpc)
796
            {
797
                this.catXPC = xpc;
798
            }
799

    
800
            public void setTestCase(XdmNode testCase)
801
            {
802
                this.testCase = testCase;
803
            }
804

    
805

    
806
			public Object GetEntity(Uri absoluteUri) {
807
				String fullPath = absoluteUri.AbsolutePath;
808
				Stream stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
809
				//javax.xml.transform.Source sourcei = new javax.xml.transform.stream.StreamSource(uri);
810

    
811
				return stream;
812
			}
813

    
814
			internal Uri resolve(Uri basei, String child) { 
815
			
816
				return (new XmlUrlResolver ()).ResolveUri (testCase.BaseUri, child);
817
			
818
			
819
			}
820

    
821

    
822
			public Uri[] GetModules(String moduleUri, Uri baseUri, String[] locationHints){
823
				XdmValue files = catXPC.Evaluate("./module[@uri='" + moduleUri + "']/@file/string()", testCase);
824
				if (files.Count == 0) {
825
					throw new Exception("Failed to find module entry for " + moduleUri);
826
				}
827

    
828
				Uri[] fullPaths = new Uri[1];
829

    
830

    
831
				fullPaths [0] = resolve (baseUri, files.Unwrap().head().getStringValue());
832
				
833
			
834
				return fullPaths;
835
			}
836

    
837
            /*public StreamSource[] resolve(string moduleURI, string baseURI, string[] locations) {
838
                try {
839
                    XdmValue files = catXPC.Evaluate("./module[@uri='" + moduleURI + "']/@file/string()", testCase);
840
                    if (files.size() == 0) {
841
                        throw new XPathException("Failed to find module entry for " + moduleURI);
842
                    }
843
                    StreamSource[] ss = new StreamSource[files.size()];
844
                    for (int i = 0; i < files.size(); i++) {
845
                        URI uri = testCase.getBaseURI().resolve(files.itemAt(i).ToString());
846
                        ss[i] = getQuerySource(uri);
847
                    }
848
                    return ss;
849
                } catch (SaxonApiException e) {
850
                    throw new XPathException(e);
851
                }
852
            }*/
853
        }
854

    
855
        public class TestUriResolver : XmlUrlResolver
856
        {
857
            Environment env1;
858

    
859
            public TestUriResolver(Environment env)
860
            {
861
                this.env1 = env;
862
            }
863

    
864
            public override Uri ResolveUri(Uri base1, string href)
865
            {
866
                XdmNode node = null;
867
                try
868
                {
869
                    node = env1.sourceDocs[href];
870
                }
871
                catch (Exception)
872
                {
873
                    try
874
                    {
875
                        return (new XmlUrlResolver()).ResolveUri(base1, href);
876
                    }
877
                    catch (Exception) {
878
                        return null;
879
                    }
880

    
881
                }
882
                if (node == null)
883
                {
884
                    return null;
885
                }
886
                else
887
                {
888
                    return node.DocumentUri;
889
                }
890
            }
891
        }
892

    
893

    
894

    
895
        /**
896
         * Static method called as an external function call to evaluate a literal when running in "unfolded" mode.
897
         * The function simply returns the value of its argument - but the optimizer doesn't know that, so it
898
         * can't pre-evaluate the call at compile time.
899
         *
900
         * @param value the value to be returned
901
         * @return the supplied value, unchanged
902
         */
903

    
904
        /*public static Sequence lazyLiteral(Sequence value) {
905
            return value;
906
        } */
907

    
908
        /**
909
         * Collect together information about all the dependencies of tests that use a given environment
910
         * @param processor the Saxon processor
911
         * @param env the environment for which dependency information is to be gathered
912
         * @
913
         */
914

    
915
        private void buildDependencyDictionary(Processor processor, Environment env)
916
        {
917
            XQueryCompiler xqCompiler = processor.NewXQueryCompiler();
918
            xqCompiler.XQueryLanguageVersion = "3.0";
919
			xqCompiler.BaseUri = testSuiteDir;
920
            XdmValue result = xqCompiler.Compile(
921
			"        declare namespace fots = \"http://www.w3.org/2010/09/qt-fots-catalog\";\n" +
922
			"        let $testsets := doc('" + testSuiteDir + "/catalog.xml')//fots:test-set/@file/doc(resolve-uri(., exactly-one(base-uri(.))))\n" +
923
			"        for $dependencyTS in $testsets//fots:dependency\n" +
924
			"        let $name := $dependencyTS/@type\n" +
925
			"        let $value := $dependencyTS/@value\n" +
926
			"        group by $name, $value\n" +
927
			"        order by $name, $value\n" +
928
			"        return <dependency type='{$name}' value='{$value}' />").Load().Evaluate();
929

    
930

    
931
            foreach (XdmItem item in result)
932
            {
933
                XdmNode node = (XdmNode)item;
934
                string type = node.GetAttributeValue(new QName("type"));
935
                string value = node.GetAttributeValue(new QName("value"));
936
                addDependency(type, value, dependencyIsSatisfied(node, env));
937
            }
938

    
939

    
940
        }
941

    
942

    
943
        protected class Dependency
944
        {
945
            public string dType;
946
            public bool satisfied;
947
        }
948

    
949

    
950
        public void addDependency(string depStr, string value, bool satisfied)
951
        {
952
            if (!dependencyDictionary.ContainsKey(value))
953
            {
954
                Dependency dep = new Dependency();
955
                dep.dType = depStr;
956
                dep.satisfied = satisfied;
957
                dependencyDictionary.Add(value, dep);
958
            }
959
        }
960

    
961
       
962
            
963

    
964

    
965
        
966
    }
967
}
968

    
969
//
970
// The contents of this file are subject to the Mozilla Public License Version
971
// 1.0 (the "License");
972
// you may not use this file except in compliance with the License. You may
973
// obtain a copy of the
974
// License at http://www.mozilla.org/MPL/
975
//
976
// Software distributed under the License is distributed on an "AS IS" basis,
977
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
978
// See the License for the specific language governing rights and limitations
979
// under the License.
980
//
981
// The Original Code is: all this file.
982
//
983
// The Initial Developer of the Original Code is Michael Kay,
984
//
985
// Portions created by (your name) are Copyright (C) (your legal entity). All
986
// Rights Reserved.
987
//
988
// Contributor(s): none.
989
//
990

    
991

    
(7-7/24)