File: Generator.t

package info (click to toggle)
libexporter-declare-perl 0.114-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 228 kB
  • sloc: perl: 1,607; makefile: 4
file content (88 lines) | stat: -r--r--r-- 2,220 bytes parent folder | download | duplicates (4)
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
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/perl
use strict;
use warnings;

use Fennec::Lite;

our $CLASS = "Exporter::Declare::Export::Generator";
require_ok $CLASS;

tests create => sub {
    throws_ok { $CLASS->new(sub{ sub {} }, exported_by => __PACKAGE__ ) }
        qr/You must specify type when calling $CLASS\->new()/,
        "Required specs";
    my $export = $CLASS->new(sub { sub {} }, exported_by => __PACKAGE__, type => 'sub' );
    isa_ok( $export, $CLASS );
    is( $export->type, 'sub', "Stored property" );
};

tests generate_subs => sub {
    my $val = 1;
    my $export = $CLASS->new(
        sub { my $out = $val++; sub { $out } },
        exported_by => __PACKAGE__,
        type => 'sub'
    );
    $export->inject( __PACKAGE__, 'foo' );
    $export->inject( __PACKAGE__, 'bar' );
    $export->inject( __PACKAGE__, 'baz' );
    is( foo(), 1, "First generated" );
    is( bar(), 2, "Second generated" );
    is( baz(), 3, "Third generated" );
    is( $val, 4, "value incrimented" );
};

tests generate_vars => sub {
    my $val = 1;
    my $export = $CLASS->new(
        sub { my $out = $val++; \$out },
        exported_by => __PACKAGE__,
        type => 'variable'
    );
    $export->inject( __PACKAGE__, 'foo' );
    $export->inject( __PACKAGE__, 'bar' );
    $export->inject( __PACKAGE__, 'baz' );
    no strict 'vars';
    is( $foo, 1, "First generated" );
    is( $bar, 2, "Second generated" );
    is( $baz, 3, "Third generated" );
    is( $val, 4, "value incrimented" );
};

run_tests();
done_testing;

__END__

sub type { shift->_data->{ type }}

sub new {
    my $class = shift;
    croak "Generators must be coderefs, not " . ref($_[0])
        unless ref( $_[0] ) eq 'CODE';
    $class->SUPER::new( @_ );
}

sub generate {
    my $self = shift;
    my ( $import_class, @args ) = @_;
    my $ref = $self->( $self->exported_by, $import_class, @args );

    return Exporter::Declare::Export::Sub->new(
        $ref,
        %{ $self->_data },
    ) if $self->type eq 'sub';

    return Exporter::Declare::Export::Variable->new(
        $ref,
        %{ $self->_data },
    );
}

sub inject {
    my $self = shift;
    my ( $class, $name, @args ) = @_;
    $self->generate( $class, @args )->inject( $class, $name );
}

1;