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> );
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;