Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise ValueError on Response.encoding being set after Response.text has been accessed #2852

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions httpx/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,16 @@ def encoding(self) -> typing.Optional[str]:

@encoding.setter
def encoding(self, value: str) -> None:
"""
Set the encoding to use for decoding the byte content into text.

If the `text` attribute has been accessed, attempting to set the
encoding will throw a ValueError.
"""
if hasattr(self, "_text"):
raise ValueError(
"Setting encoding after `text` has been accessed is not allowed."
)
self._encoding = value

@property
Expand Down
17 changes: 17 additions & 0 deletions tests/models/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,23 @@ def test_response_force_encoding():
assert response.encoding == "iso-8859-1"


def test_response_force_encoding_after_text_accessed():
response = httpx.Response(
200,
content=b"Hello, world!",
)
assert response.status_code == 200
assert response.reason_phrase == "OK"
assert response.text == "Hello, world!"
assert response.encoding == "utf-8"

with pytest.raises(ValueError):
response.encoding = "UTF8"

with pytest.raises(ValueError):
response.encoding = "iso-8859-1"


def test_read():
response = httpx.Response(
200,
Expand Down