added control to calling decode for empty contents (#237)

* added tests for all decoder

* fixed BrotliDecoder for b"" value
This commit is contained in:
Can Sarıgöl 2019-08-19 18:12:01 +03:00 committed by Tom Christie
parent ef9fc0f3a7
commit 79425b28d0
2 changed files with 29 additions and 1 deletions

View 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()

View 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)]