

package TestGosper;

sub load_expected {
  open E, "<", "EXPECTED/$ENV{DICT}" or die $!;
  while (<E>) {
    chomp;
    my ($q, $a) = split;
    $expected{$q} = $a;
  }
  close E;
}

BEGIN {
  die "Set \$DICT\n" unless $ENV{DICT};
  open SAVE_STDOUT, ">&STDOUT" or die $!;
  open STDOUT, ">", "/dev/null" or die $!;
  open STDIN, "<", "TESTS/$ENV{DICT}" or die $!;
  open 'main::DATA', "<", "/dev/null" or die $!;
  @ARGV = "TESTS/$ENV{DICT}";
  unlink 'questions', 'answers';
  load_expected();
}

sub BAD {
  warn $_[0];
  $BAD++;
}

END {

  while (my ($n, $g) = each %{"main::"}) {
    next if $n =~ /^STD/ || $n =~ /^std/;
    my $N = "main\::$n";
    next unless *{$N}{IO};
#    warn "# Closing $n\n";
    close $g;
  }

  open Q, "<", "questions" or die "not ok: questions file: $!";
  open A, "<", "answers" or die "not ok: answers file: $!";

 PAIR:
  while (1) {
    my $q = <Q>;
    my $a = <A>;
    unless (defined $a) {
      BAD "not ok: answers file ended prematurely\n" if defined $q;
      last;
    }
    unless (defined $q) {
      BAD "not ok: questions file ended prematurely\n";
      last;
    }

    chomp($q, $a);
#    warn "# checking ($q $a)\n";
    if (not exists $expected{$q}) {
      BAD "not ok: unexpected question ($q, $a)\n";
      next PAIR;
    }
    if (lc $expected{$q} ne lc $a) {
      BAD "not ok: wrong answer ($q, $a) should have been ($q, $expected{$q})\n";
      next PAIR;
    }
    delete $expected{$q};
  }

 MISSING:
  while (my($q, $a) = each %expected) {
    BAD "not ok: pair ($q, $a) omitted\n";
    next MISSING;
  }

  if ($BAD) {
    warn "# $BAD problems total\n";
  } else {
    warn "ok\n";
  }
}


"Cogito, ergo sum.";

