root/lang/perl/Text-Nyarlax/trunk/t/TestNyarlax.pm @ 474

Revision 474, 2.4 kB (checked in by nyarla, 6 years ago)

lang/perl/Text-Nyarlax: I changed the interface of Text::Nyarlax substantially.

Line 
1package t::TestNyarlax;
2
3use strict;
4use warnings;
5
6use Test::Base -Base;
7use Text::Nyarlax;
8use FindBin;
9use File::Spec;
10use FileHandle;
11use DirHandle;
12
13our @EXPORT = qw(
14    set_parser
15    set_test_elements
16    run_test_parse
17);
18
19our $nyarlax = Text::Nyarlax->new;
20
21our ( $BaseDir, $SpecDir );
22{
23    my @path = File::Spec->splitdir( $FindBin::Bin );
24    while ( defined( my $dir = pop @path ) ) {
25        if ( $dir eq 't' ) {
26            $BaseDir = File::Spec->catdir( @path );
27            $SpecDir = File::Spec->catdir( $BaseDir, qw( t parser spec ) );
28        }
29    }
30}
31
32sub set_parser() {
33    my ( $parser, $config ) = @_;
34    $nyarlax->parser(
35        class => $parser,
36        %{ $config },
37    );
38}
39
40sub set_test_elements() {
41    my ( @elements ) = @_;
42
43    if ( @elements > 0 ) {
44        $_ = "$_.tb" for @elements;
45    }
46    else {
47        my $dh = DirHandle->new( $SpecDir ) or croak $!;
48        @elements = grep { $_ =~ m{\.tb$} } $dh->read;
49        $dh->close;
50    }
51
52    my $spec_data = q{};
53    my $fh = FileHandle->new;
54    for my $name ( @elements ) {
55        my $file = File::Spec->catfile( $SpecDir, $name );
56        $fh->open( $file, '<' );
57        $spec_data .= do { local $/; <$fh> } . "\n\n";
58        $fh->close;
59    }
60
61    spec_string( $spec_data );
62}
63
64sub run_test_parse() {
65    my ( $input, $expected ) = @_;
66
67    filters {
68        $input      => [qw( parse )],
69        $expected   => [qw( yaml element )],
70    };
71
72    run_compare( $input => $expected );
73}
74
751;
76package t::TestNyarlax::Filter;
77
78use base qw( Test::Base::Filter );
79
80use Text::Nyarlax::Element;
81
82sub element {
83    my $data = shift;
84    $data ||= [];
85    $data = [ $data ] if ( ref $data ne 'ARRAY' );
86
87    my $elements = [];
88
89    for my $item ( @{ $data } ) {
90        if ( ref $item eq 'HASH' ) {
91            my $name = $item->{'name'};
92            my $attr = $item->{'attr'};
93            my $content = $self->element( $item->{'content'} );
94            my $element = Text::Nyarlax::Element->new(
95                name    => $name,
96                attr    => $attr,
97                content => $content,
98            );
99            push @{ $elements }, $element;
100        }
101        else {
102            push @{ $elements }, $item;
103        }
104    }
105
106    return $elements;
107}
108
109sub parse {
110    my $text = shift;
111    return $t::TestNyarlax::nyarlax->parse( $text );
112}
113
1141;
115__END__
Note: See TracBrowser for help on using the browser.