#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML qw( );
use Test::More;
sub _u($) { my $s = shift; utf8::upgrade($s); $s }
sub _d($) { my $s = shift; utf8::downgrade($s, 1); $s }
sub gen_text_node {
my ($encoding, $text) = @_;
my $doc = XML::LibXML::Document->new("1.0", $encoding);
my $root = $doc->createElement("root");
$doc->setDocumentElement($root);
$root->appendText($text);
return $doc->toString();
}
sub parse_text_node {
my ($xml) = @_;
my $parser = XML::LibXML->new();
my $doc = $parser->parse_string($xml);
return $doc->documentElement->textContent();
}
sub gen_attr_node {
my ($encoding, $text) = @_;
my $doc = XML::LibXML::Document->new("1.0", $encoding);
my $root = $doc->createElement("root");
$doc->setDocumentElement($root);
$root->setAttribute('attr', $text);
return $doc->toString();
}
sub parse_attr_node {
my ($xml) = @_;
my $parser = XML::LibXML->new();
my $doc = $parser->parse_string($xml);
return $doc->documentElement->getAttribute('attr');
}
{
my @encodings = qw( UTF-8 cp437 UTF-16le );
plan tests => 1+2*@encodings*2;
my $text = "\xC9\xE9";
my $text_u = _u $text;
my $text_d = _d $text;
is($text_d, $text_u, "assert(\$text_d eq \$text_u)");
for (
[ "upgraded" => $text_u ],
[ "downgraded" => $text_d ],
) {
my ($format, $text) = @$_;
for my $encoding (@encodings) {
{
my $xml = gen_text_node($encoding, $text);
if (!eval {
my $got = parse_text_node($xml);
is(sprintf("%vX", $got), sprintf("%vX", $text), "Round trip $format text node using $encoding");
return 1;
}) {
fail("Round trip $format text node using $encoding")
or diag( ( split /^/, $@ )[0] );
}
}
{
my $xml = gen_attr_node($encoding, $text);
if (!eval {
my $got = parse_attr_node($xml);
is(sprintf("%vX", $got), sprintf("%vX", $text), "Round trip $format attribute using $encoding");
return 1;
}) {
fail("Round trip $format attribute using $encoding")
or diag( ( split /^/, $@ )[0] );
}
}
}
}
}