| 1 |
use strict; |
| 2 |
use warnings; |
| 3 |
|
| 4 |
use Test::More tests => 3; |
| 5 |
use Plack::Test; |
| 6 |
use HTTP::Request::Common; |
| 7 |
|
| 8 |
{ |
| 9 |
package Dancer2::Plugin::FooDetector; |
| 10 |
|
| 11 |
use Dancer2::Plugin; |
| 12 |
|
| 13 |
plugin_hooks 'foo'; |
| 14 |
|
| 15 |
|
| 16 |
sub BUILD { |
| 17 |
my $plugin = shift; |
| 18 |
|
| 19 |
$plugin->app->add_hook( |
| 20 |
Dancer2::Core::Hook->new( |
| 21 |
name => 'after', |
| 22 |
code => sub { |
| 23 |
$plugin->app->execute_hook( 'plugin.foodetector.foo' ) |
| 24 |
if $_[0]->content =~ /foo/; |
| 25 |
} |
| 26 |
) ); |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
{ |
| 31 |
package PoC; |
| 32 |
|
| 33 |
use Dancer2; |
| 34 |
|
| 35 |
use Dancer2::Plugin::FooDetector; |
| 36 |
|
| 37 |
my $hooked = 'nope'; |
| 38 |
my $counter = 0; |
| 39 |
|
| 40 |
hook 'plugin.foodetector.foo' => sub { |
| 41 |
$counter++; |
| 42 |
$hooked = 'hooked'; |
| 43 |
}; |
| 44 |
|
| 45 |
get '/' => sub { |
| 46 |
"saying foo triggers the hook" |
| 47 |
}; |
| 48 |
|
| 49 |
get 'meh' => sub { 'meh' }; |
| 50 |
|
| 51 |
get '/hooked' => sub { $hooked }; |
| 52 |
get '/counter' => sub { $counter }; |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
my $test = Plack::Test->create( PoC->to_app ); |
| 57 |
|
| 58 |
subtest 'initial state' => sub { |
| 59 |
ok $test->request( GET '/meh' )->is_success; |
| 60 |
my $res = $test->request( GET '/hooked' ); |
| 61 |
ok $res->is_success; |
| 62 |
is $res->content, 'nope'; |
| 63 |
is $test->request( GET '/counter' )->content, '0'; |
| 64 |
}; |
| 65 |
|
| 66 |
subtest 'trigger hook' => sub { |
| 67 |
ok $test->request( GET '/' )->is_success; |
| 68 |
my $res = $test->request( GET '/hooked' ); |
| 69 |
ok $res->is_success; |
| 70 |
is $res->content, 'hooked'; |
| 71 |
is $test->request( GET '/counter' )->content, '1'; |
| 72 |
}; |
| 73 |
|
| 74 |
# GH #1018 - ensure hooks are called the correct number of times |
| 75 |
subtest 'execute hook counting' => sub { |
| 76 |
ok $test->request( GET '/' )->is_success; |
| 77 |
my $res = $test->request( GET '/hooked' ); |
| 78 |
ok $res->is_success; |
| 79 |
is $res->content, 'hooked'; |
| 80 |
is $test->request( GET '/counter' )->content, '2'; |
| 81 |
}; |
| 82 |
|