How to permanently mock return value of a function in python unittest

半世苍凉 提交于 2021-01-27 17:45:57

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/56139563/how-to-permanently-mock-return-value-of-a-function-in-python-unittest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!