Debian Codegraph @

t/11-x2h_read.t

raw
1 package main;
2 use strict;
3 use warnings;
4
5 use Test::More tests => 6;
6 use Data::Dumper;
7 $Data::Dumper::Indent = 0;
8 $Data::Dumper::Sortkeys = 1;
9
10 use XML::Hash::XS 'xml2hash';
11 $XML::Hash::XS::keep_root = 0;
12
13 our $xml_decl_utf8 = qq{<?xml version="1.0" encoding="utf-8"?>};
14
15 {
16 is
17 Dumper(xml2hash('t/test.xml', keep_root => 1)),
18 Dumper({
19 root => {
20 attr1 => '1',
21 attr2 => '2',
22 item => ['1', '2', '3'],
23 node1 => 'value1',
24 node2 => {
25 attr1 => '1',
26 content => 'value2',
27 }
28 }
29 }),
30 'read from file',
31 ;
32 }
33
34 {
35 use utf8;
36 is
37 xml2hash('<root>Привет!</root>', buf_size => 2),
38 "Привет!",
39 'read from string with buf_size=2',
40 ;
41 }
42
43 {
44 use utf8;
45 is
46 xml2hash('<?xml version="1.0" encoding="utf-8"?><root>Привет!</root>', buf_size => 2),
47 "Привет!",
48 'read from string with buf_size=2 and xml decl',
49 ;
50 }
51
52 {
53 use utf8;
54 ## no critic (InputOutput::ProhibitBarewordFileHandles)
55 open(DATA, '<:encoding(UTF-8)', 't/test_utf8.xml') or die "Can't open file 't/test_utf8.xml'";
56 ## use critic
57 is
58 xml2hash(*DATA),
59 "Привет!",
60 'read from file handle',
61 ;
62 close DATA;
63 }
64
65 {
66 tie *DATA, 'MyReader', '<?xml version="1.0" encoding="utf-8"?><root>Привет!</root>';
67 use utf8;
68 is
69 xml2hash(*DATA, buf_size => 2),
70 "Привет!",
71 'read from tied handle',
72 ;
73 untie *DATA;
74 }
75
76 {
77 eval { xml2hash('t/test_null_terminated.xml') };
78 ok(!$@, 'read from the null-terminated file');
79 }
80
81 package MyReader;
82 use base 'Tie::Handle';
83
84 sub TIEHANDLE {
85 my ($class, $str) = @_;
86 bless {str => $str, pos => 0, len => length($str)}, $class;
87 }
88
89 sub READ {
90 my $bufref = \$_[1];
91 my ($self, undef, $len, $offset) = @_;
92
93 $offset ||= 0;
94
95 if (($self->{pos} + $len) > $self->{len}) {
96 $len = $self->{len} - $self->{pos};
97 }
98 if ($len > 0) {
99 $$bufref = substr($$bufref, 0, $offset) . substr($self->{str}, $self->{pos}, $len);
100 $self->{pos} += $len;
101 }
102 return $len;
103 }
104
105 sub WRITE {}
106 sub PRINT {}