带有URL参数的python模拟响应

时间:2018-12-03 17:48:43

标签: python mocking python-responses

我有这个URL,我可以成功调用此回复。

https://www.udemy.com/api-2.0/courses/?page=1&page_size=5

现在,我正在尝试模拟响应并测试我的api,但是模拟抛出ConnectionError

with responses.RequestsMock() as rsps:
    url = 'https://www.udemy.com/api-2.0/courses/?page=1&page_size=5'
    rsps.add(responses.GET, url,
                     body=mocked_json, status=status_code,
                     content_type='application/json')

错误:-

ConnectionError: Connection refused: GET https://www.udemy.com/api-2.0/courses?page=1&page_size=5

2 个答案:

答案 0 :(得分:0)

您可以使用requests_mock

执行以下操作:

url = 'https://www.udemy.com/api-2.0/courses/?page=1&page_size=5'
expected_response = get_test_mock_response()

with requests_mock.mock() as req_mock:
    req_mock.get(url, text=expected_response, status_code=200)

    res = call_real_request_method()
    assert res == expected_response, 'Bad response received'

尝试一下它的文档,您可以用它做很多有趣的事情。

答案 1 :(得分:0)

您的示例代码不完整,但是我根据您的示例改编了一些示例。

import responses
import requests

with responses.RequestsMock() as rsps:

    url = 'https://www.udemy.com/api-2.0/courses/?page=1&page_size=5'
    mocked_json = '{"key": "value"}'
    status_code = 200

    rsps.add(
        responses.GET, 
        url,
        body=mocked_json,
        status=status_code,
        content_type='application/json'
    )

    resp = requests.get('https://www.udemy.com/api-2.0/courses/?page=1&page_size=5')
    assert resp.status_code == 200