The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Test::FormValidator - Test framework for Data::FormValidator profiles

VERSION

Version 0.07

SYNOPSIS

    use Test::FormValidator 'no_plan';

    my $tfv = Test::FormValidator->new;

    $tfv->profile(WebApp->_change_password_profile);

    # check that the profile detects missing retyped password
    $tfv->check(
        'email'     => 'someone-at-example.com',
        'old_pass'  => 'seekrit',
        'new_pass1' => 'foo',
    );
    $tfv->missing_ok(['new_pass2'], "caught missing retyped password");

    # and that it detects missing fields
    $tfv->check(
        'email'     => 'someone-at-example.com',
        'old_pass'  => 'seekrit',
        'new_pass1' => 'foo',
        'new_pass2' => 'bar',
    );
    $tfv->invalid_ok([qw(email new_pass1 new_pass2)], "caught bad email & passwd");

DESCRIPTION

This is a module for testing your Data::FormValidator profiles. It uses the standard Perl test protocol (TAP) and prints out the familiar 'ok/not ok' stuff you expect.

Basically it lets you use a test script to quickly throw a lot of different input scenarios at your profiles and make sure they work properly.

You can test for missing fields:

    # Test a profile that requires an email address and a password - if we
    # provide only a name, then the password should be flagged as missing
    $tfv->check(
        'email'       => 'test@example.com',
    );
    $tfv->missing_ok(['password'], "caught missing passwd");

You can also test for invalid fields:

    # Test a profile that should catch a bad email address
    $tfv->check(
        'email'       => 'test-at-example.com',
    );
    $tfv->invalid_ok(['email'], "caught bad email address");

And if you have custom constraint methods, you can confirm that they each work properly:

    # Test a profile that requires passwords longer than 5 characters and
    # they have to contain both letters and numbers
    $tfv->check(
        'new_pass1' => 'foo',
        'new_pass2' => 'foo',
    );
    $tfv->invalid_ok(
    {
        'new_pass1' => [qw(too_short need_alpha_num)],
    },
    "caught short, non-alpha-numeric password");

And you can also test that the form fields in your HTML form match the list of fields in your profile:

    $tfv->html_ok('/path/to/template.html', 'Template matches profile');

EXAMPLE

Here's a more complete example. Assume you have a signup form with these fields:

    name
    email
    pass1
    pass2
    newsletter

The form (signup.html) might look vaguely like this:

    <form>
     Name:            <input name="name"><br />
     Email:           <input name="email"><br />
     Password:        <input name="pass1" type="password"><br />
     Retype Password: <input name="pass2" type="password"><br />
     Yummy SPAM?      <input name="newsletter" type="checkbox=" value="yes"><br />
    </form>

In your web application, you test the input generated by this form using a Data::FormValidator profile like this:

    package WebApp;
    use Data::FormValidator::Constraints qw(:closures);

    sub _signup_profile {
        return {
            required => [ qw(
                name
                email
                pass1
                pass2
            ) ],
            optional => [ qw(
                newsletter
            ) ],
            dependencies => {
                pass1 => 'pass2',
            },
            constraint_methods => {
                # passwords must be longer than 5 characters
                pass1 => [
                    sub {
                        my ($dfv, $val) = @_;
                        $dfv->name_this('too_short');
                        return $val if (length $val) > 5;
                        return;
                    },
                    # passwords must contain both letters and numbers
                    sub {
                        my ($dfv, $val) = @_;
                        $dfv->name_this('need_alpha_num');
                        return $val if $val =~ /\d/ and $val =~ /[[:alpha:]]/;
                        return;
                    },
                ],
                # passwords must match
                pass2 => sub {
                    my ($dfv, $val) = @_;
                    $dfv->name_this('mismatch');
                    my $data = $dfv->get_input_data('as_hashref' => 1);
                    return $data->{'pass1'} if ($data->{'pass1'} || '') eq ($data->{'pass2'} || '');
                    return;
                },
                # email must be valid
                email => valid_email(),
            },
        };
    }

In your test script, you test the profile against various input scenarios. First test that the fields listed in the profile match the fields that are actually present in the HTML form:

    use Test::FormValidator 'no_plan';

    my $tfv = Test::FormValidator->new;
    $tfv->profile(WebApp->_signup_profile);

    $tfv->html_ok('signup.html', 'Template matches profile');

    # Check for missing fields
    $tfv->check(); # empty form
    $tfv->missing_ok([qw(name email pass1 pass2)], 'caught missing fields');

    # check for invalid email, password
    $tfv->check(
        name  => 'Foo',
        email => 'foo-at-example.com',
        pass1 => 'foo',
        pass2 => 'bar',
    );
    $tfv->invalid_ok(
    {
        email => 'invalid'
        pass1 => [qw(too_short need_alpha_num)],
        pass2 => 'mismatch',
    },
    'caught invalid fields');

