The problem: automating tested of a data-driven application requires creating test data to run the test, and removing the test data again when the test is finished.

The goal: Make the data clean up process automatic. The data should be cleaned up without an explicit call to a clean up function, and it should work even if the test script dies half-way through.

The solution: As part of creating the test data, keep track of the IDs of the data created in a package-scoped array. Use an END {} block to call the cleanup function, using the the package-scoped array to know what to clean up. The END block gets called when the script is exiting, even if it is "die"'ing.

Some example pseudo-code:

our @IDS_TO_DELETE; sub create_test_widget { my $widget = Widget->new; push @IDS_TO_DELETE, $widget->id; return $widget; } sub delete_test_widgets { for my $id (@IDS_TO_DELETE) { Widget->delete($id); } } END { delete_test_widgets(); }

There you have it. Now just by creating some test data, it will automatically be removed when test is finished. I suggest putting a pair of functions like this in a private testing module and then importing the test data creation function.


In reply to Test Technique: Self-removing test data by markjugg

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.