buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_short_body(self): # check to see if server closes connection when body is too short # for cl header to_send = tobytes( "GET /short_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() ...
def test_short_body(self): # check to see if server closes connection when body is too short # for cl header to_send = tobytes( "GET /short_body HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: 0\r\n" "\r\n" ) self.connec...
def test_long_body(self): # check server doesnt close connection when body is too long # for cl header to_send = tobytes( "GET /long_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() sel...
def test_long_body(self): # check server doesnt close connection when body is too long # for cl header to_send = tobytes( "GET /long_body HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: 0\r\n" "\r\n" ) self.connect() ...
def test_equal_body(self): # check server doesnt close connection when body is equal to # cl header to_send = tobytes( "GET /equal_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() self....
def test_equal_body(self): # check server doesnt close connection when body is equal to # cl header to_send = tobytes( "GET /equal_body HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: 0\r\n" "\r\n" ) self.connect() ...
def test_equal_body(self): def test_no_content_length(self): # wtf happens when there's no content-length to_send = tobytes( "GET /no_content_length HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() ...
def test_equal_body(self): def test_no_content_length(self): # wtf happens when there's no content-length to_send = tobytes( "GET /no_content_length HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: 0\r\n" "\r\n" ) self.connec...
def tearDown(self): def test_request_body_too_large_with_wrong_cl_http10(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n\n" to_send += body to_send = tobytes(to_send) self.connect()
def tearDown(self): def test_request_body_too_large_with_wrong_cl_http10(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\r\nContent-Length: 5\r\n\r\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_wrong_cl_http10(self): def test_request_body_too_large_with_wrong_cl_http10_keepalive(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n" "Connection: Keep-Alive\n\n" to_send += body to_send = tobytes(to_send) ...
def test_request_body_too_large_with_wrong_cl_http10(self): def test_request_body_too_large_with_wrong_cl_http10_keepalive(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\r\nContent-Length: 5\r\nConnection: Keep-Alive\r\n\r\n" to_send += body to_send = tobytes(to_send) ...
def test_request_body_too_large_with_wrong_cl_http10_keepalive(self): def test_request_body_too_large_with_no_cl_http10(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\n\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_wrong_cl_http10_keepalive(self): def test_request_body_too_large_with_no_cl_http10(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\r\n\r\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_no_cl_http10(self): def test_request_body_too_large_with_no_cl_http10_keepalive(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\nConnection: Keep-Alive\n\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_no_cl_http10(self): def test_request_body_too_large_with_no_cl_http10_keepalive(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_no_cl_http10_keepalive(self): def test_request_body_too_large_with_wrong_cl_http11(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\n" "Content-Length: 5\n\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_no_cl_http10_keepalive(self): def test_request_body_too_large_with_wrong_cl_http11(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\r\nContent-Length: 5\r\n\r\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_wrong_cl_http11(self): def test_request_body_too_large_with_wrong_cl_http11_connclose(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\nContent-Length: 5\nConnection: close\n\n" to_send += body to_send = tobytes(to_send) self.con...
def test_request_body_too_large_with_wrong_cl_http11(self): def test_request_body_too_large_with_wrong_cl_http11_connclose(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\r\nContent-Length: 5\r\nConnection: close\r\n\r\n" to_send += body to_send = tobytes(to_send) ...
def test_request_body_too_large_with_wrong_cl_http11_connclose(self): def test_request_body_too_large_with_no_cl_http11(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\n\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_wrong_cl_http11_connclose(self): def test_request_body_too_large_with_no_cl_http11(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\r\n\r\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_no_cl_http11(self): def test_request_body_too_large_with_no_cl_http11_connclose(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\nConnection: close\n\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_no_cl_http11(self): def test_request_body_too_large_with_no_cl_http11_connclose(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n" to_send += body to_send = tobytes(to_send) self.connect()
def test_request_body_too_large_with_no_cl_http11_connclose(self): def test_request_body_too_large_chunked_encoding(self): control_line = "20;\r\n" # 20 hex = 32 dec s = "This string has 32 characters.\r\n" to_send = "GET / HTTP/1.1\nTransfer-Encoding: chunked\n\n" repeat = control_...
def test_request_body_too_large_with_no_cl_http11_connclose(self): def test_request_body_too_large_chunked_encoding(self): control_line = "20;\r\n" # 20 hex = 32 dec s = "This string has 32 characters.\r\n" to_send = "GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" repeat = co...
def tearDown(self): self.stop_subprocess() def test_before_start_response_http_10(self): to_send = "GET /before_start_response HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def tearDown(self): self.stop_subprocess() def test_before_start_response_http_10(self): to_send = "GET /before_start_response HTTP/1.0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_before_start_response_http_10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_before_start_response_http_11(self): to_send = "GET /before_start_response HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_before_start_response_http_10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_before_start_response_http_11(self): to_send = "GET /before_start_response HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_before_start_response_http_11(self): def test_before_start_response_http_11_close(self): to_send = tobytes( "GET /before_start_response HTTP/1.1\n" "Connection: close\n\n" ) self.connect() self.sock.send(to_send)
def test_before_start_response_http_11(self): def test_before_start_response_http_11_close(self): to_send = tobytes( "GET /before_start_response HTTP/1.1\r\nConnection: close\r\n\r\n" ) self.connect() self.sock.send(to_send)
def test_before_start_response_http_11_close(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_after_start_response_http10(self): to_send = "GET /after_start_response HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_before_start_response_http_11_close(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_after_start_response_http10(self): to_send = "GET /after_start_response HTTP/1.0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_after_start_response_http10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_after_start_response_http11(self): to_send = "GET /after_start_response HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_after_start_response_http10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_after_start_response_http11(self): to_send = "GET /after_start_response HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_after_start_response_http11(self): def test_after_start_response_http11_close(self): to_send = tobytes( "GET /after_start_response HTTP/1.1\n" "Connection: close\n\n" ) self.connect() self.sock.send(to_send)
def test_after_start_response_http11(self): def test_after_start_response_http11_close(self): to_send = tobytes( "GET /after_start_response HTTP/1.1\r\nConnection: close\r\n\r\n" ) self.connect() self.sock.send(to_send)
def test_after_start_response_http11_close(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_after_write_cb(self): to_send = "GET /after_write_cb HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_after_start_response_http11_close(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_after_write_cb(self): to_send = "GET /after_write_cb HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_after_write_cb(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_in_generator(self): to_send = "GET /in_generator HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_after_write_cb(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_in_generator(self): to_send = "GET /in_generator HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def tearDown(self): self.stop_subprocess() def test_filelike_http11(self): to_send = "GET /filelike HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def tearDown(self): self.stop_subprocess() def test_filelike_http11(self): to_send = "GET /filelike HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_filelike_http11(self): # connection has not been closed def test_filelike_nocl_http11(self): to_send = "GET /filelike_nocl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def test_filelike_http11(self): # connection has not been closed def test_filelike_nocl_http11(self): to_send = "GET /filelike_nocl HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_filelike_nocl_http11(self): # connection has not been closed def test_filelike_shortcl_http11(self): to_send = "GET /filelike_shortcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def test_filelike_nocl_http11(self): # connection has not been closed def test_filelike_shortcl_http11(self): to_send = "GET /filelike_shortcl HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_filelike_shortcl_http11(self): # connection has not been closed def test_filelike_longcl_http11(self): to_send = "GET /filelike_longcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def test_filelike_shortcl_http11(self): # connection has not been closed def test_filelike_longcl_http11(self): to_send = "GET /filelike_longcl HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_filelike_longcl_http11(self): # connection has not been closed def test_notfilelike_http11(self): to_send = "GET /notfilelike HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def test_filelike_longcl_http11(self): # connection has not been closed def test_notfilelike_http11(self): to_send = "GET /notfilelike HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_http11(self): # connection has not been closed def test_notfilelike_iobase_http11(self): to_send = "GET /notfilelike_iobase HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_http11(self): # connection has not been closed def test_notfilelike_iobase_http11(self): to_send = "GET /notfilelike_iobase HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_iobase_http11(self): # connection has not been closed def test_notfilelike_nocl_http11(self): to_send = "GET /notfilelike_nocl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_iobase_http11(self): # connection has not been closed def test_notfilelike_nocl_http11(self): to_send = "GET /notfilelike_nocl HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_nocl_http11(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_shortcl_http11(self): to_send = "GET /notfilelike_shortcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_nocl_http11(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_shortcl_http11(self): to_send = "GET /notfilelike_shortcl HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_shortcl_http11(self): # connection has not been closed def test_notfilelike_longcl_http11(self): to_send = "GET /notfilelike_longcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_shortcl_http11(self): # connection has not been closed def test_notfilelike_longcl_http11(self): to_send = "GET /notfilelike_longcl HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_longcl_http11(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_filelike_http10(self): to_send = "GET /filelike HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_longcl_http11(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_filelike_http10(self): to_send = "GET /filelike HTTP/1.0\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_filelike_http10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_filelike_nocl_http10(self): to_send = "GET /filelike_nocl HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect()
def test_filelike_http10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_filelike_nocl_http10(self): to_send = "GET /filelike_nocl HTTP/1.0\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_filelike_nocl_http10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_http10(self): to_send = "GET /notfilelike HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect()
def test_filelike_nocl_http10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_http10(self): to_send = "GET /notfilelike HTTP/1.0\r\n\r\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_http10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_nocl_http10(self): to_send = "GET /notfilelike_nocl HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect()
def test_notfilelike_http10(self): self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_nocl_http10(self): to_send = "GET /notfilelike_nocl HTTP/1.0\r\n\r\n" to_send = tobytes(to_send) self.connect()
def read_http(fp): # pragma: no cover header_lines = [] while True: line = fp.readline() if line in (b"\r\n", b"\n", b""): break else: header_lines.append(line)
def read_http(fp): # pragma: no cover header_lines = [] while True: line = fp.readline() if line in (b"\r\n", b"\r\n", b""): break else: header_lines.append(line)
""" import unittest from waitress.compat import ( text_, tobytes, ) class TestHTTPRequestParser(unittest.TestCase):
""" import unittest from waitress.compat import text_, tobytes class TestHTTPRequestParser(unittest.TestCase):
def test_get_body_stream_nonNone(self): result = self.parser.get_body_stream() self.assertEqual(result, body_rcv) def test_received_nonsense_with_double_cr(self): data = b"""\ HTTP/1.0 GET /foobar """ result = self.parser.received(data) self.assertEqual(result, 22) ...
def test_get_body_stream_nonNone(self): result = self.parser.get_body_stream() self.assertEqual(result, body_rcv) def test_received_get_no_headers(self): data = b"HTTP/1.0 GET /foobar\r\n\r\n" result = self.parser.received(data) self.assertEqual(result, 24) self.asse...
def test_received_cl_too_large(self): from waitress.utilities import RequestEntityTooLarge self.parser.adj.max_request_body_size = 2 data = b"""\ GET /foobar HTTP/8.4 Content-Length: 10 """ result = self.parser.received(data) self.assertEqual(result, 41) self.assertTrue...
def test_received_cl_too_large(self): from waitress.utilities import RequestEntityTooLarge self.parser.adj.max_request_body_size = 2 data = b"GET /foobar HTTP/8.4\r\nContent-Length: 10\r\n\r\n" result = self.parser.received(data) self.assertEqual(result, 44) self.assertT...
def test_received_headers_too_large(self): from waitress.utilities import RequestHeaderFieldsTooLarge self.parser.adj.max_request_header_size = 2 data = b"""\ GET /foobar HTTP/8.4 X-Foo: 1 """ result = self.parser.received(data) self.assertEqual(result, 30) self.assertTr...
def test_received_headers_too_large(self): from waitress.utilities import RequestHeaderFieldsTooLarge self.parser.adj.max_request_header_size = 2 data = b"GET /foobar HTTP/8.4\r\nX-Foo: 1\r\n\r\n" result = self.parser.received(data) self.assertEqual(result, 34) self.asse...
def test_received_body_too_large(self): from waitress.utilities import RequestEntityTooLarge self.parser.adj.max_request_body_size = 2 data = b"""\ GET /foobar HTTP/1.1 Transfer-Encoding: chunked X-Foo: 1 20;\r\n This string has 32 characters\r\n 0\r\n\r\n""" result = self.parser.recei...
def test_received_body_too_large(self): from waitress.utilities import RequestEntityTooLarge self.parser.adj.max_request_body_size = 2 data = ( b"GET /foobar HTTP/1.1\r\n" b"Transfer-Encoding: chunked\r\n" b"X-Foo: 1\r\n" b"\r\n" b"1d;...
def test_received_body_too_large(self): def test_received_error_from_parser(self): from waitress.utilities import BadRequest data = b"""\ GET /foobar HTTP/1.1 Transfer-Encoding: chunked X-Foo: 1 garbage """ # header result = self.parser.received(data) # body result ...
def test_received_body_too_large(self): def test_received_error_from_parser(self): from waitress.utilities import BadRequest data = ( b"GET /foobar HTTP/1.1\r\n" b"Transfer-Encoding: chunked\r\n" b"X-Foo: 1\r\n" b"\r\n" b"garbage\r\n" ...
def test_close_with_no_body_rcv(self): self.parser.body_rcv = None self.parser.close() # doesn't raise class Test_split_uri(unittest.TestCase): def _callFUT(self, uri):
def test_close_with_no_body_rcv(self): self.parser.body_rcv = None self.parser.close() # doesn't raise def test_parse_header_lf_only(self): from waitress.parser import ParsingError data = b"GET /foobar HTTP/8.4\nfoo: bar" try: self.parser.parse_header(data) ...
def _callFUT(self, data): return get_header_lines(data) def test_get_header_lines(self): result = self._callFUT(b"slam\nslim") self.assertEqual(result, [b"slam", b"slim"]) def test_get_header_lines_folded(self):
def _callFUT(self, data): return get_header_lines(data) def test_get_header_lines(self): result = self._callFUT(b"slam\r\nslim") self.assertEqual(result, [b"slam", b"slim"]) def test_get_header_lines_folded(self):
def test_get_header_lines_folded(self): # interpreting the field value or forwarding the message downstream. # We are just preserving the whitespace that indicates folding. result = self._callFUT(b"slim\n slam") self.assertEqual(result, [b"slim slam"]) def test_get_header_lines_tab...
def test_get_header_lines_folded(self): # interpreting the field value or forwarding the message downstream. # We are just preserving the whitespace that indicates folding. result = self._callFUT(b"slim\r\n slam") self.assertEqual(result, [b"slim slam"]) def test_get_header_lines_t...
def setUp(self): def feed(self, data): parser = self.parser for n in range(100): # make sure we never loop forever consumed = parser.received(data) data = data[consumed:] if parser.completed: return raise ValueError("Looping") # pragma: ...
def setUp(self): def feed(self, data): parser = self.parser for n in range(100): # make sure we never loop forever consumed = parser.received(data) data = data[consumed:] if parser.completed: return raise ValueError("Looping") # pragma...
def testSimpleGET(self): self.assertFalse(parser.empty) self.assertEqual( parser.headers, {"FIRSTNAME": "mickey", "LASTNAME": "Mouse", "CONTENT_LENGTH": "7",}, ) self.assertEqual(parser.path, "/foobar") self.assertEqual(parser.command, "GET") self....
def testSimpleGET(self): self.assertFalse(parser.empty) self.assertEqual( parser.headers, {"FIRSTNAME": "mickey", "LASTNAME": "Mouse", "CONTENT_LENGTH": "6",}, ) self.assertEqual(parser.path, "/foobar") self.assertEqual(parser.command, "GET") self....
def testComplexGET(self): self.assertFalse(parser.empty) self.assertEqual( parser.headers, {"FIRSTNAME": "mickey", "LASTNAME": "Mouse", "CONTENT_LENGTH": "10",}, ) # path should be utf-8 encoded self.assertEqual(
def testComplexGET(self): self.assertFalse(parser.empty) self.assertEqual( parser.headers, {"FIRSTNAME": "mickey", "LASTNAME": "Mouse", "CONTENT_LENGTH": "10"}, ) # path should be utf-8 encoded self.assertEqual(
def testComplexGET(self): self.assertEqual(parser.get_body_stream().getvalue(), b"Hello mick") def testProxyGET(self): data = b"""\ GET https://example.com:8080/foobar HTTP/8.4 content-length: 7 Hello. """ parser = self.parser self.feed(data) self.assertTrue(parser.complete...
def testComplexGET(self): self.assertEqual(parser.get_body_stream().getvalue(), b"Hello mick") def testProxyGET(self): data = ( b"GET https://example.com:8080/foobar HTTP/8.4\r\n" b"content-length: 6\r\n" b"\r\n" b"Hello." ) parser = s...
def test_received_control_line_notfinished(self): def test_received_control_line_finished_garbage_in_input(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"garbage\n") self.assertEqual(result, 8) self.assertTrue(inst.error) def test_received_...
def test_received_control_line_notfinished(self): def test_received_control_line_finished_garbage_in_input(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"garbage\r\n") self.assertEqual(result, 9) self.assertTrue(inst.error) def test_receive...
def test_received_trailer_startswith_lf(self): inst.all_chunks_received = True result = inst.received(b"\n") self.assertEqual(result, 1) self.assertEqual(inst.completed, True) def test_received_trailer_not_finished(self): buf = DummyBuffer()
def test_received_trailer_startswith_lf(self): inst.all_chunks_received = True result = inst.received(b"\n") self.assertEqual(result, 1) self.assertEqual(inst.completed, False) def test_received_trailer_not_finished(self): buf = DummyBuffer()
def test___len__(self): inst = self._makeOne(buf) self.assertEqual(inst.__len__(), 2) class DummyBuffer(object): def __init__(self, data=None):
def test___len__(self): inst = self._makeOne(buf) self.assertEqual(inst.__len__(), 2) def test_received_chunk_is_properly_terminated(self): buf = DummyBuffer() inst = self._makeOne(buf) data = b"4\r\nWiki\r\n" result = inst.received(data) self.assertEqual(res...
def test_one_linefeed(self): self.assertEqual(self._callFUT(b"\n"), -1) def test_double_linefeed(self): self.assertEqual(self._callFUT(b"\n\n"), 2) def test_one_crlf(self): self.assertEqual(self._callFUT(b"\r\n"), -1)
def test_one_linefeed(self): self.assertEqual(self._callFUT(b"\n"), -1) def test_double_linefeed(self): self.assertEqual(self._callFUT(b"\n\n"), -1) def test_one_crlf(self): self.assertEqual(self._callFUT(b"\r\n"), -1)
def test_double_crfl(self): self.assertEqual(self._callFUT(b"\r\n\r\n"), 4) def test_mixed(self): self.assertEqual(self._callFUT(b"\n\n00\r\n\r\n"), 2) class TestBadRequest(unittest.TestCase):
def test_double_crfl(self): self.assertEqual(self._callFUT(b"\r\n\r\n"), 4) def test_mixed(self): self.assertEqual(self._callFUT(b"\n\n00\r\n\r\n"), 8) class TestBadRequest(unittest.TestCase):
def find_double_newline(s): """Returns the position just after a double newline in the given string.""" pos1 = s.find(b"\n\r\n") # One kind of double newline if pos1 >= 0: pos1 += 3 pos2 = s.find(b"\n\n") # Another kind of double newline if pos2 >= 0: pos2 += 2 if pos1 >= 0: ...
def find_double_newline(s): """Returns the position just after a double newline in the given string.""" pos = s.find(b"\r\n\r\n") if pos >= 0: pos += 4 return pos def concat(*args):
class HTTPConnection(_HTTPConnection, object): conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % ...
class HTTPConnection(_HTTPConnection, object): conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % ...
class HTTPConnectionPool(ConnectionPool, RequestMethods): # released back to the pool once the entire response is read response.read() except (TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError) as e: pass ...
class HTTPConnectionPool(ConnectionPool, RequestMethods): # released back to the pool once the entire response is read response.read() except (TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError): pass #...
class WrappedSocket(object): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else:
class WrappedSocket(object): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else:
class WrappedSocket(object): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else:
class WrappedSocket(object): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else:
class SOCKSConnection(HTTPConnection): **extra_kw ) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout))
class SOCKSConnection(HTTPConnection): **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout))
_key_fields = ( 'key__socks_options', # dict 'key_assert_hostname', # bool or string 'key_assert_fingerprint', # str 'key_server_hostname', #str ) #: The namedtuple class used to construct keys for the connection pool.
_key_fields = ( 'key__socks_options', # dict 'key_assert_hostname', # bool or string 'key_assert_fingerprint', # str 'key_server_hostname', # str ) #: The namedtuple class used to construct keys for the connection pool.
class HTTPResponse(io.IOBase): if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif ',' in content_encoding: encodings = [e.strip() for e in content_encoding.split(',') if e.strip() in self.CONTENT_DECODERS] ...
class HTTPResponse(io.IOBase): if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif ',' in content_encoding: encodings = [ e.strip() for e in content_encoding.split(',') if e.stri...
DEFAULT_CIPHERS = ':'.join([ try: from ssl import SSLContext # Modern SSL? except ImportError: import sys class SSLContext(object): # Platform-specific: Python 2 def __init__(self, protocol_version): self.protocol = protocol_version
DEFAULT_CIPHERS = ':'.join([ try: from ssl import SSLContext # Modern SSL? except ImportError: class SSLContext(object): # Platform-specific: Python 2 def __init__(self, protocol_version): self.protocol = protocol_version
from __future__ import absolute_import from collections import namedtuple from ..exceptions import LocationParseError
from __future__ import absolute_import from collections import namedtuple import re from ..exceptions import LocationParseError
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] # urllib3 infers URLs without a scheme (None) to be http. NORMALIZABLE_SCHEMES = ('http', 'https', None) class Url(namedtuple('Url', url_attrs)): """
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] # urllib3 infers URLs without a scheme (None) to be http. NORMALIZABLE_SCHEMES = ('http', 'https', None) _contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]') class Url(namedtuple('Url', url_attrs)): """
def parse_url(url): # Empty return Url() scheme = None auth = None host = None
def parse_url(url): # Empty return Url() # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 if _contains_disallowed_url_pchar_re.search(url): raise LocationParseError("URL can't contain control characters. {!r}".format(url)) scheme = None a...
import errno import functools import logging import socket import pytest
import errno import functools import logging import socket import ssl import os import pytest
def notSecureTransport(test): return wrapper _requires_network_has_route = None
def notSecureTransport(test): return wrapper def notOpenSSL098(test): """Skips this test for Python 3.4 and 3.5 macOS python.org distributions""" @functools.wraps(test) def wrapper(*args, **kwargs): is_stdlib_ssl = not ssl_.IS_SECURETRANSPORT and not ssl_.IS_PYOPENSSL if is_stdlib_ssl...
def requires_network(test): return wrapper class _ListHandler(logging.Handler): def __init__(self): super(_ListHandler, self).__init__()
def requires_network(test): return wrapper def fails_on_travis_gce(test): """Expect the test to fail on Google Compute Engine instances for Travis. Travis uses GCE for its sudo: enabled builds. Reason for this decorator: https://github.com/urllib3/urllib3/pull/1475#issuecomment-440788064 """ ...
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_Url_str(self): U = Url('http', host='google.com') assert str(U) == U.url
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_parse_url_contains_control_characters(self): # see CVE-2019-9740 with pytest.raises(LocationParseError): parse_url('http://localhost:8000/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:') ...
from dummyserver.server import (DEFAULT_CA, DEFAULT_CA_BAD, DEFAULT_CERTS, from test import ( onlyPy279OrNewer, notSecureTransport, requires_network, TARPIT_HOST, ) from urllib3 import HTTPSConnectionPool
from dummyserver.server import (DEFAULT_CA, DEFAULT_CA_BAD, DEFAULT_CERTS, from test import ( onlyPy279OrNewer, notSecureTransport, notOpenSSL098, requires_network, fails_on_travis_gce, TARPIT_HOST, ) from urllib3 import HTTPSConnectionPool
class TestHTTPS(HTTPSDummyServerTestCase): r = self._pool.request('GET', '/') self.assertEqual(r.status, 200, r.data) def test_dotted_fqdn(self): pool = HTTPSConnectionPool(self.host + '.', self.port) r = pool.request('GET', '/')
class TestHTTPS(HTTPSDummyServerTestCase): r = self._pool.request('GET', '/') self.assertEqual(r.status, 200, r.data) @fails_on_travis_gce def test_dotted_fqdn(self): pool = HTTPSConnectionPool(self.host + '.', self.port) r = pool.request('GET', '/')
class TestHTTPS(HTTPSDummyServerTestCase): @onlyPy279OrNewer @notSecureTransport # SecureTransport does not support cert directories def test_ca_dir_verified(self): https_pool = HTTPSConnectionPool(self.host, self.port, cert_reqs='CERT_REQUIRED',
class TestHTTPS(HTTPSDummyServerTestCase): @onlyPy279OrNewer @notSecureTransport # SecureTransport does not support cert directories @notOpenSSL098 # OpenSSL 0.9.8 does not support cert directories def test_ca_dir_verified(self): https_pool = HTTPSConnectionPool(self.host, self.port, ...
from urllib3.util.timeout import Timeout from urllib3.util.retry import Retry from urllib3._collections import HTTPHeaderDict from dummyserver.testcase import SocketDummyServerTestCase, consume_socket from dummyserver.server import ( DEFAULT_CERTS, DEFAULT_CA, COMBINED_CERT_AND_KEY, get_unreachable_address)
from urllib3.util.timeout import Timeout from urllib3.util.retry import Retry from urllib3._collections import HTTPHeaderDict from test import fails_on_travis_gce from dummyserver.testcase import SocketDummyServerTestCase, consume_socket from dummyserver.server import ( DEFAULT_CERTS, DEFAULT_CA, COMBINED_CERT_AND...
class TestHeaders(SocketDummyServerTestCase): pool.request('GET', '/', headers=OrderedDict(expected_request_headers)) self.assertEqual(expected_request_headers, actual_request_headers) def test_request_host_header_ignores_fqdn_dot(self): received_headers = []
class TestHeaders(SocketDummyServerTestCase): pool.request('GET', '/', headers=OrderedDict(expected_request_headers)) self.assertEqual(expected_request_headers, actual_request_headers) @fails_on_travis_gce def test_request_host_header_ignores_fqdn_dot(self): received_headers = []
class Functional(training_lib.Model): than with subclassed `Model`s, specifically: - Model cloning (`keras.models.clone`) - Serialization (`model.get_config()/from_config`, `model.to_json()/to_yaml()` - Whole-model saving (`model.save()`) A `Functional` model can be instantiated by passing two arguments to
class Functional(training_lib.Model): than with subclassed `Model`s, specifically: - Model cloning (`keras.models.clone`) - Serialization (`model.get_config()/from_config`, `model.to_json()` - Whole-model saving (`model.save()`) A `Functional` model can be instantiated by passing two arguments to
from tensorflow.python.platform import test from tensorflow.python.training.tracking.util import Checkpoint try: import yaml # pylint:disable=g-import-not-at-top except ImportError: yaml = None class NetworkConstructionTest(keras_parameterized.TestCase):
from tensorflow.python.platform import test from tensorflow.python.training.tracking.util import Checkpoint class NetworkConstructionTest(keras_parameterized.TestCase):
def test_multi_input_multi_output_recursion(self): json_str = model.to_json() models.model_from_json(json_str) if yaml is not None: yaml_str = model.to_yaml() models.model_from_yaml(yaml_str) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_invalid_g...
def test_multi_input_multi_output_recursion(self): json_str = model.to_json() models.model_from_json(json_str) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_invalid_graphs(self): a = layers.Input(shape=(32,), name='input_a')
def test_constant_initializer_with_numpy(self): json_str = model.to_json() models.model_from_json(json_str) if yaml is not None: yaml_str = model.to_yaml() models.model_from_yaml(yaml_str) def test_subclassed_error_if_init_not_called(self): class MyNetwork(training_lib.Model):
def test_constant_initializer_with_numpy(self): json_str = model.to_json() models.model_from_json(json_str) def test_subclassed_error_if_init_not_called(self): class MyNetwork(training_lib.Model):
import h5py except ImportError: h5py = None try: import yaml except ImportError: yaml = None # pylint: enable=g-import-not-at-top
import h5py except ImportError: h5py = None # pylint: enable=g-import-not-at-top
def to_json(self, **kwargs): def to_yaml(self, **kwargs): """Returns a yaml string containing the network configuration. To load a network from a yaml save file, use `keras.models.model_from_yaml(yaml_string, custom_objects={})`.
def to_json(self, **kwargs): def to_yaml(self, **kwargs): """Returns a yaml string containing the network configuration. Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError. To load a network from a yaml save file, use `keras.models.model_from_yaml(yaml_string, c...
def to_yaml(self, **kwargs): A YAML string. Raises: ImportError: if yaml module is not found. """ if yaml is None: raise ImportError( 'Requires yaml module installed (`pip install pyyaml`).') return yaml.dump(self._updated_config(), **kwargs) def reset_states(self): ...
def to_yaml(self, **kwargs): A YAML string. Raises: RuntimeError: announces that the method poses a security risk """ raise RuntimeError( 'Method `model.to_yaml()` has been removed due to security risk of ' 'arbitrary code execution. Please use `model.to_json()` instead.' ...
from tensorflow.python.keras.saving.saved_model import json_utils from tensorflow.python.util.tf_export import keras_export # pylint: disable=g-import-not-at-top try: import yaml except ImportError: yaml = None # pylint: enable=g-import-not-at-top @keras_export('keras.models.model_from_config') def model_from_co...
from tensorflow.python.keras.saving.saved_model import json_utils from tensorflow.python.util.tf_export import keras_export @keras_export('keras.models.model_from_config') def model_from_config(config, custom_objects=None): """Instantiates a Keras model from its config. Usage: ``` # for a Functional API mode...
def model_from_config(config, custom_objects=None): def model_from_yaml(yaml_string, custom_objects=None): """Parses a yaml model configuration file and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) ...
def model_from_config(config, custom_objects=None): def model_from_yaml(yaml_string, custom_objects=None): """Parses a yaml model configuration file and returns a model instance. Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError. Args: yaml_string: YAML string or open ...
def model_from_yaml(yaml_string, custom_objects=None): A Keras model instance (uncompiled). Raises: ImportError: if yaml module is not found. """ if yaml is None: raise ImportError('Requires yaml module installed (`pip install pyyaml`).') # The method unsafe_load only exists in PyYAML 5.x+, so ...
def model_from_yaml(yaml_string, custom_objects=None): A Keras model instance (uncompiled). Raises: RuntimeError: announces that the method poses a security risk """ raise RuntimeError( 'Method `model_from_yaml()` has been removed due to security risk of ' 'arbitrary code execution. Pleas...
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): str_number = '{:f}'.format(number) else: str_number = str(number) if str_number[0] == '-':
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponen...
class TestNumberFormat(TestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') def test_decimal_subclass(self): class EuroDecimal(Decimal):
class TestNumberFormat(TestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') # Very large & small numbers. tests = [ ('9e9999', None, '9e+9999'), ('9e9999', 3, '9.000e+9999'), ('9e...
class StackedRNNCells(Layer): output_dim = cell.state_size[0] else: output_dim = cell.state_size input_shape = (input_shape[0], input_shape[1], output_dim) self.built = True def get_config(self):
class StackedRNNCells(Layer): output_dim = cell.state_size[0] else: output_dim = cell.state_size input_shape = (input_shape[0], output_dim) self.built = True def get_config(self):
def test_minimal_rnn_cell_layer(): super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', n...
def test_minimal_rnn_cell_layer(): super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): # no time axis in the input shape passed to RNN cells assert len(input_shape) == 2 self.kernel = self.add_weight(shape=(input_shape[-1], self.units), ...
optional. if bin_range is not None: bin_range = self.convert_xunits(bin_range) # We need to do to 'weights' what was done to 'x' if weights is not None: w = cbook._reshape_2D(weights, 'weights')
optional. if bin_range is not None: bin_range = self.convert_xunits(bin_range) if not cbook.is_scalar_or_string(bins): bins = self.convert_xunits(bins) # We need to do to 'weights' what was done to 'x' if weights is not None: w = cbook._reshape_2D(we...
def test_hist_datetime_datasets(): ax.hist(data, stacked=False) @pytest.mark.parametrize('data, expected_number_of_hists', [([], 1), ([[]], 1),
def test_hist_datetime_datasets(): ax.hist(data, stacked=False) @pytest.mark.parametrize("bins_preprocess", [mpl.dates.date2num, lambda bins: bins, lambda bins: np.asarray(bins).astype('datetime64')], ids=['date2...
from AccessControl import ClassSecurityInfo, Unauthorized from Products.CMFPlone.PloneBaseTool import PloneBaseTool from Products.CMFPlone.PloneTool import EMAIL_RE # - remove '1', 'l', and 'I' to avoid confusion # - remove '0', 'O', and 'Q' to avoid confusion # - remove vowels to avoid spelling words
from AccessControl import ClassSecurityInfo, Unauthorized from Products.CMFPlone.PloneBaseTool import PloneBaseTool from Products.CMFPlone.PloneTool import EMAIL_RE from Products.PluggableAuthService.interfaces.authservice \ import IPluggableAuthService # - remove '1', 'l', and 'I' to avoid confusion # - remo...
class RegistrationTool(PloneBaseTool, BaseTool): return self.mail_password_response( self, self.REQUEST ) RegistrationTool.__doc__ = BaseTool.__doc__
class RegistrationTool(PloneBaseTool, BaseTool): return self.mail_password_response( self, self.REQUEST ) def isMemberIdAllowed(self, id): if len(id) < 1 or id == 'Anonymous User': return 0 if not self._ALLOWED_MEMBER_ID_PATTERN.match( id ): return 0 pas = ...
class TestRegistrationTool(PloneTestCase.PloneTestCase): def afterSetUp(self): self.registration = self.portal.portal_registration def testJoinCreatesUser(self): self.registration.addMember(member_id, 'secret',
class TestRegistrationTool(PloneTestCase.PloneTestCase): def afterSetUp(self): self.registration = self.portal.portal_registration self.portal.acl_users.userFolderAddUser("userid", "password", (), (), ()) self.portal.acl_users._doAddGroup("groupid", ()) def testJoinCrea...
class TestRegistrationTool(PloneTestCase.PloneTestCase): def testInvalidCMFDefaultEmailFailsValidation(self): # http://dev.plone.org/plone/ticket/3910 self.failIf(self.registration.isValidEmail('bogus@127.0.0.1')) class TestPasswordGeneration(PloneTestCase.PloneTestCase):
class TestRegistrationTool(PloneTestCase.PloneTestCase): def testInvalidCMFDefaultEmailFailsValidation(self): # http://dev.plone.org/plone/ticket/3910 self.failIf(self.registration.isValidEmail('bogus@127.0.0.1')) def testNewIdAllowed(self): self.assertEqual(self.registration.isMemberId...
import errno import grp import os import platform import pwd import shutil import socket import time import re from ansible.module_utils._text import to_native from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
import errno import grp import os import platform import pty import pwd import select import shutil import socket import subprocess import time import re from ansible.module_utils._text import to_native, to_bytes, to_text from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) cmd.append('-N') if self.ssh_passphrase is not None: cmd.append(self.ssh_passphrase) else: cmd.append('') (rc, out, err) = self.execute_command(cmd)...
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) if self.ssh_passphrase is not None: if self.module.check_mode: self.module.debug('In check mode, would have run: "%s"' % cmd) return (0, '', '') ...
class CertificateError(ValueError): pass def _dnsname_to_pat(dn): pats = [] for frag in dn.split(r'.'): if frag == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment.
class CertificateError(ValueError): pass def _dnsname_to_pat(dn, max_wildcards=1): pats = [] for frag in dn.split(r'.'): if frag.count('*') > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A survery of established...
def fail(cert, hostname): self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com') self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com') def test_server_side(self): # server_hostname doesn't work for server sockets ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv2...
def fail(cert, hostname): self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com') self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com') # Issue #17980: avoid denials of service by refusing more than one # wildcard per fragment. cert = {'subject': ((...
def _unstack_multiple(data, clocs, fill_value=None): result = data for i in range(len(clocs)): val = clocs[i] result = result.unstack(val) clocs = [v if i > v else v - 1 for v in clocs] return result
def _unstack_multiple(data, clocs, fill_value=None): result = data for i in range(len(clocs)): val = clocs[i] result = result.unstack(val, fill_value=fill_value) clocs = [v if i > v else v - 1 for v in clocs] return result
def test_stack_timezone_aware_values(): ), ) tm.assert_series_equal(result, expected)
def test_stack_timezone_aware_values(): ), ) tm.assert_series_equal(result, expected) def test_unstacking_multi_index_df(): # see gh-30740 df = DataFrame( { "name": ["Alice", "Bob"], "score": [9.5, 8], "employed": [False, True], "kids": [...