66Unit tests for hyper's HTTP/1.1 implementation.
77"""
88from collections import namedtuple
9- from io import BytesIO
9+ from io import BytesIO , StringIO
10+
11+ import pytest
1012
1113import hyper
1214from hyper .http11 .connection import HTTP11Connection
1315from hyper .http11 .response import HTTP11Response
1416from hyper .common .headers import HTTPHeaderMap
17+ from hyper .compat import bytes
1518
1619
1720class TestHTTP11Connection (object ):
@@ -218,6 +221,69 @@ def test_response_short_reads(self):
218221 assert r .read (5 ) == b'champ'
219222 assert r .read (5 ) == b''
220223
224+ def test_request_with_unicodestring_body (self ):
225+ c = HTTP11Connection ('http2bin.org' )
226+ c ._sock = DummySocket ()
227+
228+ with pytest .raises (ValueError ):
229+ c .request (
230+ 'POST' ,
231+ '/post' ,
232+ headers = HTTPHeaderMap ([('User-Agent' , 'hyper' )]),
233+ body = u'hi'
234+ )
235+
236+ def test_request_with_file_body_in_text_mode (self ):
237+ # Testing this is tricksy: in practice, we do this by passing a fake
238+ # file and monkeypatching out 'os.fstat'. This makes it look like a
239+ # real file.
240+ FstatRval = namedtuple ('FstatRval' , ['st_size' ])
241+ def fake_fstat (* args ):
242+ return FstatRval (16 )
243+
244+ old_fstat = hyper .http11 .connection .os .fstat
245+
246+ try :
247+ hyper .http11 .connection .os .fstat = fake_fstat
248+ c = HTTP11Connection ('http2bin.org' )
249+ c ._sock = DummySocket ()
250+
251+ f = DummyFile (b'' )
252+ f .buffer = StringIO (u'some binary data' )
253+
254+ with pytest .raises (ValueError ):
255+ c .request ('POST' , '/post' , body = f )
256+ finally :
257+ # Put back the monkeypatch.
258+ hyper .http11 .connection .os .fstat = old_fstat
259+
260+ def test_request_with_unicode_generator_body (self ):
261+ c = HTTP11Connection ('http2bin.org' )
262+ c ._sock = DummySocket ()
263+ def body ():
264+ yield u'hi'
265+ yield u'there'
266+ yield u'sir'
267+
268+ with pytest .raises (ValueError ):
269+ c .request ('POST' , '/post' , body = body ())
270+
271+ def test_content_length_overrides_generator_unicode (self ):
272+ c = HTTP11Connection ('http2bin.org' )
273+ c ._sock = DummySocket ()
274+ def body ():
275+ yield u'hi'
276+ yield u'there'
277+ yield u'sir'
278+
279+ with pytest .raises (ValueError ):
280+ c .request (
281+ 'POST' ,
282+ '/post' ,
283+ headers = {b'content-length' : b'10' },
284+ body = body ()
285+ )
286+
221287
222288class TestHTTP11Response (object ):
223289 def test_short_circuit_read (self ):
@@ -233,6 +299,9 @@ def __init__(self):
233299 self .can_read = False
234300
235301 def send (self , data ):
302+ if not isinstance (data , bytes ):
303+ raise TypeError ()
304+
236305 self .queue .append (data )
237306
238307 def recv (self , l ):
0 commit comments