I have a function
# foo.py
NUM_SHARDS = 10
def get_shard(shard_key: int) -> int
return (shard_key % NUM_SHARDS) + 1
I want to mock this function such that whenever this function is called, it returns a certain value. I've tried patching like such
# test.py
@mock.patch('foo.get_shard', return_value=11)
def testSomething(self, patched_func):
patched_func() # >> 11 ... OK so this is fine but
get_shard(4) # >> 5 .... Original impl being executed
I want to deeply modify this function to always return this value, whether this function is called directly from the unittest or not.
For context, I have a number of production shards (10) and one test shard (11). The get_shard function is called in numerous and the production version of the function is only aware of 10 shards. So, I would like for this function to always return 11 (test shard number) when executed in the context of a unit test.
The mock.patch
method is meant to temporarily mock a given object. If you want to permanently alter the return value of a function, you can simply override it by assigning to it with a Mock
object with return_value
specified:
import foo
from unittest.mock import Mock
foo.get_shard = Mock(return_value=11)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With