O'Reilly logo

Perl Testing: A Developer's Notebook by Chromatic, Ian Langworth

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Data Composition

As the data structures your code uses become more complex, so will your tests. It’s important to verify what actually makes up a data structure instead of simply comparing it to an existing structure. You could iterate through each level of a complex nested hash of arrays, checking each and every element. Fortunately, the Test::Deep module neatens up code testing complicated data structures and provides sensible error messages.

How do I do that?

Save the following as cmp_deeply.t:

    use Test::More tests => 1;
    use Test::Deep;

    my $points =
    [
        { x => 50, y =>  75 },
        { x => 19, y => -29 },
    ];

    my $is_integer = re('^-?\d+$');

    cmp_deeply( $points,
      array_each(
        {
          x => $is_integer,
          y => $is_integer,
        }
      ),
            'both sets of points should be integers' );

Now run cmp_deeply.t from the command line with prove. It will show one successful test:

    $ prove cmp_deeply.t
    cmp_deep....ok
    All tests successful.
    Files=1, Tests=1,  0 wallclock secs ( 0.06 cusr +  0.00 csys =  0.06 CPU)

What just happened?

cmp_deeply(), like most other testing functions, accepts two or three arguments: the data structure to test, what you expect the structure to look like, and an optional test description. The expected data, however, is a special test structure with a format containing special Test::Deep functions.

The test file begins by creating a regular expression using re(), a function exported by Test::Deep. re() declares that the data must match the given regular expression. If you use a regular expression reference ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required