#!/usr/bin/perl

# Copryight (C) 2004-2005  Joshua Hoblitt
#
# $Id: 07_server_find_instances.t,v 1.16 2008-09-11 22:35:52 jhoblitt Exp $

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

use Test::More tests => 19;

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

use Nebulous::Server;
use Test::URI;
use Test::Nebulous;

my $neb = Nebulous::Server->new(
    dsn         => $NEB_DB,
    dbuser      => $NEB_USER,
    dbpasswd    => $NEB_PASS,
);

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, volume
    my $uri = $neb->create_object('foo', 'node01');

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

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

Test::Nebulous->setup;

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

    my $locations = $neb->find_instances('neb://node02/foo', "~any");

    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", "~any");

    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 not a 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;
