Skip to content
Myr

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

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Raise ValueError on change encoding * Always raise ValueError for simplicity * update CHANGELOG.md

authored by xzmeng · committed by GitHub · parent e4241c6 · Browse files · 3 files+33 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+33 added−0 removed

  • tests:+17 added−0 removed
  • other:+16 added−0 removed

3 files+33 added−0 removed

modified:httpx/_models.py+10 added
601 unmodified lines
602 return self._encoding603604 @encoding.setter605 def encoding(self, value: str) -> None:606 """607 Set the encoding to use for decoding the byte content into text.608609 If the `text` attribute has been accessed, attempting to set the610 encoding will throw a ValueError.611 """612 if hasattr(self, "_text"):613 raise ValueError(614 "Setting encoding after `text` has been accessed is not allowed."615 )616 self._encoding = value617618 @property619 def charset_encoding(self) -> typing.Optional[str]:
600 unmodified lines
modified:tests/models/test_responses.py+17 added
296 unmodified lines
297 assert response.text == "Snowman: â\x98\x83"298 assert response.encoding == "iso-8859-1"299300301def test_response_force_encoding_after_text_accessed():302 response = httpx.Response(303 200,304 content=b"Hello, world!",305 )306 assert response.status_code == 200307 assert response.reason_phrase == "OK"308 assert response.text == "Hello, world!"309 assert response.encoding == "utf-8"310311 with pytest.raises(ValueError):312 response.encoding = "UTF8"313314 with pytest.raises(ValueError):315 response.encoding = "iso-8859-1"316317318def test_read():319 response = httpx.Response(320 200,321 content=b"Hello, world!",
716 unmodified lines
modified:CHANGELOG.md+6 added
2 unmodified lines
3All notable changes to this project will be documented in this file.45The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## Unreleased89### Fixed1011* Raise `ValueError` on `Response.encoding` being set after `Response.text` has been accessed. (#2852)1213## 0.25.0 (11th Sep, 2023)1415### Removed16
1027 unmodified lines