From 0c6441be35d9f8aa5bb2aa555ece5c4f762b3ff3 Mon Sep 17 00:00:00 2001 From: Cyprien Courtot Date: Thu, 17 Sep 2020 17:34:08 +0100 Subject: [PATCH] Fix: using Response.apparent_encoding when Response.encoding is None --- sseclient.py | 4 ++-- test_sseclient.py | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/sseclient.py b/sseclient.py index d2193e2..244c5c2 100644 --- a/sseclient.py +++ b/sseclient.py @@ -55,8 +55,8 @@ def _connect(self): requester = self.session or requests self.resp = requester.get(self.url, stream=True, **self.requests_kwargs) self.resp_iterator = self.iter_content() - self.decoder = codecs.getincrementaldecoder( - self.resp.encoding)(errors='replace') + encoding = self.resp.encoding or self.resp.apparent_encoding + self.decoder = codecs.getincrementaldecoder(encoding)(errors='replace') # TODO: Ensure we're handling redirects. Might also stick the 'origin' # attribute on Events like the Javascript spec requires. diff --git a/test_sseclient.py b/test_sseclient.py index 73cf7a3..6609606 100644 --- a/test_sseclient.py +++ b/test_sseclient.py @@ -73,9 +73,10 @@ def test_eols(): class FakeResponse(object): - def __init__(self, status_code, content, headers=None): + def __init__(self, status_code, content, headers=None, encoding="utf-8"): self.status_code = status_code - self.encoding = "utf-8" + self.encoding = encoding + self.apparent_encoding = "utf-8" if not isinstance(content, six.text_type): content = content.decode("utf-8") self.stream = content @@ -95,9 +96,10 @@ def join_events(*events): # Tests of parsing a multi event stream -def test_last_id_remembered(monkeypatch): +@pytest.mark.parametrize("encoding", ["utf-8", None]) +def test_last_id_remembered(monkeypatch, encoding): content = 'data: message 1\nid: abcdef\n\ndata: message 2\n\n' - fake_get = mock.Mock(return_value=FakeResponse(200, content)) + fake_get = mock.Mock(return_value=FakeResponse(200, content, encoding=encoding)) monkeypatch.setattr(requests, 'get', fake_get) c = sseclient.SSEClient('http://blah.com')