我已经阅读了多篇帖子,但我没有得到它,我在其他地方使用了相同的方法,但它有效,但这是另一个类中的方法,而不是函数。
插件/ iaw_api / helpers.py:
import requests
import json
def https_post_json(request_url, headers, data, timeout=20):
response = requests.post(request_url, json=data, headers=headers, timeout=timeout)
return json.loads(response.content)
插件/ iaw_api / iaw_api_runners.py:
from plugins.iaw_api.helpers import https_post_json
class IawApiRunner(object):
def __init__(self, runner_class_in):
self._runner_data_class = runner_class_in
self.result = None
def run_job(self):
if type(self._runner_data_class) == SomeRunner:
self._this_runner()
def _this_runner(self):
_task_id = https_post_json(<request-content>)
print _task_id
测试/ iaw_api / tests.py:
from plugins.iaw_api.helpers import https_post_json
from plugins.iaw_api.iaw_api_runners import IawApiRunner
class TestApiRunners(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestApiRunners, self).__init__(*args, **kwargs)
self.test_runner = IawApiRunner(SomeRunner)
def test_single_run_no_error(self):
with mock.patch('plugins.iaw_api.helpers.https_post_json') as MockPost:
MockPost.return_value = {'status_id': '59f0681cf9c32000132c7e89'}
self.test_runner.run_job()
这是简化的,我还没有添加断言。问题是当我运行测试时,实际的http_post会转到API,而不是响应是模拟返回值。
答案 0 :(得分:0)
您必须修补您测试代码中使用的名称;在这种情况下,它是https_post_json
(直接导入模块命名空间)。如果iaw_api_runners.py
仅使用import plugins
而_this_runner
运行_task_id = plugins.iaw_api.helpers.https_post_json(...)
,则您的补丁会正确。