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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Test Technique: Self-removing test data
by Mutant (Priest) on Jul 18, 2007 at 08:44 UTC | |
by markjugg (Curate) on Jul 18, 2007 at 13:30 UTC | |
by Anonymous Monk on Jul 19, 2007 at 03:45 UTC | |
Re: Test Technique: Self-removing test data
by perrin (Chancellor) on Jul 18, 2007 at 03:51 UTC | |
by markjugg (Curate) on Jul 18, 2007 at 13:25 UTC | |
by perrin (Chancellor) on Jul 18, 2007 at 16:01 UTC | |
by Ovid (Cardinal) on Jul 19, 2007 at 10:01 UTC | |
by Tabari (Monk) on Jul 19, 2007 at 16:04 UTC | |
Re: Test Technique: Self-removing test data
by CountZero (Bishop) on Jul 18, 2007 at 21:05 UTC | |
by markjugg (Curate) on Jul 19, 2007 at 01:55 UTC |