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

Simple Data Structure Equality

Test::More’s is() function checks scalar equality, but what about more complicated structures, such as lists of lists of lists? Good tests often need to peer into these data structures to test whether, deep down inside, they are truly equal. The first solution that may come to mind is a recursive function or a series of nested loops. Hold that thought, though—Test::More and other test modules provide a better way with their comparison functions.

How do I do that?

Save this code as deeply.t:

    use Test::More tests => 1;

    my $list1 =
    [
        [
            [ 48, 12 ],
            [ 32, 10 ],
        ],
        [
            [ 03, 28 ],
        ],
    ];

    my $list2 =
    [
        [
            [ 48, 12 ],
            [ 32, 11 ],
        ],
        [
            [ 03, 28 ],
        ],
    ];

    is_deeply( $list1, $list2, 'existential equivalence' );

Run it with prove -v to see the diagnostics:

    $ prove -v deeply.t
    deeply....1..1
    not ok 1 - existential equivalence
    #     Failed test (deeply.t at line 23)
    #     Structures begin differing at:
    #          $got->[0][1][1] = '10'
    #     $expected->[0][1][1] = '11'
    # Looks like you failed 1 tests of 1.
    dubious
      Test returned status 1 (wstat 256, 0x100)
    DIED. FAILED test 1
      Failed 1/1 tests, 0.00% okay
    Failed 1/1 test scripts, 0.00% okay. 1/1 subtests failed, 0.00% okay.
    Failed Test Stat Wstat Total Fail  Failed  List of Failed
    ---------------------------------------------------------------------------
    deeply.t       1   256     1    1 100.00%  1

What just happened?

The example test compares two lists of lists with the is_deeply() function exported by Test::More. Note the difference between the two lists. Because ...

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