如何模拟测试python请求

时间:2019-07-26 15:48:54

标签: python django mocking python-requests

我想知道如何编写模拟python请求测试。

def request_headers():
    payload = {
        'client_id': settings.STAT_SERVER['CLIENT_ID'],
        'client_secret': settings.STAT_SERVER['CLIENT_SECRET'],
        'username': settings.STAT_SERVER['USERNAME'],
        'password': settings.STAT_SERVER['PASSWORD'],
        'grant_type': 'password',
    }

我该如何模拟测试所有这些?

    token_url = settings.STAT_SERVER['URL'] + 'o/token/'

    r = requests.request(
        method="POST", url=token_url, data=payload, verify=False)

    if r.status_code != 200:
        msg = "Failed to authenticate. Error code {}: {}"
        msg = msg.format(r.status_code, r.text)
        LOGGER.error(msg)
    credentials = r.json()

这是base_headers

    base_headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json, */*'
    }
    base_headers['Authorization'] = "{} {}".format(
        credentials['token_type'], credentials['access_token']
    )
LOGGER.debug('Get token: credentials={}'.format(credentials))
return base_headers

1 个答案:

答案 0 :(得分:1)

The unittest.mock.patch decorator是解决这些问题的绝佳工具。

因此,您将执行以下操作:

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");