Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice when writing Perl tests that involve randomness?

While working on some updates to my module List::Gen, I decided to add a ->pick(num) method, which will return a num sized list of random elements from its source. To test this, I used srand to seed the random number generator, and made several tests of the form:

srand 1234;
is $src->pick(5)->str, '3 6 1 7 9';

And this all worked well on the Windows machine I was on at the time. However, when I moved the project over to a Mac workstation, all of the randomness tests failed, since despite having the same random seed, rand was producing different results. I gather this is from different underlying C implementations of rand().

So the question is, what is the best cross platform way to test these functions? Should I overload the rand function with my own? Should I build in hooks to the functions that use rand to enable a "testing" mode that produces predicable output? Are there other methods?

I would prefer answers that include core Perl techniques, as I am trying to keep the module's dependency tree small.

Test::Random and Test::MockRandom seem to be CPAN's suggestions, does anyone have experience with these modules?

like image 374
Eric Strom Avatar asked Apr 19 '11 18:04

Eric Strom


1 Answers

I have not used either one.

Looks like Test::Random would be a better choice for you since you are apparently just using randomness in your testing, not in your released code. It should be a lot simpler to use.

The Test::MockRandom module forces the rand() function to return a deterministic sequence.

like image 94
Chris Pousset Avatar answered Sep 20 '22 18:09

Chris Pousset