Devstack » Articles » Unit-Testing with Apache2::ASP

Unit-Testing with Apache2::ASP

Apache2::ASP was written from the very beginning with unit-testing in mind, so it's no wonder that it ships with the ability to perform unit tests.

Under the hood, Apache2::ASP uses a mock webserver environment complete enough to do what Apache2::ASP needs. Requests are full-fledged HTTP::Request objects and responses are actual HTTP::Response objects.

This means that if you have ever used LWP::UserAgent to access the web from Perl, you already know enough to get started unit testing with Apache2::ASP.

To make programatic (test) requests to an Apache2::ASP web application, you need an instance of Apache2::ASP::Test::Base. It abstracts the details and some boilerplate code so you can focus on your tests.


Apache2::ASP Test Template

All unit tests for Apache2::ASP should start out like this:

#!/usr/bin/perl -w

use strict;
use warnings 'all';
use base 'Apache2::ASP::Test::Base';
use Test::More 'no_plan'; # You can plan if you want:
use Data::Properties::YAML;
use HTML::Form;

# Create an instance of ourselves:
ok( my $s = __PACKAGE__->SUPER::new() );

# Get our properties object:
my $props = Data::Properties::YAML->new(
  properties_file => $s->ua->context->config->web->application_root . '/etc/properties.yaml'
);

GET Requests

To "GET" an ASP script, do this:

my $res = $s->ua->get("/index.asp");

The Response

The $res object is an instance of HTTP::Response.

This means that the following assertions work as expected:

is( $res->is_success => 1, "/index.asp was successful");
ok( ! $res->header("location"), "Not redirected anywhere" );
ok( $res->header("set-cookie"), "Got a cookie");
like $res->header("set-cookie"), qr/session\-id/, "We got a session-id cookie";

Filling in and Submitting a Form

To test a form by filling it out and submitting it, do this:

# Get the response:
my $res = $s->ua->get("/form.asp");

# Parse the response using '/' as the root:
my $form = HTML::Form->parse( $res->content, '/' );

# Continue like normal:
$form->find_input('some_field_name')->set_value('Hello, World!');

# Submit the form:
my $res2 = $s->ua->submit_form( $form );

POST Requests

To mimic an HTTP POST (i.e. to a handler), do this:

my $res = $s->ua->post("/handlers/examples.contact", [
  some_field    => "some value",
  another_field => "another_value",
]);

if( $res->is_success ) { ... }

See - nothing special.

File Uploads

To learn about handling file uploads with Apache2::ASP, see "File Uploads with Apache2::ASP."

To mimic a file upload - i.e. to test an upload handler, do this:

# Make your upload id:
my $uploadID = int(rand() * 1000) . ':' . int(rand() * 1000);

# Send the request:
my $res = $s->ua->upload("/handlers/my.uploadhandler?mode=create&uploadID=$uploadID", [
  uploaded_file => [ "/full/path/to/the/file.txt" ]
]);

# OK?:
is( $res->is_success => "Uploaded the file" );