Subject: | allow ListInput values to be forced (patch and tests attached) |
When using HTML::Form via WWW::Mechanize, I sometimes want to see how my
web application would react to invalid input. I can't do that with
HTML::Form because it won't let me set up invalid input to ListInputs.
This patch is at least a sketch of how that could be easily added.
--
rjbs
Subject: | mutable-list-inputs.patch |
diff -Nur libwww-perl-5.805/lib/HTML/Form.pm libwww-perl-rjbs/lib/HTML/Form.pm
--- libwww-perl-5.805/lib/HTML/Form.pm 2005-12-07 09:32:27.000000000 -0500
+++ libwww-perl-rjbs/lib/HTML/Form.pm 2006-08-07 08:04:09.000000000 -0400
@@ -1083,6 +1083,13 @@
return 1;
}
+sub add_options {
+ my $self = shift;
+ while (my ($name, $value) = splice @_, 0, 2) {
+ push @{$self->{menu}}, { name => $name, value => $value };
+ }
+}
+
sub value
{
my $self = shift;
@@ -1091,6 +1098,7 @@
if (@_) {
my $i = 0;
my $val = shift;
+ my $force = shift;
my $cur;
my $disabled;
for (@{$self->{menu}}) {
@@ -1130,6 +1138,11 @@
}
else {
my $n = $self->name;
+ if ($force) {
+ # Add this as a valid option and retry.
+ $self->add_options($val => $val);
+ return $self->value($val, 0);
+ }
Carp::croak("Illegal value '$val' for field '$n'");
}
}
diff -Nur libwww-perl-5.805/t/html/form.t libwww-perl-rjbs/t/html/form.t
--- libwww-perl-5.805/t/html/form.t 2005-12-07 09:28:58.000000000 -0500
+++ libwww-perl-rjbs/t/html/form.t 2006-08-07 08:02:28.000000000 -0400
@@ -503,3 +503,28 @@
ok(join(":", $f->find_input("r2")->value_names), "two");
ok(join(":", $f->find_input("r3")->value_names), "nested");
ok(join(":", $f->find_input("r4")->value_names), "before and after");
+
+$f = HTML::Form->parse(<<EOT, "http://www.example.com");
+<form action="http://example.com/">
+ <input type='checkbox' name='check_box' checked="checked" />
+ <select name='single_select'>
+ <option>foo</option>
+ <option>bar</option>
+ <option>baz</option>
+ </select>
+</form>
+EOT
+
+eval { $f->value(single_select => 'quux') };
+ok($@ =~ /illegal value/i, 1); # can't set select element to invalid option
+
+$f->find_input('single_select')->add_options(quux => 'quux');
+eval { $f->value(single_select => 'quux') };
+ok($@, ''); # add_options added a valid option
+
+eval { $f->value(single_select => 'fingo') };
+ok($@ =~ /illegal value/i, 1); # can't set select element to invalid option
+
+eval { $f->value(single_select => 'fingo', 1) };
+ok($@, ''); # providing force option forces it
+