コード例 #1
0
ファイル: test_base_events.py プロジェクト: sshyran/trollius
    def test_default_exc_handler_callback(self):
        self.loop._process_events = mock.Mock()

        def zero_error(fut):
            fut.set_result(True)
            1 / 0

        # Test call_soon (events.Handle)
        with mock.patch('trollius.base_events.logger') as log:
            fut = asyncio.Future(loop=self.loop)
            self.loop.call_soon(zero_error, fut)
            fut.add_done_callback(lambda fut: self.loop.stop())
            self.loop.run_forever()
            log.error.assert_called_with(
                test_utils.MockPattern('Exception in callback.*zero'),
                exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY))

        # Test call_later (events.TimerHandle)
        with mock.patch('trollius.base_events.logger') as log:
            fut = asyncio.Future(loop=self.loop)
            self.loop.call_later(0.01, zero_error, fut)
            fut.add_done_callback(lambda fut: self.loop.stop())
            self.loop.run_forever()
            log.error.assert_called_with(
                test_utils.MockPattern('Exception in callback.*zero'),
                exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY))
コード例 #2
0
    def test_default_exc_handler_callback(self):
        self.loop._process_events = mock.Mock()

        def zero_error(fut):
            fut.set_result(True)
            1 / 0

        # Test call_soon (events.Handle)
        with mock.patch("trollius.base_events.logger") as log:
            fut = asyncio.Future(loop=self.loop)
            self.loop.call_soon(zero_error, fut)
            fut.add_done_callback(lambda fut: self.loop.stop())
            self.loop.run_forever()
            log.error.assert_called_with(
                test_utils.MockPattern("Exception in callback.*zero"), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY)
            )

        # Test call_later (events.TimerHandle)
        with mock.patch("trollius.base_events.logger") as log:
            fut = asyncio.Future(loop=self.loop)
            self.loop.call_later(0.01, zero_error, fut)
            fut.add_done_callback(lambda fut: self.loop.stop())
            self.loop.run_forever()
            log.error.assert_called_with(
                test_utils.MockPattern("Exception in callback.*zero"), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY)
            )
コード例 #3
0
    def test_set_exc_handler_custom(self):
        def zero_error():
            1 / 0

        def run_loop():
            handle = self.loop.call_soon(zero_error)
            self.loop._run_once()
            return handle

        self.loop.set_debug(True)
        self.loop._process_events = mock.Mock()

        mock_handler = mock.Mock()
        self.loop.set_exception_handler(mock_handler)
        handle = run_loop()
        mock_handler.assert_called_with(
            self.loop,
            {
                "exception": MOCK_ANY,
                "message": test_utils.MockPattern("Exception in callback.*zero_error"),
                "handle": handle,
                "source_traceback": handle._source_traceback,
            },
        )
        mock_handler.reset_mock()

        self.loop.set_exception_handler(None)
        with mock.patch("trollius.base_events.logger") as log:
            run_loop()
            log.error.assert_called_with(
                test_utils.MockPattern("Exception in callback.*zero"), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY)
            )

        assert not mock_handler.called
コード例 #4
0
    def test_default_exc_handler_coro(self):
        self.loop._process_events = mock.Mock()
        self.loop.set_debug(True)
        asyncio.set_event_loop(self.loop)

        @asyncio.coroutine
        def zero_error_coro():
            yield From(asyncio.sleep(0.01, loop=self.loop))
            1 / 0

        # Test Future.__del__
        with mock.patch("trollius.base_events.logger") as log:
            fut = asyncio.async(zero_error_coro(), loop=self.loop)
            fut.add_done_callback(lambda *args: self.loop.stop())
            self.loop.run_forever()
            fut = None  # Trigger Future.__del__ or futures._TracebackLogger
            support.gc_collect()
            if PY34:
                # Future.__del__ in Python 3.4 logs error with
                # an actual exception context
                log.error.assert_called_with(
                    test_utils.MockPattern(".*exception was never retrieved"),
                    exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY),
                )
            else:
                # futures._TracebackLogger logs only textual traceback
                log.error.assert_called_with(
                    test_utils.MockPattern(".*exception was never retrieved.*ZeroDiv"), exc_info=False
                )
コード例 #5
0
    def test_cancel_handshake(self):
        # Python issue #23197: cancelling an handshake must not raise an
        # exception or log an error, even if the handshake failed
        sslcontext = test_utils.dummy_ssl_context()
        app_proto = asyncio.Protocol()
        waiter = asyncio.Future(loop=self.loop)
        ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext,
                                         waiter)
        handshake_fut = asyncio.Future(loop=self.loop)

        def do_handshake(callback):
            exc = Exception()
            callback(exc)
            handshake_fut.set_result(None)
            return []

        waiter.cancel()
        transport = mock.Mock()
        sslpipe = mock.Mock()
        sslpipe.shutdown.return_value = b''
        sslpipe.do_handshake.side_effect = do_handshake
        with mock.patch('trollius.sslproto._SSLPipe', return_value=sslpipe):
            ssl_proto.connection_made(transport)

        with test_utils.disable_logger():
            self.loop.run_until_complete(handshake_fut)

        # Close the transport
        ssl_proto._app_transport.close()
コード例 #6
0
ファイル: test_base_events.py プロジェクト: sshyran/trollius
    def test_default_exc_handler_coro(self):
        self.loop._process_events = mock.Mock()
        self.loop.set_debug(True)
        asyncio.set_event_loop(self.loop)

        @asyncio.coroutine
        def zero_error_coro():
            yield From(asyncio.sleep(0.01, loop=self.loop))
            1 / 0

        # Test Future.__del__
        with mock.patch('trollius.base_events.logger') as log:
            fut = asyncio. async (zero_error_coro(), loop=self.loop)
            fut.add_done_callback(lambda *args: self.loop.stop())
            self.loop.run_forever()
            fut = None  # Trigger Future.__del__ or futures._TracebackLogger
            support.gc_collect()
            if PY34:
                # Future.__del__ in Python 3.4 logs error with
                # an actual exception context
                log.error.assert_called_with(
                    test_utils.MockPattern('.*exception was never retrieved'),
                    exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY))
            else:
                # futures._TracebackLogger logs only textual traceback
                log.error.assert_called_with(test_utils.MockPattern(
                    '.*exception was never retrieved.*ZeroDiv'),
                                             exc_info=False)
コード例 #7
0
    def test_cancel_handshake(self):
        # Python issue #23197: cancelling an handshake must not raise an
        # exception or log an error, even if the handshake failed
        sslcontext = test_utils.dummy_ssl_context()
        app_proto = asyncio.Protocol()
        waiter = asyncio.Future(loop=self.loop)
        ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext,
                                         waiter)
        handshake_fut = asyncio.Future(loop=self.loop)

        def do_handshake(callback):
            exc = Exception()
            callback(exc)
            handshake_fut.set_result(None)
            return []

        waiter.cancel()
        transport = mock.Mock()
        sslpipe = mock.Mock()
        sslpipe.shutdown.return_value = b''
        sslpipe.do_handshake.side_effect = do_handshake
        with mock.patch('trollius.sslproto._SSLPipe', return_value=sslpipe):
            ssl_proto.connection_made(transport)

        with test_utils.disable_logger():
            self.loop.run_until_complete(handshake_fut)

        # Close the transport
        ssl_proto._app_transport.close()
コード例 #8
0
ファイル: test_base_events.py プロジェクト: sshyran/trollius
    def test_default_exc_handler_broken(self):
        contexts = []

        class Loop(base_events.BaseEventLoop):

            _selector = mock.Mock()
            _process_events = mock.Mock()

            def default_exception_handler(self, context):
                contexts.append(context)
                # Simulates custom buggy "default_exception_handler"
                raise ValueError('spam')

        loop = Loop()
        self.addCleanup(loop.close)
        asyncio.set_event_loop(loop)

        def run_loop():
            def zero_error():
                1 / 0

            loop.call_soon(zero_error)
            loop._run_once()

        with mock.patch('trollius.base_events.logger') as log:
            run_loop()
            log.error.assert_called_with(
                'Exception in default exception handler', exc_info=True)

        def custom_handler(loop, context):
            raise ValueError('ham')

        del contexts[:]
        loop.set_exception_handler(custom_handler)
        with mock.patch('trollius.base_events.logger') as log:
            run_loop()
            log.error.assert_called_with(test_utils.MockPattern(
                'Exception in default exception.*'
                'while handling.*in custom'),
                                         exc_info=True)

            # Check that original context was passed to default
            # exception handler.
            context = contexts[0]
            self.assertIn('context', context)
            self.assertIs(type(context['context']['exception']),
                          ZeroDivisionError)
コード例 #9
0
    def test_default_exc_handler_broken(self):
        contexts = []

        class Loop(base_events.BaseEventLoop):

            _selector = mock.Mock()
            _process_events = mock.Mock()

            def default_exception_handler(self, context):
                contexts.append(context)
                # Simulates custom buggy "default_exception_handler"
                raise ValueError('spam')

        loop = Loop()
        asyncio.set_event_loop(loop)

        def run_loop():
            def zero_error():
                1/0
            loop.call_soon(zero_error)
            loop._run_once()

        with mock.patch('trollius.base_events.logger') as log:
            run_loop()
            log.error.assert_called_with(
                'Exception in default exception handler',
                exc_info=True)

        def custom_handler(loop, context):
            raise ValueError('ham')

        del contexts[:]
        loop.set_exception_handler(custom_handler)
        with mock.patch('trollius.base_events.logger') as log:
            run_loop()
            log.error.assert_called_with(
                test_utils.MockPattern('Exception in default exception.*'
                                       'while handling.*in custom'),
                exc_info=True)

            # Check that original context was passed to default
            # exception handler.
            context = contexts[0]
            self.assertIn('context', context)
            self.assertIs(type(context['context']['exception']),
                          ZeroDivisionError)
コード例 #10
0
    def test_popen_error(self):
        # Issue #24763: check that the subprocess transport is closed
        # when BaseSubprocessTransport fails
        if sys.platform == 'win32':
            target = 'trollius.windows_utils.Popen'
        else:
            target = 'subprocess.Popen'
        with mock.patch(target) as popen:
            exc = ZeroDivisionError
            popen.side_effect = exc

            create = asyncio.create_subprocess_exec(sys.executable,
                                                    '-c',
                                                    'pass',
                                                    loop=self.loop)
            with warnings.catch_warnings(record=True) as warns:
                with self.assertRaises(exc):
                    self.loop.run_until_complete(create)
                self.assertEqual(warns, [])
コード例 #11
0
    def test_set_exc_handler_broken(self):
        def run_loop():
            def zero_error():
                1/0
            self.loop.call_soon(zero_error)
            self.loop._run_once()

        def handler(loop, context):
            raise AttributeError('spam')

        self.loop._process_events = mock.Mock()

        self.loop.set_exception_handler(handler)

        with mock.patch('trollius.base_events.logger') as log:
            run_loop()
            log.error.assert_called_with(
                test_utils.MockPattern(
                    'Unhandled error in exception handler'),
                exc_info=(AttributeError, MOCK_ANY, MOCK_ANY))
コード例 #12
0
ファイル: test_base_events.py プロジェクト: sshyran/trollius
    def test_set_exc_handler_broken(self):
        def run_loop():
            def zero_error():
                1 / 0

            self.loop.call_soon(zero_error)
            self.loop._run_once()

        def handler(loop, context):
            raise AttributeError('spam')

        self.loop._process_events = mock.Mock()

        self.loop.set_exception_handler(handler)

        with mock.patch('trollius.base_events.logger') as log:
            run_loop()
            log.error.assert_called_with(
                test_utils.MockPattern('Unhandled error in exception handler'),
                exc_info=(AttributeError, MOCK_ANY, MOCK_ANY))
コード例 #13
0
ファイル: test_base_events.py プロジェクト: sshyran/trollius
    def test_set_exc_handler_custom(self):
        def zero_error():
            1 / 0

        def run_loop():
            handle = self.loop.call_soon(zero_error)
            self.loop._run_once()
            return handle

        self.loop.set_debug(True)
        self.loop._process_events = mock.Mock()

        mock_handler = mock.Mock()
        self.loop.set_exception_handler(mock_handler)
        handle = run_loop()
        mock_handler.assert_called_with(
            self.loop, {
                'exception':
                MOCK_ANY,
                'message':
                test_utils.MockPattern('Exception in callback.*zero_error'),
                'handle':
                handle,
                'source_traceback':
                handle._source_traceback,
            })
        mock_handler.reset_mock()

        self.loop.set_exception_handler(None)
        with mock.patch('trollius.base_events.logger') as log:
            run_loop()
            log.error.assert_called_with(
                test_utils.MockPattern('Exception in callback.*zero'),
                exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY))

        assert not mock_handler.called