Question

I have this piece of code that I can use to generate a random number of values:

import random
def random_digit_number(num_of_digits, leading_zeroes=True):
    """
    Generate a random number with specified number of digits
    """
    if not leading_zeroes:
        return random.randint(10**(num_of_digits-1), 10**num_of_digits-1)
    else:
        return str("%0" + str(num_of_digits) + "d") % random.randint(0, 10**num_of_digits-1)

I am supposed to write a unittest for this function.

My question is, how do I test this function considering that it will generate random values? How do I cover all the edge cases? What do I even test for here?

Was it helpful?

Solution

I can see at least four ways you can test this, but there are probably more.

  1. Test whether it generates the correct number of values for various inputs, including requests for very large numbers of random numbers.
  2. Test whether it behaves correctly when the number of values requested is negative.
  3. Test whether the flag leading_zeroes actually works as expected.
  4. Seed the random number generator with a fixed value using random.seed() and then verify that the sequence is deterministic and matches the expected sequence. Note that this may be implementation-dependent, so this test may not be effective if your function is intended to run on different versions of Python.

OTHER TIPS

  1. Mock random in this module using unittest.mock.patch
  2. Run this function "enough times" assert every output is within expected range

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top