use strict;
use warnings;
use HTML::TreeBuilder::LibXML;
use Test::More;
use Data::Dumper;
my $original_ok = eval 'use HTML::TreeBuilder::XPath; 1';
my $tests = 32;
$tests *= 2 if $original_ok;
plan tests => $tests;
my $HTML = q{
test
wassr
};
main('HTML::TreeBuilder::XPath') if $original_ok;
main('HTML::TreeBuilder::LibXML');
sub main {
my $klass = shift;
diag $klass;
_simple($klass);
_no_eof($klass);
_look_down($klass);
_id($klass);
_attr($klass);
}
sub _simple {
my $klass = shift;
my $tree = $klass->new;
$tree->store_comments(1);
$tree->parse(q{
test
wassr
twitter
});
$tree->eof;
my @nodes = $tree->findnodes('//a');
is scalar(@nodes), 3;
is $nodes[0]->attr('href'), 'http://wassr.jp/';
ok !$nodes[0]->isTextNode;
is $nodes[0]->string_value, 'wassr';
is $nodes[0]->as_text, 'wassr';
is strip($nodes[0]->as_XML), 'wassr';
is strip($nodes[0]->clone->as_XML), 'wassr';
is strip($nodes[0]->as_HTML), 'wassr';
is $nodes[0]->tag, 'a';
my %attr = $nodes[0]->all_external_attr;
is_deeply \%attr, { href => "http://wassr.jp/" };
is_deeply [ $nodes[0]->all_external_attr_names ], [ 'href' ];
is $nodes[1]->attr('href'), 'http://mixi.jp/';
is $nodes[2]->as_trimmed_text, 'twitter';
is $nodes[2]->as_text_trimmed, 'twitter';
$nodes[1]->delete;
like strip($tree->as_HTML), qr{testwassr\s+ok.\s+
twitter\s*};
is $tree->findvalue('//a[@href="http://wassr.jp/"]/@href'), 'http://wassr.jp/';
is(($tree->findnodes('//comment()'))[0]->getValue, ' Test comment ');
$tree = $tree->delete;
}
sub _no_eof {
my $klass = shift;
my $tree = $klass->new;
$tree->parse(q{
test
wassr
});
my @nodes = $tree->findnodes('//a');
is scalar(@nodes), 2;
$tree = $tree->delete;
}
sub _look_down {
my $klass = shift;
my $tree = $klass->new;
$tree->parse(q{
test
wassr
});
$tree->eof;
{
my @nodes = $tree->look_down('_tag' => 'a');
is scalar(@nodes), 2;
is $nodes[0]->attr('href'), 'http://wassr.jp/';
}
{
my @nodes = $tree->look_down(href => qr/mixi/);
is scalar(@nodes), 1;
is $nodes[0]->attr('href'), 'http://mixi.jp/';
}
{
my @nodes = $tree->look_down('_tag' => 'a', sub { $_[0]->attr('href') =~ /mixi/ });
is scalar(@nodes), 1;
is $nodes[0]->attr('href'), 'http://mixi.jp/';
}
{
my $none = $tree->look_down('_tag' => 'a', sub { 0 });
ok !defined $none, "none because sub ref returns 0";
}
$tree = $tree->delete;
}
sub _id {
my $klass = shift;
my $tree = $klass->new;
$tree->parse($HTML);
$tree->eof;
my ($a) = $tree->look_down('_tag' => 'a');
is $a->id, undef;
$a->id("OK");
is $a->id, 'OK';
is strip($a->as_HTML), 'wassr';
$a->id(undef);
is strip($a->as_HTML), 'wassr';
$tree = $tree->delete;
}
sub _attr {
my $klass = shift;
my $tree = $klass->new;
$tree->parse($HTML);
$tree->eof;
my ($a) = $tree->look_down('_tag' => 'a');
is $a->attr('href'), 'http://wassr.jp/';
$a->attr('href', 'http://ficia.com/');
is strip($a->as_HTML), 'wassr';
$a->attr('href', undef);
is strip($a->as_HTML), 'wassr';
$tree = $tree->delete;
}
sub strip {
local $_ = shift;
s/\n$//g;
s/>\s+>