Debian Codegraph @

xt/captcha.t

raw
1 use strict;
2 use warnings;
3 use Test::More;
4 use HTML::FormHandler::Test;
5
6 BEGIN {
7 eval "use GD::SecurityImage";
8 plan skip_all => 'GD::SecurityImage required' if $@;
9 }
10
11 use_ok( 'HTML::FormHandler::Field::Captcha' );
12
13 {
14 package Test::Captcha;
15 use HTML::FormHandler::Moose;
16 extends 'HTML::FormHandler';
17 with 'HTML::FormHandler::TraitFor::Captcha';
18 with 'HTML::FormHandler::Render::Simple';
19
20 has_field 'some_field';
21 has_field 'subject';
22 has_field '+captcha' => ( id => 'captcha', wrapper_class => 'captcha' );
23
24 sub validate_subject {
25 my ( $self, $field ) = @_;
26 $field->add_error("Incorrect")
27 unless $field->value eq 'Correct';
28 }
29
30 }
31
32 {
33 package Mock::Ctx;
34 use Moose;
35 has '_session' => ( isa => 'HashRef', is => 'rw', builder => 'build_session' );
36 sub build_session {{}}
37 sub session {
38 my $self = shift;
39 my $session = $self->_session;
40 if (@_) {
41 my $new_values = @_ > 1 ? { @_ } : $_[0];
42 croak('session takes a hash or hashref') unless ref $new_values;
43
44 for my $key (keys %$new_values) {
45 $session->{$key} = $new_values->{$key};
46 }
47 }
48 $session;
49 }
50 }
51
52 my $ctx = Mock::Ctx->new;
53 ok( $ctx, 'get mock ctx' );
54
55 my $form = Test::Captcha->new( ctx => $ctx );
56 ok( $form, 'get form' );
57 my $rnd = $ctx->session->{captcha}->{rnd};
58 ok( $rnd, 'captcha is in session' );
59
60 my $params = { some_field => 'test', subject => 'Correct', captcha => '1234' };
61 $form->process( ctx => $ctx, params => $params );
62 ok( !$form->validated, 'form did not validate with wrong captcha');
63
64 my $rnd2 = $ctx->session->{captcha}->{rnd};
65 ok( $rnd ne $rnd2, 'we now have a different captcha');
66 ok( !$form->field('captcha')->fif, 'no fif for captcha' );
67 $params->{captcha} = $rnd2;
68 $params->{subject} = 'Incorrect';
69 $form->process( ctx => $ctx, params => $params );
70 # valid captcha, invalid subject
71 ok( !$form->validated, 'form did not validate: valid captcha, invalid field' );
72 ok( $rnd2 == $ctx->session->{captcha}->{rnd}, 'captcha has not changed' );
73
74 $params->{subject} = 'Correct';
75 $form->process( ctx => $ctx, params => $params );
76 ok( $form->validated, 'form validated; old captcha, valid fields' );
77
78 my $render = $form->render_field('captcha');
79 is_html( $render, '
80 <div class="captcha"><label for="captcha">Verification</label><img src="/captcha/image"/><input id="captcha" name="captcha"></div>
81 ', 'captcha renders ok' );
82
83
84 done_testing;
85