I think you're approaching it the wrong way. You need to treat it as a black box and control just the inputs -- in this case, rand.

I wrote Test::MockRandom for exactly this kind of testing. Use it to test your boundary conditions on rand, as that's the only thing that will matter to whether you get all 10 digits. It's much better than playing with srand.

PIN length is almost an invariant because it almost doesn't depend on any input data. You're only at risk of a 5 digit pin (or greater) if the maximum rand value happened to give you "10" -- so I would check length at the same time that I check what happens when the random value (before multiplication) is nearly one.

Update: Here's what it would look like to check the boundary conditions:

use Test::MockRandom 'Some::Other::Package'; use Some::Other::Package 'pin'; # exports pin() # list of values for rand to use srand( ( (0) x 4, ( oneish() ) x 4 ); # 0,0,0,0,1,1,1,1 is( pin(), '0000', "rand always zero" ); is( pin(), '9999', "rand always almost one");

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.


In reply to Re: Testing Random Code by xdg
in thread Testing Random Code by Ovid

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.