1

我有这个 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
4

2 回答 2

1

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

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
于 2018-12-05T16:59:58.800 回答
1

您可以使用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'

试试它的文档,你可以用它做很多很酷的事情。

于 2018-12-03T18:56:53.000 回答