getsentry / responses

A utility for mocking out the Python Requests library.
Apache License 2.0
4.17k stars 356 forks source link

With `urllib3>=2`, mocking HEAD response with content-length header set requires body #708

Closed KennyChenBasis closed 6 months ago

KennyChenBasis commented 8 months ago

Describe the bug

With urllib3>=2, mocking HEAD responses with content-length header set requires a body with the right length, otherwise an IncompleteRead is raised. This should not be the case since HEAD responses do not have bodies.

Additional context

The fix is probably to pass the request method to HTTPResponse when forming the response. See the code around https://github.com/urllib3/urllib3/blob/733f638a2faa02b4ff8a9f3b5668949d39396b8b/src/urllib3/response.py#L624.

Version of responses

0.25.0

Steps to Reproduce

Run pytest on

import requests
import responses

def test_download():
    url = 'http://test'
    content = b'download me'
    headers = {'Content-length': str(len(content))}
    with responses.RequestsMock() as rsps:
        rsps.head(url, headers=headers)

        res = requests.head(url)
        res.raise_for_status()
        assert int(res.headers['content-length']) == 11
        assert res.text == ''

Expected Result

Test passes, like with urllib3<2.

Actual Result

Test fails with requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(0 bytes read, 11 more expected)', IncompleteRead(0 bytes read, 11 more expected)).