#!/usr/bin/env perl

# Copyright (C) 2005  Joshua Hoblitt
#
# $Id: 02_mdb-add-new.t,v 1.1 2005-09-30 03:29:17 jhoblitt Exp $

use strict;
use warnings;

use Test::Cmd;
use Test::More tests => 29;

use Env qw( MDB_DSN MDB_USER MDB_PASS );

local $MDB_DSN;
local $MDB_USER;
local $MDB_PASS;

my $test = Test::Cmd->new(prog => 'scripts/mdb-add-new', workdir => '');
isa_ok($test, 'Test::Cmd');

{
    $test->run(args => '');
    missing_args(3, "Required options: --dsn --user");
}

{
    local $MDB_DSN  = "foo";

    $test->run(args => '');
    missing_args(3, "Required options: --dsn --user");
}

{
    local $MDB_USER = "foo";

    $test->run(args => '');
    missing_args(3, "Required options: --dsn --user");
}

{
    local $MDB_PASS = "foo";

    $test->run(args => '');
    missing_args(3, "Required options: --dsn --user");
}

{
    local $MDB_DSN  = 'foo';
    local $MDB_USER = 'bar';

    $test->run(args => '');
    missing_args(4, "Required options: --exp_id --class --class_id --url");
}

$test->run(args => '--dsn foo');
missing_args(3, "Required options: --dsn --user");

$test->run(args => '--user foo');
missing_args(3, "Required options: --dsn --user");

$test->run(args => '--pass foo');
missing_args(3, "Required options: --dsn --user");

$test->run(args => '--dsn foo --user bar');
missing_args(4, "Required options: --exp_id --class --class_id --url");

local $MDB_DSN  = "DBI:mysql:test";
local $MDB_USER = "test";

$test->run(args => '--exp_id 1');
missing_args(4, "Required options: --exp_id --class --class_id --url");

$test->run(args => '--exp_id 1 --class 2');
missing_args(4, "Required options: --exp_id --class --class_id --url");

$test->run(args => '--exp_id 1 --class 2 --class_id 3');
missing_args(4, "Required options: --exp_id --class --class_id --url");

reset_db();
$test->run(args => '--exp_id 1 --class 2 --class_id 3 --url http://example/');
is($? >> 8, 0, "all manditory options");
is($test->stderr, "", "no output to stderr");

reset_db();
$test->run(args => '--exp_id 1 --class 2 --class_id 3 --camera tc3 --stamp 2005-09-29T17:27:00Z --file_id foo.fits --size 42 --md5 768d2bcf7deba710d75a71c53470a182 --url http://example/');
is($? >> 8, 0, "all manditory + optional options");
is($test->stderr, "", "no output to stderr");

END { reset_db() }

sub missing_args
{
    my ($exit, $errstr) = @_;

    is($? >> 8, $exit, "error code is: $exit");
    like($test->stderr, qr/$errstr/, "error string is: $errstr");
}

sub reset_db
{
    use PS::IPP::MetaDB dsn => "DBI:mysql:test", user => "test";
    PS::IPP::MetaDB::Image::New->drop_table();
}
