From: Can Sarıgöl Date: Mon, 19 Aug 2019 15:12:01 +0000 (+0300) Subject: added control to calling decode for empty contents (#237) X-Git-Tag: 0.7.2~25 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=79425b28d092a0e9d2577539a571467395b768c4;p=thirdparty%2Fhttpx.git added control to calling decode for empty contents (#237) * added tests for all decoder * fixed BrotliDecoder for b"" value --- diff --git a/httpx/decoders.py b/httpx/decoders.py index bfa96540..3ae822b9 100644 --- a/httpx/decoders.py +++ b/httpx/decoders.py @@ -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() diff --git a/tests/test_decoders.py b/tests/test_decoders.py index 036a4168..1b5d6e1d 100644 --- a/tests/test_decoders.py +++ b/tests/test_decoders.py @@ -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)]