Testing things that involve randomness
Many applications rely on the random
module to create random values or put values into a random order. In many statistical tests, repeated random shuffling or random selection is done. When we want to test one of these algorithms, any intermediate results or details of the processing are essentially impossible to predict.
We have two choices for trying to make the random
module predictable enough to write meaningful unit tests:
- Set a known seed value; this is common, and we've made heavy use of this in many other recipes
- Use
unittest.mock
to replace therandom
module with something predictable
In this recipe, we'll look at ways to unit test algorithms that involve randomness.
Getting ready
Given a sample dataset, we can compute a statistical measure such as a mean or median. A common next step is to determine the likely values of these statistical measures for some overall population....