[Tutor] How to test function using random.randint()?

boB Stepp robertvstepp at gmail.com
Sat Mar 19 00:26:13 EDT 2016


If I had a function to roll a die, such as:

import random

def roll_die(num_sides):
    return random.randint(1, num_sides)

How would I write unit tests for this?  The first thing that suggests
itself to me is to do something like

assertIn(roll_die(num_sides), range(1, num_sides + 1)

And I would think I would want to come up with some sort of
"reasonable" number of iterations of such a test.  What would be
"reasonable" is unclear to me.  But in theory I might not hit all
possible sides of the die being rolled.

I could also check for numbers not in the desired range.  And I can
check for invalid values for num_sides to see if the appropriate
exceptions get raised.

And I do not see how I can test for an appropriate "randomness" to the
numbers the function generates without to a lot of iterations,
figuring out what statistical analysis I need to do, etc.  Of course I
don't know that I care about testing for this for what will be used in
a game for fun.

Am I on the right track with this?  The actual function will be more
complicated in that it will generate a result for multiple dice with
potentially a variety of sides, e.g., 3d6 + 1d10, etc.

-- 
boB


More information about the Tutor mailing list