#!/usr/local/bin/perl5.005

use Carp;
use Person;

$| = 1;
my $testno = 1;
print "1..28\n";

alarm(5) unless $^P;

my $p1 = Person->new();
ok($p1);
ok(! defined($p1->name));
ok(! defined($p1->age));
ok(! defined($p1->spouse));
my $p2 = Person->new("N2");
ok($p2);
ok($p2->name, "N2");
ok(! defined($p2->age));
ok(! defined($p2->spouse));
my $p3 = Person->new("N3", 30);
ok($p3);
ok($p3->name, "N3");
ok($p3->age, 30);
ok(! defined($p3->spouse));

$p1->name("N1");
ok($p1->name, "N1");
$p2->name("NN2");
ok($p2->name, "NN2");

$p2->age("22");
ok($p2->age, "22");
$p3->age("33");
ok($p3->age, "33");

ok(! defined($p1->spouse));
ok(! defined($p2->spouse));
ok(! defined($p3->spouse));

$p2->spouse($p3);
ok($p2->spouse->name, $p3->name);
ok($p3->spouse->name, $p2->name);
ok(! defined($p1->spouse));

$p2->spouse($p1);
$p1->age(31);
ok($p2->spouse->name, $p1->name);
ok($p1->spouse->name, $p2->name);
ok(! defined($p3->spouse));

ok($p1->as_string, "Person  N1 is 31 years old and is married to NN2"); 
ok($p2->as_string, "Person  NN2 is 22 years old and is married to N1"); 
ok($p3->as_string, "Person  N3 is 33 years old"); 

my $p4 = Person->new('N4', 44, $p3);
ok($p4);
ok($p4->name, 'N4');
ok($p4->age, 44);
ok($p4->spouse, $p3);
ok($p4->spouse->name, $p3->name);
ok($p3->spouse, $p4);
ok($p3->spouse->name, $p4->name);
eval { Person->new('X', 0, $p1) };
ok($@); 

sub ok {
  if (@_ == 1) {
    print "not " unless $_[0];
    print "ok ", $testno++, "\n";
  } elsif (@_ == 2) {
    my ($ac, $ex) = @_;
    my $bad = ($ex ne $ac);
    print "not " if $bad;
    print "ok ", $testno++;
    if ($bad) {
      for ($ex, $ac) { tr/\n//d } 
      print "# expected '$ex'; received '$ac'";
    }
    print "\n";
  } else {
    croak "Usage: ok(success?) or ok(actual, expected)";
  }
}
