I spent some time confused about how best to write a unit test for some code that involves a server based on Net::Server::PreFork, but I've finally worked something out. The problem with running the server from the test class is that calling the run() method on your server class does just that - it runs the server, until you send it SIGTERM, at which time it shuts down. So, to run a test that depends on the server being available, you need another process. fork() seemed like the most straightforward solution. For some reason I have not discerned, Test::More doesn't pick up the things written to STDOUT by the child process, so the thing to do is run the server from the child and run the tests in the parent. Here's the idea:
#!/usr/bin/perl -w
use strict;
package TestServer;
use base qw(Net::Server::PreFork);
use Test::More qw(no_plan);
use Socket;
use constant PORT => 11220;
my $child_id = fork();
if ($child_id) {
sleep 1;
my $proto = getprotobyname('tcp');
socket(Socket_Handle, PF_INET, SOCK_STREAM, $proto);
my $sin = sockaddr_in(PORT, INADDR_LOOPBACK);
ok(connect(Socket_Handle, $sin), "connect to server");
ok(kill(15, $child_id), "server shut down");
} else {
TestServer->run(port => PORT,
log_file => '/dev/null');
}
[/code]
slag code: