csd_base_stored_queries: Added filter_by_otherid for organizations and facilities

(:~
: This is a module contatining the required stored queries for Care Services Discovery
: @version 1.0
: @see https://github.com/his-interop/openinfoman @see http://ihe.net
:
:)
module namespace csd_bsq = "https://github.com/his-interop/openinfoman/csd_bsq";

import module namespace csd = "urn:ihe:iti:csd:2013" at "csd_base_library.xqm";

declare default element  namespace   "urn:ihe:iti:csd:2013";

declare variable $csd_bsq:stored_functions :=
(
   <function uuid='4e8bbeb9-f5f5-11e2-b778-0800200c9a66'
   	     method='csd_bsq:provider_search'
 	     content-type='text/xml; charset=utf-8'
	     />,
   <function uuid='dc6aedf0-f609-11e2-b778-0800200c9a66'
   	     method='csd_bsq:organization_search'
 	     content-type='text/xml; charset=utf-8'
	     />,
   <function uuid='e3d8ecd0-f605-11e2-b778-0800200c9a66'
   	     method='csd_bsq:service_search'
 	     content-type='text/xml; charset=utf-8'
	     />,
   <function uuid='c7640530-f600-11e2-b778-0800200c9a66'
   	     method='csd_bsq:facility_search'
 	     content-type='text/xml; charset=utf-8'
	     />
);

