Home > front end >  Why mock patching works with random but not with np?
Why mock patching works with random but not with np?

Time:02-23

I have a module where a number of different functions use random numbers or random choices. I am trying to use mock and patch to inject pre-chosen values in place of these random selections but can't understand an error I am receiving.

In the function I am testing, I use

np.random.randint

when I use the code

from unittest import mock
import random
mocked_random_int = lambda : 7
with mock.patch('np.random.randint', mocked_random_int):

I get an error message no module named np. However, numpy is imported as np and other functions are calling it just fine.

Even more perplexing if I edit the code above to remove the 'np' at the front it does what I want:

with mock.patch('random.randint', mocked_random_int):

But I want to understand why the code works without the np. Thank you!

CodePudding user response:

There is a difference between a module or package name and the variable it is assigned to in any given namespace. A simple import

import numpy

tells python to check its imported module list, import numpy as necessary, and assign the module to the variable "numpy"

import numpy as np

is almost the same, except that you assign to a variable "np". Its still the same numpy package, its just that you've aliased it differently.

mock.patch will import and patch the module regardless of whether you've already imported it, but you need to give the module name, not your current module's alias to the module.

  • Related