#!/use/bin/perl
use strict;
use warnings;
use Test::More tests => 16;
use File::Temp qw(tempfile);
use XML::Hash::XS 'hash2xml';
our $data;
our $xml = qq{};
{
is
$data = hash2xml( { node1 => [ 'value1', { node2 => 'value2' } ] } ),
qq{$xml\nvalue1value2},
'default',
;
}
{
is
$data = hash2xml( { node3 => 'value3', node1 => 'value1', node2 => 'value2' }, canonical => 1 ),
qq{$xml\nvalue1value2value3},
'canonical',
;
}
{
is
$data = hash2xml( { node1 => [ 'value1', { node2 => 'value2' } ] }, indent => 2 ),
<<"EOT",
$xml
value1
value2
EOT
'indent',
;
}
{
is
$data = hash2xml( { node1 => [ 1, '2', '2' + 1 ] } ),
qq{$xml\n123},
'integer, string, integer + string',
;
}
{
my $x = 1.1;
my $y = '2.2';
is
$data = hash2xml( { node1 => [ $x, $y, $y + $x ] } ),
qq{$xml\n1.12.23.3},
'double, string, double + string',
;
}
{
is
$data = hash2xml( { 1 => 'value1' } ),
qq{$xml\n<_1>value1},
'quote tag name',
;
}
{
is
$data = hash2xml( { node1 => \'value1' } ),
qq{$xml\nvalue1},
'scalar reference',
;
}
{
is
$data = hash2xml( { node1 => sub { 'value1' } } ),
qq{$xml\nvalue1},
'code reference',
;
}
{
is
$data = hash2xml( { node1 => sub { undef } } ),
qq{$xml\n},
'code reference with undef',
;
}
{
is
$data = hash2xml( { node1 => sub { [ 'value1' ] } } ),
qq{$xml\nvalue1},
'code reference with array',
;
}
{
is
$data = hash2xml( { node1 => 'Тест' }, encoding => 'cp1251' ),
qq{\n\322\345\361\362},
'encoding support',
;
}
{
is
$data = hash2xml( { node1 => '&<>' } ),
qq{$xml\n&<>},
'escaping',
;
}
{
my $fh = tempfile();
hash2xml( { node1 => 'value1' }, output => $fh );
seek($fh, 0, 0);
{ local $/; $data = <$fh> }
is
$data,
qq{$xml\nvalue1},
'filehandle output',
;
}
{
my $data = '';
tie *STDOUT, "Trapper", \$data;
hash2xml( { node1 => 'value1' }, output => \*STDOUT );
untie *STDOUT;
is
$data,
qq{$xml\nvalue1},
'tied filehandle output',
;
}
{
is
$data = hash2xml(
{
node1 => 'value1"',
node2 => 'value2&',
node3 => { node31 => 'value31' },
node4 => [ { node41 => 'value41' }, { node42 => 'value42' } ],
node5 => [ 51, 52, { node53 => 'value53' } ],
node6 => {},
node7 => [],
},
use_attr => 1,
canonical => 1,
indent => 2,
),
<<"EOT",
$xml
51
52
EOT
'use attributes',
;
}
{
my $o = TestObject->new();
is
$data = hash2xml(
{ object => $o },
),
qq{$xml\n},
'object',
;
}
package TestObject;
sub new {
return bless [], shift;
}
sub toString {
return 'value1';
}
package Trapper;
sub TIEHANDLE {
my ($class, $str) = @_;
return bless [$str], $class;
}
sub WRITE {
my ($self, $buf, $len, $offset) = @_;
$len ||= length($buf);
$offset ||= 0;
${$self->[0]} .= substr($buf, $offset, $len);
return $len;
}
sub PRINT {
${shift->[0]} .= join('', @_);
}