File: 075_complex_typemap_example.t

package info (click to toggle)
libbread-board-perl 0.37-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 716 kB
  • sloc: perl: 5,494; xml: 394; makefile: 2; sh: 1
file content (91 lines) | stat: -rw-r--r-- 2,056 bytes parent folder | download | duplicates (6)
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
89
90
91
#!/usr/bin/perl

use strict;
use warnings;

use Test::More;
use Test::Moose;

use Bread::Board;

{
    package Logger::Role;
    use Moose::Role;

    requires 'log';

    package My::Logger;
    use Moose;

    with 'Logger::Role';

    has 'level' => ( is => 'ro', isa => 'Str', default => 'warn' );

    sub log {}

    package My::DBI;
    use Moose;

    has 'dsn' => (is => 'ro', isa => 'Str');

    sub connect {
        my ($class, $dsn) = @_;
        $class->new( dsn => $dsn );
    }

    package My::Application;
    use Moose;

    has 'logger' => (is => 'ro', does => 'Logger::Role', required => 1);
    has 'dbh'    => (is => 'ro', isa  => 'My::DBI',      required => 1);
}

my $c = container 'Automat' => as {

    service 'dsn'    => 'dbi:sqlite:test';
    service 'dbh'    => (
        block => sub {
            my $s = shift;
            My::DBI->connect( $s->param( 'dsn' ) );
        },
        dependencies => [ depends_on('dsn') ]
    );

    # map a type to a service implementation ...
    typemap 'My::DBI' => 'dbh';

    # ask the container to infer a service,
    # but give it some hints ....
    typemap 'Logger::Role' => infer( class => 'My::Logger' );

    # ask the container to infer the
    # entire service ...
    typemap 'My::Application' => infer;
};

# check the inference from the top level Application ...
{
    my $app = $c->resolve( type => 'My::Application' );
    isa_ok($app, 'My::Application');

    isa_ok($app->logger, 'My::Logger');
    does_ok($app->logger, 'Logger::Role');
    is($app->logger->level, 'warn', '... got the default level');

    isa_ok($app->dbh, 'My::DBI');
    is($app->dbh->dsn, 'dbi:sqlite:test', '... got the right DSN too');
}

# check the inference from the logger object
# and its optional 'level' parameter
{
    my $logger = $c->resolve(
        type       => 'Logger::Role',
        parameters => { level => 'debug' }
    );
    isa_ok($logger, 'My::Logger');
    does_ok($logger, 'Logger::Role');
    is($logger->level, 'debug', '... got the custom level');
}

done_testing;