test-lib.pm 19.6 KB
Newer Older
Xavier Guimard's avatar
Xavier Guimard committed
1
# Base library for portal tests
Xavier Guimard's avatar
Xavier Guimard committed
2
package main;
Xavier Guimard's avatar
Xavier Guimard committed
3

Xavier Guimard's avatar
Xavier Guimard committed
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
=pod

=encoding utf8

=head1 NAME

test-lib.pm - Test framework for LLNG portal

=head1 SYNOPSIS

  use Test::More;
  use strict;
  use IO::String;
  
  require 't/test-lib.pm';
  
  my $res;
  
  my $client = LLNG::Manager::Test->new( {
      ini => {
          logLevel => 'error',
          #...
      }
    }
  );
  
  ok(
      $res = $client->_post(
          '/',
          IO::String->new('user=dwho&password=dwho'),
          length => 23
      ),
      'Auth query'
  );
  count(1);
  expectOK($res);
  my $id = expectCookie($res);
  
  clean_sessions();
  done_testing( count() );

=head1 DESCRIPTION

Xavier Guimard's avatar
Xavier Guimard committed
47
This test library permits one to simulate browser navigation.
Xavier Guimard's avatar
Xavier Guimard committed
48 49 50 51 52 53 54 55

=head2 Functions

In these functions, C<$res> is the result of a C<LLNG::Manager::Test::_get()> or
C<LLNG::Manager::Test::_post()> call I<(see below)>.

=cut

Xavier Guimard's avatar
Xavier Guimard committed
56 57
use strict;
use Data::Dumper;
Xavier Guimard's avatar
Xavier Guimard committed
58
use File::Find;
Xavier Guimard's avatar
Xavier Guimard committed
59
use LWP::UserAgent;
Xavier Guimard's avatar
Xavier Guimard committed
60
use URI::Escape;
Xavier Guimard's avatar
Xavier Guimard committed
61
use Lemonldap::NG::Common::FormEncode;
Clément OUDOT's avatar
Clément OUDOT committed
62

63
#use 5.10.0;
Xavier Guimard's avatar
Xavier Guimard committed
64

Xavier Guimard's avatar
Xavier Guimard committed
65 66
no warnings 'redefine';

Xavier Guimard's avatar
Xavier Guimard committed
67 68 69 70
BEGIN {
    use_ok('Lemonldap::NG::Portal::Main');
}

Xavier Guimard's avatar
Xavier Guimard committed
71
our $count = 1;
72 73 74
$Data::Dumper::Deparse  = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Useperl  = 1;
Xavier Guimard's avatar
Xavier Guimard committed
75
my $ini;
Xavier Guimard's avatar
Xavier Guimard committed
76

Xavier Guimard's avatar
Xavier Guimard committed
77 78 79 80 81 82 83
use File::Temp 'tempfile', 'tempdir';
our $tmpDir = $LLNG::TMPDIR
  || tempdir( 'tmpSessionXXXXX', DIR => 't/sessions', CLEANUP => 1 );
mkdir "$tmpDir/lock";
mkdir "$tmpDir/saml";
mkdir "$tmpDir/saml/lock";

Xavier Guimard's avatar
Xavier Guimard committed
84 85 86 87 88 89
=head4 count($inc)

Returns number of tests done. Increment test number if an argument is given

=cut

Xavier Guimard's avatar
Xavier Guimard committed
90 91 92 93 94 95
sub count {
    my $c = shift;
    $count += $c if ($c);
    return $count;
}

Xavier Guimard's avatar
Xavier Guimard committed
96 97 98 99 100 101 102 103 104
=head4 explain( $result, $expected_result )

Used to display error if test fails:

  ok( $res->[0] == 302, 'Get redirection' ) or
    explain( $res->[0], 302 );

=cut

Xavier Guimard's avatar
Xavier Guimard committed
105
sub main::explain {
Xavier Guimard's avatar
Xavier Guimard committed
106 107
    my ( $get, $ref ) = @_;
    $get = Dumper($get) if ( ref $get );
Xavier Guimard's avatar
Xavier Guimard committed
108
    diag("Expect $ref, get $get\n");
Xavier Guimard's avatar
Xavier Guimard committed
109 110
}

