我正在为使用requests库的模块创建测试套件。但是,我尝试模拟特定请求的多个不同返回值时遇到了问题。这是我不起作用的代码片段:
class MyTests(unittest.TestCase):
@patch('mypackage.mymodule.requests.post')
def test_change_nested_dict_function(self, mock_post):
mock_post.return_value.status_code = 200
mock_post.return_value.json = nested_dictionary
modified_dict = mymodule.change_nested_dict()
self.assertEqual(modified_dict['key1']['key2'][0]['key3'], 'replaced_value')
我正在尝试模拟的函数:
import requests
def change_nested_dict():
uri = 'http://this_is_the_endpoint/I/am/hitting'
payload = {'param1': 'foo', 'param2': 'bar'}
r = requests.post(uri, params=payload)
# This function checks to make sure the response is giving the
# correct status code, hence why I need to mock the status code above
raise_error_if_bad_status_code(r)
dict_to_be_changed = r.json()
def _internal_fxn_to_change_nested_value(dict):
''' This goes through the dict and finds the correct key to change the value.
This is the actual function I am trying to test above'''
return changed_dict
modified_dict = _internal_fxn_to_change_nested_value(dict_to_be_changed)
return modified_dict
我知道简单的方法是不要有嵌套函数,但我只是展示整个函数代码的一部分。相信我,嵌套函数是必要的,我真的不想改变它。
我的问题是,我不知道如何模拟`requests.post`,然后设置状态码和内部JSON解码器的返回值。我也找不到绕过此问题的方法,因为我好像无法修补内部函数,这也将解决此问题。有人有任何建议/想法吗?非常感谢。
_internal_fxn_to_change_nested_value
,我在你的测试中没有看到这个函数的任何参数,给出的答案似乎是正确的。 - Gang