summaryrefslogtreecommitdiff
path: root/t/tests/middleware/authentication.t
blob: b696aaab037c211f730a2f7975a06e6b83547b7e (plain)
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
use v6.d.PREVIEW;
use Test;
use Ultramarine::Middleware::Authentication;
 
class TestUsers {
    has @.responses;
    has @!calls;
 
    method authenticate(|c{
        @!calls.push(c);
        return @.responses.shift;
    }
 
    method calls() { return @!calls }
}
 
class TestRequest {
    has %!query;
    submethod BUILD(:%!query{}
    method query-value($key{
        return [ %!query{$key} ];
    }
}
 
my $users = TestUsers.new(responses=>[0,1,0,1]);
 
my $auth = Ultramarine::Middleware::Authentication.new(:$users);
 
sub test_auth(%query,$expected,$message?{
    my $req = TestRequest.new(:%query);
    my $supply = supply { emit $req };
    react {
        whenever $auth.process($supply-> $maybe-authed {
            my $is-authed = $maybe-authed ~~ Ultramarine::Request::Authed;
            if ($expected{
                subtest {
                    ok($is-authed,'should be authed');
                    is($maybe-authed.user,%query<u>,'with the correct user');
                }, $message;
            }
            else {
                nok($is-authed,$message);
            }
            done;
        };
    };
}
 
my %user-password = ( :u<user>,:p<password> );
my %user-token = ( :u<user>,:t<token>,:s<salt> );
 
# the fail-pass-fail-pass comes from $users.responses 
test_auth(%user-password,0,'auth fail should pass through');
test_auth(%user-password,1,'auth pass should apply trait');
test_auth(%user-token,0,'auth fail should pass through');
test_auth(%user-token,1,'auth pass should apply trait');
 
is-deeply(
    $users.calls,
    [ |(\(:user<user>,:password<password>xx 2),
      |(\(:user<user>,:token<token>,:salt<salt>xx 2) ],
    'the model should have been called with the correct parameters'
);
 
done-testing;