Application Testing 

#!/usr/bin/perl
use strict;
use warnings;

use Test::More;
use HTTP::Request::Common;
use HTTP::Engine;
use MyApp;

plan tests => 6;

my $engine = HTTP::Engine->new({
    interface => {
        module => 'Test',
        request_handler => \&MyApp::handler
    }
});

my ($req, $res);

$req = GET( 'http://example.com/' );
$res = $engine->run( $req );

# check that we are told we are not signed in
like( $res->content, qr{Not signed in}, q{Not signed in} );

# ---
# sign in
$req = POST(
    'http://example.com/sign-in.html',
    { username => 'andychilton', password => 'password' }
);
$res = $engine->run( $req );

like( $res->header('Set-Cookie'), qr{^session=[A-Za-z0-9]{32}; path=/}, q{A Signed In Cookie} );

# ---
# check the app tells us we are signed in

$req = GET(
    'http://example.com/',
    Cookie => $res->header('Set-Cookie'),
);
$res = $engine->run( $req );

like( $res->content, qr{Hello andychilton}, q{Signed In Ok} );

# ---
# when signing out, check the session is expired (ignoring date)

$req = GET(
    'http://example.com/sign-out.html',
    Cookie => $res->header('Set-Cookie'),
);
$res = $engine->run( $req );

like( $res->header('Set-Cookie'), qr{^session=; path=/; }, q{Now Signed Out} );

# --
# check we are no longer signed in (even with the same cookie)

$req = GET(
    'http://example.com/',
    Cookie => $res->header('Set-Cookie'),
);
$res = $engine->run( $req );

like( $res->content, qr{Not signed in}, q{Not signed in} );

# --
# check that when logging in with the wrong password, no cookie is given

$req = POST(
    'http://example.com/sign-in.html',
    { username => 'andychilton', password => 'wrong' }
);
$res = $engine->run( $req );

is( $res->header('Set-Cookie'), undef, q{Didn't sign in} );