declare function csd_bsq:provider_search($requestParams, $doc) as element()
{
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory>
    {

      let $provs0 := csd:filter_by_primary_id($doc/CSD/providerDirectory/*,$requestParams/id)

      let $provs1 := csd:filter_by_other_id($provs0,$requestParams/otherID)

      let $provs2 := csd:filter_by_common_name($provs1,$requestParams/commonName)

      let $provs3 := csd:filter_by_coded_type($provs2,$requestParams/type)

      let $provs4 := csd:filter_by_address($provs3, $requestParams/address/addressLine)

      let $provs5 :=  csd:filter_by_record($provs4,$requestParams/record)

      return csd:limit_items($provs5,$requestParams/start,$requestParams/max)
    }
  </providerDirectory>
</CSD>

};

declare function csd_bsq:organization_search($requestParams, $doc) as element()
{
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory>
    {
      let $orgs0 := csd:filter_by_primary_id($doc/CSD/organizationDirectory/*,$requestParams/id)

      let $orgs1 := csd:filter_by_primary_name($orgs0,$requestParams/primaryName)

      let $orgs2 := csd:filter_by_name($orgs1,$requestParams/name)

      let $orgs3 := csd:filter_by_coded_type($orgs2,$requestParams/codedType)

      let $orgs4 := csd:filter_by_address($orgs3, $requestParams/address/addressLine)

      let $orgs5 := csd:filter_by_record($orgs4,$requestParams/record)

	  let $orgs6 := csd:filter_by_other_id($orgs5,$requestParams/otherID)

      return csd:limit_items($orgs6,$requestParams/start,$requestParams/max)

    }
  </organizationDirectory>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory/>
</CSD>
};

declare function csd_bsq:facility_search($requestParams, $doc) as element()
{
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory>
    {
      let $facs0 := csd:filter_by_primary_id($doc/CSD/facilityDirectory/*,$requestParams/id)

      let $facs1 := csd:filter_by_primary_name($facs0,$requestParams/primaryName)

      let $facs2 := csd:filter_by_name($facs1,$requestParams/name)

      let $facs3 := csd:filter_by_coded_type($facs2,$requestParams/codedType)

      let $facs4 := csd:filter_by_address($facs3, $requestParams/address/addressLine)

      let $facs5 := csd:filter_by_record($facs4,$requestParams/record)

      let $facs6 := csd:filter_by_other_id($facs5,$requestParams/otherID)

      return csd:limit_items($facs6,$requestParams/start,$requestParams/max)

    }
  </facilityDirectory>
  <providerDirectory/>
</CSD>
};

declare function csd_bsq:service_search($requestParams, $doc) as element()
{
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory>
    {
      let $svcs0 := csd:filter_by_primary_id($doc/CSD/serviceDirectory/*,$requestParams/id)

      let $svcs1 := csd:filter_by_coded_type($svcs0,$requestParams/codedType)

      let $svcs2 :=  csd:filter_by_record($svcs1,$requestParams/record)

      return csd:limit_items($svcs2,$requestParams/start,$requestParams/max)
    }
  </serviceDirectory>
  <facilityDirectory/>
  <providerDirectory/>
</CSD>

};

(:~
: This is a module contatining the required stored queries for Care Services Discovery
: @version 1.0
: @see https://github.com/his-interop/openinfoman @see http://ihe.net
:
:)
module namespace csd_bsq = "https://github.com/his-interop/openinfoman/csd_bsq";

import module namespace csd = "urn:ihe:iti:csd:2013" at "csd_base_library.xqm";

declare default element  namespace   "urn:ihe:iti:csd:2013";

declare variable $csd_bsq:stored_functions :=
(
   <function uuid='4e8bbeb9-f5f5-11e2-b778-0800200c9a66'
   	     method='csd_bsq:provider_search'
 	     content-type='text/xml; charset=utf-8'
	     />,
   <function uuid='dc6aedf0-f609-11e2-b778-0800200c9a66'
   	     method='csd_bsq:organization_search'
 	     content-type='text/xml; charset=utf-8'
	     />,
   <function uuid='e3d8ecd0-f605-11e2-b778-0800200c9a66'
   	     method='csd_bsq:service_search'
 	     content-type='text/xml; charset=utf-8'
	     />,
   <function uuid='c7640530-f600-11e2-b778-0800200c9a66'
   	     method='csd_bsq:facility_search'
 	     content-type='text/xml; charset=utf-8'
	     />
);

declare function csd_bsq:provider_search($requestParams, $doc) as element()
{
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory>
    {

      let $provs0 := csd:filter_by_primary_id($doc/CSD/providerDirectory/*,$requestParams/id)

      let $provs1 := csd:filter_by_other_id($provs0,$requestParams/otherID)

      let $provs2 := csd:filter_by_common_name($provs1,$requestParams/commonName)

      let $provs3 := csd:filter_by_coded_type($provs2,$requestParams/type)

      let $provs4 := csd:filter_by_address($provs3, $requestParams/address/addressLine)

      let $provs5 :=  csd:filter_by_record($provs4,$requestParams/record)

      return csd:limit_items($provs5,$requestParams/start,$requestParams/max)
    }
  </providerDirectory>
</CSD>

};

declare function csd_bsq:organization_search($requestParams, $doc) as element()
{
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory>
    {
      let $orgs0 := csd:filter_by_primary_id($doc/CSD/organizationDirectory/*,$requestParams/id)

      let $orgs1 := csd:filter_by_primary_name($orgs0,$requestParams/primaryName)

      let $orgs2 := csd:filter_by_name($orgs1,$requestParams/name)

      let $orgs3 := csd:filter_by_coded_type($orgs2,$requestParams/codedType)

      let $orgs4 := csd:filter_by_address($orgs3, $requestParams/address/addressLine)

      let $orgs5 :=  csd:filter_by_record($orgs4,$requestParams/record)

      return csd:limit_items($orgs5,$requestParams/start,$requestParams/max)

    }
  </organizationDirectory>
  <serviceDirectory/>
  <facilityDirectory/>
  <providerDirectory/>
</CSD>
};

declare function csd_bsq:facility_search($requestParams, $doc) as element()
{
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory/>
  <facilityDirectory>
    {
      let $facs0 := csd:filter_by_primary_id($doc/CSD/facilityDirectory/*,$requestParams/id)

      let $facs1 := csd:filter_by_primary_name($facs0,$requestParams/primaryName)

      let $facs2 := csd:filter_by_name($facs1,$requestParams/name)

      let $facs3 := csd:filter_by_coded_type($facs2,$requestParams/codedType)

      let $facs4 := csd:filter_by_address($facs3, $requestParams/address/addressLine)

      let $facs5 :=  csd:filter_by_record($facs4,$requestParams/record)

      return csd:limit_items($facs5,$requestParams/start,$requestParams/max)

    }
  </facilityDirectory>
  <providerDirectory/>
</CSD>
};

declare function csd_bsq:service_search($requestParams, $doc) as element()
{
<CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
  <organizationDirectory/>
  <serviceDirectory>
    {
      let $svcs0 := csd:filter_by_primary_id($doc/CSD/serviceDirectory/*,$requestParams/id)

      let $svcs1 := csd:filter_by_coded_type($svcs0,$requestParams/codedType)

      let $svcs2 :=  csd:filter_by_record($svcs1,$requestParams/record)

      return csd:limit_items($svcs2,$requestParams/start,$requestParams/max)
    }
  </serviceDirectory>
  <facilityDirectory/>
  <providerDirectory/>
</CSD>

};


Store test results in a collection hierarchy reflecting the hierarchy of test groups.

svn path=/trunk/eXist-1.0/; revision=2719

declare namespace xqts="http://exist-db.org/xquery/xqts";
declare namespace catalog="http://www.w3.org/2005/02/query-test-XQTSCatalog";

import module namespace util="http://exist-db.org/xquery/util";
import module namespace xdb="http://exist-db.org/xquery/xmldb";
import module namespace xdiff="http://exist-db.org/xquery/xmldiff";

(:~ ----------------------------------------------------------------------------------------
     W3C XQuery Test Suite

     This is the main module for running the XQTS on eXist. You can either
     run the whole test suite, a specific test group or a single test case.

     Setup:

     * Make sure the XmlDiff module is registered in conf.xml

     * Change the $xqts:XQTS_HOME variable below to point to the directory into
     which you unzipped the XQTS sources.

     * Create a collection /db/XQTS in the database.

     * From the XQTS directory, upload XQTSCatalog.xml into the created
     collection.

     * Upload the "TestSources" directory so the source docs can be found
     in /db/XQTS/TestSources.

     * Run this script with the client.
     ------------------------------------------------------------------------------------------- :)
declare variable $xqts:XQTS_HOME { "file:///d:/Data/XQTS/" };

declare function xqts:create-collections($group as element(catalog:test-group)) as node() {
    let $rootColl := xdb:create-collection("/db/XQTS", "test-results")
    let $ancestors := reverse(($group/ancestor::catalog:test-group, $group))
    let $collection := xqts:create-collections($rootColl, $ancestors, "/db/XQTS/test-results")
    let $results := xdb:store($collection, "results.xml", <test-result failed="0" passed="0"/>)
    return
        doc($results)
};

declare function xqts:create-collections($parent as object,
    $pathElements as element()+, $currentPath as xs:string)
as object {
    let $next := $pathElements[last()]
    let $remainder := subsequence($pathElements, 1, count($pathElements) - 1)
    let $newColl := xdb:create-collection($parent, $next/@name)
    return
        if ($remainder) then
            xqts:create-collections($newColl, $remainder, concat($currentPath, "/", $next/@name))
        else
            $newColl
};

declare function xqts:get-query($case as element(catalog:test-case)) {
   let $query-name := $case//catalog:query/@name
   let $path := concat( $xqts:XQTS_HOME, "Queries/XQuery/", $case/@FilePath, $query-name, ".xq" )
   let $xq-string := util:file-read($path)
   return $xq-string
};

declare function xqts:print-result($test-name as xs:string, $passed as xs:boolean, $query as xs:string,
    $result as item()*, $expected as item()*, $case as element(catalog:test-case)) as element() {
    <test-case name="{$test-name}" result="{if ($passed) then 'pass' else 'fail'}">
    {
        if (not($passed)) then (
            <result>{$result}</result>,
            if ($expected instance of element() and count($expected/*) > 10) then
            	<expected truncated="">{$expected/*[position() < 10]}</expected>
            else
                <expected>{$expected}</expected>,
            (: element {$case/catalog:input-file/@variable} { xqts:getInputValue($case) }, :)
            <query>{$query}</query>
        ) else ()
    }
    </test-case>
};

declare function xqts:normalize-text($result as item()*) as xs:string {
    let $str := string-join($result, " ")
    return
        (: Remove leading and trailing whitespace :)
        replace(replace($str, "^\s+", ""), "\s+$", "")
};

declare function xqts:check-output($query as xs:string, $result as item()*, $case as element(catalog:test-case)) {
    let $output := $case/catalog:output-file[last()]
    return
        (: Comparison method: "Text" :)
        if ($output/@compare eq "Text") then
            let $text := util:file-read(concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                "/", $output/text()))
            let $test := xqts:normalize-text($text) eq xqts:normalize-text($result)
            return
                xqts:print-result($case/@name, $test, $query, $result, $text, $case)
        (: Comparison method: "XML" :)
        else if ($output/@compare eq "XML") then
            let $filePath := concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                $output/text())
            let $expected := doc(xdb:store("/db", "temp.xml", xs:anyURI($filePath), "text/xml"))
            let $test := xdiff:compare($expected, $result)
            return
                xqts:print-result($case/@name, $test, $query, $result, $expected, $case)
        (: Comparison method: "Fragment" :)
        else if ($output/@compare eq "Fragment") then
            let $filePath := concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath, $output/text())
            let $expectedFrag := util:file-read($filePath)
            let $xmlFrag := concat("<f>", $expectedFrag, "</f>")
            let $log := util:log("DEBUG", ("Frag stored: ", $xmlFrag))
            let $expected := doc(xdb:store("/db", "temp.xml", $xmlFrag, "text/xml"))
            let $test := xdiff:compare($expected, <f>{$result}</f>)
            return
                xqts:print-result($case/@name, $test, $query, $result, $expected, $case)
        (: Don't know how to compare :)
        else
            <error test="{$case/@name}">Unknown comparison method: {$output/@compare}.</error>
};

declare function xqts:run-test-case( $case as element(catalog:test-case)) as item()* {
   let $query := xqts:get-query($case)
   let $context :=
       <static-context>
       {
           for $input in $case/catalog:input-file
           return
               <variable name="{$input/@variable}">{xqts:get-input-value($input)}</variable>
       }
       </static-context>
   let $result :=
       util:catch("java.lang.Exception",
           let $result :=
               util:eval-with-context($query, $context, false())
           return
               xqts:check-output($query, $result, $case),
           if (exists($case/catalog:expected-error)) then
               <test-case name="{$case/@name}" result="pass"/>
           else
               <test-case name="{$case/@name}" result="fail">
                   <exception>{$util:exception-message}</exception>
                   <query>{$query}</query>
               </test-case>
       )
   return $result
};

declare function xqts:finish($result as element()) as empty() {
    let $passed := count($result//test-case[@result = 'pass'])
    let $failed := count($result//test-case[@result = 'fail'])
    return (
        update value $result/@passed with xs:int($passed),
        update value $result/@failed with xs:int($failed)
    )
};

declare function xqts:run-single-test-case($case as element(catalog:test-case),
    $resultRoot as element()?) as empty() {
    let $result := xqts:run-test-case($case)
    return
        update insert $result into $resultRoot
};

declare function xqts:run-test-group($group as element(catalog:test-group)) as empty() {
    (: Create the collection hierarchy for this group and get the results.xml doc to
        append to. :)
    let $resultsDoc := xqts:create-collections($group)
    return (
        (: Execute the test cases :)
        for $test in $group/catalog:test-case
        let $log := util:log("DEBUG", ("Running test case: ", string($test/@name)))
        return
            xqts:run-single-test-case($test, $resultsDoc/test-result),
        xqts:finish($resultsDoc/test-result),
        (: Execute tests in child groups :)
        for $childGroup in $group/catalog:test-group
        let $log := util:log("DEBUG", ("Entering group: ", string($childGroup/@name)))
        return
            xqts:run-test-group($childGroup)
    )
};

declare function xqts:test-single($name as xs:string) as element() {
    let $test := //catalog:test-case[@name = $name]
    return
        if ($test) then
            let $resultsDoc := xqts:create-collections($test/parent::catalog:test-group)
            let $dummy := xqts:run-single-test-case($test, $resultsDoc/test-result)
            return
                $resultsDoc/test-result/test-case
        else
            util:log("WARN", ("Test case not found: ", $name))
};

declare function xqts:test-group($groupName as xs:string) as empty() {
    let $group := //catalog:test-group[@name = $groupName]
    return
        xqts:run-test-group($group)
};

declare function xqts:test-all() as empty() {
    for $test in /catalog:test-suite/catalog:test-group
    return
        xqts:test-group($test/@name)
};

declare function xqts:get-input-value($input as element(catalog:input-file)) as item()* {
   if ($input eq "emptydoc") then
       ()
   else (
       let $source := root($input)//catalog:source[@ID = $input/text()]
       return
           if (empty($source)) then
               concat("no input found: ", $input/text())
           else
               doc(concat("/db/XQTS/", $source/@FileName))
   )
};

(: xqts:test-single("Axes066-2") :)
xqts:test-group("Axes")
(: xqts:test-all(), :)

declare namespace xqts="http://exist-db.org/xquery/xqts";
declare namespace catalog="http://www.w3.org/2005/02/query-test-XQTSCatalog";

import module namespace util="http://exist-db.org/xquery/util";
import module namespace xdb="http://exist-db.org/xquery/xmldb";
import module namespace xdiff="http://exist-db.org/xquery/xmldiff";

(:~ ----------------------------------------------------------------------------------------
     W3C XQuery Test Suite

     This is the main module for running the XQTS on eXist. You can either
     run the whole test suite, a specific test group or a single test case.

     Setup:

     * Make sure the XmlDiff module is registered in conf.xml

     * Change the $xqts:XQTS_HOME variable below to point to the directory into
     which you unzipped the XQTS sources.

     * Create a collection /db/XQTS in the database.

     * From the XQTS directory, upload XQTSCatalog.xml into the created
     collection.

     * Upload the "TestSources" directory so the source docs can be found
     in /db/XQTS/TestSources.

     * Run this script with the client.
     ------------------------------------------------------------------------------------------- :)
declare variable $xqts:XQTS_HOME { "file:///d:/Data/XQTS/" };

declare function xqts:initialize() as empty() {
    let $output-coll := xdb:create-collection("/db/XQTS", "test-results")
    let $dummy := xdb:store("/db/XQTS/test-results", "results.xml", <test-result failed="0" passed="0"/>)
    return ()
};

declare function xqts:get-query($case as element(catalog:test-case)) {
   let $query-name := $case//catalog:query/@name
   let $path := concat( $xqts:XQTS_HOME, "Queries/XQuery/", $case/@FilePath, $query-name, ".xq" )
   let $xq-string := util:file-read($path)
   return $xq-string
};

declare function xqts:print-result($test-name as xs:string, $passed as xs:boolean, $query as xs:string,
    $result as item()*, $expected as item()*, $case as element(catalog:test-case)) as element() {
    <test-case name="{$test-name}" result="{if ($passed) then 'pass' else 'fail'}">
    {
        if (not($passed)) then (
            <result>{$result}</result>,
            if ($expected instance of element() and count($expected/*) > 10) then
            	<expected truncated="">{$expected/*[position() < 10]}</expected>
            else
                <expected>{$expected}</expected>,
            (: element {$case/catalog:input-file/@variable} { xqts:getInputValue($case) }, :)
            <query>{$query}</query>
        ) else ()
    }
    </test-case>
};

declare function xqts:normalize-text($result as item()*) as xs:string {
    let $str := string-join($result, " ")
    return
        (: Remove leading and trailing whitespace :)
        replace(replace($str, "^\s+", ""), "\s+$", "")
};

declare function xqts:check-output($query as xs:string, $result as item()*, $case as element(catalog:test-case)) {
    let $output := $case/catalog:output-file[last()]
    return
        (: Comparison method: "Text" :)
        if ($output/@compare eq "Text") then
            let $text := util:file-read(concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                "/", $output/text()))
            let $test := xqts:normalize-text($text) eq xqts:normalize-text($result)
            return
                xqts:print-result($case/@name, $test, $query, $result, $text, $case)
        (: Comparison method: "XML" :)
        else if ($output/@compare eq "XML") then
            let $filePath := concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                $output/text())
            let $expected := doc(xdb:store("/db", "temp.xml", xs:anyURI($filePath), "text/xml"))
            let $test := xdiff:compare($expected, $result)
            return
                xqts:print-result($case/@name, $test, $query, $result, $expected, $case)
        (: Comparison method: "Fragment" :)
        else if ($output/@compare eq "Fragment") then
            let $filePath := concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath, $output/text())
            let $expectedFrag := util:file-read($filePath)
            let $xmlFrag := concat("<f>", $expectedFrag, "</f>")
            let $log := util:log("DEBUG", ("Frag stored: ", $xmlFrag))
            let $expected := doc(xdb:store("/db", "temp.xml", $xmlFrag, "text/xml"))
            let $test := xdiff:compare($expected, <f>{$result}</f>)
            return
                xqts:print-result($case/@name, $test, $query, $result, $expected, $case)
        (: Don't know how to compare :)
        else
            <error test="{$case/@name}">Unknown comparison method: {$output/@compare}.</error>
};

declare function xqts:run-test-case( $case as element(catalog:test-case)) as item()* {
   let $query := xqts:get-query($case)
   let $context :=
       <static-context>
       {
           for $input in $case/catalog:input-file
           return
               <variable name="{$input/@variable}">{xqts:get-input-value($input)}</variable>
       }
       </static-context>
   let $result :=
       util:catch("java.lang.Exception",
           let $result :=
               util:eval-with-context($query, $context, false())
           return
               xqts:check-output($query, $result, $case),
           if (exists($case/catalog:expected-error)) then
               <test-case name="{$case/@name}" result="pass"/>
           else
               <test-case name="{$case/@name}" result="fail">
                   <exception>{$util:exception-message}</exception>
                   <query>{$query}</query>
               </test-case>
       )
   return $result
};

declare function xqts:finish() as empty() {
    let $result := doc("/db/XQTS/test-results/results.xml")/test-result
    let $passed := count($result//test-case[@result = 'pass'])
    let $failed := count($result//test-case[@result = 'fail'])
    return (
        update value $result/@passed with xs:int($passed),
        update value $result/@failed with xs:int($failed)
    )
};

declare function xqts:run-single-test-case($case as element(catalog:test-case),
    $group as element()?) as empty() {
    let $result := xqts:run-test-case($case)
    return
        if ($group) then
            update insert $result into $group
        else
            update insert $result into doc("/db/XQTS/test-results/results.xml")/test-result
};

declare function xqts:run-test-group($group as element(catalog:test-group),
    $parent as element()?) as empty() {
    update insert <test-group name="{$group/@name}">{$group/catalog:GroupInfo}</test-group>
        into $parent,
    let $newGroup := $parent/test-group[last()]
    return (
        for $test in $group/catalog:test-case
        let $log := util:log("DEBUG", ("Running test case: ", string($test/@name)))
        return
            xqts:run-single-test-case($test, $newGroup),
        for $childGroup in $group/catalog:test-group
        let $log := util:log("DEBUG", ("Entering group: ", string($childGroup/@name)))
        return
            xqts:run-test-group($childGroup, $newGroup)
    )
};

declare function xqts:test-single($name as xs:string) as empty() {
    let $test := //catalog:test-case[@name = $name]
    return
        xqts:run-single-test-case($test, collection("/db/XQTS/test-results")/test-result)
};

declare function xqts:test-group($groupName as xs:string) as empty() {
    let $group := //catalog:test-group[@name = $groupName]
    return
        xqts:run-test-group($group, collection("/db/XQTS/test-results")/test-result)
};

declare function xqts:test-all() as empty() {
    for $test in /catalog:test-suite/catalog:test-group
    return
        xqts:test-group($test/@name)
};

declare function xqts:get-input-value($input as element(catalog:input-file)) as item()* {
   if ($input eq "emptydoc") then
       ()
   else (
       let $source := root($input)//catalog:source[@ID = $input/text()]
       return
           if (empty($source)) then
               concat("no input found: ", $input/text())
           else
               doc(concat("/db/XQTS/", $source/@FileName))
   )
};

xqts:initialize(),
(: xqts:test-single("Axes001"), :)
xqts:test-group("MinimalConformance"),
(: xqts:test-all(), :)
xqts:finish(),
doc("/db/XQTS/test-results/results.xml")


[ignore] it possible to have no setup element at test

svn path=/trunk/eXist/; revision=17333

xquery version "1.0";

module namespace t="http://exist-db.org/xquery/testing";

import module namespace xdb="http://exist-db.org/xquery/xmldb";
import module namespace xdiff="http://exist-db.org/xquery/xmldiff"
at "java:org.exist.xquery.modules.xmldiff.XmlDiffModule";

declare function t:setup-action($action) {
    typeswitch ($action)
        case element(create-collection) return
            xdb:create-collection($action/@parent, $action/@name)
        case element(store) return
			t:store($action)
		case element(store-files) return
            t:store-files($action)
        case element(remove-collection) return
            xdb:remove($action/@collection)
        case element(remove-document) return
            xdb:remove($action/@collection, $action/@name)
        default return
            ()
};

declare function t:store($action as element(store)) {
    let $type := if ($action/@type) then $action/@type/string() else "application/xml"
    let $data :=
		if ($action/*) then
			$action/*[1]
		else
			$action/string()
	return
        xdb:store($action/@collection, $action/@name, $data, $type)
};

declare function t:store-files($action as element(store-files)) {
    let $type := if ($action/@type) then $action/@type/string() else "application/xml"
    return
        xdb:store-files-from-pattern($action/@collection, $action/@dir, $action/@pattern, $type)
};

declare function t:setup($setup as element(setup)?) {
    for $action in $setup/*
    return
        t:setup-action($action)
};

declare function t:tearDown($tearDown as element(tearDown)?) {
    for $action in $tearDown/*
    return
        t:setup-action($action)
};

declare function t:declare-variable($var as element(variable)) as item()? {
    let $children := $var/*
    return
        if (empty($children)) then
            string-join($var/node(), '')
        else
            util:serialize($children, ())
};

declare function t:init-prolog($test as element(test)) {
	let $imports := $test/../imports
	let $vars :=
	    string-join(
        	for $var in $test/../variable
        	return
        	    concat("declare variable $", $var/@name, " := ", t:declare-variable($var), ";"),
            ""
        )
	return
		string-join(($imports, $vars, $test/../functions), '')
};

declare function t:test($result as item()*) {
    if ($result instance of xs:boolean) then
        $result
    else
        exists($result)
};

declare function t:run-test($test as element(test), $count as xs:integer) {
	let $context := t:init-prolog($test)
	let $null :=
	   if ($test/@trace eq 'yes') then
	       (system:clear-trace(), system:enable-tracing(true(), false()))
       else ()
    let $highlight-option := concat("highlight-matches=",
          if ($test/expected//@*[matches(., '^(\|{3}).*\1$')] and $test/expected//exist:match) then "both"
          else if ($test/expected//@*[matches(., '^(\|{3}).*\1$')]) then "attributes"
          else if ($test/expected//exist:match) then "elements"
          else "none"
          )
    let $serialize-options :=
      let $decls := ($test/../*[name() ne 'test']|$test/code)[matches(., 'declare[\- ]option(\(("|')|\s+)exist:serialize(\2,)?\s+("|').*?\4[;)]')]
      let $ops1 := $decls/replace(., "declare[\- ]option(\(("|')|\s+)exist:serialize(\2,)?\s+("|')(.*?)\4[;)]", "_|$5_")
      let $ops2 :=
        for $a in $ops1
        for $b in tokenize($a, '_')[starts-with(., '|')]
        return tokenize(substring-after($b, '|'), '\s+')
      return if (count($ops2[matches(., 'highlight-matches')]))
        then string-join($ops2, ' ')
        else string-join(($ops2, $highlight-option), ' ')
    let $queryOutput :=
		util:catch("*",
			util:eval(concat($context, $test/code/string()), false()),
			<error>Compilation error: {$util:exception-message}</error>
		)
	let $output := if ($test/@trace eq 'yes') then system:trace() else $queryOutput
    let $expanded :=
        if ($output instance of element(error)) then
            $output
        else if ($test/@serialize) then
            let $options := $test/@serialize
            let $serialized :=
                util:catch("*",
                    for $x in $output
                    return
                        util:serialize($x, $options),
                    <error>Serialization error: {$util:exception-message}</error>
                )
            return
                if ($serialized instance of element(error)) then
                    $serialized
                else
                    normalize-space(string-join($serialized, ' '))
		else if ($output instance of node()) then
        	util:expand($output, $serialize-options)
		else
			$output
    let $expected :=
        if ($test/@output eq 'text') then
            data($test/expected)
        else $test/expected/node()
    let $OK :=
        if ($test/error) then
            $expanded instance of element(error) and contains($expanded, $test/error)
        else if ($test/xpath) then
            t:test(t:xpath($output, $test/xpath))
        else if ($test/@output eq 'text') then
            let $asString :=
                if ($test/@serialize) then
                    $expanded
                else
                    normalize-space(string-join(for $x in $output return string($x),' '))
            return
                $asString eq normalize-space($expected)
        else
            let $xn := t:normalize($expanded)
            let $en := t:normalize($expected)
            return
        	   deep-equal($xn, $en)
    return
        <test n="{$count}" pass="{$OK}">
        { $test/@id }
        {
            if (not($OK)) then
                ($test/task, $test/expected, <result>{$expanded}</result>)
            else
                ()
        }
        </test>
};

declare function t:normalize($nodes as node()*) {
	for $node in $nodes return t:normalize-node($node)
};

declare function t:normalize-node($node as node()) {
	typeswitch ($node)
		case element() return
			element { node-name($node) } {
				$node/@*, for $child in $node/node() return t:normalize-node($child)
			}
		case text() return
			let $norm := normalize-space($node)
			return
				if (string-length($norm) eq 0) then () else $node
		default return
			$node
};

declare function t:xpath($output as item()*, $xpath as element()) {
    for $prefix in in-scope-prefixes($xpath)
    let $nsuri := namespace-uri-for-prefix($prefix, $xpath)
    return
        if ($prefix != 'xml') then
            util:declare-namespace($prefix, $nsuri)
        else (),
    let $expr := $xpath/string()
    return
        if (matches($expr, "^\s*/")) then
            util:eval(concat("$output", $expr))
        else
            util:eval($expr)
};

declare function t:run-testSet($set as element(TestSet), $id as xs:string?) {
    let $copy := util:expand($set)
    let $null := t:setup($copy/setup)
    let $tests :=
        if ($id) then
            $copy/test[@id = $id]
        else
            $copy/test[empty(@ignore) or @ignore = "no"]
    let $result := util:expand(
           <TestSet>
           {$copy/testName}
           {$copy/description}
           {
               for $test at $p in $tests
               return
                   t:run-test($test, $p)
           }
           </TestSet>
        )
    let $null := t:tearDown($copy/tearDown)
    return $result
};

declare function t:format-testResult($result) {
    let $formatted :=

{$result/testName}

{$result/description/p}

          {for $test in $result//test
           return

                    {$test/@n/.}
                    {$test/@pass/.}

          }

     return
        $formatted
};

xquery version "1.0";

module namespace t="http://exist-db.org/xquery/testing";

import module namespace xdb="http://exist-db.org/xquery/xmldb";
import module namespace xdiff="http://exist-db.org/xquery/xmldiff"
at "java:org.exist.xquery.modules.xmldiff.XmlDiffModule";

declare function t:setup-action($action) {
    typeswitch ($action)
        case element(create-collection) return
            xdb:create-collection($action/@parent, $action/@name)
        case element(store) return
			t:store($action)
		case element(store-files) return
            t:store-files($action)
        case element(remove-collection) return
            xdb:remove($action/@collection)
        case element(remove-document) return
            xdb:remove($action/@collection, $action/@name)
        default return
            ()
};

declare function t:store($action as element(store)) {
    let $type := if ($action/@type) then $action/@type/string() else "application/xml"
    let $data :=
		if ($action/*) then
			$action/*[1]
		else
			$action/string()
	return
        xdb:store($action/@collection, $action/@name, $data, $type)
};

declare function t:store-files($action as element(store-files)) {
    let $type := if ($action/@type) then $action/@type/string() else "application/xml"
    return
        xdb:store-files-from-pattern($action/@collection, $action/@dir, $action/@pattern, $type)
};

declare function t:setup($setup as element(setup)) {
    for $action in $setup/*
    return
        t:setup-action($action)
};

declare function t:tearDown($tearDown as element(tearDown)?) {
    for $action in $tearDown/*
    return
        t:setup-action($action)
};

declare function t:declare-variable($var as element(variable)) as item()? {
    let $children := $var/*
    return
        if (empty($children)) then
            string-join($var/node(), '')
        else
            util:serialize($children, ())
};

declare function t:init-prolog($test as element(test)) {
	let $imports := $test/../imports
	let $vars :=
	    string-join(
        	for $var in $test/../variable
        	return
        	    concat("declare variable $", $var/@name, " := ", t:declare-variable($var), ";"),
            ""
        )
	return
		string-join(($imports, $vars, $test/../functions), '')
};

declare function t:test($result as item()*) {
    if ($result instance of xs:boolean) then
        $result
    else
        exists($result)
};

declare function t:run-test($test as element(test), $count as xs:integer) {
	let $context := t:init-prolog($test)
	let $null :=
	   if ($test/@trace eq 'yes') then
	       (system:clear-trace(), system:enable-tracing(true(), false()))
       else ()
    let $highlight-option := concat("highlight-matches=",
          if ($test/expected//@*[matches(., '^(\|{3}).*\1$')] and $test/expected//exist:match) then "both"
          else if ($test/expected//@*[matches(., '^(\|{3}).*\1$')]) then "attributes"
          else if ($test/expected//exist:match) then "elements"
          else "none"
          )
    let $serialize-options :=
      let $decls := ($test/../*[name() ne 'test']|$test/code)[matches(., 'declare[\- ]option(\(("|')|\s+)exist:serialize(\2,)?\s+("|').*?\4[;)]')]
      let $ops1 := $decls/replace(., "declare[\- ]option(\(("|')|\s+)exist:serialize(\2,)?\s+("|')(.*?)\4[;)]", "_|$5_")
      let $ops2 :=
        for $a in $ops1
        for $b in tokenize($a, '_')[starts-with(., '|')]
        return tokenize(substring-after($b, '|'), '\s+')
      return if (count($ops2[matches(., 'highlight-matches')]))
        then string-join($ops2, ' ')
        else string-join(($ops2, $highlight-option), ' ')
    let $queryOutput :=
		util:catch("*",
			util:eval(concat($context, $test/code/string()), false()),
			<error>Compilation error: {$util:exception-message}</error>
		)
	let $output := if ($test/@trace eq 'yes') then system:trace() else $queryOutput
    let $expanded :=
        if ($output instance of element(error)) then
            $output
        else if ($test/@serialize) then
            let $options := $test/@serialize
            let $serialized :=
                util:catch("*",
                    for $x in $output
                    return
                        util:serialize($x, $options),
                    <error>Serialization error: {$util:exception-message}</error>
                )
            return
                if ($serialized instance of element(error)) then
                    $serialized
                else
                    normalize-space(string-join($serialized, ' '))
		else if ($output instance of node()) then
        	util:expand($output, $serialize-options)
		else
			$output
    let $expected :=
        if ($test/@output eq 'text') then
            data($test/expected)
        else $test/expected/node()
    let $OK :=
        if ($test/error) then
            $expanded instance of element(error) and contains($expanded, $test/error)
        else if ($test/xpath) then
            t:test(t:xpath($output, $test/xpath))
        else if ($test/@output eq 'text') then
            let $asString :=
                if ($test/@serialize) then
                    $expanded
                else
                    normalize-space(string-join(for $x in $output return string($x),' '))
            return
                $asString eq normalize-space($expected)
        else
            let $xn := t:normalize($expanded)
            let $en := t:normalize($expected)
            return
        	   deep-equal($xn, $en)
    return
        <test n="{$count}" pass="{$OK}">
        { $test/@id }
        {
            if (not($OK)) then
                ($test/task, $test/expected, <result>{$expanded}</result>)
            else
                ()
        }
        </test>
};

declare function t:normalize($nodes as node()*) {
	for $node in $nodes return t:normalize-node($node)
};

declare function t:normalize-node($node as node()) {
	typeswitch ($node)
		case element() return
			element { node-name($node) } {
				$node/@*, for $child in $node/node() return t:normalize-node($child)
			}
		case text() return
			let $norm := normalize-space($node)
			return
				if (string-length($norm) eq 0) then () else $node
		default return
			$node
};

declare function t:xpath($output as item()*, $xpath as element()) {
    for $prefix in in-scope-prefixes($xpath)
    let $nsuri := namespace-uri-for-prefix($prefix, $xpath)
    return
        if ($prefix != 'xml') then
            util:declare-namespace($prefix, $nsuri)
        else (),
    let $expr := $xpath/string()
    return
        if (matches($expr, "^\s*/")) then
            util:eval(concat("$output", $expr))
        else
            util:eval($expr)
};

declare function t:run-testSet($set as element(TestSet), $id as xs:string?) {
    let $copy := util:expand($set)
    let $null := t:setup($copy/setup)
    let $tests :=
        if ($id) then
            $copy/test[@id = $id]
        else
            $copy/test[empty(@ignore) or @ignore = "no"]
    let $result := util:expand(
           <TestSet>
           {$copy/testName}
           {$copy/description}
           {
               for $test at $p in $tests
               return
                   t:run-test($test, $p)
           }
           </TestSet>
        )
    let $null := t:tearDown($copy/tearDown)
    return $result
};

declare function t:format-testResult($result) {
    let $formatted :=

{$result/testName}

{$result/description/p}

          {for $test in $result//test
           return

                    {$test/@n/.}
                    {$test/@pass/.}

          }

     return
        $formatted
};


removed extra slash in displayed URL for care services request

module namespace page = 'http://basex.org/modules/web-page';

import module namespace csr_proc = "https://github.com/his-interop/openinfoman/csr_proc";
import module namespace csd_dm = "https://github.com/his-interop/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/his-interop/openinfoman/csd_webconf";

declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare default element  namespace   "urn:ihe:iti:csd:2013";

declare variable $page:csd_docs := csd_dm:registered_documents($csd_webconf:db);

declare
  %rest:path("/CSD/csr/{$name}/careServicesRequest")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST("{$careServicesRequest}")
  function page:csr($name,$careServicesRequest)
{
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
 csr_proc:process_CSR($csd_webconf:db,$careServicesRequest/careServicesRequest,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare updating
  %rest:path("/CSD/csr/{$name}/careServicesRequest/update")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST("{$careServicesRequest}")
  function page:csr_updating($name,$careServicesRequest)
{
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
 csr_proc:process_updating_CSR($csd_webconf:db,$careServicesRequest/careServicesRequest,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr/{$name}/adhoc")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST
  %rest:form-param("adhoc","{$adhoc}")
  %rest:form-param("content", "{$content}","application/xml")
function page:adhoc($name,$adhoc,$content) {
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
let  $adhoc_doc := csr_proc:create_adhoc_doc(string($adhoc),$content)
  return  csr_proc:process_CSR($csd_webconf:db, $adhoc_doc,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr")
  %rest:GET
  %output:method("xhtml")
  function page:csr_list()
{
let $response := page:endpoints()
return page:wrapper($response)
};

declare function page:wrapper($requests) {

    <link href="{$csd_webconf:baseurl}static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="{$csd_webconf:baseurl}static/bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>


Change github path to reflect new situation

xquery version "3.1";

(:~
 : Test fn:unparsed-text and friends
 :)
module namespace upt="http://exist-db.org/xquery/test/unparsed-text";

import module namespace system="http://exist-db.org/xquery/system";
import module namespace test="http://exist-db.org/xquery/xqsuite" at "resource:org/exist/xquery/lib/xqsuite/xqsuite.xql";
import module namespace xmldb="http://exist-db.org/xquery/xmldb";

declare
    %test:setUp
function upt:store() {
    let $col := xmldb:create-collection("/db", "test-unparsed-text")
    return (
        xmldb:store($col, "test.txt", "Hello
world!
Hello
world!", "application/octet-stream"),
        xmldb:store($col, "test.xml", "
Hello world!
", "application/xml")
    )
};

declare
    %test:tearDown
function upt:cleanup() {
    xmldb:remove("/db/test-unparsed-text")
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertXPath("contains($result, 'eXist')")
function upt:unparsed-text-from-url() {
    unparsed-text("https://raw.githubusercontent.com/eXist-db/exist/develop/src/test/xquery/README")
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertXPath("contains($result, '----')")
function upt:unparsed-text-lines-from-url() {
    unparsed-text-lines("https://raw.githubusercontent.com/eXist-db/exist/develop/src/test/xquery/README")[2]
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertEquals(6)
function upt:unparsed-text-lines-from-url-count() {
    count(unparsed-text-lines("https://raw.githubusercontent.com/eXist-db/exist/develop/src/test/xquery/README"))
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertXPath("contains($result, 'eXist')")
function upt:unparsed-text-from-url-encoding() {
    unparsed-text("https://raw.githubusercontent.com/eXist-db/exist/develop/src/test/xquery/README", "UTF-8")
};

declare
    %test:assertEquals("Hello
world!
Hello
world!")
function upt:unparsed-text-from-db() {
    unparsed-text("/db/test-unparsed-text/test.txt")
};

declare
    %test:assertEquals("Hello
world!
Hello
world!")
function upt:unparsed-text-from-db-full() {
    unparsed-text("xmldb:exist:///db/test-unparsed-text/test.txt")
};

declare
    %test:assertEquals("Hello", "world!", "Hello", "world!")
function upt:unparsed-text-lines-from-db() {
    unparsed-text-lines("/db/test-unparsed-text/test.txt")
};

declare
    %test:assertEquals("
Hello world!
")
function upt:unparsed-text-from-db-xml() {
    unparsed-text("/db/test-unparsed-text/test.xml")
};

declare
    %test:assertEquals(26436)
function upt:unparsed-text-from-file-dba() {
    let $home := translate(system:get-exist-home(), "\", "/")
    let $url := ``[file://`{$home}`/LICENSE]``
    return
        string-length(unparsed-text($url))
};

declare
    %test:assertEquals(504)
function upt:unparsed-text-lines-from-file-dba() {
    let $home := translate(system:get-exist-home(), "\", "/")
    let $url := ``[file://`{$home}`/LICENSE]``
    return
        count(unparsed-text-lines($url))
};

declare
    %test:assertError("FOUT1170")
function upt:unparsed-text-from-file-not-allowed() {
    system:as-user("guest", "guest", unparsed-text("file:///etc/passwd"))
};

declare
    %test:assertError("FOUT1170")
function upt:fragment-identifier() {
    unparsed-text-lines("http://www.example.org/#fragment")
};

declare
    %test:assertError("FOUT1170")
function upt:fragment-identifier-encoding() {
    unparsed-text("http://www.example.org/#fragment", "UTF-8")
};

declare
    %test:assertError("FOUT1170")
function upt:invalid-uri() {
    unparsed-text-lines("http://www.example.org/%gg")
};

declare
    %test:assertError("FOUT1170")
function upt:invalid-uri2() {
    unparsed-text-lines(":/")
};

declare
    %test:assertError("FOUT1170")
function upt:non-existant() {
    unparsed-text-lines("http://www.w3.org/fots/unparsed-text/does-not-exist.txt")
};

declare
    %test:assertError("FOUT1170")
function upt:unsupported-scheme() {
    fn:unparsed-text-lines("surely-nobody-supports-this:/path.txt")
};

declare
    %test:assertError("FOUT1170")
function upt:windows-path() {
    unparsed-text-lines("C:\file-might-exist.txt", "utf-8")
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertTrue
function upt:unparsed-text-available-from-url() {
    unparsed-text-available("https://raw.githubusercontent.com/eXist-db/exist/develop/src/test/xquery/README")
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertTrue
function upt:unparsed-text-available-from-url-encoding() {
    unparsed-text-available("https://raw.githubusercontent.com/eXist-db/exist/develop/src/test/xquery/README", "UTF-8")
};

declare
    %test:assertTrue
function upt:unparsed-text-available-from-db() {
    unparsed-text-available("/db/test-unparsed-text/test.txt")
};

declare
    %test:assertTrue
function upt:unparsed-text-available-from-db-full() {
    unparsed-text-available("xmldb:exist:///db/test-unparsed-text/test.txt")
};

declare
    %test:assertTrue
function upt:unparsed-text-available-from-db-xml() {
    unparsed-text-available("/db/test-unparsed-text/test.xml")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-fragment-identifier() {
    unparsed-text-available("http://www.example.org/#fragment")
};

declare
    %test:assertFalse
function upt:fragment-identifier-encoding() {
    unparsed-text-available("http://www.example.org/#fragment", "UTF-8")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-invalid-uri() {
    unparsed-text-available("http://www.example.org/%gg")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-invalid-uri2() {
    unparsed-text-available(":/")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-non-existant() {
    unparsed-text-available("http://www.w3.org/fots/unparsed-text/does-not-exist.txt")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-unsupported-scheme() {
    fn:unparsed-text-available("surely-nobody-supports-this:/path.txt")
};

xquery version "3.1";

(:~
 : Test fn:unparsed-text and friends
 :)
module namespace upt="http://exist-db.org/xquery/test/unparsed-text";

import module namespace system="http://exist-db.org/xquery/system";
import module namespace test="http://exist-db.org/xquery/xqsuite" at "resource:org/exist/xquery/lib/xqsuite/xqsuite.xql";
import module namespace xmldb="http://exist-db.org/xquery/xmldb";

declare
    %test:setUp
function upt:store() {
    let $col := xmldb:create-collection("/db", "test-unparsed-text")
    return (
        xmldb:store($col, "test.txt", "Hello
world!
Hello
world!", "application/octet-stream"),
        xmldb:store($col, "test.xml", "
Hello world!
", "application/xml")
    )
};

declare
    %test:tearDown
function upt:cleanup() {
    xmldb:remove("/db/test-unparsed-text")
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertXPath("contains($result, 'eXist')")
function upt:unparsed-text-from-url() {
    unparsed-text("https://raw.githubusercontent.com/eXist-db/exist/develop/test/src/xquery/README")
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertXPath("contains($result, '----')")
function upt:unparsed-text-lines-from-url() {
    unparsed-text-lines("https://raw.githubusercontent.com/eXist-db/exist/develop/test/src/xquery/README")[2]
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertEquals(6)
function upt:unparsed-text-lines-from-url-count() {
    count(unparsed-text-lines("https://raw.githubusercontent.com/eXist-db/exist/develop/test/src/xquery/README"))
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertXPath("contains($result, 'eXist')")
function upt:unparsed-text-from-url-encoding() {
    unparsed-text("https://raw.githubusercontent.com/eXist-db/exist/develop/test/src/xquery/README", "UTF-8")
};

declare
    %test:assertEquals("Hello
world!
Hello
world!")
function upt:unparsed-text-from-db() {
    unparsed-text("/db/test-unparsed-text/test.txt")
};

declare
    %test:assertEquals("Hello
world!
Hello
world!")
function upt:unparsed-text-from-db-full() {
    unparsed-text("xmldb:exist:///db/test-unparsed-text/test.txt")
};

declare
    %test:assertEquals("Hello", "world!", "Hello", "world!")
function upt:unparsed-text-lines-from-db() {
    unparsed-text-lines("/db/test-unparsed-text/test.txt")
};

declare
    %test:assertEquals("
Hello world!
")
function upt:unparsed-text-from-db-xml() {
    unparsed-text("/db/test-unparsed-text/test.xml")
};

declare
    %test:assertEquals(26436)
function upt:unparsed-text-from-file-dba() {
    let $home := translate(system:get-exist-home(), "\", "/")
    let $url := ``[file://`{$home}`/LICENSE]``
    return
        string-length(unparsed-text($url))
};

declare
    %test:assertEquals(504)
function upt:unparsed-text-lines-from-file-dba() {
    let $home := translate(system:get-exist-home(), "\", "/")
    let $url := ``[file://`{$home}`/LICENSE]``
    return
        count(unparsed-text-lines($url))
};

declare
    %test:assertError("FOUT1170")
function upt:unparsed-text-from-file-not-allowed() {
    system:as-user("guest", "guest", unparsed-text("file:///etc/passwd"))
};

declare
    %test:assertError("FOUT1170")
function upt:fragment-identifier() {
    unparsed-text-lines("http://www.example.org/#fragment")
};

declare
    %test:assertError("FOUT1170")
function upt:fragment-identifier-encoding() {
    unparsed-text("http://www.example.org/#fragment", "UTF-8")
};

declare
    %test:assertError("FOUT1170")
function upt:invalid-uri() {
    unparsed-text-lines("http://www.example.org/%gg")
};

declare
    %test:assertError("FOUT1170")
function upt:invalid-uri2() {
    unparsed-text-lines(":/")
};

declare
    %test:assertError("FOUT1170")
function upt:non-existant() {
    unparsed-text-lines("http://www.w3.org/fots/unparsed-text/does-not-exist.txt")
};

declare
    %test:assertError("FOUT1170")
function upt:unsupported-scheme() {
    fn:unparsed-text-lines("surely-nobody-supports-this:/path.txt")
};

declare
    %test:assertError("FOUT1170")
function upt:windows-path() {
    unparsed-text-lines("C:\file-might-exist.txt", "utf-8")
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertTrue
function upt:unparsed-text-available-from-url() {
    unparsed-text-available("https://raw.githubusercontent.com/eXist-db/exist/develop/test/src/xquery/README")
};

declare
    %test:assumeInternetAccess("https://raw.githubusercontent.com")
    %test:assertTrue
function upt:unparsed-text-available-from-url-encoding() {
    unparsed-text-available("https://raw.githubusercontent.com/eXist-db/exist/develop/test/src/xquery/README", "UTF-8")
};

declare
    %test:assertTrue
function upt:unparsed-text-available-from-db() {
    unparsed-text-available("/db/test-unparsed-text/test.txt")
};

declare
    %test:assertTrue
function upt:unparsed-text-available-from-db-full() {
    unparsed-text-available("xmldb:exist:///db/test-unparsed-text/test.txt")
};

declare
    %test:assertTrue
function upt:unparsed-text-available-from-db-xml() {
    unparsed-text-available("/db/test-unparsed-text/test.xml")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-fragment-identifier() {
    unparsed-text-available("http://www.example.org/#fragment")
};

declare
    %test:assertFalse
function upt:fragment-identifier-encoding() {
    unparsed-text-available("http://www.example.org/#fragment", "UTF-8")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-invalid-uri() {
    unparsed-text-available("http://www.example.org/%gg")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-invalid-uri2() {
    unparsed-text-available(":/")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-non-existant() {
    unparsed-text-available("http://www.w3.org/fots/unparsed-text/does-not-exist.txt")
};

declare
    %test:assertFalse
function upt:unparsed-text-available-unsupported-scheme() {
    fn:unparsed-text-available("surely-nobody-supports-this:/path.txt")
};


Improved XQTS collected results. More to add...

svn path=/trunk/eXist/; revision=6551

xquery version "1.0";
(: $Id$ :)
declare namespace response="http://exist-db.org/xquery/response";
declare namespace catalog="http://www.w3.org/2005/02/query-test-XQTSCatalog";
declare namespace hack="http://exist-db.org/xquery/xqts/hacked-test-cases";
declare option exist:serialize "method=xml indent=yes";
declare option exist:output-size-limit "-1";

let $product-version := util:system-property("product-version")
let $product-build := util:system-property("product-build")
let $revision := system:get-revision()
let $test-suite := doc('/db/XQTS/XQTSCatalog.xml')/catalog:test-suite/@version
let $dummy := response:set-header("Content-Disposition", concat(
	"attachment; filename="results_XQTS-" , $test-suite , "_eXist-" ,
	$product-version , '_' , $product-build , ".xml"" ) )

let $cases := fn:collection(  '/db/XQTS' )//test-case
return
<test-suite-result xmlns="http://www.w3.org/2005/02/query-test-XQTSResult">
    <implementation name="eXist-db" version="{$product-version} (revision {$revision} {$product-build})" anonymous-result-column="false">

        <organization name="eXist Open Source Native XML database"  website="http://www.exist-db.org" anonymous="false"/>

        <submittor name="eXist XQTS testsuite runner" email="eXistAdmin@gmail.com"/>

        <description>

eXist is an Open Source native XML database featuring efficient,
                index-based XQuery processing, automatic indexing, extensions for full-text
                search,  XUpdate  support and tight integration with existing XML development tools.

        </description>

        <implementation-defined-items>

        </implementation-defined-items>

        <features>

        <feature name="Minimal Conformance" supported="true"/>
        <feature name="Schema Import" supported="false"/>
        <feature name="Schema Validation" supported="false"/>
        <feature name="Static Typing" supported="false"/>
        <feature name="Static Typing Extensions" supported="false"/>
        <feature name="Full Axis" supported="true"/>
        <feature name="Module" supported="true"/>
        <feature name="Serialization" supported="true"/>
        <feature name="Trivial XML Embedding" supported="false"/>
				  </features>

        <context-properties>
      <context-property name="Statically known namespaces" context-type="static"
      value="XQuery default augmented with xmlns:exist='http://exist.sourceforge.net/NS/exist' (unbound when the XQTS is run)"/>
      <context-property name="Default element/type namespace" context-type="static" value="XQuery default"/>
      <context-property name="Default function namespace" context-type="static"
      value="'http://www.w3.org/2005/xpath-functions' by default"/>
      <context-property name="In-scope schema types" context-type="static" value="N/A"/>
      <context-property name="In-scope element declarations" context-type="static" value="N/A"/>
      <context-property name="In-scope attribute declarations" context-type="static" value="N/A"/>
      <context-property name="In-scope variables" context-type="static" value="None"/>
      <context-property name="Context item static type" context-type="static" value="item()?"/>
      <context-property name="Function signatures" context-type="static" value="XQuery default"/>
      <context-property name="Statically known collations" context-type="static" value="See http://exist.sourceforge.net/xquery.html#N10676"/>
      <context-property name="Default collation" context-type="static" value="http://www.w3.org/2005/xpath-functions/collation/codepoint"/>
      <context-property name="Construction mode" context-type="static"/>
      <context-property name="Ordering mode" context-type="static"/>
      <context-property name="Default order for empty sequences" context-type="static"/>
      <context-property name="Boundary-space policy" context-type="static"/>
      <context-property name="Copy-namespaces mode" context-type="static"/>
      <context-property name="Base URI" context-type="static" value="'/db' by default"/>
      <context-property name="Statically known documents" context-type="static" value="all documents in the database by default"/>
      <context-property name="Statically known collections" context-type="static" value="all collections in the database by default"/>
      <context-property name="Statically known default collection type" context-type="static"/>
      <context-property name="Context item" context-type="dynamic"/>
      <context-property name="Context position" context-type="dynamic"/>
      <context-property name="Context size" context-type="dynamic"/>
      <context-property name="Variable values" context-type="dynamic"/>
      <context-property name="Function implementations" context-type="dynamic"/>
      <context-property name="Current dateTime" context-type="dynamic" value="Settable using an option, a pragma, or API"/>
      <context-property name="Implicit timezone" context-type="dynamic" value="Settable using an option, a pragma, or API"/>
      <context-property name="Available documents" context-type="dynamic" value="Any document in the database for which the user has required permissions + external URLs"/>
      <context-property name="Available collections" context-type="dynamic" value="Any collection in the database for which the user has required permissions"/>
      <context-property name="Default collection" context-type="dynamic" value="all collections"/>
        </context-properties>

    </implementation>

    <syntax>XQuery</syntax>

    <test-run dateRun="{fn:current-dateTime()}">
        <test-suite version="{$test-suite}"/>
        <transformation>
        {
            if (empty(doc('/db/XQTS/hacked-tests.xml')/hack:test-cases/hack:test-case/hack:expected-result)) then

No unusual transformations.

            else

The following tests have been evaluated against results provided by other XQuery processors.
,

                    Test name	Reference software	Considered result
                    {
                        for $hackedTest in doc('/db/XQTS/hacked-tests.xml')/hack:test-cases/hack:test-case/hack:expected-result
                        return

                                {string($hackedTest/../@name)}
                                {string($hackedTest/@from)}
                                {string($hackedTest)}

                     }

        }
        </transformation>
        <comparison>
        {
            if (empty(doc('/db/XQTS/hacked-tests.xml')/hack:test-cases/hack:test-case/@compare)) then

No unusual comparisons

            else

The following tests have required a comparison method different from the standard one.
,

                    Test name	Comparison method
                    {
                        for $hackedTest in doc('/db/XQTS/hacked-tests.xml')/hack:test-cases/hack:test-case[@compare]
                        return

                                {$hackedTest/@name}
                                {$hackedTest/@compare}

                     }

,

UnnormalizedText : result text nodes are concatenated without introducing (normalized) spaces between them.
,

TextAsXML : result string is evaluated as if it were XML, then an XML comparison is done.

        }
        </comparison>
        <otherComments>

The test run took {let $b := for $a in $cases//@dateRun return xs:time($a)
return (max($b) - min($b)) div xs:dayTimeDuration('PT1S')} seconds.

        </otherComments>
    </test-run>

{
    for $case in $cases
    order by $case/@name
    return <test-case name="{$case/@name}" result="{$case/@result}" />
}
</test-suite-result>

xquery version "1.0";
(: $Id$ :)
declare namespace response="http://exist-db.org/xquery/response";
declare namespace empty="";
declare option exist:serialize "method=xml indent=yes";
declare option exist:output-size-limit "-1";

let $product-version := util:system-property("product-version")
let $product-build := util:system-property("product-build")
let $revision := system:get-revision()
let $test-suite := doc('/db/XQTS/XQTSCatalog.xml')/*:test-suite/@version
let $dummy := response:set-header("Content-Disposition", concat(
	"attachment; filename="results_XQTS-" , $test-suite , "_eXist-" ,
	$product-version , '_' , $product-build , ".xml"" ) )

let $cases := fn:collection(  '/db/XQTS' )//test-case
return
<test-suite-result xmlns="http://www.w3.org/2005/02/query-test-XQTSResult">
    <implementation name="eXist-db" version="{$product-version} (revision {$revision} {$product-build})" anonymous-result-column="false">

        <organization name="eXist Open Source Native XML database"  website="http://www.exist-db.org" anonymous="false"/>

        <submittor name="eXist XQTS testsuite runner" email="eXistAdmin@gmail.com"/>

        <description>

eXist is an Open Source native XML database featuring efficient,
                index-based XQuery processing, automatic indexing, extensions for full-text
                search,  XUpdate  support and tight integration with existing XML development tools.

        </description>

        <implementation-defined-items>

        </implementation-defined-items>

        <features>

        <feature name="Minimal Conformance" supported="true"/>
        <feature name="Schema Import" supported="false"/>
        <feature name="Schema Validation" supported="false"/>
        <feature name="Static Typing" supported="false"/>
        <feature name="Static Typing Extensions" supported="false"/>
        <feature name="Full Axis" supported="true"/>
        <feature name="Module" supported="true"/>
        <feature name="Serialization" supported="true"/>
        <feature name="Trivial XML Embedding" supported="false"/>
				  </features>

        <context-properties>

        </context-properties>

    </implementation>

    <syntax>XQuery</syntax>

    <test-run dateRun="{fn:current-dateTime()}">
        <test-suite version="{$test-suite}"/>
        <transformation>

No unusual transformations.

        </transformation>
        <comparison>

No unusual comparisons

        </comparison>
        <otherComments>

The test run took {let $b := for $a in $cases//@dateRun return xs:time($a)
return (max($b) - min($b)) div xs:dayTimeDuration('PT1S')} seconds.

        </otherComments>
    </test-run>

{
    for $case in $cases
    order by $case/@name
    return <test-case name="{$case/@name}" result="{$case/@result}" />
}
</test-suite-result>