Skip to content

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

@KennyChenBasis

Description

@KennyChenBasis

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)).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions