def test_no_result_future(self): with ignore_deprecation(): future = self.no_result_future(self.stop) result = self.wait() self.assertIs(result, None) # result of this future is undefined, but not an error future.result()
def test_add_future_stack_context(self): ready = threading.Event() def task(): # we must wait for the ioloop callback to be scheduled before # the task completes to ensure that add_future adds the callback # asynchronously (which is the scenario in which capturing # the stack_context matters) ready.wait(1) assert ready.isSet(), "timed out" raise Exception("worker") def callback(future): self.future = future raise Exception("callback") def handle_exception(typ, value, traceback): self.exception = value self.stop() return True # stack_context propagates to the ioloop callback, but the worker # task just has its exceptions caught and saved in the Future. with ignore_deprecation(): with futures.ThreadPoolExecutor(1) as pool: with ExceptionStackContext(handle_exception): self.io_loop.add_future(pool.submit(task), callback) ready.set() self.wait() self.assertEqual(self.exception.args[0], "callback") self.assertEqual(self.future.exception().args[0], "worker")
def connect_to_server(self, server_cls): server = client = None try: sock, port = bind_unused_port() server = server_cls(ssl_options=_server_ssl_options()) server.add_socket(sock) ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) ssl_ctx.check_hostname = False ssl_ctx.verify_mode = ssl.CERT_NONE # These tests fail with ConnectionAbortedErrors with TLS # 1.3 on windows python 3.7.4 (which includes an upgrade # to openssl 1.1.c. Other platforms might be affected with # newer openssl too). Disable it until we figure out # what's up. # Update 2021-12-28: Still happening with Python 3.10 on # Windows. OP_NO_TLSv1_3 now raises a DeprecationWarning. with ignore_deprecation(): ssl_ctx.options |= getattr(ssl, "OP_NO_TLSv1_3", 0) client = SSLIOStream(socket.socket(), ssl_options=ssl_ctx) yield client.connect(("127.0.0.1", port)) self.assertIsNotNone(client.socket.cipher()) finally: if server is not None: server.stop() if client is not None: client.close()
def test_add_future_stack_context(self): ready = threading.Event() def task(): # we must wait for the ioloop callback to be scheduled before # the task completes to ensure that add_future adds the callback # asynchronously (which is the scenario in which capturing # the stack_context matters) ready.wait(1) assert ready.isSet(), "timed out" raise Exception("worker") def callback(future): self.future = future raise Exception("callback") def handle_exception(typ, value, traceback): self.exception = value self.stop() return True # stack_context propagates to the ioloop callback, but the worker # task just has its exceptions caught and saved in the Future. with ignore_deprecation(): with futures.ThreadPoolExecutor(1) as pool: with ExceptionStackContext(handle_exception): self.io_loop.add_future(pool.submit(task), callback) ready.set() self.wait() self.assertEqual(self.exception.args[0], "callback") self.assertEqual(self.future.exception().args[0], "worker")
def test_stack_context(self): with ExpectLog(app_log, "Uncaught exception GET /"): with ignore_deprecation(): self.http_client.fetch(self.get_url('/'), self.handle_response) self.wait() self.assertEqual(self.response.code, 500) self.assertTrue(b'got expected exception' in self.response.body)
def test_no_result_future(self): with ignore_deprecation(): future = self.no_result_future(self.stop) result = self.wait() self.assertIs(result, None) # result of this future is undefined, but not an error future.result()
def test_stack_context(self): with ExpectLog(app_log, "Uncaught exception GET /"): with ignore_deprecation(): self.http_client.fetch(self.get_url('/'), self.handle_response) self.wait() self.assertEqual(self.response.code, 500) self.assertTrue(b'got expected exception' in self.response.body)
def test_kw_only_callback(self): with ignore_deprecation(): @return_future def f(**kwargs): kwargs['callback'](42) future = f() self.assertEqual(future.result(), 42)
class OAuth1ClientLoginHandlerLegacy(RequestHandler, OAuthMixin): def initialize(self, test, version): self._OAUTH_VERSION = version self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token') self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth1/server/authorize') self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/oauth1/server/access_token') def _oauth_consumer_token(self): return dict(key='asdf', secret='qwer') with ignore_deprecation(): @asynchronous def get(self): if self.get_argument('oauth_token', None): with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) self.get_authenticated_user( self.on_user, http_client=self.settings['http_client']) return res = self.authorize_redirect(http_client=self.settings['http_client']) assert isinstance(res, Future) def on_user(self, user): if user is None: raise Exception("user is None") self.finish(user) def _oauth_get_user(self, access_token, callback): if self.get_argument('fail_in_get_user', None): raise Exception("failing in get_user") if access_token != dict(key='uiop', secret='5678'): raise Exception("incorrect access token %r" % access_token) callback(dict(email='*****@*****.**'))
class TestRequestHandler(RequestHandler): def __init__(self, app, request): super(TestRequestHandler, self).__init__(app, request) with ignore_deprecation(): @asynchronous def get(self): logging.debug('in get()') # call self.part2 without a self.async_callback wrapper. Its # exception should still get thrown IOLoop.current().add_callback(self.part2) def part2(self): logging.debug('in part2()') # Go through a third layer to make sure that contexts once restored # are again passed on to future callbacks IOLoop.current().add_callback(self.part3) def part3(self): logging.debug('in part3()') raise Exception('test exception') def write_error(self, status_code, **kwargs): if 'exc_info' in kwargs and str( kwargs['exc_info'][1]) == 'test exception': self.write('got expected exception') else: self.write('unexpected failure')
def test_callback_positional(self): # When the callback is passed in positionally, future_wrap shouldn't # add another callback in the kwargs. with ignore_deprecation(): future = self.sync_future(self.stop) result = self.wait() self.assertEqual(result, 42) self.assertEqual(future.result(), 42)
def test_exception_in_callback(self): with ignore_deprecation(): self.io_loop.add_callback(lambda: 1 / 0) try: self.wait() self.fail("did not get expected exception") except ZeroDivisionError: pass
def test_exception_in_callback(self): with ignore_deprecation(): self.io_loop.add_callback(lambda: 1 / 0) try: self.wait() self.fail("did not get expected exception") except ZeroDivisionError: pass
def test_callback_positional(self): # When the callback is passed in positionally, future_wrap shouldn't # add another callback in the kwargs. with ignore_deprecation(): future = self.sync_future(self.stop) result = self.wait() self.assertEqual(result, 42) self.assertEqual(future.result(), 42)
def test_delayed_failure(self): future = self.delayed_failure() with ignore_deprecation(): self.io_loop.add_future(future, self.stop) future2 = self.wait() self.assertIs(future, future2) with self.assertRaises(ZeroDivisionError): future.result()
def test_delayed_failure(self): future = self.delayed_failure() with ignore_deprecation(): self.io_loop.add_future(future, self.stop) future2 = self.wait() self.assertIs(future, future2) with self.assertRaises(ZeroDivisionError): future.result()
def test_kw_only_callback(self): with ignore_deprecation(): @return_future def f(**kwargs): kwargs['callback'](42) future = f() self.assertEqual(future.result(), 42)
def test_oauth10a_get_user_legacy(self): with ignore_deprecation(): response = self.fetch( '/legacy/oauth10a/client/login?oauth_token=zxcv', headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='}) response.rethrow() parsed = json_decode(response.body) self.assertEqual(parsed['email'], '*****@*****.**') self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))
def test_oauth10a_get_user_legacy(self): with ignore_deprecation(): response = self.fetch( '/legacy/oauth10a/client/login?oauth_token=zxcv', headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='}) response.rethrow() parsed = json_decode(response.body) self.assertEqual(parsed['email'], '*****@*****.**') self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))
def test_204_invalid_content_length(self): # 204 status with non-zero content length is malformed with ExpectLog(gen_log, ".*Response with code 204 should not have body"): with ignore_deprecation(): response = self.fetch("/?error=1") if not self.http1: self.skipTest("requires HTTP/1.x") if self.http_client.configured_class != SimpleAsyncHTTPClient: self.skipTest("curl client accepts invalid headers") self.assertEqual(response.code, 599)
def test_bad_host(self): def handler(exc_typ, exc_val, exc_tb): self.stop(exc_val) return True # Halt propagation. with ignore_deprecation(): with ExceptionStackContext(handler): self.resolver.resolve('an invalid domain', 80, callback=self.stop) result = self.wait() self.assertIsInstance(result, Exception)
def setUp(self): # This simulates the effect of an asyncio test harness like # pytest-asyncio. with ignore_deprecation(): try: self.orig_loop = asyncio.get_event_loop() except RuntimeError: self.orig_loop = None # type: ignore[assignment] self.new_loop = asyncio.new_event_loop() asyncio.set_event_loop(self.new_loop) super().setUp()
def respond_100(self, request): self.http1 = request.version.startswith('HTTP/1.') if not self.http1: request.connection.write_headers(ResponseStartLine('', 200, 'OK'), HTTPHeaders()) request.connection.finish() return self.request = request with ignore_deprecation(): self.request.connection.stream.write( b"HTTP/1.1 100 CONTINUE\r\n\r\n", self.respond_200)
def test_204_invalid_content_length(self): # 204 status with non-zero content length is malformed with ExpectLog(gen_log, ".*Response with code 204 should not have body"): with ignore_deprecation(): response = self.fetch("/?error=1") if not self.http1: self.skipTest("requires HTTP/1.x") if self.http_client.configured_class != SimpleAsyncHTTPClient: self.skipTest("curl client accepts invalid headers") self.assertEqual(response.code, 599)
def test_multiple_errors(self): with ignore_deprecation(): def fail(message): raise Exception(message) self.io_loop.add_callback(lambda: fail("error one")) self.io_loop.add_callback(lambda: fail("error two")) # The first error gets raised; the second gets logged. with ExpectLog(app_log, "multiple unhandled exceptions"): with self.assertRaises(Exception) as cm: self.wait() self.assertEqual(str(cm.exception), "error one")
def test_bad_host(self): def handler(exc_typ, exc_val, exc_tb): self.stop(exc_val) return True # Halt propagation. with ExceptionStackContext(handler): with ignore_deprecation(): self.resolver.resolve('an invalid domain', 80, callback=self.stop) result = self.wait() self.assertIsInstance(result, Exception)
def respond_100(self, request): self.http1 = request.version.startswith('HTTP/1.') if not self.http1: request.connection.write_headers(ResponseStartLine('', 200, 'OK'), HTTPHeaders()) request.connection.finish() return self.request = request with ignore_deprecation(): self.request.connection.stream.write( b"HTTP/1.1 100 CONTINUE\r\n\r\n", self.respond_200)
class TwitterClientLoginGenEngineHandler(TwitterClientHandler): with ignore_deprecation(): @asynchronous @gen.engine def get(self): if self.get_argument("oauth_token", None): user = yield self.get_authenticated_user() self.finish(user) else: # Old style: with @gen.engine we can ignore the Future from # authorize_redirect. self.authorize_redirect()
def raw_fetch(self, headers, body, newline=b"\r\n"): with closing(IOStream(socket.socket())) as stream: with ignore_deprecation(): stream.connect(('127.0.0.1', self.get_http_port()), self.stop) self.wait() stream.write( newline.join(headers + [utf8("Content-Length: %d" % len(body))]) + newline + newline + body) read_stream_body(stream, self.stop) start_line, headers, body = self.wait() return body
class TwitterClientLoginHandlerLegacy(TwitterClientHandler): with ignore_deprecation(): @asynchronous def get(self): if self.get_argument("oauth_token", None): self.get_authenticated_user(self.on_user) return self.authorize_redirect() def on_user(self, user): if user is None: raise Exception("user is None") self.finish(user)
def test_multiple_errors(self): with ignore_deprecation(): def fail(message): raise Exception(message) self.io_loop.add_callback(lambda: fail("error one")) self.io_loop.add_callback(lambda: fail("error two")) # The first error gets raised; the second gets logged. with ExpectLog(app_log, "multiple unhandled exceptions"): with self.assertRaises(Exception) as cm: self.wait() self.assertEqual(str(cm.exception), "error one")
def test_spawn_callback(self): with ignore_deprecation(): # An added callback runs in the test's stack_context, so will be # re-raised in wait(). self.io_loop.add_callback(lambda: 1 / 0) with self.assertRaises(ZeroDivisionError): self.wait() # A spawned callback is run directly on the IOLoop, so it will be # logged without stopping the test. self.io_loop.spawn_callback(lambda: 1 / 0) self.io_loop.add_callback(self.stop) with ExpectLog(app_log, "Exception in callback"): self.wait()
def test_spawn_callback(self): with ignore_deprecation(): # An added callback runs in the test's stack_context, so will be # re-raised in wait(). self.io_loop.add_callback(lambda: 1 / 0) with self.assertRaises(ZeroDivisionError): self.wait() # A spawned callback is run directly on the IOLoop, so it will be # logged without stopping the test. self.io_loop.spawn_callback(lambda: 1 / 0) self.io_loop.add_callback(self.stop) with ExpectLog(app_log, "Exception in callback"): self.wait()
def test_failed_setup(self): self.http_client = self.create_client(max_clients=1) for i in range(5): with ignore_deprecation(): response = self.fetch(u'/ユニコード') self.assertIsNot(response.error, None) with self.assertRaises((UnicodeEncodeError, HTTPClientError)): # This raises UnicodeDecodeError on py3 and # HTTPClientError(404) on py2. The main motivation of # this test is to ensure that the UnicodeEncodeError # during the setup phase doesn't lead the request to # be dropped on the floor. response = self.fetch(u'/ユニコード', raise_error=True)
def test_failed_setup(self): self.http_client = self.create_client(max_clients=1) for i in range(5): with ignore_deprecation(): response = self.fetch(u'/ユニコード') self.assertIsNot(response.error, None) with self.assertRaises((UnicodeEncodeError, HTTPClientError)): # This raises UnicodeDecodeError on py3 and # HTTPClientError(404) on py2. The main motivation of # this test is to ensure that the UnicodeEncodeError # during the setup phase doesn't lead the request to # be dropped on the floor. response = self.fetch(u'/ユニコード', raise_error=True)
def test_request_timeout(self): timeout = 0.1 timeout_min, timeout_max = 0.099, 0.15 if os.name == 'nt': timeout = 0.5 timeout_min, timeout_max = 0.4, 0.6 with ignore_deprecation(): response = self.fetch('/trigger?wake=false', request_timeout=timeout) self.assertEqual(response.code, 599) self.assertTrue(timeout_min < response.request_time < timeout_max, response.request_time) self.assertEqual(str(response.error), "Timeout during request") # trigger the hanging request to let it clean up after itself self.triggers.popleft()()
def test_prepare_curl_callback_stack_context(self): exc_info = [] error_event = Event() def error_handler(typ, value, tb): exc_info.append((typ, value, tb)) error_event.set() return True with ignore_deprecation(): with ExceptionStackContext(error_handler): request = HTTPRequest(self.get_url('/custom_reason'), prepare_curl_callback=lambda curl: 1 / 0) yield [error_event.wait(), self.http_client.fetch(request)] self.assertEqual(1, len(exc_info)) self.assertIs(exc_info[0][0], ZeroDivisionError)
def test_pre_wrap(self): # A pre-wrapped callback is run in the context in which it was # wrapped, not when it was added to the IOLoop. def f1(): self.assertIn('c1', self.active_contexts) self.assertNotIn('c2', self.active_contexts) self.stop() with ignore_deprecation(): with StackContext(functools.partial(self.context, 'c1')): wrapped = wrap(f1) with StackContext(functools.partial(self.context, 'c2')): self.add_callback(wrapped) self.wait()
def test_prepare_curl_callback_stack_context(self): exc_info = [] error_event = Event() def error_handler(typ, value, tb): exc_info.append((typ, value, tb)) error_event.set() return True with ignore_deprecation(): with ExceptionStackContext(error_handler): request = HTTPRequest(self.get_url('/custom_reason'), prepare_curl_callback=lambda curl: 1 / 0) yield [error_event.wait(), self.http_client.fetch(request)] self.assertEqual(1, len(exc_info)) self.assertIs(exc_info[0][0], ZeroDivisionError)
def test_header_callback_stack_context(self): exc_info = [] def error_handler(typ, value, tb): exc_info.append((typ, value, tb)) return True def header_callback(header_line): if header_line.lower().startswith('content-type:'): 1 / 0 with ignore_deprecation(): with ExceptionStackContext(error_handler): self.fetch('/chunk', header_callback=header_callback) self.assertEqual(len(exc_info), 1) self.assertIs(exc_info[0][0], ZeroDivisionError)
def test_pre_wrap(self): # A pre-wrapped callback is run in the context in which it was # wrapped, not when it was added to the IOLoop. def f1(): self.assertIn('c1', self.active_contexts) self.assertNotIn('c2', self.active_contexts) self.stop() with ignore_deprecation(): with StackContext(functools.partial(self.context, 'c1')): wrapped = wrap(f1) with StackContext(functools.partial(self.context, 'c2')): self.add_callback(wrapped) self.wait()
def test_request_timeout(self): timeout = 0.1 timeout_min, timeout_max = 0.099, 0.15 if os.name == 'nt': timeout = 0.5 timeout_min, timeout_max = 0.4, 0.6 with ignore_deprecation(): response = self.fetch('/trigger?wake=false', request_timeout=timeout) self.assertEqual(response.code, 599) self.assertTrue(timeout_min < response.request_time < timeout_max, response.request_time) self.assertEqual(str(response.error), "Timeout during request") # trigger the hanging request to let it clean up after itself self.triggers.popleft()()
def test_header_callback_stack_context(self): exc_info = [] def error_handler(typ, value, tb): exc_info.append((typ, value, tb)) return True def header_callback(header_line): if header_line.lower().startswith('content-type:'): 1 / 0 with ignore_deprecation(): with ExceptionStackContext(error_handler): self.fetch('/chunk', header_callback=header_callback) self.assertEqual(len(exc_info), 1) self.assertIs(exc_info[0][0], ZeroDivisionError)
class TwitterClientShowUserHandlerLegacy(TwitterClientHandler): with ignore_deprecation(): @asynchronous @gen.engine def get(self): # TODO: would be nice to go through the login flow instead of # cheating with a hard-coded access token. with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) response = yield gen.Task(self.twitter_request, '/users/show/%s' % self.get_argument('name'), access_token=dict(key='hjkl', secret='vbnm')) if response is None: self.set_status(500) self.finish('error from twitter request') else: self.finish(response)
def test_connect_timeout(self): timeout = 0.1 timeout_min, timeout_max = 0.099, 1.0 class TimeoutResolver(Resolver): def resolve(self, *args, **kwargs): return Future() # never completes with closing(self.create_client(resolver=TimeoutResolver())) as client: with ignore_deprecation(): response = yield client.fetch(self.get_url('/hello'), connect_timeout=timeout, raise_error=False) self.assertEqual(response.code, 599) self.assertTrue(timeout_min < response.request_time < timeout_max, response.request_time) self.assertEqual(str(response.error), "Timeout while connecting")
def test_future_traceback_legacy(self): with ignore_deprecation(): @return_future @gen.engine def f(callback): yield gen.Task(self.io_loop.add_callback) try: 1 / 0 except ZeroDivisionError: self.expected_frame = traceback.extract_tb( sys.exc_info()[2], limit=1)[0] raise try: yield f() self.fail("didn't get expected exception") except ZeroDivisionError: tb = traceback.extract_tb(sys.exc_info()[2]) self.assertIn(self.expected_frame, tb)
def test_future_traceback_legacy(self): with ignore_deprecation(): @return_future @gen.engine def f(callback): yield gen.Task(self.io_loop.add_callback) try: 1 / 0 except ZeroDivisionError: self.expected_frame = traceback.extract_tb( sys.exc_info()[2], limit=1)[0] raise try: yield f() self.fail("didn't get expected exception") except ZeroDivisionError: tb = traceback.extract_tb(sys.exc_info()[2]) self.assertIn(self.expected_frame, tb)
def test_pre_wrap_with_args(self): # Same as test_pre_wrap, but the function takes arguments. # Implementation note: The function must not be wrapped in a # functools.partial until after it has been passed through # stack_context.wrap def f1(foo, bar): self.assertIn('c1', self.active_contexts) self.assertNotIn('c2', self.active_contexts) self.stop((foo, bar)) with ignore_deprecation(): with StackContext(functools.partial(self.context, 'c1')): wrapped = wrap(f1) with StackContext(functools.partial(self.context, 'c2')): self.add_callback(wrapped, 1, bar=2) result = self.wait() self.assertEqual(result, (1, 2))
def test_connect_timeout(self): timeout = 0.1 timeout_min, timeout_max = 0.099, 1.0 class TimeoutResolver(Resolver): def resolve(self, *args, **kwargs): return Future() # never completes with closing(self.create_client(resolver=TimeoutResolver())) as client: with ignore_deprecation(): response = yield client.fetch(self.get_url('/hello'), connect_timeout=timeout, raise_error=False) self.assertEqual(response.code, 599) self.assertTrue( timeout_min < response.request_time < timeout_max, response.request_time) self.assertEqual(str(response.error), "Timeout while connecting")
def test_queue_timeout(self): with ignore_deprecation(): with closing(self.create_client(max_clients=1)) as client: # Wait for the trigger request to block, not complete. fut1 = client.fetch(self.get_url('/trigger'), request_timeout=10, raise_error=False) self.wait() fut2 = client.fetch(self.get_url('/hello'), connect_timeout=0.1, raise_error=False) fut2.add_done_callback(self.stop) response = self.wait().result() self.assertEqual(response.code, 599) self.assertTrue(response.request_time < 1, response.request_time) self.assertEqual(str(response.error), "Timeout in request queue") self.triggers.popleft()() fut1.add_done_callback(self.stop) self.wait() fut1.result()
def test_pre_wrap_with_args(self): # Same as test_pre_wrap, but the function takes arguments. # Implementation note: The function must not be wrapped in a # functools.partial until after it has been passed through # stack_context.wrap def f1(foo, bar): self.assertIn('c1', self.active_contexts) self.assertNotIn('c2', self.active_contexts) self.stop((foo, bar)) with ignore_deprecation(): with StackContext(functools.partial(self.context, 'c1')): wrapped = wrap(f1) with StackContext(functools.partial(self.context, 'c2')): self.add_callback(wrapped, 1, bar=2) result = self.wait() self.assertEqual(result, (1, 2))
def test_connection_refused(self): cleanup_func, port = refusing_port() self.addCleanup(cleanup_func) with ExpectLog(gen_log, ".*", required=False): with ignore_deprecation(): response = self.fetch("http://127.0.0.1:%d/" % port) self.assertEqual(599, response.code) if sys.platform != 'cygwin': # cygwin returns EPERM instead of ECONNREFUSED here contains_errno = str(errno.ECONNREFUSED) in str(response.error) if not contains_errno and hasattr(errno, "WSAECONNREFUSED"): contains_errno = str(errno.WSAECONNREFUSED) in str(response.error) self.assertTrue(contains_errno, response.error) # This is usually "Connection refused". # On windows, strerror is broken and returns "Unknown error". expected_message = os.strerror(errno.ECONNREFUSED) self.assertTrue(expected_message in str(response.error), response.error)
def test_connection_refused(self): cleanup_func, port = refusing_port() self.addCleanup(cleanup_func) with ExpectLog(gen_log, ".*", required=False): with ignore_deprecation(): response = self.fetch("http://127.0.0.1:%d/" % port) self.assertEqual(599, response.code) if sys.platform != 'cygwin': # cygwin returns EPERM instead of ECONNREFUSED here contains_errno = str(errno.ECONNREFUSED) in str(response.error) if not contains_errno and hasattr(errno, "WSAECONNREFUSED"): contains_errno = str(errno.WSAECONNREFUSED) in str( response.error) self.assertTrue(contains_errno, response.error) # This is usually "Connection refused". # On windows, strerror is broken and returns "Unknown error". expected_message = os.strerror(errno.ECONNREFUSED) self.assertTrue(expected_message in str(response.error), response.error)
def test_streaming_stack_context(self): chunks = [] exc_info = [] def error_handler(typ, value, tb): exc_info.append((typ, value, tb)) return True def streaming_cb(chunk): chunks.append(chunk) if chunk == b'qwer': 1 / 0 with ignore_deprecation(): with ExceptionStackContext(error_handler): self.fetch('/chunk', streaming_callback=streaming_cb) self.assertEqual(chunks, [b'asdf', b'qwer']) self.assertEqual(1, len(exc_info)) self.assertIs(exc_info[0][0], ZeroDivisionError)
def get_app(self): class HelloHandler(RequestHandler): def get(self): self.write("Hello world!") class PathQuotingHandler(RequestHandler): def get(self, path): self.write(path) # It would be better to run the wsgiref server implementation in # another thread instead of using our own WSGIContainer, but this # fits better in our async testing framework and the wsgiref # validator should keep us honest with ignore_deprecation(): return WSGIContainer(validator(WSGIAdapter( Application([ ("/", HelloHandler), ("/path/(.*)", PathQuotingHandler), ("/typecheck", TypeCheckHandler), ]))))
def test_final_callback_stack_context(self): # The final callback should be run outside of the httpclient's # stack_context. We want to ensure that there is not stack_context # between the user's callback and the IOLoop, so monkey-patch # IOLoop.handle_callback_exception and disable the test harness's # context with a NullContext. # Note that this does not apply to secondary callbacks (header # and streaming_callback), as errors there must be seen as errors # by the http client so it can clean up the connection. exc_info = [] def handle_callback_exception(callback): exc_info.append(sys.exc_info()) self.stop() self.io_loop.handle_callback_exception = handle_callback_exception with NullContext(): with ignore_deprecation(): self.http_client.fetch(self.get_url('/hello'), lambda response: 1 / 0) self.wait() self.assertEqual(exc_info[0][0], ZeroDivisionError)
def test_localhost(self): with ignore_deprecation(): self.resolver.resolve('localhost', 80, callback=self.stop) result = self.wait() self.assertIn((socket.AF_INET, ('127.0.0.1', 80)), result)
def respond_200(self): with ignore_deprecation(): self.request.connection.stream.write( b"HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nA", self.request.connection.stream.close)
def test_fetch_full_https_url(self): path = 'https://localhost:%d/path' % self.external_port with ignore_deprecation(): response = self.fetch(path, request_timeout=0.1) self.assertEqual(response.request.url, path)