private void processCatalog(String catalogFile) { if (generateByteCode == 1) { driverProc.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true"); driverProc.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false"); } else if (generateByteCode == 2) { driverProc.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true"); driverProc.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true"); } else { driverProc.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false"); driverProc.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false"); } DocumentBuilder catbuilder = driverProc.NewDocumentBuilder(); catbuilder.TreeModel = treeModel; XdmNode catalog = catbuilder.Build(new Uri(catalogFile.ToString())); XPathCompiler xpc = driverProc.NewXPathCompiler(); //xpc.XPathLanguageVersion = "3.1"; xpc.Caching = true; xpc.DeclareNamespace("", catalogNamespace()); createGlobalEnvironments(catalog, xpc); try { writeResultFilePreamble(driverProc, catalog); } catch (Exception e) { System.Console.WriteLine(e.Message); } readExceptionsFile(); if (requestedTestSet != null) { try { XdmNode funcSetNode = (XdmNode)xpc.EvaluateSingle("//test-set[@name='" + requestedTestSet + "']", catalog); if (funcSetNode == null) { throw new Exception("Test-set " + requestedTestSet + " not found!"); } processTestSet(catbuilder, xpc, funcSetNode); } catch (Exception e1) { //e1.printStackTrace(); System.Console.WriteLine(e1.Message); } } else { foreach (XdmItem testSet in xpc.Evaluate("//test-set", catalog)) { processTestSet(catbuilder, xpc, ((XdmNode)testSet.Simplify)); } } try { writeResultFilePostamble(); } catch (Exception e) { System.Console.WriteLine(e.Message); //e.printStackTrace(); } }
private static void CreateCollectionUriResolver(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder) { Dictionary <Uri, List <JItem> > collections = new Dictionary <Uri, List <JItem> >(); XmlUrlResolver res = new XmlUrlResolver(); foreach (XdmItem coll in xpc.Evaluate("collection", env)) { String collectionURI = ((XdmNode)coll).GetAttributeValue(new QName("uri")); if (collectionURI == null) { collectionURI = ""; } Uri u; try { u = new Uri(collectionURI); } catch (Exception e) { driver.println("**** Invalid collection URI " + collectionURI); break; } if (!collectionURI.Equals("") && !u.IsAbsoluteUri) { u = res.ResolveUri(((XdmNode)env).BaseUri, collectionURI); collectionURI = u.ToString(); } List <JItem> docs = new List <JItem>(); foreach (XdmItem source in xpc.Evaluate("source", coll)) { String href = ((XdmNode)source).GetAttributeValue(new QName("file")); String frag = null; int hash = href.IndexOf('#'); if (hash > 0) { frag = href.Substring(hash + 1); href = href.Substring(0, hash); } FileStream file = new FileStream(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read); // String id = ((XdmNode) source).GetAttributeValue(new QName(JNamespaceConstant.XML, "id")); String uriStr = res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri; builder.BaseUri = new Uri(uriStr); XdmNode doc = builder.Build(file); if (frag != null) { XdmNode selected = (XdmNode)environment.xpathCompiler.EvaluateSingle("id('" + frag + "')", doc); if (selected == null) { driver.println("**** Fragment not found: " + frag); break; } docs.Add(selected.Implementation); } else { docs.Add(new JAnyURIValue(doc.DocumentUri.ToString())); } environment.sourceDocs.Add(uriStr, doc); } try { collections.Add(new Uri(collectionURI), docs); } catch (Exception e) { driver.println("**** Invalid collection URI " + collectionURI); } } if (collections.Count != 0) { /* environment.processor.Implementation.setCollectionURIResolver( * new CollectionURIResolver() { * public SequenceIterator resolve(String href, String base, XPathContext context) throws XPathException { * try { * List<? extends Item> docs; * if (href == null || base == null) { * docs = collections.get(new URI("")); * } else { * URI abs = new URI(base).resolve(href); * docs = collections.get(abs); * } * if (docs == null) { * throw new XPathException("Collection URI not known", "FODC0002"); * //driver.println("** Collection URI " + href + " not known"); * //return EmptyIterator.getInstance(); * } else { * return new ListIterator(docs); * } * } catch (URISyntaxException e) { * driver.println("** Invalid URI: " + e.getMessage()); * return EmptyIterator.getInstance(); * } * } * } * );*/ } }
public void RequiresPath() { Assert.Throws <ArgumentNullException>(() => XPathCompiler.Compile(null)); }
/** * Run a test case * * * @param testCase the test case element in the catalog * @param xpc the XPath compiler to be used for compiling XPath expressions against the catalog * @ */ protected override void runTestCase(XdmNode testCase, XPathCompiler xpc) { bool run = true; bool xpDependency = false; string hostLang; string langVersion; Spec specOpt = Spec.NULL; XPathCompiler xpath = driverProc.NewXPathCompiler(); string testCaseName = testCase.GetAttributeValue(new QName("name")); string testSetName = testCase.Parent.GetAttributeValue(new QName("name")); bool needSerializedResult = ((XdmAtomicValue)xpc.EvaluateSingle( "exists(./result//assert-serialization-error) or exists(./result//serialization-matches)", testCase)).GetBooleanValue(); bool needResultValue = true; if (needSerializedResult) { needResultValue = ((XdmAtomicValue)xpc.EvaluateSingle( "exists(./result//*[not(self::serialization-matches or self::assert-serialization-error or self::any-of or self::all-of)])", testCase)).GetBooleanValue(); } XdmNode alternativeResult = null; XdmNode optimization = null; hostLang = ((SpecAttr)spec.GetAttr()).sname; langVersion = ((SpecAttr)spec.GetAttr()).version; Environment env = getEnvironment(testCase, xpc); if (env == null) { notrun++; return; } env.xpathCompiler.BackwardsCompatible = false; env.processor.XmlVersion = (decimal)1.0; //test bool icuColCheck = net.sf.saxon.Version.platform.hasICUCollator(); bool icuNumCheck = net.sf.saxon.Version.platform.hasICUNumberer(); Console.WriteLine("ICUCol: " + (icuColCheck ? "true" : "false")); Console.WriteLine("ICUNum: " + (icuNumCheck ? "true" : "false")); //end of test foreach (XdmItem dependency in xpc.Evaluate("/*/dependency, ./dependency", testCase)) { string type = ((XdmNode)dependency).GetAttributeValue(new QName("type")); if (type == null) { // throw new IllegalStateException("dependency/@type is missing"); //TODO } string value = ((XdmNode)dependency).GetAttributeValue(new QName("value")); if (value == null) { //throw new IllegalStateException("dependency/@value is missing"); //TODO } if (type.Equals("spec")) { bool applicable = false; if (!value.Contains(((SpecAttr)spec.GetAttr()).sname)) { applicable = false; } else if (value.Contains(((SpecAttr)spec.GetAttr()).svname)) { applicable = true; } else if (((SpecAttr)spec.GetAttr()).svname.Equals("XQ30") && value.Contains("XQ10+")) { applicable = true; } else if (((SpecAttr)spec.GetAttr()).svname.Equals("XP30") && value.Contains("XP20+")) { applicable = true; } if (!applicable) { writeTestcaseElement(testCaseName, "n/a", "not" + ((SpecAttr)spec.GetAttr()).svname, spec); notrun++; return; } } if (langVersion.Equals("3.0")) { /* EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() { * public Set<string> getAvailableEnvironmentVariables() { * Set<string> strings = new HashSet<string>(); * strings.add("QTTEST"); * strings.add("QTTEST2"); * strings.add("QTTESTEMPTY"); * return strings; * } * * public string getEnvironmentVariable(string name) { * if (name.Equals("QTTEST")) { * return "42"; * } else if (name.Equals("QTTEST2")) { * return "other"; * } else if (name.Equals("QTTESTEMPTY")) { * return ""; * } else { * return null; * } * } * }; */ //TODO //env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); } if (type.Equals("feature") && value.Equals("xpath-1.0-compatibility")) { hostLang = "XP"; langVersion = "3.0"; xpDependency = true; specOpt = Spec.XP30; } if (type.Equals("feature") && value.Equals("namespace-axis")) { hostLang = "XP"; langVersion = "3.0"; xpDependency = true; specOpt = Spec.XP30; } if (!dependencyIsSatisfied((XdmNode)dependency, env)) { println("*** Dependency not satisfied: " + ((XdmNode)dependency).GetAttributeValue(new QName("type"))); writeTestcaseElement(testCaseName, "n/a", "Dependency not satisfied", spec); run = false; notrun++; return; } } XdmNode exceptionElement; try{ exceptionElement = exceptionsMap[testCaseName]; } catch (Exception) { exceptionElement = null; } if (exceptionElement != null) { XdmItem config = xpath.EvaluateSingle("configuration", exceptionElement); string runAtt = exceptionElement.GetAttributeValue(new QName("run")); string reasonMsg = xpath.EvaluateSingle("reason", exceptionElement).ToString(); string reportAtt = exceptionElement.GetAttributeValue(new QName("report")); if (config != null) { XdmItem paramValue = xpath.EvaluateSingle("param[@name='not-unfolded' and @value='yes']/@name", config); if (unfolded && paramValue != null) { writeTestcaseElement(testCaseName, "notRun", reasonMsg, spec); notrun++; return; } } if ("false".Equals(runAtt)) { writeTestcaseElement(testCaseName, reportAtt, reasonMsg, spec); notrun++; return; } alternativeResult = (XdmNode)xpc.EvaluateSingle("result", exceptionElement); optimization = (XdmNode)xpc.EvaluateSingle("optimization", exceptionElement); } if (run && (specOpt == Spec.NULL || specOpt == spec)) { TestOutcome outcome = new TestOutcome(this); string exp = null; try { exp = xpc.Evaluate("if (test/@file) then unparsed-text(resolve-uri(test/@file, base-uri(.))) else string(test)", testCase).ToString(); } catch (Exception err) { println("*** Failed to read query: " + err.Message); outcome.SetException((DynamicError)err); } //noinspection ThrowableResultOfMethodCallIgnored if (outcome.GetException() == null) { if (hostLang.Equals("XP") || hostLang.Equals("XT")) { XPathCompiler testXpc = env.xpathCompiler; testXpc.XPathLanguageVersion = langVersion; testXpc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions"); testXpc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema"); testXpc.DeclareNamespace("map", "http://www.w3.org/2005/xpath-functions/map"); //testXpc.DeclareNamespace("math", NamespaceConstant.MATH); //testXpc.DeclareNamespace("Dictionary", NamespaceConstant.Dictionary_FUNCTIONS); try { XPathSelector selector = testXpc.Compile(exp).Load(); foreach (QName varName in env.params1.Keys) { selector.SetVariable(varName, env.params1[varName]); } if (env.contextItem != null) { selector.ContextItem = env.contextItem; } selector.InputXmlResolver = new TestUriResolver(env); if (env.unparsedTextResolver != null) { //selector.getUnderlyingXPathContext().setUnparsedTextURIResolver(env.unparsedTextResolver); //TODO } XdmValue result = selector.Evaluate(); outcome.SetPrincipalResult(result); } catch (Exception err) { println(err.Message); outcome.SetException(err); } } else if (hostLang.Equals("XQ")) { XQueryCompiler testXqc = env.xqueryCompiler; testXqc.XQueryLanguageVersion = langVersion; testXqc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions"); testXqc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema"); //testXqc.DeclareNamespace("math", NamespaceConstant.MATH); testXqc.DeclareNamespace("map", "http://www.w3.org/2005/xpath-functions/map"); // ErrorCollector errorCollector = new ErrorCollector(); testXqc.ErrorList = new ArrayList(); string decVars = env.paramDecimalDeclarations.ToString(); if (decVars.Length != 0) { int x = (exp.IndexOf("(:%DECL%:)")); if (x < 0) { exp = decVars + exp; } else { exp = exp.Substring(0, x) + decVars + exp.Substring(x + 13); } } string vars = env.paramDeclarations.ToString(); if (vars.Length != 0) { int x = (exp.IndexOf("(:%VARDECL%:)")); if (x < 0) { exp = vars + exp; } else { exp = exp.Substring(0, x) + vars + exp.Substring(x + 13); } } ModuleResolver mr = new ModuleResolver(xpc); mr.setTestCase(testCase); // testXqc.QueryResolver = mr;// .setModuleURIResolver(mr); //TODO testXqc.QueryResolver = mr; try { XQueryExecutable q = testXqc.Compile(exp); if (optimization != null) { // Test whether required optimizations have been performed XdmDestination expDest = new XdmDestination(); JConfiguration config = driverProc.Implementation; //ExpressionPresenter presenter = new ExpressionPresenter(config, expDest.getReceiver(config)); //q.getUnderlyingCompiledQuery().explain(presenter); //presenter.close(); XdmNode explanation = expDest.XdmNode; XdmItem optResult = xpc.EvaluateSingle(optimization.GetAttributeValue(new QName("assert")), explanation); if (((XdmAtomicValue)optResult).GetBooleanValue()) { println("Optimization result OK"); } else { println("Failed optimization test"); Serializer ser = new Serializer(); ser.SetOutputStream((Stream)System.Console.OpenStandardError()); driverProc.WriteXdmValue(explanation, ser); writeTestcaseElement(testCaseName, "fail", "Failed optimization assertions", spec); failures++; return; } } XQueryEvaluator selector = q.Load(); foreach (QName varName in env.params1.Keys) { selector.SetExternalVariable(varName, env.params1[varName]); } if (env.contextItem != null) { selector.ContextItem = env.contextItem; } selector.InputXmlResolver = env; //selector.InputXmlResolver = .SetURIResolver(new TestURIResolver(env)); //TODO if (env.unparsedTextResolver != null) { selector.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);// TODO } if (needSerializedResult) { StringWriter sw = new StringWriter(); Serializer serializer = new Serializer(); //env.processor.NewSerializer(sw); //TODO serializer.SetOutputWriter(sw); selector.Run(serializer); outcome.SetPrincipalSerializedResult(sw.ToString()); } if (needResultValue) { XdmValue result = selector.Evaluate(); outcome.SetPrincipalResult(result); } } catch (Exception err) { println("in TestSet " + testSetName + err.StackTrace); println(err.Message); outcome.SetException(err); outcome.SetErrorsReported((IList)testXqc.ErrorList); } } else { writeTestcaseElement(testCaseName, "notRun", "No processor found", spec); notrun++; return; } } if (env.resetAction != null) { env.resetAction.reset(env); } XdmNode assertion; if (alternativeResult != null) { assertion = (XdmNode)xpc.EvaluateSingle("*[1]", alternativeResult); } else { assertion = (XdmNode)xpc.EvaluateSingle("result/*[1]", testCase); } if (assertion == null) { println("*** No assertions found for test case " + testCaseName); writeTestcaseElement(testCaseName, "disputed", "No assertions in test case", spec); feedback.Feedback(successes, failures++, total); return; } XPathCompiler assertXpc = env.processor.NewXPathCompiler(); assertXpc.XPathLanguageVersion = "3.1"; assertXpc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions"); assertXpc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema"); assertXpc.DeclareNamespace("math", "http://www.w3.org/2005/xpath-functions/math"); assertXpc.DeclareNamespace("MAP_FUNCTIONS", "http://www.w3.org/2005/xpath-functions/map"); assertXpc.DeclareVariable(new QName("result")); bool b = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertXpc, xpc, debug); if (b) { //println("OK"); writeTestcaseElement(testCaseName, "pass", null, spec); feedback.Feedback(successes++, failures, total); } else { if (outcome.IsException()) { XdmItem expectedError = xpc.EvaluateSingle("result//error/@code", testCase); if (expectedError == null) { // if (debug) { // outcome.getException().printStackTrace(System.out); // } writeTestcaseElement(testCaseName, "fail", "Expected success, got ", spec); println("*** fail, result " + outcome.GetException() + " Expected success."); feedback.Feedback(successes, failures++, total); } else { writeTestcaseElement(testCaseName, "wrongError", "Expected error:" + expectedError.ToString() + ", got " + outcome.GetErrorCode().LocalName, spec); println("*** fail, result " + outcome.GetErrorCode().LocalName + " Expected error:" + expectedError.ToString()); wrongErrorResults++; feedback.Feedback(successes++, failures, total); } } else { writeTestcaseElement(testCaseName, "fail", "Wrong results, got " + truncate(outcome.Serialize(assertXpc.Processor, outcome.GetPrincipalResultDoc())), spec); feedback.Feedback(successes, failures++, total); if (debug) { try { println("Result:"); driverProc.WriteXdmValue(outcome.GetPrincipalResult(), driverSerializer); println("<======="); } catch (Exception err) { } //println(outcome.getResult()); } else { println("*** fail (use -debug to show actual result)"); //failures++; } } } } }
protected override void runTestCase(XdmNode testCase, XPathCompiler xpath) { TestOutcome outcome = new TestOutcome(this); string testName = testCase.GetAttributeValue(new QName("name")); string testSetName = testCase.Parent.GetAttributeValue(new QName("name")); //// if (testName.Equals("type-0174")) { int num = 0; System.Console.WriteLine("Test driver" + num); } /// if (exceptionsMap.ContainsKey(testName)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason"))); return; } if (exceptionsMap.ContainsKey(testName) || isSlow(testName)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources"); return; } XdmValue specAtt = (XdmValue)(xpath.EvaluateSingle("(/test-set/dependencies/spec/@value, ./dependencies/spec/@value)[last()]", testCase)); string spec = specAtt.ToString(); Environment env = getEnvironment(testCase, xpath); if (env == null) { resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error"); return; } /*if(testName("environment-variable")) { * EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() { * public Set<string> getAvailableEnvironmentVariables() { * Set<string> strings = new HashSet<string>(); * strings.add("QTTEST"); * strings.add("QTTEST2"); * strings.add("QTTESTEMPTY"); * return strings; * } * * public string getEnvironmentVariable(string name) { * if (name.Equals("QTTEST")) { * return "42"; * } else if (name.Equals("QTTEST2")) { * return "other"; * } else if (name.Equals("QTTESTEMPTY")) { * return ""; * } else { * return null; * } * } * }; //TODO * } */ // env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO XdmNode testInput = (XdmNode)xpath.EvaluateSingle("test", testCase); XdmNode stylesheet = (XdmNode)xpath.EvaluateSingle("stylesheet", testInput); XdmNode pack = (XdmNode)xpath.EvaluateSingle("package", testInput); foreach (XdmItem dep in xpath.Evaluate("(/test-set/dependencies/*, ./dependencies/*)", testCase)) { if (!dependencyIsSatisfied((XdmNode)dep, env)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", "dependency not satisfied"); return; } } XsltExecutable sheet = env.xsltExecutable; //ErrorCollector collector = new ErrorCollector(); string baseOutputURI = resultsDir + "/results/output.xml"; ErrorCollector collector = new ErrorCollector(outcome); IList errorList = new List <StaticError> (); XmlUrlResolver res = new XmlUrlResolver(); string xsltLanguageVersion = spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0"; if (stylesheet != null) { XsltCompiler compiler = env.xsltCompiler; compiler.ErrorList = errorList; Uri hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file"))); Stream stream = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read); compiler.BaseUri = hrefFile; compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0"); foreach (XdmItem param in xpath.Evaluate("param[@static='yes']", testInput)) { String name = ((XdmNode)param).GetAttributeValue(new QName("name")); String select = ((XdmNode)param).GetAttributeValue(new QName("select")); XdmValue value; try { value = xpath.Evaluate(select, null); } catch (Exception e) { Console.WriteLine("*** Error evaluating parameter " + name + ": " + e.Message); //throw e; continue; } compiler.SetParameter(new QName(name), value); } try { sheet = compiler.Compile(stream); } catch (Exception err) { Console.WriteLine(err.Message); //Console.WriteLine(err.StackTrace); IEnumerator enumerator = errorList.GetEnumerator(); bool checkCur = enumerator.MoveNext(); /*if (checkCur && enumerator.Current != null) { * outcome.SetException ((Exception)(enumerator.Current)); * } else { * Console.WriteLine ("Error: Unknown exception thrown"); * }*/ outcome.SetErrorsReported(errorList); //outcome.SetErrorsReported(collector.GetErrorCodes); } // compiler.setErrorListener(collector); } else if (pack != null) { Uri hrefFile = res.ResolveUri(pack.BaseUri, pack.GetAttributeValue(new QName("file"))); Stream stream = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read); XsltCompiler compiler = env.xsltCompiler; compiler.ErrorList = errorList; compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0"); //compiler.setErrorListener(collector); try { XsltPackage xpack = compiler.CompilePackage(stream); sheet = xpack.Link(); } catch (Exception err) { Console.WriteLine(err.Message); IEnumerator enumerator = errorList.GetEnumerator(); enumerator.MoveNext(); outcome.SetException((Exception)(enumerator.Current)); outcome.SetErrorsReported(errorList); } } if (sheet != null) { XdmItem contextItem = env.contextItem; XdmNode initialMode = (XdmNode)xpath.EvaluateSingle("initial-mode", testInput); XdmNode initialFunction = (XdmNode)xpath.EvaluateSingle("initial-function", testInput); XdmNode initialTemplate = (XdmNode)xpath.EvaluateSingle("initial-template", testInput); QName initialModeName = GetQNameAttribute(xpath, testInput, "initial-mode/@name"); QName initialTemplateName = GetQNameAttribute(xpath, testInput, "initial-template/@name"); if (useXslt30Transformer) { try { bool assertsSerial = xpath.Evaluate("result//(assert-serialization|assert-serialization-error|serialization-matches)", testCase).Count > 0; bool resultAsTree = env.outputTree; bool serializationDeclared = env.outputSerialize; XdmNode needsTree = (XdmNode)xpath.EvaluateSingle("output/@tree", testInput); if (needsTree != null) { resultAsTree = needsTree.StringValue.Equals("yes"); } XdmNode needsSerialization = (XdmNode)xpath.EvaluateSingle("output/@serialize", testInput); if (needsSerialization != null) { serializationDeclared = needsSerialization.StringValue.Equals("yes"); } bool resultSerialized = serializationDeclared || assertsSerial; if (assertsSerial) { String comment = outcome.GetComment(); comment = (comment == null ? "" : comment) + "*Serialization " + (serializationDeclared ? "declared* " : "required* "); outcome.SetComment(comment); } Xslt30Transformer transformer = sheet.Load30(); transformer.InputXmlResolver = env; if (env.unparsedTextResolver != null) { transformer.GetUnderlyingController.setUnparsedTextURIResolver(env.unparsedTextResolver); } Dictionary <QName, XdmValue> caseGlobalParams = GetNamedParameters(xpath, testInput, false, false); Dictionary <QName, XdmValue> caseStaticParams = GetNamedParameters(xpath, testInput, true, false); Dictionary <QName, XdmValue> globalParams = new Dictionary <QName, XdmValue>(env.params1); foreach (KeyValuePair <QName, XdmValue> entry in caseGlobalParams) { globalParams.Add(entry.Key, entry.Value); } foreach (KeyValuePair <QName, XdmValue> entry in caseStaticParams) { globalParams.Add(entry.Key, entry.Value); } transformer.SetStylesheetParameters(globalParams); if (contextItem != null) { transformer.GlobalContextItem = contextItem; } transformer.MessageListener = collector; transformer.BaseOutputURI = baseOutputURI; transformer.MessageListener = new TestOutcome.MessageListener(outcome); XdmValue result = null; TextWriter sw = new StringWriter(); Serializer serializer = env.processor.NewSerializer(); serializer.SetOutputWriter(sw); //serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes"); OutputResolver serializingOutput = new OutputResolver(env.processor, outcome, true); net.sf.saxon.Controller controller = transformer.GetUnderlyingController; controller.setOutputURIResolver(serializingOutput); XmlDestination dest = null; if (resultAsTree) { // If we want non-serialized, we need to accumulate any result documents as trees too controller.setOutputURIResolver( new OutputResolver(env.processor, outcome, false)); dest = new XdmDestination(); } if (resultSerialized) { dest = serializer; } Stream src = null; Uri srcBaseUri = new Uri("http://uri"); XdmNode srcNode = null; DocumentBuilder builder2 = env.processor.NewDocumentBuilder(); if (env.streamedPath != null) { src = new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read); srcBaseUri = new Uri(env.streamedPath); } else if (env.streamedContent != null) { byte[] byteArray = Encoding.UTF8.GetBytes(env.streamedContent); src = new MemoryStream(byteArray); //, "inlineDoc"); builder2.BaseUri = new Uri("http://uri"); } else if (initialTemplate == null && contextItem != null) { srcNode = (XdmNode)(contextItem); } if (initialMode != null) { QName name = GetQNameAttribute(xpath, initialMode, "@name"); try { if (name != null) { transformer.InitialMode = name; } else { controller.getInitialMode(); /// has the side effect of setting to the unnamed } } catch (Exception e) { if (e.InnerException is net.sf.saxon.trans.XPathException) { Console.WriteLine(e.Message); outcome.SetException(e); //throw new SaxonApiException(e.getCause()); } else { throw e; } } } if (initialMode != null || initialTemplate != null) { XdmNode init = (XdmNode)(initialMode == null ? initialTemplate : initialMode); Dictionary <QName, XdmValue> params1 = GetNamedParameters(xpath, init, false, false); Dictionary <QName, XdmValue> tunnelledParams = GetNamedParameters(xpath, init, false, true); if (xsltLanguageVersion.Equals("2.0")) { if (!(params1.Count == 0 && tunnelledParams.Count == 0)) { Console.WriteLine("*** Initial template parameters ignored for XSLT 2.0"); } } else { transformer.SetInitialTemplateParameters(params1, false); transformer.SetInitialTemplateParameters(tunnelledParams, true); } } if (initialTemplate != null) { QName name = GetQNameAttribute(xpath, initialTemplate, "@name"); transformer.GlobalContextItem = contextItem; if (dest == null) { result = transformer.CallTemplate(name); } else { transformer.CallTemplate(name, dest); } } else if (initialFunction != null) { QName name = getQNameAttribute(xpath, initialFunction, "@name"); XdmValue[] params2 = getParameters(xpath, initialFunction); if (dest == null) { result = transformer.CallFunction(name, params2); } else { transformer.CallFunction(name, params2, dest); } } else { if (dest == null) { if (src != null) { result = transformer.ApplyTemplates(src, srcBaseUri); } else { result = transformer.ApplyTemplates(srcNode); } } else { if (src != null) { transformer.ApplyTemplates(src, dest); } else { transformer.ApplyTemplates(srcNode, dest); } } } //outcome.SetWarningsReported(collector.getFoundWarnings()); if (resultAsTree && !resultSerialized) { result = ((XdmDestination)(dest)).XdmNode; } if (resultSerialized) { outcome.SetPrincipalSerializedResult(sw.ToString()); } outcome.SetPrincipalResult(result); if (saveResults) { String s = sw.ToString(); // If a transform result is entirely xsl:result-document, then result will be null if (!resultSerialized && result != null) { StringWriter sw2 = new StringWriter(); Serializer se = env.processor.NewSerializer(sw2); se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes"); env.processor.WriteXdmValue(result, se); se.Close(); s = sw2.ToString(); } // currently, only save the principal result file in the result directory saveResultsToFile(s, resultsDir + "/results/" + testSetName + "/" + testName + ".out"); Dictionary <Uri, TestOutcome.SingleResultDoc> xslResultDocuments = outcome.GetSecondaryResultDocuments(); foreach (KeyValuePair <Uri, TestOutcome.SingleResultDoc> entry in xslResultDocuments) { Uri key = entry.Key; String path = key.AbsolutePath; String serialization = outcome.Serialize(env.processor, entry.Value); saveResultsToFile(serialization, path); } } } catch (Exception err) { //if (err.getCause() is XPathException && //!((XPathException) err.getCause()).hasBeenReported()) { //System.err.println("Unreported ERROR: " + err.getCause()); //} outcome.SetException(err); if (collector.getErrorCodes().Count > 0) { outcome.SetErrorsReported((IList)collector.getErrorCodes()); } //Console.WriteLine(err.StackTrace); /*if(err.getErrorCode() == null) { * int b = 3 + 4; } * if(err.getErrorCode() != null) * outcome.AddReportedError(err.getErrorCode().getLocalName()); * } else { * outcome.SetErrorsReported(collector.getErrorCodes()); * }*/ } /*catch (Exception err) { * err.printStackTrace(); * failures++; * resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage()); * return; * }*/ } else { try { XsltTransformer transformer = sheet.Load(); //transformer.SetURIResolver(env); //TODO if (env.unparsedTextResolver != null) { transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver); } if (initialTemplate != null) { transformer.InitialTemplate = initialTemplateName; } if (initialMode != null) { transformer.InitialMode = initialModeName; } foreach (XdmItem param in xpath.Evaluate("param", testInput)) { string name = ((XdmNode)param).GetAttributeValue(new QName("name")); string select = ((XdmNode)param).GetAttributeValue(new QName("select")); XdmValue value = xpath.Evaluate(select, null); transformer.SetParameter(new QName(name), value); } if (contextItem != null) { transformer.InitialContextNode = (XdmNode)contextItem; } if (env.streamedPath != null) { transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri); } foreach (QName varName in env.params1.Keys) { transformer.SetParameter(varName, env.params1[varName]); } //transformer.setErrorListener(collector); transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml"); /*transformer.MessageListener = (new MessageListener() { * public void message(XdmNode content, bool terminate, SourceLocator locator) { * outcome.addXslMessage(content); * } * });*/ // Run the transformation twice, once for serialized results, once for a tree. // TODO: we could be smarter about this and capture both // run with serialization StringWriter sw = new StringWriter(); Serializer serializer = env.processor.NewSerializer(sw); transformer.Implementation.setOutputURIResolver(new OutputResolver(driverProc, outcome, true)); transformer.Run(serializer); outcome.SetPrincipalSerializedResult(sw.ToString()); if (saveResults) { // currently, only save the principal result file saveResultsToFile(sw.ToString(), resultsDir + "/results/" + testSetName + "/" + testName + ".out"); } transformer.MessageListener = new TestOutcome.MessageListener(outcome); // run without serialization if (env.streamedPath != null) { transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri); } XdmDestination destination = new XdmDestination(); transformer.Implementation.setOutputURIResolver( new OutputResolver(env.processor, outcome, false)); transformer.Run(destination); //transformer. .transform(); outcome.SetPrincipalResult(destination.XdmNode); //} } catch (Exception err) { outcome.SetException(err); //outcome.SetErrorsReported(collector.getErrorCodes()); // err.printStackTrace(); // failures++; //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message); //return; } } XdmNode assertion = (XdmNode)xpath.EvaluateSingle("result/*", testCase); if (assertion == null) { failures++; resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found"); return; } XPathCompiler assertionXPath = env.processor.NewXPathCompiler(); //assertionXPath.setLanguageVersion("3.0"); bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug); if (success) { if (outcome.GetWrongErrorMessage() != null) { outcome.SetComment(outcome.GetWrongErrorMessage()); wrongErrorResults++; } else { successes++; } resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment()); } else { failures++; resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment()); } } }
public void go(String[] args) { processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true"); testSuiteDir = args[0]; if (testSuiteDir.EndsWith("/")) { testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1); } saxonResultsDir = args[1]; if (saxonResultsDir.EndsWith("/")) { saxonResultsDir = saxonResultsDir.Substring(0, testSuiteDir.Length - 1); } Hashtable exceptions = new Hashtable(); if (args.Length > 1) { testPattern = (args[2]); // TODO: allow a regex } for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-w")) { //showWarnings = true; } } fileComparer = new FileComparer(processor, testSuiteDir); XPathCompiler xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); xpc.DeclareVariable(new QName("", "param")); findSourcePath = xpc.Compile("//t:test-suite/t:sources/t:source[@ID=$param]"); findCollection = xpc.Compile("//t:test-suite/t:sources/t:collection[@ID=$param]"); xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); xpc.DeclareVariable(new QName("", "testcase")); xpc.DeclareVariable(new QName("", "moduleuri")); findModule = xpc.Compile("for $m in $testcase/t:module[@namespace=$moduleuri] " + "return concat('file:///" + testSuiteDir + "/', root($testcase)/t:test-suite/t:sources/t:module[@ID=string($m)]/@FileName, '.xq')"); //xpc = processor.NewXPathCompiler(); //xpc.DeclareNamespace("saxon", "http://saxon.sf.net/"); //xpc.DeclareVariable(new QName("", "actual")); //xpc.DeclareVariable(new QName("", "gold")); //xpc.DeclareVariable(new QName("", "debug")); //compareDocuments = xpc.Compile("saxon:deep-equal($actual, $gold, (), if ($debug) then 'JNCPS?!' else 'JNCPS')"); QName testCaseNT = new QName(testURI, "test-case"); QName nameNT = new QName(testURI, "name"); QName queryNT = new QName(testURI, "query"); QName inputNT = new QName(testURI, "input"); QName inputFileNT = new QName(testURI, "input-file"); QName inputUriNT = new QName(testURI, "input-URI"); QName defaultCollectionNT = new QName(testURI, "defaultCollection"); QName outputFileNT = new QName(testURI, "output-file"); QName expectedErrorNT = new QName(testURI, "expected-error"); QName schemaNT = new QName(testURI, "schema"); QName contextItemNT = new QName(testURI, "contextItem"); QName inputQueryNT = new QName(testURI, "input-query"); QName sourceDocumentNT = new QName(testURI, "source-document"); QName errorNT = new QName(testURI, "error"); QName validationNT = new QName(testURI, "validation"); QName discretionaryItemsNT = new QName(testURI, "discretionary-items"); QName discretionaryFeatureNT = new QName(testURI, "discretionary-feature"); QName discretionaryChoiceNT = new QName(testURI, "discretionary-choice"); QName initialContextNodeNT = new QName(testURI, "initial-context-node"); QName fileAtt = new QName("", "file"); QName filePathAtt = new QName("", "FilePath"); QName fileNameAtt = new QName("", "FileName"); QName errorIdAtt = new QName("", "error-id"); QName compareAtt = new QName("", "compare"); QName nameAtt = new QName("", "name"); QName behaviorAtt = new QName("", "behavior"); QName qnameAtt = new QName("", "qname"); QName modeAtt = new QName("", "mode"); QName validatesAtt = new QName("", "validates"); QName variableAtt = new QName("", "variable"); QName roleAtt = new QName("", "role"); DocumentBuilder builder = processor.NewDocumentBuilder(); XdmNode exceptionsDoc = builder.Build(new Uri(saxonResultsDir + "/exceptions-n.xml")); // The exceptions.xml file contains details of tests that aren't to be run, for example // because they have known bugs or require special configuration IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, new QName("", "exception")); while (exceptionTestCases.MoveNext()) { XdmNode n = (XdmNode)exceptionTestCases.Current; String nameAttVal = n.StringValue; char[] seps = { ' ', '\n', '\t' }; String[] parts = nameAttVal.Split(seps); foreach (string p in parts) { if (!exceptions.ContainsKey(p)) { exceptions.Add(p, "Exception"); } } } // Hash table containing all source documents. The key is the document name in the // catalog, the value is the corresponding document node Hashtable sourceDocs = new Hashtable(50); // Load the catalog XdmNode catalog = builder.Build(new Uri(testSuiteDir + "/XQTScatalog.xml")); // Add all Static Typing test cases to the exceptions list xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); XPathSelector st = xpc.Compile("//t:test-group[@name='StaticTyping']//t:test-case").Load(); st.ContextItem = catalog; IEnumerator ste = st.GetEnumerator(); while (ste.MoveNext()) { XdmNode testCase = (XdmNode)ste.Current; exceptions.Add(testCase.GetAttributeValue(nameAtt), "StaticTypingException"); } // Create the results file and log file results = new StreamWriter(saxonResultsDir + "/results" + processor.ProductVersion + "n.xml"); log = new StreamWriter(saxonResultsDir + "/log" + processor.ProductVersion + "n.xml"); log.WriteLine("Testing Saxon " + processor.ProductVersion); results.WriteLine("<test-suite-result xmlns='http://www.w3.org/2005/02/query-test-XQTSResult'>"); // Pre-load all the schemas SchemaManager mgr = processor.SchemaManager; IEnumerator se = catalog.EnumerateAxis(XdmAxis.Descendant, schemaNT); while (se.MoveNext()) { XdmNode schemaNode = (XdmNode)se.Current; log.WriteLine("Loading schema " + schemaNode.GetAttributeValue(fileNameAtt)); Uri location = new Uri(testSuiteDir + "/" + schemaNode.GetAttributeValue(fileNameAtt)); mgr.Compile(location); } total = 0; IEnumerator testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { total++; } // Process the test cases in turn testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { XdmNode testCase = (XdmNode)testCases.Current; String testName = testCase.GetAttributeValue(nameAtt); if (testPattern != null && !testName.StartsWith(testPattern)) { continue; } if (exceptions.ContainsKey(testName)) { continue; } log.WriteLine("Test " + testName); // Compile the query String errorCode = null; String filePath = testCase.GetAttributeValue(filePathAtt); XdmNode query = getChildElement(testCase, queryNT); String queryName = query.GetAttributeValue(nameAtt); String queryPath = testSuiteDir + "/Queries/XQuery/" + filePath + queryName + ".xq"; XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.BaseUri = new Uri(queryPath).ToString(); compiler.QueryResolver = new XqtsModuleResolver(testCase, findModule); compiler.SchemaAware = true; // Set all queries to schema-aware, because we don't really know whether they will have to handle typed input or not. ArrayList errors = new ArrayList(); compiler.ErrorList = errors; XQueryEvaluator xqe = null; FileStream stream = null; try { stream = new FileStream(queryPath, FileMode.Open, FileAccess.Read, FileShare.Read); xqe = compiler.Compile(stream).Load(); } catch (Exception e) { if (errors.Count > 0 && ((StaticError)errors[0]).ErrorCode != null) { errorCode = ((StaticError)errors[0]).ErrorCode.LocalName; } else if (e is StaticError && ((StaticError)e).ErrorCode != null) { log.WriteLine(e.Message); errorCode = ((StaticError)e).ErrorCode.LocalName; } else { log.WriteLine(e.Message); errorCode = "ErrorXXX"; } } finally { if (stream != null) { stream.Close(); } } // if the query compiled successfully, try to run it String outputPath = null; if (errorCode == null && xqe != null) { // Supply any input documents IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, inputFileNT); while (en.MoveNext()) { XdmNode file = (XdmNode)en.Current; String var = file.GetAttributeValue(variableAtt); if (var != null) { String sourceName = file.StringValue; XdmNode sourceDoc; if (sourceDocs.ContainsKey(sourceName)) { sourceDoc = (XdmNode)sourceDocs[sourceName]; } else { sourceDoc = buildSource(catalog, builder, sourceName); sourceDocs.Add(sourceName, sourceDoc); } xqe.SetExternalVariable(new QName("", var), sourceDoc); } } // Supply any input URIs IEnumerator eu = testCase.EnumerateAxis(XdmAxis.Child, inputUriNT); while (eu.MoveNext()) { XdmNode file = (XdmNode)eu.Current; String var = file.GetAttributeValue(variableAtt); if (var != null) { String sourceName = file.StringValue; if (sourceName.StartsWith("collection")) { // Supply a collection URI. // This seems to be the only way to distinguish a document URI // from a collection URI. String uri = "collection:" + sourceName; XPathSelector xpe = findCollection.Load(); xpe.SetVariable(new QName("", "param"), new XdmAtomicValue(sourceName)); xpe.ContextItem = catalog; XdmNode collectionNode = (XdmNode)xpe.EvaluateSingle(); if (collectionNode == null) { log.WriteLine("*** Collection " + sourceName + " not found"); } processor.RegisterCollection(new Uri(uri), getCollection(collectionNode)); xqe.SetExternalVariable(new QName("", var), new XdmAtomicValue(uri)); } else { // Supply a document URI. // We exploit the fact that the short name of the document is // always the same as the file name in these tests. With one exception! if (sourceName == "Char010D") { sourceName = "0x010D"; } String uri = "file:///" + testSuiteDir + "/TestSources/" + sourceName + ".xml"; xqe.SetExternalVariable(new QName("", var), new XdmAtomicValue(uri)); } } } // Supply the default collection if required XdmNode defaultCollection = getChildElement(testCase, defaultCollectionNT); if (defaultCollection != null) { String sourceName = defaultCollection.StringValue; XPathSelector xpe = findCollection.Load(); xpe.SetVariable(new QName("", "param"), new XdmAtomicValue(sourceName)); xpe.ContextItem = catalog; XdmNode collectionNode = (XdmNode)xpe.EvaluateSingle(); if (collectionNode == null) { log.WriteLine("*** Collection " + sourceName + " not found"); } processor.RegisterCollection(null, getCollection(collectionNode)); } // Supply any external variables defined as the result of a separate query IEnumerator ev = testCase.EnumerateAxis(XdmAxis.Child, inputQueryNT); while (ev.MoveNext()) { XdmNode inputQuery = (XdmNode)ev.Current; String fileName = inputQuery.GetAttributeValue(nameAtt); String subQueryPath = testSuiteDir + "/Queries/XQuery/" + filePath + fileName + ".xq"; XQueryCompiler subCompiler = processor.NewXQueryCompiler(); compiler.BaseUri = new Uri(subQueryPath).ToString(); FileStream subStream = new FileStream(subQueryPath, FileMode.Open, FileAccess.Read, FileShare.Read); XdmValue value = subCompiler.Compile(subStream).Load().Evaluate(); String var = inputQuery.GetAttributeValue(variableAtt); xqe.SetExternalVariable(new QName("", var), value); } // Supply the context item if required IEnumerator ci = testCase.EnumerateAxis(XdmAxis.Child, contextItemNT); while (ci.MoveNext()) { XdmNode file = (XdmNode)ci.Current; String sourceName = file.StringValue; if (!sourceDocs.ContainsKey(sourceName)) { XdmNode doc = buildSource(catalog, builder, sourceName); sourceDocs.Add(sourceName, doc); } XdmNode sourceDoc = (XdmNode)sourceDocs[sourceName]; xqe.ContextItem = sourceDoc; } // Create a serializer for the output outputPath = saxonResultsDir + "/results.net/" + filePath + queryName + ".out"; Serializer sr = new Serializer(); try { sr.SetOutputFile(outputPath); sr.SetOutputProperty(new QName("", "method"), "xml"); sr.SetOutputProperty(new QName("", "omit-xml-declaration"), "yes"); sr.SetOutputProperty(new QName("", "indent"), "no"); } catch (DynamicError) { // probably means that no output directory exists, which is probably because // an error is expected outputPath = saxonResultsDir + "/results.net/" + filePath + queryName + ".out"; sr.SetOutputFile(outputPath); } // Finally, run the query try { xqe.Run(sr); } catch (DynamicError e) { log.WriteLine(e.Message); QName code = e.ErrorCode; if (code != null && code.LocalName != null) { errorCode = code.LocalName; } else { errorCode = "ErrYYYYY"; } } catch (Exception e2) { log.WriteLine("Unexpected exception: " + e2.Message); log.WriteLine(e2.StackTrace); errorCode = "CRASH!!!"; } } // Compare actual results with expected results if (errorCode != null) { // query returned an error at compile time or run-time, check this was expected string expectedError = ""; bool matched = false; IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, expectedErrorNT); while (en.MoveNext()) { XdmNode error = (XdmNode)en.Current; String expectedErrorCode = error.StringValue; expectedError += (expectedErrorCode + " "); if (expectedErrorCode.Equals(errorCode)) { matched = true; feedback.Feedback(passed++, failed, total); log.WriteLine("Error " + errorCode + " as expected"); results.WriteLine("<test-case name='" + testName + "' result='pass'/>"); break; } } if (!matched) { if (expectedError.Equals("")) { feedback.Feedback(passed, failed++, total); log.WriteLine("Error " + errorCode + ", expected success"); results.WriteLine("<test-case name='" + testName + "' result='fail' comment='error " + errorCode + ", expected success'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } else { feedback.Feedback(passed++, failed, total); log.WriteLine("Error " + errorCode + ", expected " + expectedError); results.WriteLine("<test-case name='" + testName + "' result='pass' comment='error " + errorCode + ", expected " + expectedError + "'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } } } else { // query returned no error bool matched = false; String diag = ""; IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, outputFileNT); while (en.MoveNext()) { XdmNode outputFile = (XdmNode)en.Current; String fileName = testSuiteDir + "/ExpectedTestResults/" + filePath + outputFile.StringValue; String comparator = outputFile.GetAttributeValue(compareAtt); if (comparator.Equals("Inspect")) { matched = true; feedback.Feedback(passed++, failed, total); results.WriteLine("<test-case name='" + testName + "' result='inspect'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); break; } else { String comparison = fileComparer.compare(outputPath, fileName, comparator); matched = (comparison == "OK" || comparison.StartsWith("#")); if (matched) { feedback.Feedback(passed++, failed, total); results.WriteLine("<test-case name='" + testName + "' result='pass'/>"); diag = diag + ("<!-- " + comparison + " -->\n"); break; } } } if (!matched) { string expectedError = ""; IEnumerator ee = testCase.EnumerateAxis(XdmAxis.Child, expectedErrorNT); while (ee.MoveNext()) { XdmNode error = (XdmNode)ee.Current; String expectedErrorCode = error.StringValue; expectedError += (expectedErrorCode + " "); } if (expectedError.Equals("")) { feedback.Feedback(passed, failed++, total); log.WriteLine("Results differ from expected results"); results.WriteLine("<test-case name='" + testName + "' result='fail'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } else { feedback.Feedback(passed, failed++, total); log.WriteLine("Error " + expectedError + "expected but not reported"); results.WriteLine("<test-case name='" + testName + "' result='fail' comment='expected error " + expectedError + "not reported'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } } } } results.WriteLine("</test-suite-result>"); results.Close(); log.Close(); }
/** * Run the application */ public void go(String filename) { Processor processor = new Processor(); XPathCompiler xpe = processor.NewXPathCompiler(); // Build the source document. DocumentBuilder builder = processor.NewDocumentBuilder(); builder.BaseUri = new Uri(filename); builder.WhitespacePolicy = WhitespacePolicy.StripAll; XdmNode indoc = builder.Build( new FileStream(filename, FileMode.Open, FileAccess.Read)); // Compile the XPath expressions used by the application QName wordName = new QName("", "", "word"); xpe.DeclareVariable(wordName); XPathSelector findLine = xpe.Compile("//LINE[contains(., $word)]").Load(); XPathSelector findLocation = xpe.Compile("concat(ancestor::ACT/TITLE, ' ', ancestor::SCENE/TITLE)").Load(); XPathSelector findSpeaker = xpe.Compile("string(ancestor::SPEECH/SPEAKER[1])").Load(); // Loop until the user enters "." to end the application while (true) { // Prompt for input Console.WriteLine("\n>>>> Enter a word to search for, or '.' to quit:\n"); // Read the input String word = Console.ReadLine().Trim(); if (word == ".") { break; } if (word != "") { // Set the value of the XPath variable currentWord = word; // Find the lines containing the requested word bool found = false; findLine.ContextItem = indoc; findLine.SetVariable(wordName, new XdmAtomicValue(word)); foreach (XdmNode line in findLine) { // Note that we have found at least one line found = true; // Find where it appears in the play findLocation.ContextItem = line; Console.WriteLine("\n" + findLocation.EvaluateSingle()); // Output the name of the speaker and the content of the line findSpeaker.ContextItem = line; Console.WriteLine(findSpeaker.EvaluateSingle() + ": " + line.StringValue); } // If no lines were found, say so if (!found) { Console.WriteLine("No lines were found containing the word '" + word + '\''); } } } // Finish when the user enters "." Console.WriteLine("Finished."); }
protected abstract void runTestCase(XdmNode testCase, XPathCompiler catalogXpc);
/// <summary> /// Run the transformation /// </summary> /// <param name="testName"></param> /// <param name="xml"></param> /// <param name="xsl"></param> /// <param name="initialMode"></param> /// <param name="initialTemplate"></param> /// <param name="outfile"></param> /// <param name="paramTable"></param> /// <param name="initialContextPath"></param> /// <param name="useAssociated"></param> /// <param name="schemaAware"></param> /// <param name="validationMode"></param> /// <param name="recoverRecoverable"></param> /// <returns>Either null, indicating success, or an Exception object with information about the failure</returns> protected Exception runXSLT(String testName, String xml, String xsl, QName initialMode, QName initialTemplate, String outfile, Hashtable paramTable, String initialContextPath, bool useAssociated, bool schemaAware, String validationMode, bool recoverRecoverable, bool useXSLT30) { Serializer sr = new Serializer(); sr.SetOutputFile(outfile); Processor f; if (noCacheTests.ContainsKey(testName)) { //create a custom Processor to avoid schema caching f = new Processor(true); } else if (schemaAware) { f = schemaAwareProcessor; if (f == null) { return(new DynamicError("Saxon-SA not available")); } } else if (xml11) { f = processor; // Use an Xml 1.1 processor } else { f = processor; } XdmNode source = null; IList errors = new ArrayList(); XsltCompiler compiler = f.NewXsltCompiler(); compiler.SchemaAware = schemaAware; compiler.ErrorList = errors; if (useXSLT30) { compiler.XsltLanguageVersion = "3.0"; } XsltExecutable sheet = null; XsltTransformer inst; if (useAssociated) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { log.WriteLine("Failed to build source document: " + e.Message); return(e); } try { sheet = compiler.CompileAssociatedStylesheet(source); } catch (Exception e) { log.WriteLine("Failed to compile stylesheet: " + e.Message); if (errors.Count > 0) { return((Exception)errors[0]); //QName code = ((StaticError)errors[0]).ErrorCode; //(code == null ? "Failed to compile stylesheet: " + e.Message : code.LocalName); } else { return(e); } } } else { Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read); compiler.BaseUri = new Uri(xsl); try { sheet = compiler.Compile(stream); } catch (StaticError e) { if (errors.Count > 0) { return((StaticError)errors[0]); } else { log.WriteLine(e.Message); return(e); } } catch (Exception e2) { log.WriteLine("Unexpected CRASH: " + e2.Message); log.WriteLine(e2.StackTrace); return(e2); } finally { stream.Close(); } } if (initialContextPath != null) { if (source == null && xml != null) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { log.WriteLine("Failed to build source document: " + e.Message); return(e); } } XPathCompiler xc = f.NewXPathCompiler(); XPathExecutable exp = xc.Compile(initialContextPath); XPathSelector xpe = exp.Load(); xpe.ContextItem = source; XdmNode node = (XdmNode)xpe.EvaluateSingle(); source = node; } inst = sheet.Load(); if (source != null) { inst.InitialContextNode = source; } if (source == null && xml != null) { Stream stream = new FileStream(xml, FileMode.Open, FileAccess.Read); inst.SetInputStream(stream, new Uri(xml)); } if (initialMode != null) { inst.InitialMode = initialMode; } if (initialTemplate != null) { try { inst.InitialTemplate = initialTemplate; } catch (DynamicError e) { return(e); } } if (paramTable != null) { foreach (DictionaryEntry de in paramTable) { inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString())); } } inst.BaseOutputUri = new Uri(outfile); inst.RecoveryPolicy = recoverRecoverable ? RecoveryPolicy.RecoverSilently : RecoveryPolicy.DoNotRecover; if ("strict" == validationMode) { inst.SchemaValidationMode = SchemaValidationMode.Strict; } else { inst.SchemaValidationMode = SchemaValidationMode.None; } //inst.setURIResolver(factory.getURIResolver()); //inst.setErrorListener(errorListener); //((Controller)inst).setRecoveryPolicy(recoverRecoverable ? Configuration.RECOVER_SILENTLY : Configuration.DO_NOT_RECOVER); // To avoid test results being dependent on the date and time (and timezone), set a fixed // date and time for the run //((Controller)inst).setCurrentDateTime(new DateTimeValue("2005-01-01T12:49:30.5+01:00")); try { inst.Run(sr); } catch (DynamicError e) { log.WriteLine(e.Message); return(e); } catch (Exception e2) { log.WriteLine("Unexpected CRASH: " + e2.Message); log.WriteLine(e2.StackTrace); return(e2); } return(null); // indicating success }
protected string runXSLT(String testName, String xml, String xsl, QName initialMode, QName initialTemplate, String outfile, Hashtable paramTable, String initialContextPath, bool useAssociated, bool schemaAware, String validationMode, bool recoverRecoverable) { Serializer sr = new Serializer(); sr.SetOutputFile(outfile); Processor f; //if (noCacheTests.contains(testName) || testName.startsWith("schemaas20") || // testName.startsWith("striptype20") || testName.startsWith("notation20")) { // create a custom Processor to avoid schema caching //} else { if (schemaAware) { f = schemaAwareProcessor; } else if (xml11) { f = processor; // Use an Xml 1.1 processor } else { f = processor; } //} XdmNode source = null; IList errors = new ArrayList(); XsltCompiler compiler = f.NewXsltCompiler(); compiler.ErrorList = errors; XsltExecutable sheet = null; XsltTransformer inst; if (useAssociated) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { Console.WriteLine("Failed to build source document: " + e.Message); return("ErrorBBB"); } try { sheet = compiler.CompileAssociatedStylesheet(source); } catch (Exception e) { Console.WriteLine("Failed to compile stylesheet: " + e.Message); if (errors.Count > 0) { QName code = ((StaticError)errors[0]).ErrorCode; return(code == null ? "ErrorXXX" : code.LocalName); } else { return("ErrorXXX"); } } } else { Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read); compiler.BaseUri = new Uri(xsl); try { sheet = compiler.Compile(stream); } catch (Exception e) { if (errors.Count > 0) { return(((StaticError)errors[0]).ErrorCode.LocalName); } else { Console.WriteLine(e.Message); return("ErrorXXX"); } } finally { stream.Close(); } } if (source == null && xml != null) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { Console.WriteLine("Failed to build source document: " + e.Message); return("ErrorCCC"); } } if (initialContextPath != null) { XPathCompiler xc = f.NewXPathCompiler(); XPathExecutable exp = xc.Compile(initialContextPath); XPathSelector xpe = exp.Load(); xpe.ContextItem = source; XdmNode node = (XdmNode)xpe.EvaluateSingle(); source = node; } inst = sheet.Load(); if (initialMode != null) { inst.InitialMode = initialMode; } if (initialTemplate != null) { try { inst.InitialTemplate = initialTemplate; } catch (DynamicError e) { QName code = e.ErrorCode; if (code != null) { return(code.LocalName); } else { return("ErrorYYY"); } } } if (paramTable != null) { foreach (DictionaryEntry de in paramTable) { inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString())); } } inst.InitialContextNode = source; //inst.setURIResolver(factory.getURIResolver()); //inst.setErrorListener(errorListener); //((Controller)inst).setRecoveryPolicy(recoverRecoverable ? Configuration.RECOVER_SILENTLY : Configuration.DO_NOT_RECOVER); // To avoid test results being dependent on the date and time (and timezone), set a fixed // date and time for the run //((Controller)inst).setCurrentDateTime(new DateTimeValue("2005-01-01T12:49:30.5+01:00")); try { inst.Run(sr); } catch (DynamicError e) { Console.WriteLine(e.Message); QName code = e.ErrorCode; if (code != null) { return(code.LocalName); } else { return("ErrYYYYY"); } } return(null); // indicating success }
public SaxonProcessor() { _processor = new Processor(); _compiler = _processor.NewXPathCompiler(); _builder = _processor.NewDocumentBuilder(); }
protected override void runTestCase(XdmNode testCase, XPathCompiler xpath) { TestOutcome outcome = new TestOutcome(this); string testName = testCase.GetAttributeValue(new QName("name")); string testSetName = testCase.Parent.GetAttributeValue(new QName("name")); //// if (testName.Equals("type-0174")) { int num = 0; System.Console.WriteLine("Test driver" + num); } /// if (exceptionsMap.ContainsKey(testName)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason"))); return; } if (exceptionsMap.ContainsKey(testName) || isSlow(testName)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources"); return; } XdmValue specAtt = (XdmValue)(xpath.EvaluateSingle("(/test-set/dependencies/spec/@value, ./dependencies/spec/@value)[last()]", testCase)); string spec = specAtt.ToString(); Environment env = getEnvironment(testCase, xpath); if (env == null) { resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error"); return; } /*if(testName("environment-variable")) { * EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() { * public Set<string> getAvailableEnvironmentVariables() { * Set<string> strings = new HashSet<string>(); * strings.add("QTTEST"); * strings.add("QTTEST2"); * strings.add("QTTESTEMPTY"); * return strings; * } * * public string getEnvironmentVariable(string name) { * if (name.Equals("QTTEST")) { * return "42"; * } else if (name.Equals("QTTEST2")) { * return "other"; * } else if (name.Equals("QTTESTEMPTY")) { * return ""; * } else { * return null; * } * } * }; //TODO * } */ // env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO XdmNode testInput = (XdmNode)xpath.EvaluateSingle("test", testCase); XdmNode stylesheet = (XdmNode)xpath.EvaluateSingle("stylesheet", testInput); foreach (XdmItem dep in xpath.Evaluate("(/test-set/dependencies/*, ./dependencies/*)", testCase)) { if (!dependencyIsSatisfied((XdmNode)dep, env)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", "dependency not satisfied"); return; } } XsltExecutable sheet = env.xsltExecutable; //ErrorCollector collector = new ErrorCollector(); XmlUrlResolver res = new XmlUrlResolver(); if (stylesheet != null) { XsltCompiler compiler = env.xsltCompiler; Uri hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file"))); Stream stream = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read); compiler.BaseUri = hrefFile; compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0"); try { sheet = compiler.Compile(stream); } catch (Exception err) { outcome.SetException(err); //outcome.SetErrorsReported(collector.GetErrorCodes); } // compiler.setErrorListener(collector); } if (sheet != null) { XdmItem contextItem = env.contextItem; QName initialMode = getQNameAttribute(xpath, testInput, "initial-mode/@name"); QName initialTemplate = getQNameAttribute(xpath, testInput, "initial-template/@name"); try { XsltTransformer transformer = sheet.Load(); //transformer.SetURIResolver(env); //TODO if (env.unparsedTextResolver != null) { transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver); } if (initialTemplate != null) { transformer.InitialTemplate = initialTemplate; } if (initialMode != null) { transformer.InitialMode = initialMode; } foreach (XdmItem param in xpath.Evaluate("param", testInput)) { string name = ((XdmNode)param).GetAttributeValue(new QName("name")); string select = ((XdmNode)param).GetAttributeValue(new QName("select")); XdmValue value = xpath.Evaluate(select, null); transformer.SetParameter(new QName(name), value); } if (contextItem != null) { transformer.InitialContextNode = (XdmNode)contextItem; } if (env.streamedPath != null) { transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri); } foreach (QName varName in env.params1.Keys) { transformer.SetParameter(varName, env.params1[varName]); } //transformer.setErrorListener(collector); transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml"); /*transformer.MessageListener = (new MessageListener() { * public void message(XdmNode content, bool terminate, SourceLocator locator) { * outcome.addXslMessage(content); * } * });*/ // Run the transformation twice, once for serialized results, once for a tree. // TODO: we could be smarter about this and capture both // run with serialization StringWriter sw = new StringWriter(); Serializer serializer = env.processor.NewSerializer(sw); transformer.Implementation.setOutputURIResolver(new OutputResolver(driverProc, outcome, true)); transformer.Run(serializer); outcome.SetPrincipalSerializedResult(sw.ToString()); if (saveResults) { // currently, only save the principal result file saveResultsToFile(sw.ToString(), resultsDir + "/results/" + testSetName + "/" + testName + ".out"); } transformer.MessageListener = new TestOutcome.MessageListener(outcome); // run without serialization if (env.streamedPath != null) { transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri); } XdmDestination destination = new XdmDestination(); transformer.Implementation.setOutputURIResolver( new OutputResolver(env.processor, outcome, false)); transformer.Run(destination); //transformer. .transform(); outcome.SetPrincipalResult(destination.XdmNode); //} } catch (Exception err) { outcome.SetException(err); //outcome.SetErrorsReported(collector.getErrorCodes()); // err.printStackTrace(); // failures++; //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message); //return; } } XdmNode assertion = (XdmNode)xpath.EvaluateSingle("result/*", testCase); if (assertion == null) { failures++; resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found"); return; } XPathCompiler assertionXPath = env.processor.NewXPathCompiler(); //assertionXPath.setLanguageVersion("3.0"); bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug); if (success) { if (outcome.GetWrongErrorMessage() != null) { outcome.SetComment(outcome.GetWrongErrorMessage()); wrongErrorResults++; } else { successes++; } resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment()); } else { failures++; resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment()); } }
private static void LoadSourceDocuments(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder, SchemaManager manager, bool validateSources) { XmlUrlResolver res = new XmlUrlResolver(); foreach (XdmItem source in xpc.Evaluate("source", env)) { XdmNode doc = null; String uri = ((XdmNode)source).GetAttributeValue(new QName("uri")); String mime = ((XdmNode)source).GetAttributeValue(new QName("media-type")); if (mime != null && "application/xml".Equals(mime)) { continue; } String validation = ((XdmNode)source).GetAttributeValue(new QName("", "validation")); if (validation == null) { validation = "skip"; } String streaming = ((XdmNode)source).GetAttributeValue(new QName("", "streaming")); if (!validateSources && validation.Equals("skip")) { builder.SchemaValidationMode = SchemaValidationMode.None; } else { SchemaValidator validator = manager.NewSchemaValidator(); if ("lax".Equals(validation)) { validator.IsLax = true; builder.SchemaValidationMode = SchemaValidationMode.Lax; } else { builder.SchemaValidationMode = SchemaValidationMode.Strict; } environment.xpathCompiler.SchemaAware = true; environment.xqueryCompiler.SchemaAware = true; if (environment.xsltCompiler != null) { environment.xsltCompiler.SchemaAware = true; } } String role = ((XdmNode)source).GetAttributeValue(new QName("role")); String href = ((XdmNode)source).GetAttributeValue(new QName("file")); if ("true".Equals(streaming)) { if (".".Equals(role)) { if (href == null) { environment.streamedContent = xpc.Evaluate("string(content)", source).ToString(); } else { environment.streamedPath = res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath; } } else { try { System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath); System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri); System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).ToString()); environment.streamedSecondaryDocs.Add(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri, validation); }catch (Exception) {} } } else { Stream ss; /*if (uri != null) { * uri = res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri; * }*/ if (href != null) { Uri fileLoc = res.ResolveUri(((XdmNode)env).BaseUri, href); FileStream file = null; if (fileLoc.Scheme.Equals("file")) { file = new FileStream(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read); if (uri == null) { uri = fileLoc.AbsoluteUri; } } try { ss = (file == null ? new FileStream(fileLoc.ToString(), FileMode.Open, FileAccess.Read) : file); builder.BaseUri = ((XdmNode)env).BaseUri; } catch (java.io.FileNotFoundException e) { driver.println("*** failed to find source document " + href + ", Exception:" + e.Message); continue; } } else { // content is inline in the catalog if (uri == null) { uri = ((XdmNode)env).BaseUri.AbsolutePath; } string content = xpc.Evaluate("string(content)", source).ToString(); byte[] byteArray = Encoding.ASCII.GetBytes(content); ss = new MemoryStream(byteArray); builder.BaseUri = ((XdmNode)env).BaseUri; } try { builder.BaseUri = new Uri(res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri); doc = builder.Build(ss); environment.sourceDocs.Add(uri, doc); } catch (Exception e) { driver.println("*** failed to build source document " + href + ", Exception:" + e.Message); } XdmItem selectedItem = doc; String select = ((XdmNode)source).GetAttributeValue(new QName("select")); if (select != null) { XPathSelector selector = environment.xpathCompiler.Compile(select).Load(); selector.ContextItem = selectedItem; selectedItem = selector.EvaluateSingle(); } if (role != null) { if (".".Equals(role)) { environment.contextItem = selectedItem; } else if (role.StartsWith("$")) { String varName = role.Substring(1); environment.params1.Add(new QName(varName), selectedItem); environment.xpathCompiler.DeclareVariable(new QName(varName)); environment.paramDeclarations.append("declare variable $" + varName + " external; "); } } } String definesStylesheet = ((XdmNode)source).GetAttributeValue(new QName("defines-stylesheet")); if (definesStylesheet != null) { definesStylesheet = definesStylesheet.Trim(); } if ("true".Equals(definesStylesheet) || "1".Equals(definesStylesheet)) { // try using an embedded stylesheet from the source document try { //environment.xsltExecutable = environment.xsltCompiler.Compile(XdmNode.Wrap(JPreparedStylesheet.getAssociatedStylesheet( // environment.processor.Implementation, // ((XdmNode) environment.contextItem), null, null, null))); environment.xsltExecutable = environment.xsltCompiler.CompileAssociatedStylesheet(((XdmNode)environment.contextItem)); } catch (Exception) { driver.println("*** failed to compile stylesheet referenced in source document " + href); } } } }
protected Environment getEnvironment(XdmNode testCase, XPathCompiler xpc) { string testCaseName = testCase.GetAttributeValue(new QName("name")); XdmNode environmentNode = (XdmNode)xpc.EvaluateSingle("environment", testCase); Environment env; if (environmentNode == null) { env = localEnvironments["default"]; } else { string envName = environmentNode.GetAttributeValue(new QName("ref")); if (envName == null || envName.Equals("")) { env = Environment.processEnvironment(this, xpc, environmentNode, null, localEnvironments["default"]); bool baseUriCheck = ((XdmAtomicValue)xpc.EvaluateSingle("static-base-uri/@uri='#UNDEFINED'", environmentNode)).GetBooleanValue(); if (baseUriCheck) { //writeTestcaseElement(testCaseName, "notRun", "static-base-uri not supported", null); return(null); } } else { try { env = localEnvironments[envName]; }catch (Exception) { env = null; } if (env == null) { try { env = globalEnvironments[envName]; } catch (Exception e) { } } if (env == null) { foreach (XdmNode e in testCase.Parent.Select(Steps.Descendant("environment").Where(Predicates.AttributeEq("name", envName)))) { Environment.processEnvironment(this, xpc, e, localEnvironments, localEnvironments["default"]); } try { env = localEnvironments[envName]; } catch (Exception e) {} } if (env == null) { System.Console.WriteLine("*** Unknown environment " + envName); //println("*** Unknown environment " + envName); //writeTestcaseElement(testCaseName, "fail", "Environment " + envName + " not found", null); failures++; return(null); } } } return(env); }
public bool TestAssertion(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) { try { string tag = assertion.NodeName.LocalName; bool success = TestAssertion2(assertion, result, assertXpc, catalogXpc, debug); if (debug && !("all-of".Equals(tag)) && !("any-of".Equals(tag))) { driver.println("Assertion " + tag + " (" + assertion.StringValue + ") " + (success ? " succeeded" : " failed")); if (tag.Equals("error")) { if (IsException()) { bool b = compareExpectedError(assertion); if (b) { driver.println("Returned error as expected"); } else { driver.println(wrongError); } // QName code = getException().getErrorCode(); // if (code == null) { // actual = "error with no code"; // } else { // actual = code.getLocalName(); // } } else { driver.println("Expected exception " + assertion.GetAttributeValue(new QName("code")) + "; got success"); } // driver.println("Expected exception " + assertion.getAttributeValue(new QName("code")) + // ", got " + actual); } } if (!success && wrongError != null) { // treat getting the wrong error as a pass success = true; } return(success); } catch (Exception e) { System.Console.WriteLine(e.StackTrace); //To change body of catch statement use File | Settings | File Templates. return(false); } }
private void processTestSet(DocumentBuilder catbuilder, XPathCompiler xpc, XdmNode testSetNode) { string testName; string testSet; startTestSetElement(testSetNode); Uri testSetFile = new Uri(testSuiteDir + "/" + testSetNode.GetAttributeValue(new QName("file"))); XdmNode testSetDocNode = catbuilder.Build(testSetFile); createLocalEnvironments(testSetDocNode); bool run = true; IEnumerable <XdmNode> testdocEnum = testSetDocNode.Select(Steps.Child("test-set").Then(Steps.Child("dependency"))); IEnumerator <XdmNode> testDocEnumerator = testdocEnum.GetEnumerator(); if (testDocEnumerator.MoveNext()) { // pick up any test-set level dependencies in the QT3 catalog foreach (XdmNode dependency in testSetDocNode.Select(Steps.Child("test-set").Then(Steps.Child("dependency")))) { if (!EnsureDependencySatisfied(dependency, localEnvironments["default"])) { foreach (XdmNode testCase in testSetDocNode.Select(Steps.Descendant("test-case"))) { String testCaseName = testCase.GetAttributeValue("name"); resultsDoc.writeTestcaseElement(testCaseName, "n/a", "test-set dependencies not satisfied"); notrun++; } run = false; break; } } // pick up any test-set level dependencies in the QT3 catalog foreach (XdmNode dependency in testSetDocNode.Select(Steps.Path("test-set", "dependencies", "*"))) { if (!EnsureDependencySatisfied(dependency, localEnvironments["default"])) { foreach (XdmNode testCase in testSetDocNode.Select(Steps.Descendant("test-case"))) { String type = dependency.NodeName.LocalName; String value = testCase.GetAttributeValue("value"); if (value == null) { value = type; } else { value = type + ":" + value; } if ("false".Equals(dependency.GetAttributeValue("satisfied"))) { value = "!" + value; } String testCaseName = testCase.GetAttributeValue("name"); resultsDoc.writeTestcaseElement(testCaseName, "n/a", "test-set dependencies not satisfied: " + value); notrun++; } run = false; break; } } } if (run) { if (testPattern == null) { foreach (XdmNode env in testSetDocNode.Select(Steps.Descendant("environment").Where(Predicates.HasAttribute("name")))) // xpc.Evaluate("//environment[@name]", testSetDocNode)) { { String envName = env.GetAttributeValue("name"); if (!unsharedEnvironments.Contains(envName)) { try { Environment.processEnvironment(this, xpc, env, localEnvironments, localEnvironments["default"]); } catch (Exception ex) { Console.WriteLine("Failure loading environment, in processTestSet " + ex.Message); } } } } IEnumerator <XdmNode> testEnum = testSetDocNode.Select(Steps.Path("/", "test-set", "@name")).GetEnumerator(); if (testEnum.MoveNext() == false) { Console.WriteLine("Test-set does not have a @name attribute"); return; } testSet = testEnum.Current.GetStringValue(); IEnumerable <XdmNode> enumerable = testSetDocNode.Select(Steps.Descendant("test-case")); foreach (XdmNode testCase in enumerable) { String name = testCase.GetAttributeValue("name"); if (testPattern == null || testPattern.Match(name).Success) { println("-s:" + testSet + " -t:" + name); try { runTestCase(testCase, xpc); } catch (Exception ex) { Console.WriteLine("*** Error in evaluating testcase:" + ex.Message); } } } // testSet = testSetDocNode.Select(Steps.Path(new List<String> {"/", "test-set", "@name" })).GetEnumerator(). xpc.EvaluateSingle("/test-set/@name", testSetDocNode).GetStringValue(); //foreach (XdmItem testCase in xpc.Evaluate("//test-case", testSetDocNode)) { //testName = xpc.EvaluateSingle("@name", testCase).GetStringValue(); } writeTestSetEndElement(); }
private bool TestAssertion2(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) { string tag = assertion.NodeName.LocalName; if (tag.Equals("assert-eq")) { return(assertEq(assertion, result, assertXpc)); } else if (tag.Equals("assert-deep-eq")) { return(assertDeepEq(assertion, result, assertXpc)); } else if (tag.Equals("assert-permutation")) { return(assertPermutation(assertion, result, assertXpc)); } else if (tag.Equals("assert-xml")) { return(assertXml(assertion, result, assertXpc, catalogXpc, debug)); } else if (tag.Equals("serialization-matches")) { return(AssertSerializationMatches(assertion, result, catalogXpc)); } else if (tag.Equals("assert-serialization-error")) { return(AssertSerializationError(assertion, result, assertXpc)); } else if (tag.Equals("assert-empty")) { return(assertEmpty(result.value)); } else if (tag.Equals("assert-count")) { return(assertCount(assertion, result)); } else if (tag.Equals("assert")) { return(AssertXPath(assertion, result, assertXpc, debug)); } else if (tag.Equals("assert-string-value")) { return(AssertstringValue(assertion, result, debug)); } else if (tag.Equals("assert-serialization")) { return(AssertSerialization(assertion, result, catalogXpc, debug)); } else if (tag.Equals("assert-type")) { return(AssertType(assertion, result, assertXpc)); } else if (tag.Equals("assert-true")) { return(AssertTrue(result)); } else if (tag.Equals("assert-false")) { return(AssertFalse(result)); } else if (tag.Equals("assert-warning")) { return(AssertWarning()); } else if (tag.Equals("assert-message")) { XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion); foreach (XdmNode message in xslMessages) { if (TestAssertion2(subAssertion, new SingleResultDoc(message, ""), assertXpc, catalogXpc, debug)) { return(true); } } return(false); } else if (tag.Equals("assert-result-document")) { XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion); XmlUrlResolver res = new XmlUrlResolver(); Uri uri = new Uri(driver.getResultsDir() + "/results/output.xml"); uri = res.ResolveUri(uri, assertion.GetAttributeValue(new QName("uri"))); SingleResultDoc doc = GetSecondaryResult(uri); if (doc == null) { System.Console.WriteLine("**** No output document found for " + uri); return(false); } bool ok = TestAssertion2(subAssertion, doc, assertXpc, catalogXpc, debug); if (!ok) { System.Console.WriteLine("**** Assertion failed for result-document " + uri); } return(ok); } else if (tag.Equals("error")) { bool b = false; try { b = IsException() && compareExpectedError(assertion); } catch (Exception) { if (GetException() is StaticError) { string expectedError = assertion.GetAttributeValue(new QName("code")); QName expectedErrorQ; if (expectedError.Equals("*")) { expectedErrorQ = null; } else if (expectedError.StartsWith("Q{")) { expectedErrorQ = QName.FromEQName(expectedError); } else { expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError); } JFastStringBuffer fsb = new JFastStringBuffer(100); fsb.append("Expected "); fsb.append(expectedErrorQ.LocalName); fsb.append("; got "); fsb.append("err:XXX"); fsb.setLength(fsb.length() - 1); wrongError = fsb.ToString(); return(true); } if (GetException() is DynamicError) { string expectedError = assertion.GetAttributeValue(new QName("code")); QName expectedErrorQ; if (expectedError.Equals("*")) { expectedErrorQ = null; } else if (expectedError.StartsWith("Q{")) { expectedErrorQ = QName.FromEQName(expectedError); } else { expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError); } JFastStringBuffer fsb = new JFastStringBuffer(100); fsb.append("Expected "); fsb.append(expectedErrorQ.LocalName); fsb.append("; got "); fsb.append("err:XXX"); fsb.setLength(fsb.length() - 1); wrongError = fsb.ToString(); return(true); } } return(b); } else if (tag.Equals("all-of")) { foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) { if (!TestAssertion((XdmNode)child, result, assertXpc, catalogXpc, debug)) { return(false); } } return(true); } else if (tag.Equals("any-of")) { bool partialSuccess = false; foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) { if (TestAssertion((XdmNode)child, result, assertXpc, catalogXpc, debug)) { if (wrongError != null) { partialSuccess = true; continue; } return(true); } } return(partialSuccess); } else if (tag.Equals("not")) { XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion); return(!TestAssertion(subAssertion, result, assertXpc, catalogXpc, debug)); } throw new Exception("Unknown assertion element " + tag); }
protected static CompiledXPath Path(string path) { return(XPathCompiler.Compile(path)); }
private bool AssertSerialization(XdmNode assertion, SingleResultDoc result, XPathCompiler xpath, bool debug) { if (IsException()) { return(false); } else { String method = assertion.GetAttributeValue(new QName("method")); if (method == null) { method = "xml"; } String resultString = result.serialization; String comparand = xpath.Evaluate( "if (@file) then " + "if (@encoding) " + "then unparsed-text(resolve-uri(@file, base-uri(.)), @encoding) " + "else unparsed-text(resolve-uri(@file, base-uri(.))) " + "else string(.)", assertion).ToString(); comparand = comparand.Replace("\r\n", "\n"); if (comparand.EndsWith("\n")) { comparand = comparand.Substring(0, comparand.Length - 1); } if (resultString == null) { if (result.value is XdmItem) { resultString = ((XdmItem)result.value).Simplify.ToString(); } else { if (debug) { driver.println("Assert serialization fails: result is a sequence"); } return(false); } } bool isHtml = method.Equals("html") || method.Equals("xhtml"); bool normalize = isHtml; if (!normalize) { String normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space")); normalize = normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1")); } if (normalize) { comparand = JWhitespace.collapseWhitespace(comparand).toString(); resultString = JWhitespace.collapseWhitespace(resultString).toString(); } else if (resultString.EndsWith("\n")) { resultString = resultString.Substring(0, resultString.Length - 1); } if (isHtml) { // should really do this only for block-level elements comparand = comparand.Replace(" <", "<"); comparand = comparand.Replace("> ", ">"); resultString = resultString.Replace(" <", "<"); resultString = resultString.Replace("> ", ">"); } if (resultString.Equals(comparand)) { return(true); } else { if (debug) { if (resultString.Length != comparand.Length) { driver.println("Result length " + resultString.Length + "; expected length " + comparand.Length); } int len = Math.Min(resultString.Length, comparand.Length); for (int i = 0; i < len; i++) { if (resultString[1] != comparand[i]) { driver.println("Results differ at index " + i + "(\"" + resultString.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" + comparand.Substring(i, (i + 10 > len ? len : i + 10)) + "\")"); break; } } } driver.println("Serialized results differ"); return(false); } } }
internal bool mustSerialize(XdmNode testCase, XPathCompiler xpath) { return(saveResults || ((XdmAtomicValue)xpath.EvaluateSingle( "exists(./result//(assert-serialization-error|serialization-matches|assert-serialization)[not(parent::*[self::assert-message|self::assert-result-document])])", testCase)).GetBooleanValue()); }
private bool AssertXPath(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, bool debug) { if (IsException()) { return(false); } else { IEnumerator iter = assertion.EnumerateAxis(XdmAxis.Namespace); while (iter.MoveNext()) { XdmNode namespace1 = (XdmNode)iter.Current; if (namespace1.NodeName != null) { assertXpc.DeclareNamespace(namespace1.NodeName.LocalName, namespace1.StringValue); } } XPathExecutable exp = assertXpc.Compile(assertion.StringValue); XPathSelector s = exp.Load(); QName resultVar = new QName("result"); if (exp.GetRequiredCardinalityForVariable(resultVar) == '0') { if (result.value is XdmItem) // this path used in XSLT tests { s.ContextItem = ((XdmItem)result.value); } } else { s.SetVariable(resultVar, result.value); } bool b = s.EffectiveBooleanValue(); if (!b && debug) { driver.println("XPath assertion " + assertion.StringValue + " failed"); try { string ass = assertion.StringValue; int eq = ass.IndexOf("="); if (eq > 0) { ass = ass.Substring(0, eq); exp = assertXpc.Compile(ass); s = exp.Load(); if (exp.GetRequiredCardinalityForVariable(resultVar) == null) { if (result.value is XdmItem) // this path used in XSLT tests { s.ContextItem = ((XdmItem)result.value); } } else { s.SetVariable(resultVar, result.value); } XdmValue val = s.Evaluate(); driver.println("Actual result of " + ass + ": " + val.ToString()); } } catch (Exception err) {} driver.println("Actual results: " + result.value); } return(b); } }
protected XMLContext() { xpath = processor.NewXPathCompiler(); xpath.Caching = true; }
private bool AssertSerializationError(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc) { if (IsException()) { return(compareExpectedError(assertion)); } else { string expectedError = assertion.GetAttributeValue(new QName("code")); StringWriter sw = new StringWriter(); Serializer serializer = assertXpc.Processor.NewSerializer(); serializer.SetOutputProperty(Serializer.METHOD, "xml"); serializer.SetOutputProperty(Serializer.INDENT, "no"); serializer.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes"); try { assertXpc.Processor.WriteXdmValue(result.value, serializer); //serializer.serializeXdmValue(result.value); return(false); } catch (DynamicError err) { bool b = expectedError.Equals(err.ErrorCode.LocalName); if (!b) { driver.println("Expected " + expectedError + ", got " + err.ErrorCode.LocalName); } return(true); } } }
public void Node_IsSimple_NoNextNodeOrDependency() { var p = XPathCompiler.Compile("a"); Assert.True(p.FirstStep.IsSimple); }
private bool AssertSerializationMatches(XdmNode assertion, SingleResultDoc result, XPathCompiler catalogXpc) { if (IsException()) { return(false); } else { //string testSet = catalogXpc.Evaluate("string(/*/@name)", assertion).ToString(); string flagsAtt = assertion.GetAttributeValue(new QName("flags")); if (flagsAtt == null) { flagsAtt = ""; } string regex = assertion.StringValue; //IList warnings = new ArrayList(); try { JRegularExpression re = JConfiguration.getPlatform().compileRegularExpression(regex, flagsAtt, "XP30", new java.util.ArrayList()); if (re.containsMatch(getPrincipalSerializedResult())) { return(true); } else { driver.println("Serialized result:"); driver.println(getPrincipalSerializedResult()); return(false); } } catch (DynamicError e) { throw e; } } }
public ModuleResolver(XPathCompiler xpc) { this.catXPC = xpc; }
private bool assertXml(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) { if (IsException()) { return(false); } else { string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space")); bool normalize = normalizeAtt != null && ("true".Equals(normalizeAtt.Trim()) || "1".Equals(normalizeAtt.Trim())); string ignoreAtt = assertion.GetAttributeValue(new QName("ignore-prefixes")); bool ignorePrefixes = ignoreAtt != null && ("true".Equals(ignoreAtt.Trim()) || "1".Equals(ignoreAtt.Trim())); string xmlVersion = assertion.GetAttributeValue(new QName("xml-version")); bool xml11 = "1.1".Equals(xmlVersion); string comparand = catalogXpc.Evaluate("if (@file) then unparsed-text(resolve-uri(@file, base-uri(.))) else string(.)", assertion).ToString(); if (comparand.StartsWith("<?xml")) { int index = comparand.IndexOf("?>"); comparand = comparand.Substring(index + 2); } comparand = comparand.Trim(); comparand = comparand.Replace("\r\n", "\n"); if (normalize) { comparand = JWhitespace.collapseWhitespace(comparand).ToString(); } if (comparand.Equals(Serialize(assertXpc.Processor, result))) { return(true); } DocumentBuilder builder = assertXpc.Processor.NewDocumentBuilder(); if (xml11) { assertXpc.Processor.SetProperty(JFeatureKeys.XML_VERSION, "1.1"); } StringReader reader = new StringReader((xml11 ? "<?xml version='1.1'?>" : "") + "<z>" + comparand + "</z>"); builder.BaseUri = assertion.BaseUri; XdmNode expected = builder.Build(reader); int flag = 0; flag |= JDeepEqual.INCLUDE_COMMENTS; flag |= JDeepEqual.INCLUDE_PROCESSING_INSTRUCTIONS; flag |= JDeepEqual.EXCLUDE_VARIETY; if (!ignorePrefixes) { flag |= JDeepEqual.INCLUDE_NAMESPACES; flag |= JDeepEqual.INCLUDE_PREFIXES; } flag |= JDeepEqual.COMPARE_STRING_VALUES; if (debug) { flag |= JDeepEqual.WARNING_IF_FALSE; } try { JSequenceIterator iter0; if (result == null) { System.Console.WriteLine("Result value is null"); return(false); } XdmValue value = result.value; if (value == null) { System.Console.WriteLine("Result value is null (perhaps serialized?)"); return(false); } if (value.Count == 1 && value.Simplify is XdmNode && ((XdmNode)value.Simplify).NodeKind == System.Xml.XmlNodeType.Document) { iter0 = ((XdmNode)value.Simplify).Implementation.iterateAxis(JAxisInfo.CHILD); } else { iter0 = value.Unwrap().iterate(); } JSequenceIterator iter1 = expected.Implementation.iterateAxis(JAxisInfo.CHILD).next().iterateAxis(JAxisInfo.CHILD); bool success = JDeepEqual.deepEquals( iter0, iter1, new JGenericAtomicComparer(JCodepointCollator.getInstance(), null), assertXpc.Processor.Implementation.getConversionContext(), flag); // if necessary try again ignoring whitespace nodes if (!success) { iter0 = iter0.getAnother(); iter1 = iter1.getAnother(); // deep-equals with the EXCLUDE_WHITESPACE flag doesn't ignore top-level whitespace, so we // need to filter that out ourselves iter0 = new JItemMappingIterator(iter0, new RemoveWhitespace()); iter1 = new JItemMappingIterator(iter1, new RemoveWhitespace()); success = JDeepEqual.deepEquals( iter0, iter1, new JGenericAtomicComparer(JCodepointCollator.getInstance(), null), assertXpc.Processor.Implementation.getConversionContext(), flag | JDeepEqual.EXCLUDE_WHITESPACE_TEXT_NODES); if (success) { comment = "OK after ignoring whitespace text"; } } if (!success) { System.Console.WriteLine("assert-xml comparison failed"); if (debug) { System.Console.WriteLine("assert-xml comparison failed"); System.Console.WriteLine("Reference results:"); System.Console.WriteLine(expected.ToString()); System.Console.WriteLine("Actual results:"); //System.Console.WriteLine(result.serialization); System.Console.WriteLine(value.ToString()); } } return(success); } catch (DynamicError e) { Console.WriteLine(e.StackTrace); return(false); } } }
protected abstract void createGlobalEnvironments( XdmNode catalog, XPathCompiler xpc);
/** * Construct an Environment * * @param xpc the XPathCompiler used to process the catalog file * @param env the Environment element in the catalog file * @param environments the set of environments to which this one should be added (may be null) * @return the constructed Environment object * @throws SaxonApiException */ public static Environment processEnvironment(TestRunner.TestDriver driver, XPathCompiler xpc, XdmItem env, Dictionary <string, Environment> environments, Environment defaultEnvironment) { Environment environment = new Environment(); String name = ((XdmNode)env).GetAttributeValue(new QName("name")); if (name != null) { System.Console.WriteLine("Loading environment " + name); } environment.processor = new Processor(true); if (defaultEnvironment != null) { environment.processor.SetProperty(JFeatureKeys.XSD_VERSION, defaultEnvironment.processor.Implementation.getConfigurationProperty(JFeatureKeys.XSD_VERSION).ToString()); } // AutoActivate.activate(environment.processor); if (driver.GenerateByteCode == 1) { environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true"); environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false"); } else if (driver.GenerateByteCode == 2) { environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true"); environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true"); //environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE_DIR, "debugByteCode"); } else { environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false"); environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false"); } environment.xpathCompiler = environment.processor.NewXPathCompiler(); environment.xpathCompiler.BaseUri = ((XdmNode)env).BaseUri.ToString(); environment.xqueryCompiler = environment.processor.NewXQueryCompiler(); environment.xqueryCompiler.BaseUri = ((XdmNode)env).BaseUri.AbsolutePath; if (driver.Spec.ToString().Contains("XT")) { environment.xsltCompiler = environment.processor.NewXsltCompiler(); environment.xsltCompiler.XsltLanguageVersion = ((SpecAttr)(driver.Spec.GetAttr())).version; } if (driver.Unfolded) { // environment.xqueryCompiler.Implementation.setCodeInjector(new LazyLiteralInjector()); //TODO } DocumentBuilder builder = environment.processor.NewDocumentBuilder(); builder.TreeModel = driver.TreeModel; environment.sourceDocs = new Dictionary <string, XdmNode>(); if (environments != null && name != null) { try { environments.Add(name, environment); } catch (Exception) { } } foreach (XdmItem dependency in xpc.Evaluate("dependency", env)) { if (!driver.dependencyIsSatisfied((XdmNode)dependency, environment)) { environment.usable = false; } } // set the base URI if specified SetBaseUri(driver, xpc, env, environment); // set any requested collations RegisterCollations(xpc, env, environment); // declare the requested namespaces DeclareNamespaces(xpc, env, environment); // load the requested schema documents SchemaManager manager = environment.processor.SchemaManager; bool validateSources = LoadSchemaDocuments(xpc, env, manager); // load the requested source documents LoadSourceDocuments(driver, xpc, env, environment, builder, manager, validateSources); // create a collection URI resolver to handle the requested collections CreateCollectionUriResolver(driver, xpc, env, environment, builder); // create an unparsed text resolver to handle any unparsed text resources CreateUnparsedTextResolver(driver, xpc, env, environment); // register any required decimal formats // registerDecimalFormats(driver, xpc, env, environment); // declare any variables DeclareExternalVariables(driver, xpc, env, environment); // declare any output controls DeclareOutputControls(driver, xpc, env, environment); // handle requested context item foreach (XdmItem param in xpc.Evaluate("context-item", env)) { String select = ((XdmNode)param).GetAttributeValue(new QName("select")); XdmValue value = xpc.Evaluate(select, null); environment.contextItem = (XdmItem)value; } XmlUrlResolver res = new XmlUrlResolver(); // compile any stylesheet defined as part of the environment (only one allowed) DocumentBuilder builder1 = environment.processor.NewDocumentBuilder(); foreach (XdmItem stylesheet in xpc.Evaluate("stylesheet[not(@role='secondary')]", env)) { string fileName = ((XdmNode)stylesheet).GetAttributeValue(new QName("file")); try { XdmNode styleSource = builder1.Build(res.ResolveUri(((XdmNode)env).BaseUri, fileName)); environment.xsltExecutable = environment.xsltCompiler.Compile(styleSource); } catch (Exception e) { driver.println("**** failure while compiling environment-defined stylesheet " + fileName); } } // compile any stylesheet packages defined as part of the environment // Support this only in EE - an unusable environment in PE/HE foreach (XdmItem stylesheet in xpc.Evaluate("package[@role='secondary']", env)) { if (!"EE".Equals(environment.processor.Edition)) { environment.usable = false; break; } string fileName = ((XdmNode)stylesheet).GetAttributeValue(new QName("file")); Uri uri = res.ResolveUri(((XdmNode)env).BaseUri, fileName); FileStream file = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read); try { XsltPackage pkg = environment.xsltCompiler.CompilePackage(file); environment.xsltCompiler.ImportPackage(pkg); } catch (Exception e) { //e.printStackTrace(); driver.println("**** failure while compiling environment-defined stylesheet package " + fileName); driver.println("****Failure " + e.Message + " in compiling environment " + name); environment.usable = false; } } return(environment); }