Debian Codegraph @

t/18-oop-lifetime.t

raw
1 use strict;
2 use warnings;
3
4 use Test::More tests => 6;
5
6 use XML::Hash::XS qw();
7
8 my $xml = '<root><a>one</a><b>two</b></root>';
9
10 {
11 my $conv;
12 {
13 my $filter = '/root/a';
14 $conv = XML::Hash::XS->new(filter => $filter, keep_root => 1);
15 }
16
17 is_deeply(
18 [ map { $conv->xml2hash($xml) } 1 .. 3 ],
19 [
20 [ { a => 'one' } ],
21 [ { a => 'one' } ],
22 [ { a => 'one' } ],
23 ],
24 'object filter remains valid across repeated calls',
25 );
26 }
27
28 {
29 my @nodes;
30 my $cb = sub { push @nodes, $_[0] };
31 my $conv = XML::Hash::XS->new(
32 filter => '/root/a',
33 keep_root => 1,
34 cb => $cb,
35 );
36 undef $cb;
37
38 $conv->xml2hash($xml) for 1 .. 3;
39
40 is_deeply(
41 \@nodes,
42 [
43 { a => 'one' },
44 { a => 'one' },
45 { a => 'one' },
46 ],
47 'object callback remains valid across repeated calls',
48 );
49 }
50
51 {
52 my (@base, @override);
53 my $conv = XML::Hash::XS->new(
54 filter => '/root/a',
55 keep_root => 1,
56 cb => sub { push @base, $_[0] },
57 );
58
59 $conv->xml2hash($xml);
60 $conv->xml2hash(
61 $xml,
62 filter => '/root/b',
63 cb => sub { push @override, $_[0] },
64 );
65 $conv->xml2hash($xml);
66
67 is_deeply(
68 \@base,
69 [ { a => 'one' }, { a => 'one' } ],
70 'per-call override preserves object callback',
71 );
72 is_deeply(\@override, [ { b => 'two' } ], 'per-call override uses replacement callback');
73 }
74
75 {
76 my $output = '';
77 my $conv;
78
79 {
80 open(my $fh, '>', \$output) or die "Can't open scalar filehandle: $!";
81 $conv = XML::Hash::XS->new(output => $fh, root => 'doc', xml_decl => 0);
82 }
83
84 $conv->hash2xml({ item => 'value' });
85
86 is($output, '<doc><item>value</item></doc>', 'object retains output filehandle');
87 }
88
89 {
90 my $output = '';
91 open(my $fh, '>', \$output) or die "Can't open scalar filehandle: $!";
92 local $XML::Hash::XS::output = $fh;
93
94 XML::Hash::XS::hash2xml({ item => 'value' }, root => 'doc', xml_decl => 0);
95
96 is($output, '<doc><item>value</item></doc>', 'global output filehandle is normalized');
97 }