public override int runCommand(XdmNode node) { if (getProperties().ContainsKey("test")) { string exp = getProperties()["test"]; XdmItem child = XMLContext.instance.xpath.EvaluateSingle(exp, node); if (child.IsAtomic() && child.Matches(XdmAtomicType.BOOLEAN)) { if (((XdmAtomicValue)child).GetBooleanValue()) { runChilds(node); } return(0); } else { logger.log("Expression \"" + exp + "\" not a boolean!"); return(-1); } // } else { logger.log("Check \"test\" parameter at If command!"); return(-1); } }
public static XPathItem ToXPathItem(this XdmItem value) { if (value == null) throw new ArgumentNullException("value"); return (value.IsAtomic()) ? ToXPathItem((XdmAtomicValue)value) : ToXPathItem((XdmNode)value); }
private static bool LoadSchemaDocuments(XPathCompiler xpc, XdmItem env, SchemaManager manager) { bool validateSources = false; XmlUrlResolver res = new XmlUrlResolver(); foreach (XdmItem schema in xpc.Evaluate("schema", env)) { String role = ((XdmNode)schema).GetAttributeValue(new QName("role")); String xsdVersion = ((XdmNode)schema).GetAttributeValue(new QName("xsd-version")); if (xsdVersion != null) { manager.XsdVersion = xsdVersion; } if (!"secondary".Equals(role)) { String href = ((XdmNode)schema).GetAttributeValue(new QName("file")); Uri uri = res.ResolveUri(((XdmNode)env).BaseUri, href); FileStream file = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read); try { manager.Compile(file, uri); } catch (Exception err) { System.Console.WriteLine("*** Failed to load schema: " + err.Message + ", Trace:" + err.StackTrace); } if ("source-reference".Equals(role)) { validateSources = true; } } } return(validateSources); }
private static void DeclareNamespaces(XPathCompiler xpc, XdmItem env, Environment environment) { foreach (XdmItem nsElement in xpc.Evaluate("namespace", env)) { String prefix = ((XdmNode)nsElement).GetAttributeValue(new QName("prefix")); String uri = ((XdmNode)nsElement).GetAttributeValue(new QName("uri")); environment.xpathCompiler.DeclareNamespace(prefix, uri); environment.xqueryCompiler.DeclareNamespace(prefix, uri); if (uri.Equals("http://expath.org/ns/file")) { // For EXPath file tests, set the EXPath base directory to the catalog directory string basei = ((XdmNode)nsElement).BaseUri.ToString(); if (basei.StartsWith("file:///")) { basei = basei.Substring(7); } else if (basei.StartsWith("file:/")) { basei = basei.Substring(5); } FileStream file = new FileStream(basei, FileMode.Open, FileAccess.Read); //new File(base); //System.SetProperty("expath.base.directory", file.ToString()); } } }
private static void RegisterCollations(XPathCompiler xpc, XdmItem env, Environment environment) { CompareInfo info = CultureInfo.CurrentCulture.CompareInfo; CompareOptions options = CompareOptions.IgnoreCase; foreach (XdmItem basei in xpc.Evaluate("collation", env)) { string uri = ((XdmNode)basei).GetAttributeValue(new QName("uri")); String defaultAtt = ((XdmNode)basei).GetAttributeValue(new QName("default")); bool isDefault = defaultAtt != null && (defaultAtt.Trim().Equals("true") || defaultAtt.Trim().Equals("1")); if (uri.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind") || uri.Equals("http://www.w3.org/xslts/collation/caseblind")) { JConfiguration config = xpc.Processor.Implementation; JStringCollator collator = config.getCollationURIResolver().resolve("http://saxon.sf.net/collation?ignore-case=yes", config); environment.xpathCompiler.DeclareCollation(new Uri(uri), info, options, isDefault);//(Collator) ((SimpleCollation) collator.).getCollation()); environment.xqueryCompiler.DeclareCollation(new Uri(uri), info, options, isDefault); if (environment.xsltCompiler != null) { environment.xsltCompiler.DeclareCollation(new Uri(uri), info, options, isDefault); } } } }
/*private static string getCanonicalPath(File file) { * try { * return file.getCanonicalPath(); * } catch (IOException err) { * return file.getAbsolutePath(); * } * }*/ private static QName getQNameAttribute(XPathCompiler xpath, XdmItem contextItem, string attributePath) { string exp = "for $att in " + attributePath + " return if (contains($att, ':')) then resolve-QName($att, $att/..) else QName('', $att)"; XdmAtomicValue qname = (XdmAtomicValue)xpath.EvaluateSingle(exp, contextItem); return(qname == null ? null : (QName)qname.Value); }
internal static QName GetQNameAttribute(XPathCompiler xpath, XdmItem contextItem, string attributePath) { string exp = "for $att in " + attributePath + " return if (contains($att, ':')) then resolve-QName($att, $att/..) else " + " if (contains($att,'{')) then QName(substring-before(substring-after($att,'{'),'}'),substring-after($att,'}')) else" + " QName('', $att)"; XdmAtomicValue qname = (XdmAtomicValue)xpath.EvaluateSingle(exp, contextItem); return(qname == null ? null : new QName(qname.ToString())); }
public static object GetJTokenFromXdmItem(XdmItem xdmItem) { var xdmAtomicValue = xdmItem as XdmAtomicValue; if (xdmAtomicValue != null) { return(JToken.FromObject(xdmAtomicValue.Value)); } var output = new XmlDocument(); output.LoadXml(xdmItem.ToString()); return(JToken.FromObject(output)); }
/** * Show a query producing a sequence as its result and returning the sequence * to the Java application in the form of an iterator. For each item in the * result, its string value is output. */ public static void ExampleToSequence() { Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); XQueryExecutable exp = compiler.Compile("for $i in 1 to 10 return $i * $i"); XQueryEvaluator eval = exp.Load(); XdmValue value = eval.Evaluate(); IEnumerator e = value.GetEnumerator(); while (e.MoveNext()) { XdmItem item = (XdmItem)e.Current; Console.WriteLine(item.ToString()); } }
public override XPathItem CreateAtomicValue(object value, XmlQualifiedName qualifiedName) { if (value == null) { throw new ArgumentNullException("value"); } if (qualifiedName == null) { throw new ArgumentNullException("qualifiedName"); } XdmAtomicValue atomicValue; XdmValue xdmValue = value.ToXdmValue(this); if (xdmValue.Count != 1) { throw new ArgumentException("value cannot be empty, or more than one item.", "value"); } try { XdmItem item = xdmValue.GetXdmEnumerator().AsItems().Single(); if (item.IsAtomic()) { atomicValue = (XdmAtomicValue)item; if (!qualifiedName.IsEmpty) { XmlQualifiedName typeName = atomicValue.GetTypeName(this.processor).ToXmlQualifiedName(); if (typeName != qualifiedName) { atomicValue = new XdmAtomicValue(value.ToString(), new QName(qualifiedName), this.processor); } } } else { atomicValue = (!qualifiedName.IsEmpty) ? new XdmAtomicValue(value.ToString(), new QName(qualifiedName), this.processor) : new XdmAtomicValue(value.ToString()); } } catch (Exception ex) { throw new SaxonException(ex.Message, ex); } return(atomicValue.ToXPathItem()); }
public override int runCommand(XdmNode node) { if (selectParam != null && selectParam.Length > 0) { //XmlElement selectNode = (XmlElement)node.SelectSingleNode(selectParam); XdmItem selectNode = XMLContext.instance.xpath.EvaluateSingle(selectParam, node); if (selectNode != null && selectNode.IsNode()) { runChilds((XdmNode)selectNode); } } else { logger.log("Check \"select\" parameter at Switch command!"); } return(0); }
public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context) { XdmNode node = arguments[0].AsNodes().Single(); var options = new XPathSerializationOptions(); XdmItem arg2 = null; if (arguments.Length > 1 && (arg2 = arguments[1].AsItems().SingleOrDefault()) != null) { if (arg2.IsAtomic()) { string methodLexical = arg2.ToString(); QName method = (context.ContextItem == null || context.ContextItem.IsAtomic()) ? new QName(methodLexical) : new QName(methodLexical, (XdmNode)context.ContextItem); options.Method = method.ToXmlQualifiedName(); } } Serializer serializer = this.itemFactory.CreateSerializer(options); if (arg2 != null && !arg2.IsAtomic()) { foreach (XdmNode attr in ((IXdmEnumerator)((XdmNode)arg2).EnumerateAxis(XdmAxis.Attribute)).AsNodes()) { serializer.SetOutputProperty(attr.NodeName, attr.StringValue); } } using (var writer = new StringWriter()) { serializer.SetOutputWriter(writer); this.itemFactory.processor.WriteXdmValue(node, serializer); return(writer.ToString().ToXdmAtomicValue().GetXdmEnumerator()); } }
public int GetMetaID(String meta) { Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); //compiler.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions"); compiler.BaseUri = BaseUri; XQueryExecutable exp = compiler.Compile(XQueries.GetMetaID); XQueryEvaluator eval = exp.Load(); eval.SetExternalVariable(new QName("meta"), new XdmAtomicValue(meta)); //XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle(); XdmItem value = eval.EvaluateSingle(); IEnumerator e = value.GetEnumerator(); while (e.MoveNext()) { //XdmItem item = (XdmItem)e.Current; //Console.WriteLine(item.ToString()); return(Convert.ToInt32(e.Current.ToString())); } return(-1); }
private static void SetBaseUri(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) { foreach (XdmItem basei in xpc.Evaluate("static-base-uri", env)) { string uri = ((XdmNode)basei).GetAttributeValue(new QName("uri")); if (uri == null || "#UNDEFINED".Equals(uri)) { driver.println("**** Error: The BaseURI null and #UNDEFINED is not supported"); } else { try { environment.xpathCompiler.BaseUri = uri; environment.xqueryCompiler.BaseUri = uri; } catch (Exception e) { driver.println("**** invalid base URI " + uri); } } } }
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()); } } }
private static void DeclareExternalVariables(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) { foreach (XdmItem param in xpc.Evaluate("param", env)) { String varName = ((XdmNode)param).GetAttributeValue(new QName("name")); XdmValue value; String source = ((XdmNode)param).GetAttributeValue(new QName("source")); if (source != null) { XdmNode sourceDoc = null; try { sourceDoc = environment.sourceDocs[source]; } catch (Exception) { } if (sourceDoc == null) { driver.println("**** Unknown source document " + source); } value = sourceDoc; } else { String select = ((XdmNode)param).GetAttributeValue(new QName("select")); value = xpc.Evaluate(select, null); } environment.params1.Add(new QName(varName), value); environment.xpathCompiler.DeclareVariable(new QName(varName)); String declared = ((XdmNode)param).GetAttributeValue(new QName("declared")); if (declared != null && "true".Equals(declared) || "1".Equals(declared)) { // no action } else { environment.paramDeclarations.append("declare variable $" + varName + " external; "); } } }
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(); * } * } * } * );*/ } }
/*private void RegisterDecimalFormats(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) { * foreach (XdmItem decimalFormat in xpc.Evaluate("decimal-format", env)) { * DecimalFormatManager dfm = environment.xpathCompiler.getUnderlyingStaticContext().getDecimalFormatManager(); * * XdmNode formatElement = (XdmNode) decimalFormat; * String formatName = formatElement.getAttributeValue(new QName("name")); * StructuredQName formatQName = null; * if (formatName != null) { * if (formatName.indexOf(':') < 0) { * formatQName = new StructuredQName("", "", formatName); * } else { * try { * formatQName = StructuredQName.fromLexicalQName(formatName, false, true, Name11Checker.getInstance(), * new InscopeNamespaceResolver(formatElement.getUnderlyingNode())); * } catch (XPathException e) { * driver.println("**** Invalid QName as decimal-format name"); * formatQName = new StructuredQName("", "", "error-name"); * } * } * environment.paramDecimalDeclarations.append("declare decimal-format " + formatQName.getEQName() + " "); * } else { * environment.paramDecimalDeclarations.append("declare default decimal-format "); * } * DecimalSymbols symbols = (formatQName == null ? dfm.getDefaultDecimalFormat() : dfm.obtainNamedDecimalFormat(formatQName)); * symbols.setHostLanguage(Configuration.XQUERY); * for (XdmItem decimalFormatAtt : xpc.Evaluate("@* except @name", formatElement)) { * XdmNode formatAttribute = (XdmNode) decimalFormatAtt; * String property = formatAttribute.getNodeName().getLocalName(); * String value = formatAttribute.getStringValue(); * environment.paramDecimalDeclarations.append(property + "=\"" + value + "\" "); * try { * if (property.Equals("decimal-separator")) { * symbols.setDecimalSeparator(value); * } else if (property.Equals("grouping-separator")) { * symbols.setGroupingSeparator(value); * } else if (property.Equals("infinity")) { * symbols.setInfinity(value); * } else if (property.Equals("NaN")) { * symbols.setNaN(value); * } else if (property.Equals("minus-sign")) { * symbols.setMinusSign((value)); * } else if (property.Equals("percent")) { * symbols.setPercent((value)); * } else if (property.Equals("per-mille")) { * symbols.setPerMille((value)); * } else if (property.Equals("zero-digit")) { * symbols.setZeroDigit((value)); * } else if (property.Equals("digit")) { * symbols.setDigit((value)); * } else if (property.Equals("pattern-separator")) { * symbols.setPatternSeparator((value)); * } else { * driver.println("**** Unknown decimal format attribute " + property); * } * } catch (XPathException e) { * driver.println("**** " + e.getMessage()); * } * } * environment.paramDecimalDeclarations.append(";"); * try { * symbols.checkConsistency(formatQName); * } catch (XPathException err) { * driver.println("**** " + err.getMessage()); * } * * } * }*/ private static void CreateUnparsedTextResolver(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) { Dictionary <Uri, Object> resources = new Dictionary <Uri, Object>(); Dictionary <Uri, String> encodings = new Dictionary <Uri, String>(); XmlUrlResolver res = new XmlUrlResolver(); foreach (XdmItem resource in xpc.Evaluate("resource", env)) { String uri = ((XdmNode)resource).GetAttributeValue(new QName("uri")); String href = ((XdmNode)resource).GetAttributeValue(new QName("file")); String encoding = ((XdmNode)resource).GetAttributeValue(new QName("encoding")); if (href != null) { Object obj = null; if (href.StartsWith("http")) { try { obj = new Uri(href); } catch (Exception e) { throw e; } } else { obj = new java.io.File(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath); } try { resources.Add(new Uri(uri), obj); encodings.Add(new Uri(uri), encoding); Uri abs = res.ResolveUri(((XdmNode)resource).BaseUri, uri); resources.Add(abs, obj); encodings.Add(abs, encoding); } catch (Exception e) { driver.println("** Invalid URI in environment: " + e.Message); } } } if (resources.Count != 0) { environment.unparsedTextResolver = new UnparsedTextURIResolver(encodings, resources); } }
public QuerySingleResults(XdmItem item) { _xdmItem = item; _data = new Lazy <object>(() => _xdmItem != null ? Extensions.GetXmlOrAtomicObject(_xdmItem) : null); _jToken = new Lazy <object>(() => _xdmItem != null ? Extensions.GetJTokenFromXdmItem(_xdmItem): null); }
public static object GetXmlOrAtomicObject(XdmItem item) { var xdmAtomicValue = item as XdmAtomicValue; return(xdmAtomicValue != null ? xdmAtomicValue.Value : item.ToString()); }
/** * 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); }
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 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()); } }
/** * 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++; } } } } }
private static void DeclareOutputControls(TestRunner.TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) { String needsTree = xpc.Evaluate("string((output/@tree,'yes')[1])", env).ToString(); environment.outputTree = "yes".Equals(needsTree); String needsSerialization = xpc.Evaluate("string((output/@serialize,'no')[1])", env).ToString(); environment.outputSerialize = "yes".Equals(needsSerialization); }