| 1 |
use strict; |
| 2 |
use warnings; |
| 3 |
use Test::More tests => 8; |
| 4 |
use Test::Fatal; |
| 5 |
|
| 6 |
use Dancer2::Core::Hook; |
| 7 |
|
| 8 |
my $h = |
| 9 |
Dancer2::Core::Hook->new( name => 'before_template', code => sub {'BT'} ); |
| 10 |
is $h->name, 'before_template_render'; |
| 11 |
is $h->code->(), 'BT'; |
| 12 |
|
| 13 |
{ |
| 14 |
|
| 15 |
package Foo; |
| 16 |
use Moo; |
| 17 |
with 'Dancer2::Core::Role::Hookable'; |
| 18 |
sub hook_aliases { +{} } |
| 19 |
sub supported_hooks {'foobar'} |
| 20 |
} |
| 21 |
|
| 22 |
my $f = Foo->new; |
| 23 |
|
| 24 |
like( |
| 25 |
exception { $f->execute_hook() }, |
| 26 |
qr{execute_hook needs a hook name}, |
| 27 |
'execute_hook needs a hook name', |
| 28 |
); |
| 29 |
|
| 30 |
my $count = 0; |
| 31 |
my $some_hook = Dancer2::Core::Hook->new( |
| 32 |
name => 'foobar', |
| 33 |
code => sub { |
| 34 |
$count++; |
| 35 |
} |
| 36 |
); |
| 37 |
|
| 38 |
ok( !exception { $f->add_hook($some_hook) }, |
| 39 |
'Supported hook can be installed', |
| 40 |
); |
| 41 |
|
| 42 |
like( |
| 43 |
exception { |
| 44 |
$f->add_hook( |
| 45 |
Dancer2::Core::Hook->new( |
| 46 |
name => 'unknown_hook', |
| 47 |
code => sub { $count++; } |
| 48 |
) |
| 49 |
); |
| 50 |
}, |
| 51 |
qr{Unsupported hook 'unknown_hook'}, |
| 52 |
'Unsupported hook cannot be installed', |
| 53 |
); |
| 54 |
|
| 55 |
$f->execute_hook('foobar'); |
| 56 |
is $count, 1; |
| 57 |
|
| 58 |
like( |
| 59 |
exception { $f->replace_hook( 'doesnotexist', [] ) }, |
| 60 |
qr{Hook 'doesnotexist' must be installed first}, |
| 61 |
'Nonexistent hook fails', |
| 62 |
); |
| 63 |
|
| 64 |
my $new_hooks = [ sub { $count-- }, sub { $count-- }, sub { $count-- } ]; |
| 65 |
$f->replace_hook( 'foobar', $new_hooks ); |
| 66 |
$f->execute_hook('foobar'); |
| 67 |
is $count, -2, 'replaced hooks were installed and executed'; |