summary refs log tree commit diff
path: root/t/spore/02_enable.t
blob: 2bd74025a6471dfb55e9555e2316ccf7009efb6c (plain) (blame)
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
use strict;
use warnings;
use Test::More;
use Test::Exception;

plan tests => 9;

use IO::All;
use Net::HTTP::Spore;
use Net::HTTP::Spore::Request;

package Net::HTTP::Spore::Middleware::Dummy;
use base qw/Net::HTTP::Spore::Middleware/;

sub call { 1 }

package main;

my $api_spec = 't/specs/api.json';
my %args = ( base_url => 'http://localhost/', );
my $content < io($api_spec);

ok my $client = Net::HTTP::Spore->new_from_spec( $api_spec, %args );

is scalar @{$client->middlewares}, 0, 'no middleware';

dies_ok {
    $client->enable();
}, 'middleware name is required';

dies_ok {
    $client->enable('FOOBARBAZAWESOMEMIDDLEWARE');
}, 'middleware should be loadable';

dies_ok {
    $client->enable_if('Format::JSON');
}, 'enable if require a coderef';

$client->enable('Dummy');
is scalar @{$client->middlewares}, 1, 'middleware dummy added';

$client->reset_middlewares();
is scalar @{$client->middlewares}, 0, 'no middleware loaded';

my $mw_test = sub { (shift)->method eq 'GET'; };

my $request = Net::HTTP::Spore::Request->new({REQUEST_METHOD => 'GET'});

$client->enable_if($mw_test, 'Dummy');

my $res = $client->middlewares->[0]->($request);
is $res, 1, 'condition match';

$request->env->{REQUEST_METHOD} = 'POST';
$res = $client->middlewares->[0]->($request);
ok !$res, 'condition is not matched';