Xavier Guimard's avatar
Xavier Guimard committed
111 112 113 114 115 116
=head4 clean_sessions()

Clean sessions created during tests

=cut

Xavier Guimard's avatar
Xavier Guimard committed
117
sub clean_sessions {
Xavier Guimard's avatar
Xavier Guimard committed
118
    find( sub { unlink if -f }, $tmpDir );
Xavier Guimard's avatar
Xavier Guimard committed
119 120 121 122 123 124 125
    foreach my $dir (qw(t/sessions/lock t/sessions/saml/lock t/sessions/saml)) {
        if ( -d $dir ) {
            opendir D, $dir or die $!;
            foreach ( grep { /^[^\.]/ } readdir(D) ) {
                unlink "$dir/$_";
            }
        }
Xavier Guimard's avatar
Xavier Guimard committed
126
    }
127 128
}

129 130
sub count_sessions {
    my $dir = shift;
Xavier Guimard's avatar
Xavier Guimard committed
131
    $dir ||= $tmpDir;
132 133 134 135 136 137 138 139 140
    my $nbr = 0;

    opendir D, $dir or die $!;
    foreach ( grep { /^\w{64}$/ } readdir(D) ) {
        $nbr++;
    }
    $nbr;
}

141
sub getCache {
Xavier Guimard's avatar
Xavier Guimard committed
142
    require Cache::FileCache;
143 144
    return Cache::FileCache->new(
        {
145
            namespace   => 'lemonldap-ng-session',
Xavier Guimard's avatar
Xavier Guimard committed
146
            cache_root  => $tmpDir,
147 148 149
            cache_depth => 0,
        }
    );
Xavier Guimard's avatar
Xavier Guimard committed
150 151
}

Xavier Guimard's avatar
Xavier Guimard committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
=head4 expectRedirection( $res, $location )

Verify that request result is a redirection to $location. $location can be:

=over

=item a string: location must match exactly