METHODS

Seting up the Validator

new

You set up Test::FormValidator by calling new. You can pass any arguments to new that you can pass to Data::FormValidator.

For instance, to use default profile settings, you would use:

    my $tfv = Test::FormValidator->new({}, \%defaults);
profile(\%profile)

This sets up the current profile for all subsequent tests

    $tfv->profile(\%profile);

Typically, you will fetch the profile from your web application:

    $tfv->profile(Webapp->_some_profile);

You can switch profiles in the same script:

    $tfv->profile(Webapp->_first_profile);

    # ... run some tests ...

    $tfv->profile(Webapp->_second_profile);

    # ... run some other tests ...

You can also explicitly pass a profile to check.

prefix('some text')

This is a convenience function to set some text to be printed at the start of every test description.

It's useful to save typing:

    $tfv->profile(WebApp->_login_profile);
    $tfv->prefix('[login form] ');

    $tfv->check({
        'email'    => 'test-at-example.com',
    });

    $tfv->missing_ok(['password'], 'password missing');
    $tfv->invalid_ok(['email'], 'email invalid');

This prints out:

    ok 1 - [login form] password missing
    ok 2 - [login form] email invalid

You can switch prefixes in the same script; just call prefix with a new value:

    $tfv->profile(Webapp->_first_profile);
    $tfv->prefix('FIRST: ');

    # ... run some tests ...

    $tfv->profile(Webapp->_second_profile);
    $tfv->prefix('SECOND: ');

    # ... run some other tests ...

To remove the prefix either pass a value of undef:

    $tfv->prefix(undef);

or the empty string (''):

    $tfv->prefix('');

Checking the input

check(%input)

This runs %input through the current profile, and returns a Data::FormValidator results object.

If you want to use a new profile for this check only, you can do so:

    $tfv->check(\%input, WebApp->_some_profile);
results

Returns the Data::FormValidator results object corresponding to the most recent check, check_ok, or check_not_ok. Throws an error if there has not yet been a check.

    $tfv->check_not_ok(\%input, 'some comment');
    my $results = $tfv->results;

Test Methods

Methods ending in _ok do the standard Test:: thing: on success, they print out 'ok' and return a true value. On failure, they print out 'not ok' and return false.

check_ok(%input, 'description')

Checks that the given input is valid:

    $tfv->check_ok(\%input, 'some comment');

This is the equivalent of:

    ok($tfv->check(\%input), 'some comment') or $tfv->diag;

It returns a Data::FormValidator results object which is overloaded to be true or false depending on the check of the test.

check_not_ok(%input)

Checks that the given input is not valid:

    $tfv->check_not_ok(\%input, 'some comment');

This is the equivalent of:

    ok(!$tfv->check(\%input), 'some comment') or $tfv->diag;
missing_ok(\@fields, 'description')

Checks \%input against the current profile, and verifies that @fields are all flagged as missing, and that no other fields are flagged as mising.

For example:

    $tfv->check(
        email => 'foo@example.com',
    );
    $tfv->missing_ok(['password'], "caught missing password");
invalid_ok(\@fields, 'description');

Checks \%input against the current profile, and verifies that @fields are all flagged as invalid, and that no other fields are flagged as invalid.

    $tfv->check(
        email => 'foo-at-example.com',
    );
    $tfv->invalid_ok(['email'], "caught invalid email address");
invalid_ok(\%fields_and_constraints, 'description');

Runs the current profile against \%input, and verifies that specific fields were invalid. It also verifies that specific constraints failed:

    $tfv->check(
        email => 'foo-at-example.com',
        pass1 => 'foo',
        pass2 => 'bar',
    )
    $tfv->invalid_ok(
    {
        email => 'invalid',
        pass1 => [qw(too_short )],
        pass2 => 'mismatch',
    }
    "caught invalid email address, mismatched password and bad password");

@fields are all flagged as invalid, and that no other fields are flagged as invalid.

valid_ok(\@fields, 'description');

Checks \%input against the current profile, and verifies that @fields are all flagged as valid, and that no other fields are flagged as valid.

    $tfv->check(
        email => 'foo@example.com',
    );
    $tfv->valid_ok(['email'], "only email is valid");
html_ok($file, 'description');
html_ok($file, { ignore => [qw(foo bar)] }, 'description');
html_ok($file, { ignore => /^foo/ }, 'description');

