]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
Raise ValueError on `Response.encoding` being set after `Response.text` has been...
authorxzmeng <aumo@foxmail.com>
Tue, 19 Sep 2023 07:54:32 +0000 (15:54 +0800)
committerGitHub <noreply@github.com>
Tue, 19 Sep 2023 07:54:32 +0000 (08:54 +0100)
* Raise ValueError on change encoding

* Always raise ValueError for simplicity

* update CHANGELOG.md

CHANGELOG.md
httpx/_models.py
tests/models/test_responses.py

index 66d2b080cd4fde82a7d6a7258ae04ee677aa0ff2..4842dfff8247592c80246840315f7ca02f6e10ff 100644 (file)
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.
 
 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
 
+## Unreleased
+
+### Fixed
+
+* Raise `ValueError` on `Response.encoding` being set after `Response.text` has been accessed. (#2852)
+
 ## 0.25.0 (11th Sep, 2023)
 
 ### Removed
index e1e45cf06b25a0bc9751d5e5ae22f85f304e2b4d..8a6bda04bbdd8fa534726464ca4bd1a6f26bbfd5 100644 (file)
@@ -603,6 +603,16 @@ class Response:
 
     @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
index 9e65de8154575d25b6bfa03a4cddc942e3969849..9177773a50480cd65926f7ec61e56965963c9d27 100644 (file)
@@ -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,