]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
added control to calling decode for empty contents (#237)
authorCan Sarıgöl <cansarigol@derinbilgi.com.tr>
Mon, 19 Aug 2019 15:12:01 +0000 (18:12 +0300)
committerTom Christie <tom@tomchristie.com>
Mon, 19 Aug 2019 15:12:00 +0000 (16:12 +0100)
* added tests for all decoder

* fixed BrotliDecoder for b"" value

httpx/decoders.py
tests/test_decoders.py

index bfa965404c60c5d775a918cedeab9002967b1e16..3ae822b9c0e603f8615718223ac0390cdf6dda0e 100644 (file)
@@ -98,8 +98,12 @@ class BrotliDecoder(Decoder):
             brotli is not None
         ), "The 'brotlipy' or 'brotli' library must be installed to use 'BrotliDecoder'"
         self.decompressor = brotli.Decompressor()
+        self.seen_data = False
 
     def decode(self, data: bytes) -> bytes:
+        if not data:
+            return b""
+        self.seen_data = True
         try:
             if hasattr(self.decompressor, "decompress"):
                 return self.decompressor.decompress(data)
@@ -108,6 +112,8 @@ class BrotliDecoder(Decoder):
             raise DecodingError from exc
 
     def flush(self) -> bytes:
+        if not self.seen_data:
+            return b""
         try:
             if hasattr(self.decompressor, "finish"):
                 self.decompressor.finish()
index 036a4168703591a885b56b6d3ccb9eedbec44b57..1b5d6e1dee4971e924a15e832cd36209558b05fb 100644 (file)
@@ -4,7 +4,13 @@ import brotli
 import pytest
 
 import httpx
-from httpx.decoders import TextDecoder
+from httpx.decoders import (
+    BrotliDecoder,
+    DeflateDecoder,
+    GZipDecoder,
+    IdentityDecoder,
+    TextDecoder,
+)
 
 
 def test_deflate():
@@ -79,6 +85,22 @@ def test_streaming():
     assert response.read() == body
 
 
+@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))
+def test_empty_content(header_value):
+    headers = [(b"Content-Encoding", header_value)]
+    response = httpx.Response(200, headers=headers, content=b"")
+    assert response.content == b""
+
+
+@pytest.mark.parametrize(
+    "decoder", (BrotliDecoder, DeflateDecoder, GZipDecoder, IdentityDecoder)
+)
+def test_decoders_empty_cases(decoder):
+    instance = decoder()
+    assert instance.decode(b"") == b""
+    assert instance.flush() == b""
+
+
 @pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))
 def test_decoding_errors(header_value):
     headers = [(b"Content-Encoding", header_value)]