PageRenderTime 44ms CodeModel.GetById 18ms app.highlight 23ms RepoModel.GetById 1ms app.codeStats 0ms

/xt/captcha.t

http://github.com/gshank/html-formhandler
Unknown | 85 lines | 68 code | 17 blank | 0 comment | 0 complexity | 161129f43ea86479c5f30358fec84222 MD5 | raw file
 1use strict;
 2use warnings;
 3use Test::More;
 4use HTML::FormHandler::Test;
 5
 6BEGIN {
 7   eval "use GD::SecurityImage";
 8   plan skip_all => 'GD::SecurityImage required' if $@;
 9}
10
11use_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
52my $ctx = Mock::Ctx->new;
53ok( $ctx, 'get mock ctx' );
54
55my $form = Test::Captcha->new( ctx => $ctx );
56ok( $form, 'get form' );
57my $rnd = $ctx->session->{captcha}->{rnd};
58ok( $rnd, 'captcha is in session' );
59
60my $params = { some_field => 'test', subject => 'Correct', captcha => '1234' };
61$form->process( ctx => $ctx, params => $params );
62ok( !$form->validated, 'form did not validate with wrong captcha');
63
64my $rnd2 = $ctx->session->{captcha}->{rnd};
65ok( $rnd ne $rnd2, 'we now have a different captcha');
66ok( !$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
71ok( !$form->validated, 'form did not validate: valid captcha, invalid field' );
72ok( $rnd2 == $ctx->session->{captcha}->{rnd}, 'captcha has not changed' );
73
74$params->{subject} = 'Correct';
75$form->process( ctx => $ctx, params => $params );
76ok( $form->validated, 'form validated; old captcha, valid fields' );
77
78my $render = $form->render_field('captcha');
79is_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
84done_testing;
85