Mini howto: Testing HTTP::Engine-based applications.

作者:   發佈於: ,更新於:   #perl

HTTP::Engine is an abstraction layer over several environments that an web application might be deployed under. For example, CGI, FastCGI, mod_perl, or stand-alone application server. It's not a full-featured web-appication framework, but a helpful library when writing applications. This kinds of idea is especially tasteful when it comes to testing -- because it's often cumbersome to fully prepare the environment for testing.

So it's pretty easy to test your application without actually launching it with the "Test" interface of HTTP::Engine.

First your create an engine object, telling it to use "Test" interface:

my $engine = HTTP::Engine->new(
    interface => {
	module => 'Test',
	request_handler => sub {
            my $request = shift;
            # This should returns an HTTP::Engine::Response object
            return MyApp->dispatch($request);

Then you can give it a HTTP::Request object, with a few extra parameters:

my $response = $engine->run(
    HTTP::Request->new(GET => 'http://localhost/welcome/here'),
    env => \%ENV,
    connection_info => {
	request_uri => "/welcome/here"

It'll return you a HTTP::Response object that you can latter examine its content or headers etc. The connection_info is required if you use $request->request_uri inside your code. The Test interface does not read any environment variable like normal CGI mode, therefore you can fully control the testing environment, and you'll need to pass those in. In certain deploy configurations, the REQUEST_URI variable might be different from the actual URL, that's why it's needed.

The http://localhost/` part of the URL is also required but only to let it be parsed correctly. The$engineis not going to make any real connection to that URL, but only invoking therequest_handlerwith a test environment prepared out of the parameters passed to therun()`function.

And that's how you write a simple test to of your application with HTTP::Engine.