Folks might remember my talk at, I think it was YAPC 2008, "Generating Test
Data With The Sims".
http://schwern.org/talks/Generating%20Test%20Data%20With%20The%20Sims.pdf

It was about building up little functions to generate random, but valid, data
and then using those to make random, but valid, objects which were used to
make more objects and in this way quickly build up interesting, dynamic test
databases.  This solves the very common problem of "how do I test things that
need lots of data to work" possibly involving objects that need more objects
and so on.

Its mostly technique, but there were a few bits of technology missing like
being able to repeat a failed test.  I taught the technique at "Better
Programming Through Testing" at this year's YAPC and the issue came up again.

So here's Test::Sims, a support module for the Sim's testing technique.  It...

* Allow repeatable testing of failures (see TEST_SIMS_SEED)
* Provides an easy way to quickly write random data functions (make_rand)
* Sets up exports for your random and sim functions

You can get it off github:
http://github.com/schwern/Test-Sims

Or from CPAN.

Here's an example of making a simple package to generate random dates.

    package Sim::Date;

    use strict;
    use warnings;

    use DateTime;
    use Test::Sims;

    # Create rand_year(), rand_month(), etc...
    # All exportable on demand or with the :rand tag
    make_rand year  => [1800..2100];
    make_rand month => [1..12];
    make_rand day   => [1..31];
    make_rand hour  => [0..23];
    make_rand minute=> [0..59];
    make_rand second=> [0..59];

    sub sim_datetime {
        my %defaults = (
            year   => rand_year(),
            month  => rand_month(),
            day    => rand_day(),
            hour   => rand_hour(),
            minute => rand_minute(),
            second => rand_second(),
        );

        return DateTime->new(
            %defaults, @_
        );
    }

    # Export sim_datetime()
    export_sims();

And then using it.

    use Sim::Date;

    # Random date.
    my $date = sim_datetime;

    # Random date in the year 2009
    my $date = sim_datetime(
        year => 2009
    );

Sim functions can combine together to make more complicated sims.

    package Sim::Person;

    use Test::Sims;

    sub sim_person {
        my %defaults = (
            name     => rand_name(),
            age      => rand_age(),
            birthday => sim_datetime(),
        );

        return Person->new( %defaults, @_ );
    }

    export_sims();

Combine with things like Data::Random and Data::Generate to create yet more
random data quickly.


-- 
54. "Napalm sticks to kids" is *not* a motivational phrase.
    -- The 213 Things Skippy Is No Longer Allowed To Do In The U.S. Army
           http://skippyslist.com/list/

Reply via email to