如何模拟requests.post(XXXXXX).json()

时间:2018-04-10 09:32:47

标签: python amazon-web-services aws-lambda

我正在努力模拟HTTP请求。

请告诉我如何使用json()方法模拟请求。

模拟代码(测试)

class TestHandle(TestCase):
    response_json = {
        'id': 'UJ1jmz-0t6CADWtTuR4DOqfOuDzxCV0m',
    }

    # @patch('botocore.vendored.requests.post')
    @patch('botocore.vendored.requests.post', return_value=response_json)
    def test_handle(self, post_mock1):
        event = {"body": "{\"id\": \"user000001\",\"password\": \"pw000001\"}"}
        handle(event, context)
        self.assertEqual(post_mock1.call_count, 1)

模拟代码

response_json = requests.post('https://aaaa.sample/test', data=json.dumps(payload), headers=headers).json()

结果

Ran 2 tests in 5.463s

FAILED (errors=1)

Error
Traceback (most recent call last):
  File "C:\Users\TempUser\AppData\Local\Programs\Python\Python36-32\lib\unittest\case.py", line 59, in testPartExecutor
    yield
  File "C:\Users\TempUser\AppData\Local\Programs\Python\Python36-32\lib\unittest\case.py", line 605, in run
    testMethod()
  File "C:\Users\TempUser\AppData\Local\Programs\Python\Python36-32\lib\site-packages\mock\mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "C:\Users\TempUser\PycharmProjects\sample\functions\login\test\test_handle.py", line 27, in test_handle
    handle(event, context)
  File "C:\Users\TempUser\PycharmProjects\sample\functions\login\main.py", line 33, in handle
    response_json = requests.post('https://aaaa.sample/test', data=json.dumps(payload), headers=headers).json()
AttributeError: 'dict' object has no attribute 'json'


Process finished with exit code 1

我想做的只是从HTTP响应中提取body(json格式)。

0 个答案:

没有答案