Skip to content
Myr

Merge pull request #4976 from eduardomourar/feature/strip-utf8-bom

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fix for response with UTF-8 BOM

authored by Kenneth Reitz · committed by GitHub · parents 3e7d0a8, 4bce5a0 · Browse files · 4 files+39 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+39 added−0 removed

  • tests:+31 added−0 removed
  • other:+8 added−0 removed

4 files+39 added−0 removed

modified:requests/models.py+3 added
871 unmodified lines
872873 # Fallback to auto-detected encoding.874 if self.encoding is None:875 encoding = self.apparent_encoding876 # Forcefully remove BOM from UTF-8877 elif self.encoding.lower() == 'utf-8':878 encoding = 'utf-8-sig'879880 # Decode unicode from given encoding.881 try:882 content = str(self.content, encoding, errors='replace')
92 unmodified lines
modified:tests/test_testserver.py+30 added
54 unmodified lines
55 assert r.status_code == 20056 assert r.text == u'roflol'57 assert r.headers['Content-Length'] == '6'5859 def test_text_bom_response(self):60 """the text_response_server sends the given text with UTF-8 BOM"""61 server = Server.text_response_server(62 "HTTP/1.1 200 OK\r\n" +63 "Content-Type: text/html; charset=UTF-8\r\n" +64 u'\r\n\ufeff<doctype html><html><body>ジェーピーニック</body></html>'65 )6667 with server as (host, port):68 r = requests.get('http://{}:{}'.format(host, port))6970 assert r.status_code == 20071 assert r.text == u'<doctype html><html><body>ジェーピーニック</body></html>'72 assert r.headers['Content-Type'] == 'text/html; charset=UTF-8'7374 def test_json_bom_response(self):75 """the text_response_server sends the given JSON with UTF-8 BOM"""76 server = Server.text_response_server(77 "HTTP/1.1 200 OK\r\n" +78 "Content-Type: application/json; charset=utf-8\r\n" +79 u'\r\n\ufeff{"success": true}'80 )8182 with server as (host, port):83 r = requests.get('http://{}:{}'.format(host, port))8485 assert r.status_code == 20086 assert r.json() == {'success': True}87 assert r.headers['Content-Type'] == 'application/json; charset=utf-8'8889 def test_basic_response(self):90 """the basic response server returns an empty http response"""91 with Server.basic_response_server() as (host, port):92 r = requests.get('http://{}:{}'.format(host, port))
104 unmodified lines
modified:tests/test_utils.py+1 added
331 unmodified lines
332 assert guess_json_utf(b'\x00\x00\x00\x00') is None333334 @pytest.mark.parametrize(335 ('encoding', 'expected'), (336 ('utf-8-sig', 'utf-8-sig'),337 ('utf-16-be', 'utf-16'),338 ('utf-16-le', 'utf-16'),339 ('utf-32-be', 'utf-32'),340 ('utf-32-le', 'utf-32')
444 unmodified lines
modified:.gitignore+5 added
12 unmodified lines
13*.pyc14*.swp15*.egg16env/17.venv/18.eggs/19.tox/20.pytest_cache/21.vscode/22.eggs/2324.workon2526t.py
5 unmodified lines