#!/usr/bin/perl
#
# gnats-test.pl -
#      Test code for gnats-lib.pl
#
# $Id: test.pl,v 1.2 1999/04/01 05:16:03 kenstir Exp $

#-----------------------------------------------------------------------------
# test harness setup

use POSIX;

$suppress_main = 1;
do 'gnatsweb.pl';
do 'gnatsweb-site.pl' if (-e 'gnatsweb-site.pl');

$errors = 0;

open(LOG, ">test.log") || die;

#-----------------------------------------------------------------------------
# support subs

# print the test summary
sub sum {
    my($test, $passed) = @_;
    print $test, '.' x (50 - length($test));
    if ($passed) {
        print "pass\n";
    }
    else {
        $errors++;
        print "FAIL\n";
    }
}

# if program exits while we are running a test, this is a failure!
END {
    if ($test) {
        sum($test, 0);
    }
    # can't exit from here
    #exit $errors;
}

#-----------------------------------------------------------------------------
# connect

$test = 'connect';
$user     = $ENV{'USERNAME'} || 'anonymous';
$password = $ENV{'PASSWORD'} || 'guest';
$database = $ENV{'DATABASE'} || 'main';
# TODO: figure out how to catch exception here, so that if connect fails
# the user gets a 'FAILED' report from sum().
initialize();
sum($test, $access_level);

# can't do anything if this test fails
exit $errors if $errors;

#-----------------------------------------------------------------------------
# parse_pr, unparse_pr -
#
#     loop over first 50 PRs and make sure
#     that parsing and then unparsing them does not change the PR.

#local($client_cmd_debug) = 1;

foreach my $mypr (1..50) {
    $test = "parsepr/unparsepr $mypr";
    my %fields = readpr($mypr);
    my $reconstructed_pr = unparsepr('', %fields);
    my @pr_lines = client_cmd("full $mypr");
    my $orig_pr = join("\n", @pr_lines);
    my $ok = 1;
    if ($orig_pr ne $reconstructed_pr) {
        # print PRs into two files and use diff for ease of debugging
        my $origfile = POSIX::tmpnam();
        open(ORIG, ">$origfile") || die;
        print ORIG $orig_pr;
        close(ORIG) || die;

        my $newfile = POSIX::tmpnam();
        open(NEW, ">$newfile") || die;
        print NEW $reconstructed_pr;
        close(NEW) || die;

        my $cmd = "diff -u $origfile $newfile";
        my $result = `$cmd`;
        if ($?) {
            print LOG "-"x50, " pr: $mypr\n$cmd\n", $result;
            $ok = 0;
        }
        #unlink($origfile, $newfile);
    }
    sum($test, $ok);
}

#-----------------------------------------------------------------------------
# finalize

$test = '';
if ($errors) {
    exit $errors;
}
else {
    print "All tests passed.\n";
    exit 0;
}