This checks that the form fields in the given file match the fields listed in the current profile (including both optional and required fields).

    $tfv->html_ok('/path/to/template.html');

If there are any extra fields in the HTML that aren't in the profile, the test fails. Similarly, if there are any extra fields in the profile that aren't in the HTML, the test fails.

It's designed to catch typos and inconsistencies between the form and the profile.

For example, given a form like this (login.html):

    <form>
     Email:           <input name="email"><br />
     Password:        <input name="password" type="password"><br />
    </form>

and a profile like this:

    package WebApp;

    sub _login_profile {
        return {
            required => [ qw(
                email
                passwd
            ) ],
        };
    }

and the following test script (login_profile.t):

    use Test::FormValidator 'no_plan';

    use WebApp;
    my $tfv = Test::FormValidator->new;
    $tfv->profile(Webapp->_login_profile);

    $tfv->html_ok('template.html');

in this scenario, the form contains the fields 'email' and 'passwd', and the profile contains the fields 'email' and 'passwd'. So running the test would fail:

    $ prove login_profile.t
    t/login_profile....NOK 1
    #     Failed test (t/login_profile.t at line 7)
    # HTML Form does not match profile:
    #    field 'password' is in the HTML but not in the profile
    #    field 'passwd' is in the profile but not in the HTML
    #
    # Looks like you failed 1 test of 1.
    t/01-tfv....dubious
            Test returned status 1 (wstat 256, 0x100)
    DIED. FAILED test 1
            Failed 1/1 tests, 0.00% okay
    Failed Test Stat Wstat Total Fail  Failed  List of Failed
    -------------------------------------------------------------------------------
    t/login_profile.t    1   256     1    1 100.00%  1
    Failed 1/1 test scripts, 0.00% okay. 1/1 subtests failed, 0.00% okay.

If you want to ignore the presense or absense of certain fields, you can do so by passing an 'ignore' option. Its value is either a list of fields to ignore or a regex to match all fields against.

    # ignore the fields 'foo' and 'bar'
    $tfv->html_ok($file, { ignore => [qw(foo bar)] }, 'form good!');

    # ignore the fields beginning with 'foo_'
    $tfv->html_ok($file, { ignore => /^foo_/ }, 'form good!');

Utility Methods

These functions do not print out 'ok' or 'not ok'.

diag()

All of the test methods (the methods ending in '_ok') print out diagnostic information on failure. However, if you are using other test functions (such as Test::More's 'ok'), calling $dfv->diag will display the same diagnostics.

For instance:

    use Test::More 'no_plan';
    use Test::FormValidator;

    my $results = $tfv->check(
        email => 'foo-at-example.com',
        pass1 => 'foo',
        pass2 => 'bar',
    );

    ok($results, 'form was perfect!') or $tfv->diag;

Running this test would produce the following output:

    $ prove profile.t
    t/profile....NOK 1
    #     Failed test (t/profile.t at line 10)
    # Validation results:
    #   missing:  name, phone
    #   invalid:
    #      email   => invalid
    #      pass1   => too_short, need_alpha_num
    #      pass2   => password_mismatch
    #   msgs:
    #     {
    #       'email' => '<span style="color:red;font-weight:bold"><span class="dfv_errors">* Invalid</span></span>',
    #       'pass1' => '<span style="color:red;font-weight:bold"><span class="dfv_errors">* Invalid</span></span>',
    #       'pass2' => '<span style="color:red;font-weight:bold"><span class="dfv_errors">* Invalid</span></span>'
    #     }
    # Looks like you failed 1 test of 1.
    t/profile....dubious
            Test returned status 1 (wstat 256, 0x100)
    DIED. FAILED test 1
            Failed 1/1 tests, 0.00% okay
    Failed Test Stat Wstat Total Fail  Failed  List of Failed
    -------------------------------------------------------------------------------
    t/profile.t    1   256     1    1 100.00%  1
    Failed 1/1 test scripts, 0.00% okay. 1/1 subtests failed, 0.00% okay.

AUTHOR

Michael Graham, <mgraham@cpan.org>

BUGS

Please report any bugs or feature requests to bug-test-formvalidator@rt.cpan.org, or through the web interface at http://rt.cpan.org. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SOURCE

The source code repository for this module can be found at http://github.com/mgraham/Test-FormValidator

ACKNOWLEDGEMENTS

Thanks to Mark Stosberg for input, including the crucially sensible suggestion to go with an object oriented approach. He also provided the code that extracts form fields from an HTML file.

COPYRIGHT & LICENSE

Copyright 2005 Michael Graham, All Rights Reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.