File: 02expect.t

package info (click to toggle)
libparser-mgc-perl 0.22-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 536 kB
  • sloc: perl: 1,881; makefile: 2; sh: 1
file content (78 lines) | stat: -rw-r--r-- 1,824 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/perl

use v5.14;
use warnings;

use Test2::V0;

package TestParser {
   use base qw( Parser::MGC );

   sub parse_hello
   {
      my $self = shift;

      [ $self->expect( "hello" ), $self->expect( qr/world/ ) ];
   }

   sub parse_hex
   {
      my $self = shift;

      return hex +( $self->expect( qr/0x([0-9A-F]+)/i ) )[1];
   }

   sub parse_foo_or_bar
   {
      my $self = shift;

      return $self->maybe_expect( qr/foo/i ) ||
             $self->maybe_expect( qr/bar/i );
   }

   sub parse_numrange
   {
      my $self = shift;

      return [ ( $self->maybe_expect( qr/(\d+)(?:-(\d+))?/ ) )[1,2] ];
   }
}

my $parser = TestParser->new( toplevel => "parse_hello" );

is( $parser->from_string( "hello world" ),
   [ "hello", "world" ],
   '"hello world"' );

is( $parser->from_string( "  hello world  " ),
   [ "hello", "world" ],
   '"  hello world  "' );

is( dies { $parser->from_string( "goodbye world" ) },
   qq[Expected (?^u:hello) on line 1 at:\n] . 
   qq[goodbye world\n] . 
   qq[^\n],
   'Exception from "goodbye world" failure' );

$parser = TestParser->new( toplevel => "parse_hex" );

is( $parser->from_string( "0x123" ), 0x123, "Hex parser captures substring" );

$parser = TestParser->new( toplevel => "parse_foo_or_bar" );

is( $parser->from_string( "Foo" ), "Foo", "FooBar parser first case" );
is( $parser->from_string( "Bar" ), "Bar", "FooBar parser first case" );

$parser = TestParser->new( toplevel => "parse_numrange" );

is( $parser->from_string( "123-456" ), [ 123, 456 ], "Number range parser complete" );

{
   my $warnings = "";
   local $SIG{__WARN__} = sub { $warnings .= join "", @_ };

   is( $parser->from_string( "789" ), [ 789, undef ],   "Number range parser lacking max" );
   is( $warnings, "", "Number range lacking max yields no warnings" );
}

done_testing;