=item a regexp: location must match this regexp. In this case, the list of
matching strings are returned. Example:

  my( $uri, $query ) = expectRedirection( $res, qr#http://host(/[^\?]*)?(.*)$# );

=back

=cut

169 170
sub expectRedirection {
    my ( $res, $location ) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
171
    ok( $res->[0] == 302, ' Get redirection' )
172
      or explain( $res->[0], 302 );
Xavier Guimard's avatar
Xavier Guimard committed
173
    count(1);
174 175 176
    if ( ref $location ) {
        my @match;
        @match = ( getRedirection($res) =~ $location );
Xavier Guimard's avatar
Xavier Guimard committed
177
        ok( @match, ' Location header found' )
178
          or explain( $res->[1], "Location match: " . Dumper($location) );
Xavier Guimard's avatar
Xavier Guimard committed
179
        count(1);
180 181 182
        return @match;
    }
    else {
Xavier Guimard's avatar
Xavier Guimard committed
183
        ok( getRedirection($res) eq $location, " Location is $location" )
184
          or explain( $res->[1], "Location => $location" );
185
        count(1);
186 187 188
    }
}

Xavier Guimard's avatar
Xavier Guimard committed
189 190 191 192 193 194 195 196
=head4 expectAutoPost(@args)

Same behaviour as C<expectForm()> but verify also that form method is post.

TODO: verify javascript

=cut

Xavier Guimard's avatar
Xavier Guimard committed
197
sub expectAutoPost {
198
    my @r      = expectForm(@_);
Xavier Guimard's avatar
Xavier Guimard committed
199
    my $method = pop @r;
Xavier Guimard's avatar
Xavier Guimard committed
200
    ok( $method =~ /^post$/i, ' Method is POST' ) or explain( $method, 'POST' );
Xavier Guimard's avatar
Xavier Guimard committed
201
    count(1);
Xavier Guimard's avatar
Xavier Guimard committed
202
    return @r;
Xavier Guimard's avatar
Xavier Guimard committed
203 204
}

Xavier Guimard's avatar
Xavier Guimard committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
=head4 expectForm( $res, $hostRe, $uriRe, @requiredFields )

Verify form in HTML result and return ( $host, $uri, $query, $method ):

=over

=item verify that a GET/POST form exists

=item if a $hostRe regexp is given, verify that form target matches and
populates $host. Skipped if $hostRe eq "#"

=item if a $uriRe regexp is given, verify that form target matches and
populates $uri

=item if @requiredFields exists, verify that each element is an input name

=item build form-url-encoded string looking at parameters/values and store it
in $query

=back

=cut

Xavier Guimard's avatar
Xavier Guimard committed
228
sub expectForm {
Xavier Guimard's avatar
Xavier Guimard committed
229 230
    my ( $res, $hostRe, $uriRe, @requiredFields ) = @_;
    expectOK($res);
Xavier Guimard's avatar
Xavier Guimard committed
231
    count(1);
Xavier Guimard's avatar
Xavier Guimard committed
232 233 234
    if (
        ok(
            $res->[2]->[0] =~
235
m@<form.+?action="(?:(?:http://([^/]+))?(/.*?)?|(#))".+method="(post|get)"@is,
Xavier Guimard's avatar
Xavier Guimard committed
236
            ' Page contains a form'
Xavier Guimard's avatar
Xavier Guimard committed
237 238 239
        )
      )
    {
Xavier Guimard's avatar
Xavier Guimard committed
240
        my ( $host, $uri, $hash, $method ) = ( $1, $2, $3, $4 );
241
        if ( $hash and $hash eq '#' ) {
Xavier Guimard's avatar
Xavier Guimard committed
242
            $host = '#';
243
            $uri  = '';
Xavier Guimard's avatar
Xavier Guimard committed
244
        }
Xavier Guimard's avatar
Xavier Guimard committed
245 246
        if ($hostRe) {
            if ( ref $hostRe ) {
Xavier Guimard's avatar
Xavier Guimard committed
247
                ok( $host =~ $hostRe, ' Host match' )
Xavier Guimard's avatar
Xavier Guimard committed
248 249 250
                  or explain( $host, $hostRe );
            }
            else {
Xavier Guimard's avatar
Xavier Guimard committed
251
                ok( $host eq $hostRe, ' Host match' )
Xavier Guimard's avatar
Xavier Guimard committed
252 253 254 255 256 257
                  or explain( $host, $hostRe );
            }
            count(1);
        }
        if ($uriRe) {
            if ( ref $uriRe ) {
Xavier Guimard's avatar
Xavier Guimard committed
258
                ok( $uri =~ $uriRe, ' URI match' ) or explain( $uri, $uriRe );
Xavier Guimard's avatar
Xavier Guimard committed
259 260
            }
            else {
Xavier Guimard's avatar
Xavier Guimard committed
261
                ok( $uri eq $uriRe, ' URI match' ) or explain( $uri, $uriRe );
Xavier Guimard's avatar
Xavier Guimard committed
262 263 264
            }
            count(1);
        }
Xavier Guimard's avatar
Xavier Guimard committed
265 266

        # Fields with values
267
        my %fields =
Xavier Guimard's avatar
Xavier Guimard committed
268
          ( $res->[2]->[0] =~
Xavier Guimard's avatar
Xavier Guimard committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
              m#<input.+?name="([^"]+)"[^>]+(?:value="([^"]*?)")#gs );

        # Add fields without values
        %fields = (
            $res->[2]->[0] =~
              m#<input.+?name="([^"]+)"[^>]+(?:value="([^"]*?)")?#gs,
            %fields
        );
        my $query = join(
            '&',
            map {
                "$_="
                  . (
                    $fields{$_}
                    ? uri_escape( uri_unescape( $fields{$_} ) )
                    : ''
                  )
              }
              keys(%fields)
        );
Xavier Guimard's avatar
Xavier Guimard committed
289
        foreach my $f (@requiredFields) {
Xavier Guimard's avatar
Xavier Guimard committed
290
            ok( exists $fields{$f}, qq{ Field "$f" is defined} );
Xavier Guimard's avatar
Xavier Guimard committed
291 292
            count(1);
        }
293
        exceptCspFormOK( $res, $host );
Xavier Guimard's avatar
Xavier Guimard committed
294
        return ( $host, $uri, $query, $method );
Xavier Guimard's avatar
Xavier Guimard committed
295 296 297 298 299 300
    }
    else {
        return ();
    }
}

Xavier Guimard's avatar
Xavier Guimard committed
301 302 303 304 305 306
=head4 expectAuthenticatedAs($user)

Verify that result has a C<Lm-Remote-User> header and value is $user

=cut

307 308
sub expectAuthenticatedAs {
    my ( $res, $user ) = @_;
309 310
    ok( getHeader( $res, 'Lm-Remote-User' ) eq $user,
        " Authenticated as $user" )
311 312 313 314
      or explain( $res->[1], "Lm-Remote-User => $user" );
    count(1);
}

Xavier Guimard's avatar
Xavier Guimard committed
315 316 317 318 319 320
=head4 expectOK($res)

Verify that returned code is 200

=cut

321 322
sub expectOK {
    my ($res) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
323
    ok( $res->[0] == 200, ' HTTP code is 200' ) or explain( $res, 200 );
324 325 326
    count(1);
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
=head4 expectJSON($res)

Verify that the HTTP response contains valid JSON and returns the corresponding object

=cut

sub expectJSON {
    my ($res) = @_;
    is( $res->[0], 200, ' HTTP code is 200' ) or explain( $res, 200 );
    my %hdr = @{$res->[1]};
    like( $hdr{'Content-Type'}, qr,^application/json,i , ' Content-Type is JSON' ) or explain( $res );
    my $json;
    eval { $json = JSON::from_json($res->[2]->[0]) };
    ok( not($@), 'Content is valid JSON' );
    count(3);
    return $json;
}

Xavier Guimard's avatar
Xavier Guimard committed
345 346 347 348 349 350 351
=head4 expectBadRequest($res)

Verify that returned code is 400. Note that it works only for Ajax request
(see below).

=cut

352 353
sub expectBadRequest {
    my ($res) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
354
    ok( $res->[0] == 400, ' HTTP code is 400' ) or explain( $res->[0], 400 );
355 356 357
    count(1);
}

Xavier Guimard's avatar
Xavier Guimard committed
358 359 360 361 362 363 364
=head4 expectReject( $res, $code )

Verify that returned code is 401 and JSON result contains C<error:"$code">.
Note that it works only for Ajax request (see below).

=cut

365
sub expectReject {
366 367 368
    my ( $res, $status, $code ) = @_;
    $status ||= 401;
    cmp_ok( $res->[0], '==', $status, " Response status is $status" );
Xavier Guimard's avatar
Xavier Guimard committed
369
    eval { $res = JSON::from_json( $res->[2]->[0] ) };
370
    ok( not($@), ' Content is JSON' )
Xavier Guimard's avatar
Xavier Guimard committed
371 372
      or explain( $res->[2]->[0], 'JSON content' );
    if ( defined $code ) {
373
        is( $res->{error}, $code, " Error code is $code" );
Xavier Guimard's avatar
Xavier Guimard committed
374 375
    }
    else {
376
        pass("Error code is $res->{error}");
Xavier Guimard's avatar
Xavier Guimard committed
377 378
    }
    count(3);
379 380
}

Xavier Guimard's avatar
Xavier Guimard committed
381 382 383 384 385 386 387
=head4 expectCookie( $res, $cookieName )

Check if a C<Set-Cookie> exists and set a cookie named $cookieName. Return
its value.

=cut

388 389 390 391 392
sub expectCookie {
    my ( $res, $cookieName ) = @_;
    $cookieName ||= 'lemonldap';
    my $cookies = getCookies($res);
    my $id;
393 394 395 396
    ok(
        defined( $id = $cookies->{$cookieName} ),
        " Get cookie $cookieName ($id)"
    ) or explain( $res->[1], "Set-Cookie: $cookieName=something" );
397 398 399 400
    count(1);
    return $id;
}

Xavier Guimard's avatar
Xavier Guimard committed
401 402
=head4 exceptCspFormOK( $res, $host )

Xavier Guimard's avatar
Xavier Guimard committed
403
Verify that C<Content-Security-Policy> header allows one to connect to $host.
Xavier Guimard's avatar
Xavier Guimard committed
404 405 406

=cut

407 408 409 410 411 412 413 414 415 416
sub exceptCspFormOK {
    my ( $res, $host ) = @_;
    return 1 unless ($host);
    my $csp = getHeader( $res, 'Content-Security-Policy' );
    return 1 unless ($csp);
    unless ( $csp =~ s/^.*form-action (.*?)(?:;.*)?$/$1/ ) {
        $csp =~ s/^.*default-src (.*?)(?:;.*)?$/$1/;
    }
    if (   $csp =~ /\s\*(?:\s.*)?\s*$/
        or ( $host eq '#' and $csp =~ /'self'/ )
417
        or $csp =~ m#\bhttps?://$host\b# )
418
    {
419
        pass(" CSP header authorize POST request to $host");
420 421
    }
    else {
422
        fail(" CSP header authorize POST request to $host");
423 424 425 426 427
        explain( $res->[1], "form-action ... $host" );
    }
    count(1);
}

Xavier Guimard's avatar
Xavier Guimard committed
428 429 430 431 432 433
=head4 getCookies($res)

Returns an hash ref with names => values of cookies set by server.

=cut

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
sub getCookies {
    my ($resp) = @_;
    my @hdrs   = @{ $resp->[1] };
    my $res    = {};
    while ( my $name = shift @hdrs ) {
        my $v = shift @hdrs;
        if ( $name eq 'Set-Cookie' ) {
            if ( $v =~ /^(\w+)=([^;]*)/ ) {
                $res->{$1} = $2;
            }
        }
    }
    return $res;
}

Xavier Guimard's avatar
Xavier Guimard committed
449 450 451 452 453 454
=head4 getHeader( $res, $hname )

Returns value of first header named $hname in $res response.

=cut

455 456 457 458 459 460 461 462 463 464 465 466 467
sub getHeader {
    my ( $resp, $hname ) = @_;
    my @hdrs = @{ $resp->[1] };
    my $res  = {};
    while ( my $name = shift @hdrs ) {
        my $v = shift @hdrs;
        if ( $name eq $hname ) {
            return $v;
        }
    }
    return undef;
}

Xavier Guimard's avatar
Xavier Guimard committed
468 469 470 471 472 473
=head4 getRedirection($res)

Returns value of C<Location> header.

=cut

474 475 476 477 478
sub getRedirection {
    my ($resp) = @_;
    return getHeader( $resp, 'Location' );
}

Xavier Guimard's avatar
Xavier Guimard committed
479 480 481 482 483 484
=head4 getUser($res)

Returns value of C<Lm-Remote-User> header.

=cut

485 486 487 488 489
sub getUser {
    my ($resp) = @_;
    return getHeader( $resp, 'Lm-Remote-User' );
}

Xavier Guimard's avatar
Xavier Guimard committed
490 491 492 493 494 495 496 497 498 499
=head4 tempdb

Return a temporary file named XXXX.db

=cut

sub tempdb {
    return "$tmpDir/userdb.db";
}

Xavier Guimard's avatar
Xavier Guimard committed
500 501 502 503
=head2 LLNG::Manager::Test Class

=cut

Xavier Guimard's avatar
Xavier Guimard committed
504 505 506 507 508 509 510 511
package LLNG::Manager::Test;

use strict;
use Mouse;

extends 'Lemonldap::NG::Common::PSGI::Cli::Lib';

our $defaultIni = {
512 513 514 515 516 517 518
    configStorage => {
        type    => 'File',
        dirName => 't',
    },
    localSessionStorage        => 'Cache::FileCache',
    localSessionStorageOptions => {
        namespace   => 'lemonldap-ng-session',
Xavier Guimard's avatar
Xavier Guimard committed
519
        cache_root  => $tmpDir,
520 521
        cache_depth => 0,
    },
Xavier Guimard's avatar
Xavier Guimard committed
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    logLevel             => 'error',
    cookieName           => 'lemonldap',
    domain               => 'example.com',
    templateDir          => 'site/templates',
    staticPrefix         => '/static',
    securedCookie        => 0,
    https                => 0,
    globalStorageOptions => {
        Directory     => $tmpDir,
        LockDirectory => "$tmpDir/lock",
        generateModule =>
          'Lemonldap::NG::Common::Apache::Session::Generate::SHA256',
    },
    casStorageOptions => {
        Directory     => "$tmpDir/saml",
        LockDirectory => "$tmpDir/saml/lock",
        generateModule =>
          'Lemonldap::NG::Common::Apache::Session::Generate::SHA256',
    },
    samlStorageOptions => {
        Directory     => "$tmpDir/saml",
        LockDirectory => "$tmpDir/saml/lock",
        generateModule =>
          'Lemonldap::NG::Common::Apache::Session::Generate::SHA256',
    },
    oidcStorageOptions => {
        Directory     => "$tmpDir/saml",
        LockDirectory => "$tmpDir/saml/lock",
        generateModule =>
          'Lemonldap::NG::Common::Apache::Session::Generate::SHA256',
    },
Xavier Guimard's avatar
Xavier Guimard committed
553 554
};

Xavier Guimard's avatar
Xavier Guimard committed
555 556 557 558 559 560 561 562
=head3 Accessors

=over

=item app: built application

=cut

Xavier Guimard's avatar
Xavier Guimard committed
563
has app => (
564 565
    is  => 'rw',
    isa => 'CodeRef',
Xavier Guimard's avatar
Xavier Guimard committed
566 567
);

Xavier Guimard's avatar
Xavier Guimard committed
568 569 570 571
=item class: class to test (default Lemonldap::NG::Portal::Main)

=cut

Xavier Guimard's avatar
Xavier Guimard committed
572 573
has class => ( is => 'ro', default => 'Lemonldap::NG::Portal::Main' );

Xavier Guimard's avatar
Xavier Guimard committed
574 575 576 577
=item p: portal object

=cut

Xavier Guimard's avatar
Xavier Guimard committed
578 579
has p => ( is => 'rw' );

Xavier Guimard's avatar
Xavier Guimard committed
580 581 582 583
=item ini: initialization parameters ($defaultIni values + given parameters)

=cut

584 585
has confFailure => ( is => 'rw' );

586 587
has ini => (
    is      => 'rw',
588
    lazy    => 1,
589 590 591 592 593 594 595
    default => sub { $defaultIni; },
    trigger => sub {
        my ( $self, $ini ) = @_;
        foreach my $k ( keys %$defaultIni ) {
            $ini->{$k} //= $defaultIni->{$k};
        }
        $self->{ini} = $ini;
Xavier Guimard's avatar
Xavier Guimard committed
596
        main::ok( $self->{p} = $self->class->new(), 'Portal object' );
597 598 599 600 601 602 603
        main::count(1);
        unless ( $self->confFailure ) {
            main::ok( $self->{p}->init($ini),           'Init' );
            main::ok( $self->{app} = $self->{p}->run(), 'Portal app' );
            main::count(2);
            no warnings 'redefine';
            eval
604
'sub Lemonldap::NG::Common::Logger::Std::error {return $_[0]->warn($_[1])}';
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
            $Lemonldap::NG::Portal::UserDB::Demo::demoAccounts{french} = {
                uid  => 'french',
                cn   => 'Frédéric Accents',
                mail => 'fa@badwolf.org',
            };
            $Lemonldap::NG::Portal::UserDB::Demo::demoAccounts{davros} = {
                uid  => 'davros',
                cn   => 'Bad Guy',
                mail => 'davros@badguy.org',
            };
            $Lemonldap::NG::Portal::UserDB::Demo::demoAccounts{russian} = {
                uid  => 'russian',
                cn   => 'Русский',
                mail => 'ru@badwolf.org',
            };
        }
621
        $self;
Xavier Guimard's avatar
Xavier Guimard committed
622 623 624
    }
);

Xavier Guimard's avatar
Xavier Guimard committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
=back

=head3 Methods

=head4 logout($id)

Launch a C</?logout=1> request an test:

=over

=item if response is 200

=item if cookie 'lemonldap' and 'lemonldappdata' have no value

=item if a GET request with previous cookie value I<($i)> is rejected

=back

=cut

Xavier Guimard's avatar
Xavier Guimard committed
645
sub logout {
646
    my ( $self, $id ) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
647
    my $res;
Xavier Guimard's avatar
Xavier Guimard committed
648 649
    main::ok(
        $res = $self->_get(
Xavier Guimard's avatar
Xavier Guimard committed
650 651 652 653 654
            '/',
            query  => 'logout',
            cookie => "lemonldap=$id",
            accept => 'text/html'
        ),
655
        'Logout request'
Xavier Guimard's avatar
Xavier Guimard committed
656
    );
657
    main::ok( $res->[0] == 200, ' Response is 200' )
658
      or main::explain( $res->[0], 200 );
659
    my $c;
660
    main::ok(
661
        ( defined( $c = main::getCookies($res)->{lemonldap} ) and not $c ),
662
        ' Cookie is deleted' )
Xavier Guimard's avatar
Xavier Guimard committed
663
      or main::explain( $res->[1], "Set-Cookie => 'lemonldap='" );
664
    main::ok( not( main::getCookies($res)->{lemonldappdata} ), ' No pdata' );
Xavier Guimard's avatar
Xavier Guimard committed
665
    main::ok( $res = $self->_get( '/', cookie => "lemonldap=$id" ),
666 667
        'Disconnect request' )
      or explain( $res, '[<code>,<hdrs>,<content>]' );
668
    main::ok( $res->[0] == 401, ' Response is 401' )
669
      or main::explain( $res, 401 );
670
    main::count(6);
Xavier Guimard's avatar
Xavier Guimard committed
671 672 673

}

Xavier Guimard's avatar
Xavier Guimard committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
=head4 _get( $path, %args )

Simulates a GET requests to $path. Accepted arguments:

=over

=item accept: accepted content, default to Ajax request. Use 'text/html'
to test content I<(to launch a C<expectForm()> for example)>.

=item cookie: full cookie string

=item custom: additional headers (hash ref only)

=item ip: remote address. Default to 127.0.0.1

=item method: default to GET. Only GET/DELETE values are acceptable
(use C<_post()> if you want to launch a POST/PUT request)

=item query: query string

=item referer

=item remote_user: REMOTE_USER header value

=back

=cut

Xavier Guimard's avatar
Xavier Guimard committed
702 703
sub _get {
    my ( $self, $path, %args ) = @_;
704 705
    my $res = $self->app->(
        {
Xavier Guimard's avatar
Xavier Guimard committed
706 707 708
            'HTTP_ACCEPT' => $args{accept}
              || 'application/json, text/plain, */*',
            'HTTP_ACCEPT_LANGUAGE' => 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
Xavier Guimard's avatar
Xavier Guimard committed
709
            'HTTP_CACHE_CONTROL'   => 'max-age=0',
710
            ( $args{cookie} ? ( HTTP_COOKIE => $args{cookie} ) : () ),
Xavier Guimard's avatar
Xavier Guimard committed
711 712 713
            'HTTP_HOST' => 'auth.example.com',
            'HTTP_USER_AGENT' =>
              'Mozilla/5.0 (VAX-4000; rv:36.0) Gecko/20350101 Firefox',
714 715
            'PATH_INFO' => $path,
            ( $args{referer} ? ( REFERER => $args{referer} ) : () ),
Xavier Guimard's avatar
Xavier Guimard committed
716
            (
Xavier Guimard's avatar
Xavier Guimard committed
717 718 719 720 721
                $args{ip} ? ( 'REMOTE_ADDR' => $args{ip} )
                : ( 'REMOTE_ADDR' => '127.0.0.1' )
            ),
            (
                $args{remote_user} ? ( 'REMOTE_USER' => $args{remote_user} )
Xavier Guimard's avatar
Xavier Guimard committed
722 723
                : ()
            ),
724 725
            'REQUEST_METHOD' => $args{method} || 'GET',
            'REQUEST_URI'    => $path . ( $args{query} ? "?$args{query}" : '' ),
726
            ( $args{query} ? ( QUERY_STRING => $args{query} ) : () ),
Xavier Guimard's avatar
Xavier Guimard committed
727 728
            'SCRIPT_NAME'     => '',
            'SERVER_NAME'     => 'auth.example.com',
729
            'SERVER_PORT'     => '80',
Xavier Guimard's avatar
Xavier Guimard committed
730
            'SERVER_PROTOCOL' => 'HTTP/1.1',
Xavier Guimard's avatar
Xavier Guimard committed
731
            ( $args{custom} ? %{ $args{custom} } : () ),
Xavier Guimard's avatar
Xavier Guimard committed
732 733
        }
    );
734
    return $res;
Xavier Guimard's avatar
Xavier Guimard committed
735 736
}

Xavier Guimard's avatar
Xavier Guimard committed
737 738 739 740 741
=head4 _post( $path, $body, %args )

Same as C<_get> except that a body is required. $body must be a file handle.
Example with IO::String:

Xavier Guimard's avatar
Xavier Guimard committed
742
  ok(
Xavier Guimard's avatar
Xavier Guimard committed
743 744 745 746 747 748 749 750 751 752
      $res = $client->_post(
          '/',
          IO::String->new('user=dwho&password=dwho'),
          length => 23
      ),
      'Auth query'
  );

=cut

Xavier Guimard's avatar
Xavier Guimard committed
753 754 755 756
sub _post {
    my ( $self, $path, $body, %args ) = @_;
    die "$body must be a IO::Handle"
      unless ( ref($body) and $body->can('read') );
757 758
    my $res = $self->app->(
        {
Xavier Guimard's avatar
Xavier Guimard committed
759 760 761 762 763 764 765 766 767
            'HTTP_ACCEPT' => $args{accept}
              || 'application/json, text/plain, */*',
            'HTTP_ACCEPT_LANGUAGE' => 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
            'HTTP_CACHE_CONTROL'   => 'max-age=0',
            ( $args{cookie} ? ( HTTP_COOKIE => $args{cookie} ) : () ),
            'HTTP_HOST' => 'auth.example.com',
            'HTTP_USER_AGENT' =>
              'Mozilla/5.0 (VAX-4000; rv:36.0) Gecko/20350101 Firefox',
            'PATH_INFO' => $path,
768 769
            ( $args{query}   ? ( QUERY_STRING => $args{query} )   : () ),
            ( $args{referer} ? ( REFERER      => $args{referer} ) : () ),
Xavier Guimard's avatar
Xavier Guimard committed
770 771 772 773 774 775
            'REMOTE_ADDR' => '127.0.0.1',
            (
                $args{remote_user}
                ? ( 'REMOTE_USER' => $args{remote_user} )
                : ()
            ),
776
            'REQUEST_METHOD' => $args{method} || 'POST',
777 778 779 780
            'REQUEST_URI'    => $path . ( $args{query} ? "?$args{query}" : '' ),
            'SCRIPT_NAME'    => '',
            'SERVER_NAME'    => 'auth.example.com',
            'SERVER_PORT'    => '80',
Xavier Guimard's avatar
Xavier Guimard committed
781 782
            'SERVER_PROTOCOL' => 'HTTP/1.1',
            ( $args{custom} ? %{ $args{custom} } : () ),
Xavier Guimard's avatar
Xavier Guimard committed
783
            'psgix.input.buffered' => 0,
Xavier Guimard's avatar
Xavier Guimard committed
784 785 786 787 788 789
            'psgi.input'           => $body,
            'CONTENT_LENGTH' => $args{length} // scalar( ( stat $body )[7] ),
            'CONTENT_TYPE'   => $args{type}
              || 'application/x-www-form-urlencoded',
        }
    );
790
    return $res;
Xavier Guimard's avatar
Xavier Guimard committed
791 792
}

Xavier Guimard's avatar
Xavier Guimard committed
793 794 795 796 797 798
=head4 _delete( $path, %args )

Call C<_get()> with method set to DELETE.

=cut

799 800 801
sub _delete {
    my ( $self, $path, %args ) = @_;
    $args{method} = 'DELETE';
Christophe Maudoux's avatar
Christophe Maudoux committed
802
    $self->_get( $path, %args );
803 804
}

805 806 807 808 809 810 811 812 813 814 815 816
=head4 _options( $path, %args )

Call C<_get()> with method set to OPTIONS.

=cut

sub _options {
    my ( $self, $path, %args ) = @_;
    $args{method} = 'OPTIONS';
    $self->_get( $path, %args );
}

Xavier Guimard's avatar
Xavier Guimard committed
817 818 819 820 821 822
=head4 _put( $path, $body, %args )

Call C<_post()> with method set to PUT

=cut

823 824 825 826 827 828
sub _put {
    my ( $self, $path, $body, %args ) = @_;
    $args{method} = 'PUT';
    return $self->_post( $path, $body, %args );
}

Xavier Guimard's avatar
Xavier Guimard committed
829
1;