Blog

Perl 以外の言語でかかれたTCPサーバーをTest::TCPでテストする

Test::TCP の中で exec 発行すれば、groonga だろうと KT だろうと memcached だろうと、サーバープロセスのテストは簡単にできるのであって、サーバーごとにモジュールにする必要はない。以下は、groonga をテストする例。

Test::TCP は、さまざまなTCPサーバーのテストにつかわれており、さまざまな BK をふくんだ実装となっていて、これを再発明しようとすると、意外とめんどくさかったりするので、素直につかうとよいです。

use strict;
use warnings;
use utf8;
use Test::More;
use Test::TCP 1.08;
use File::Temp ();
use File::Which;

my $bin = scalar which 'groonga';
plan skip_all => 'groonga binary is not found' unless defined $bin;

my $db = File::Temp::tmpnam();

my $groonga = Test::TCP->new(
    code => sub {
        my $port = shift;

        # -s : server mode
        # -n : create new database
        exec $bin, '-s', '--port', $port, '--protocol', 'http', '-n', $db;
        die "cannot execute $bin: $!";
    },
);

use LWP::UserAgent;
my $url = "http://127.0.0.1:@{[ $groonga->port ]}/d/status";
my $res = LWP::UserAgent->new()->get($url);
is $res->code, 200;
diag $res->content;

unlink $db;

done_testing;

RDBMS のように、やたらいっぱいオプションをつけなきゃいけない場合はともかく、たいがいのサーバーは、こういう風に起動した方が楽です。