#!/usr/bin/perl

# Copryight (C) 2004-2005  Joshua Hoblitt
#
# $Id: 07_server_find_instances.t,v 1.8 2007-05-03 01:44:24 jhoblitt Exp $

use strict;
use warnings FATAL => qw( all );

use Test::More tests => 15;

use lib qw( ./t ./lib );

use Nebulous::Server;
use Nebulous::Util qw( :standard );
use Test::URI;
use Test::Nebulous;

my $neb = Nebulous::Server->new(
    dsn         => "DBI:mysql:database=test:host=localhost",
    dbuser      => "test",
    dbpasswd    => "",
);

Test::Nebulous->setup;

{
    # key
    my $uri = $neb->create_object("foo");

    my $locations = $neb->find_instances("foo");

    uri_scheme_ok($locations->[0], 'file');
    is($uri, $locations->[0], "URIs match");
}

Test::Nebulous->setup;

{
    # key
    my $uri1 = $neb->create_object("foo");
    my $uri2 = $neb->replicate_object("foo");

    my $locations = $neb->find_instances("foo");

    uri_scheme_ok($locations->[0], 'file');
    uri_scheme_ok($locations->[1], 'file');
    ok(eq_set([$uri1, $uri2], $locations), "URIs match");
}

Test::Nebulous->setup;

{
    # key, volume
    my $uri = $neb->create_object('foo', 'node01');

    my $locations = $neb->find_instances('foo', 'node01');

    uri_scheme_ok($locations->[0], 'file');
    is($uri, $locations->[0], "URIs match");
}

Test::Nebulous->setup;

{
    # key
    my $uri1 = $neb->create_object("foo");
    my $uri2 = $neb->replicate_object("foo");

    my $locations = $neb->find_instances("foo", "node01");

    uri_scheme_ok($locations->[0], 'file');
    uri_scheme_ok($locations->[1], 'file');
    ok(eq_set([$uri1, $uri2], $locations), "URIs match");
}

# object exists but instance is on a different volume
Test::Nebulous->setup;

eval {
    # key, volume
    my $uri = $neb->create_object('foo', 'node01');

    my $locations = $neb->find_instances('foo', 'node02');
};
like($@, qr/no instances on storage volume/, 'instances on a different volume');


Test::Nebulous->setup;

eval {
    $neb->find_instances('foo');
};
like($@, qr/is valid object key/, "storage object does not exist");

Test::Nebulous->setup;

eval {
    $neb->create_object('foo');
    $neb->find_instances('foo', 'bar');
};
like($@, qr/is valid volume name/, "storage volume does not exist");

Test::Nebulous->setup;

eval {
    $neb->find_instances();
};
like($@, qr/1 - 2 were expected/, "no params");

Test::Nebulous->setup;

eval {
    $neb->create_object('foo');
    $neb->find_instances('foo', 'node01', 3);
};
like($@, qr/1 - 2 were expected/, "too many params");

Test::Nebulous->cleanup;
