SKWAT.pm 

package SKWAT;  # Super Kewl Web Application Tester

use strict;
use warnings;
use Carp;

use base qw(Test::WWW::Mechanize);

use Test::Builder;

my $Test = Test::Builder->new();

sub get_ok {
  my($self, $url) = @_;

  if($url =~ m{^/}) {
    $url = "http://localhost/~grant/talks/tdd/code/web_app$url";
  }
  local $Test::Builder::Level = $Test::Builder::Level + 1;
  $self->SUPER::get_ok($url);
}

sub template_is {
  my($self, $path, $desc) = @_;

  $desc ||= qq{returned page used "$path" template};

  my $ok   = 0;
  my $diag = '';
  if($self->content =~ m{<!--\s+Template:\s+(\S+)}) {
    if($1 eq $path) {
      $ok = 1;
    }
    else {
      $diag = qq{Page template mismatch: expected "$path" got "$1"};
    }
  }
  else {
    $diag = qq{Couldn't find template marker in "} .
            $self->content . '"';
  }

  $Test->ok($ok, $desc);
  $Test->diag($diag) if $diag;
}

sub value_is {
  my($self, $name, $value, $desc) = @_;

  $desc ||= qq{field "$name" contains the value "$value"};

  my $ok   = 0;
  my $diag = '';

  my $form = $self->current_form or croak "Page contains no form";

  my @inputs = $form->find_input($name);
  if(@inputs == 0) {
    $diag = qq{There is no field called "$name"};
  }
  elsif(@inputs > 1) {
    $diag = qq{There are multiple fields called "$name"};
  }
  elsif($inputs[0]->value ne $value) {
    $diag = qq{Field "$name" contains "} .
            $inputs[0]->value . qq{" expected "$value"};
  }
  else {
    $ok = 1;
  }

  $Test->ok($ok, $desc);
  $Test->diag($diag) if $diag;
}

sub submit_form_ok {
  my $self = shift;
  my $desc = shift || 'submitted form';

  $self->submit_form(@_);

  my $ok = $self->success;

  $Test->ok($ok, $desc);
  if(!$ok) {
    $Test->diag($self->status);
    $Test->diag($self->response->message) if $self->response;
  }

  return $ok;
}

1;