parse-wormedit: level rendering
[wormy.git] / t / parser.t
1 #!/usr/bin/env perl
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Data::Dumper;
8
9 plan tests => 11;
10
11 use_ok('Parse::Binary::Nested');
12
13 my @example = (
14         foos => [
15                 'C',
16                 message => 'Z*',
17                 period  => 'a',
18         ],
19         trail => 'a*',
20 );
21 my $testdata = "\2foo\0!\0.rest";
22 my $testresult = {
23         foos => [
24                 {message => 'foo', period => '!'},
25                 {message => '',    period => '.'},
26         ],
27         trail => 'rest',
28 };
29
30 my $parser = Parse::Binary::Nested->new(\@example);
31 ok($parser, 'new object');
32 is_deeply($parser->unpackf($testdata), $testresult, 'object unpackf');
33
34 Parse::Binary::Nested->import('unpackf');
35 is_deeply(
36         unpackf(\@example, $testdata),
37         $testresult,
38         'unprepared unpackf'
39 );
40
41 my @commonargs = ('cxaXv', "\1\2hi\0");
42 is_deeply(
43         [ values %{ unpackf(@commonargs) } ],
44         [[ unpack($commonargs[0], $commonargs[1]) ]],
45         'unpack compatibility'
46 );
47
48 is_deeply(
49         unpackf([ lstr => 'C/a3', rest => 'a*' ], "\2quux"),
50         { lstr => 'qu', rest => 'x' },
51         'length string'
52 );
53
54 is_deeply(
55         unpackf([ ignoreme => 'x2X', value => 'xC' ], "\0\1\2"),
56         { value => 2 },
57         'empty values'
58 );
59
60 is_deeply(
61         unpackf([
62                 begin => 'c',
63                 asciiz => ['?0', lead => 'v', string => 'Z*'],
64                 end   => 'c',
65         ], "\377\1\0Hi\0\2\0zer0\0\0\376"),
66         {
67                 begin => -1,
68                 asciiz => [
69                         { lead => 1, string => 'Hi' },
70                         { lead => 2, string => 'zer0' },
71                 ],
72                 end => -2,
73         },
74         'zero-terminated group'
75 );
76
77 my $looptest = Parse::Binary::Nested->new([
78         begin => 'xc',
79         loop  => ['?1', lead => 'c', string => 'Z*'],
80         end   => '=.',
81 ]);
82 is_deeply(
83         $looptest->unpackf("\0\1\0Hello\0\377bye"),
84         {
85                 begin => 1,
86                 loop => [
87                         { lead =>  0, string => 'Hello' },
88                         { lead => -1, string => 'bye' },
89                 ],
90                 end => 15,
91         },
92         'unterminated group'
93 );
94 is_deeply(
95         $looptest->unpackf("\0\1\1trailing"),
96         {
97                 begin => 1,
98                 end => 3,
99         },
100         'preterminated group'
101 );
102
103 is_deeply(
104         unpackf([
105                 loop => ['?0', byte => 'C'],
106         ], "\1\2\3"),
107         {
108                 loop => [map { {byte => $_} } 1..3],
109         },
110         'last byte in unterminated loop'
111 );
112