@@ -269,13 +269,14 @@ def body():
269269 def test_content_length_overrides_generator (self ):
270270 c = HTTP11Connection ('httpbin.org' )
271271 c ._sock = sock = DummySocket ()
272+
272273 def body ():
273274 yield b'hi'
274275 yield b'there'
275276 yield b'sir'
276277
277278 c .request (
278- 'POST' , '/post' , headers = {b'content-length' : b'10' }, body = body ()
279+ 'POST' , '/post' , body = body (), headers = {b'content-length' : b'10' }
279280 )
280281
281282 expected = (
@@ -288,8 +289,8 @@ def body():
288289 b"\r \n "
289290 b"hitheresir"
290291 )
291- received = b'' .join (sock .queue )
292292
293+ received = b'' .join (sock .queue )
293294 assert received == expected
294295
295296 def test_chunked_overrides_body (self ):
@@ -414,6 +415,7 @@ def body():
414415 def test_content_length_overrides_generator_unicode (self ):
415416 c = HTTP11Connection ('httpbin.org' )
416417 c ._sock = DummySocket ()
418+
417419 def body ():
418420 yield u'hi'
419421 yield u'there'
@@ -446,6 +448,40 @@ def test_http_upgrade_headers_only_sent_once(self):
446448
447449 assert received == expected
448450
451+ def test_exception_raised_for_illegal_body_type (self ):
452+ c = HTTP11Connection ('httpbin.org' )
453+
454+ with pytest .raises (ValueError ) as exc_info :
455+ body = 1234
456+ # content-length set so body type is set to BODY_FLAT. value doesn't matter
457+ c .request ('GET' , '/get' , body = body , headers = {'content-length' : str (len (str (body )))})
458+ assert 'Request body must be a bytestring, a file-like object returning bytestrings ' \
459+ 'or an iterable of bytestrings. Got: {}' .format (type (body )) in str (exc_info )
460+
461+ def test_exception_raised_for_illegal_elements_in_iterable_body (self ):
462+ c = HTTP11Connection ('httpbin.org' )
463+
464+ rogue_element = 123
465+ with pytest .raises (ValueError ) as exc_info :
466+ # content-length set so body type is set to BODY_FLAT. value doesn't matter
467+ body = ['legal1' , 'legal2' , rogue_element ]
468+ c .request ('GET' , '/get' , body = body , headers = {'content-length' : str (len (map (str , body )))})
469+ assert 'Elements in iterable body must be bytestrings. Illegal element: {}' .format (rogue_element )\
470+ in str (exc_info )
471+
472+ def test_exception_raised_for_filelike_body_not_returning_bytes (self ):
473+ c = HTTP11Connection ('httpbin.org' )
474+
475+ class RogueFile (object ):
476+ def read (self , size ):
477+ return 42
478+
479+ with pytest .raises (ValueError ) as exc_info :
480+ # content-length set so body type is BODY_FLAT. value doesn't matter
481+ c .request ('GET' , '/get' , body = RogueFile (), headers = {'content-length' : str (10 )})
482+ assert 'File-like bodies must return bytestrings. Got: {}' .format (int ) in str (exc_info )
483+
484+
449485class TestHTTP11Response (object ):
450486 def test_short_circuit_read (self ):
451487 r = HTTP11Response (200 , 'OK' , {b'content-length' : [b'0' ]}, None , None )
0 commit comments