perl-XML-LibXML / t / 32xpc_variables.t

# -*- cperl -*-

use strict;
use warnings;

use Test;
BEGIN { plan tests => 35 };

use XML::LibXML;
use XML::LibXML::XPathContext;

my $doc = XML::LibXML->new->parse_string(<<'XML');
<foo><bar a="b">Bla</bar><bar/></foo>

my %variables = (
	'a' => XML::LibXML::Number->new(2),
	'b' => "b",

sub get_variable {
  my ($data, $name, $uri)=@_;
  return exists($data->{$name}) ? $data->{$name} : undef;

# $c: nodelist
$variables{c} = XML::LibXML::XPathContext->new($doc)->findnodes('//bar');
ok($variables{c}->size() == 2);
ok($variables{c}->get_node(1)->nodeName eq 'bar');

# $d: a single element node
$variables{d} = XML::LibXML::XPathContext->new($doc)->findnodes('/*')->pop;
ok($variables{d}->nodeName() eq 'foo');

# $e: a single text node
$variables{e} = XML::LibXML::XPathContext->new($doc)->findnodes('//text()');
ok($variables{e}->get_node(1)->data() eq 'Bla');

# $f: a single attribute node
$variables{f} = XML::LibXML::XPathContext->new($doc)->findnodes('//@*')->pop;
ok($variables{f}->nodeName() eq 'a');
ok($variables{f}->value() eq 'b');

# $f: a single document node
$variables{g} = XML::LibXML::XPathContext->new($doc)->findnodes('/')->pop;
ok($variables{g}->nodeType() == XML::LibXML::XML_DOCUMENT_NODE);

# test registerVarLookupFunc() and getVarLookupData()
my $xc = XML::LibXML::XPathContext->new($doc);
my $h1=$xc->getVarLookupData;
my $h2=\%variables;
ok("$h1" eq "$h2" );
ok($h1 eq $xc->getVarLookupData);
ok(\&get_variable eq $xc->getVarLookupFunc);

# test values returned by XPath queries
ok($xc->find('$a') == 2);
ok($xc->find('$b') eq "b");
ok($xc->findnodes('//@a[.=$b]')->size() == 1);
ok($xc->findnodes('//@a[.=$b]')->size() == 1);
ok($xc->findnodes('$c')->size() == 2);
ok($xc->findnodes('$c')->size() == 2);
ok($xc->findnodes('$c[@a="b"]')->size() == 1);
ok($xc->findnodes('$d')->size() == 1);
ok($xc->findnodes('$d/*')->size() == 2);
ok($xc->findvalue('$e') eq 'Bla');
ok($xc->findnodes('$c[@*=$f]')->size() == 1);
ok($xc->findvalue('$f') eq 'b');
ok($xc->findnodes('$f')->pop->nodeName eq 'a');

# unregiser variable lookup
eval { $xc->find('$a') };

my $foo='foo';
$xc->registerVarLookupFunc(sub {},$foo);
ok($xc->getVarLookupData eq 'foo');
ok($xc->getVarLookupData eq 'foo');
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.