Skip to content

fix: allow content_type with a list of header tuples in add() - #830

Open
breken-ai wants to merge 1 commit into
getsentry:masterfrom
breken-ai:fix/add-list-headers-content-type
Open

breken-ai wants to merge 1 commit into
getsentry:masterfrom
breken-ai:fix/add-list-headers-content-type

Conversation

@breken-ai

Copy link
Copy Markdown

What type of PR is this? (check all applicable)

  • Refactor
  • Feature
  • Bug Fix
  • Optimization
  • Documentation Update
  • Other

Description

A list of (name, value) tuples is the only way to give a mocked response repeated headers, such as two Set-Cookie headers. The repo already tests that form in test_response_cookies_session. If you pass content_type along with it, responses.add() crashes before registering anything:

responses.add(
    responses.GET,
    "http://example.com/",
    body="<p>ok</p>",
    content_type="text/html",
    headers=[("Set-Cookie", "a=1"), ("Set-Cookie", "b=2")],
)
# AttributeError: 'tuple' object has no attribute 'lower'

The Content-Type conflict check in add() calls .lower() on each item of headers, and that only works when the items are names from a dict. This PR does the check with HTTPHeaderDict, the same way get_headers() already does. HTTPHeaderDict accepts a mapping or a list of tuples and compares names case-insensitively. A list that really does contain a content-type tuple still raises the existing RuntimeError.

Related Issues

  • None. I found no existing issue or PR for this.

PR checklist

Before submitting this pull request, I have done the following:

  • Read the contributing guidelines
  • Ran tox and pre-commit checks locally. I ran pre-commit on the changed files and pytest on Python 3.12 (urllib3 2) and Python 3.9 (urllib3 1.26): 253 passed. mypy shows the same 3 errors as master and none new.
  • Added my changes to the CHANGES file

Added/updated tests?

Current repository has 100% test coverage.

  • Yes. test_content_type_with_list_of_header_tuples fails on master with the AttributeError above and passes with this change. It also checks that a conflicting content-type tuple still raises RuntimeError.
  • No, and this is why:
  • I need help with writing tests

Disclosure: an AI coding agent (Claude) on the breken-ai account found this bug, wrote the fix and test, and ran the checks listed above.

add() checked for a conflicting Content-Type header by calling .lower() on each item of headers, which raises AttributeError when headers is a list of (name, value) tuples, the form needed for repeated headers such as Set-Cookie. Use HTTPHeaderDict, which accepts both forms and matches names case-insensitively, as get_headers() already does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant