当前位置: 首页>>代码示例>>Python>>正文


Python MementoHandler.check_error方法代码示例

本文整理汇总了Python中ubuntuone.devtools.handlers.MementoHandler.check_error方法的典型用法代码示例。如果您正苦于以下问题:Python MementoHandler.check_error方法的具体用法?Python MementoHandler.check_error怎么用?Python MementoHandler.check_error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ubuntuone.devtools.handlers.MementoHandler的用法示例。


在下文中一共展示了MementoHandler.check_error方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SSLTestCase

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]
class SSLTestCase(BaseSSLTestCase):
    """Test error handling when dealing with ssl."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set the diff tests."""
        yield super(SSLTestCase, self).setUp()

        self.memento = MementoHandler()
        self.memento.setLevel(logging.DEBUG)
        logger = webclient.webclient_module().logger
        logger.addHandler(self.memento)
        self.addCleanup(logger.removeHandler, self.memento)

        self.wc = webclient.webclient_factory()
        self.addCleanup(self.wc.shutdown)

        self.called = []

    def test_ssl_fail(self):
        """Test showing the dialog and rejecting."""
        self.failUnlessFailure(self.wc.request(
                self.base_iri + SIMPLERESOURCE), WebClientError)
        self.assertNotEqual(None, self.memento.check_error('SSL errors'))

    if (WEBCLIENT_MODULE_NAME.endswith(".txweb") or
            WEBCLIENT_MODULE_NAME.endswith(".libsoup")):
        reason = 'SSL support has not yet been implemented.'
        test_ssl_fail.skip = reason
开发者ID:magicicada-bot,项目名称:magicicada-client,代码行数:31,代码来源:test_webclient.py

示例2: test_message

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]
 def test_message(self):
     """Just a message."""
     handler = MementoHandler()
     handler.setLevel(logging.DEBUG)
     deferror_handler(dict(isError=True, message="foobar"))
     self.assertFalse(handler.check_error("Unhandled error in deferred",
                                          "foobar"))
开发者ID:CSRedRat,项目名称:magicicada-gui,代码行数:9,代码来源:test_logger.py

示例3: test_failure

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]
 def test_failure(self):
     """Received a full failure."""
     handler = MementoHandler()
     handler.setLevel(logging.DEBUG)
     f = failure.Failure(ValueError('foobar'))
     deferror_handler(dict(isError=True, failure=f, message=''))
     self.assertFalse(handler.check_error("Unhandled error in deferred",
                                          "ValueError", "foobar"))
开发者ID:CSRedRat,项目名称:magicicada-gui,代码行数:10,代码来源:test_logger.py

示例4: GetProjectDirTestCase

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]
class GetProjectDirTestCase(TestCase):
    """Test case for get_project_dir when constants module is not defined."""

    DIR_NAME = utils.DATA_SUFFIX
    DIR_CONSTANT = 'PROJECT_DIR'
    DIR_GETTER = 'get_project_dir'

    @defer.inlineCallbacks
    def setUp(self):
        yield super(GetProjectDirTestCase, self).setUp()
        self._constants = sys.modules.get(CONSTANTS_MODULE, NOT_DEFINED)
        sys.modules[CONSTANTS_MODULE] = None  # force ImportError

        self.memento = MementoHandler()
        self.memento.setLevel(logging.DEBUG)
        utils.logger.addHandler(self.memento)
        self.addCleanup(utils.logger.removeHandler, self.memento)

        self.get_dir = getattr(utils, self.DIR_GETTER)

    @defer.inlineCallbacks
    def tearDown(self):
        if self._constants is not NOT_DEFINED:
            sys.modules[CONSTANTS_MODULE] = self._constants
        else:
            sys.modules.pop(CONSTANTS_MODULE)
        yield super(GetProjectDirTestCase, self).tearDown()

    def test_get_dir_relative(self):
        """The relative path for the data directory is correctly retrieved."""
        module = utils.os.path.dirname(utils.__file__)
        rel_data = utils.os.path.join(module,
                                      utils.os.path.pardir,
                                      utils.os.path.pardir,
                                      self.DIR_NAME)
        expected_dir = utils.os.path.abspath(rel_data)

        # ensure expected_path exists at os level
        self.patch(utils.os.path, 'exists', lambda path: path == expected_dir)

        result = self.get_dir()
        self.assertEqual(expected_dir, result)

    def test_get_dir_none_exists(self):
        """No data directory exists, return None and log as error."""
        self.patch(utils.os.path, 'exists', lambda path: False)
        sys.modules[CONSTANTS_MODULE] = None

        self.assertRaises(AssertionError, self.get_dir)
        msg = 'get_dir: can not build a valid path.'
        self.assertTrue(self.memento.check_error(msg))
开发者ID:magicicada-bot,项目名称:magicicada-client,代码行数:53,代码来源:test_common.py

示例5: test_logs

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]
    def test_logs(self):
        """Unhandled exceptions logs in error."""
        # set up logger
        handler = MementoHandler()
        handler.setLevel(logging.DEBUG)
        l = logging.getLogger('magicicada')

        # call
        l.addHandler(handler)
        self.addCleanup(l.removeHandler, handler)
        exc = self._get_exception_data()
        try:
            exception_handler(*exc)
        finally:
            l.removeHandler(handler)

        # check
        self.assertTrue(handler.check_error("Unhandled exception",
                                            "ZeroDivisionError"))
开发者ID:CSRedRat,项目名称:magicicada-gui,代码行数:21,代码来源:test_logger.py

示例6: test_noerror

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]
 def test_noerror(self):
     """No error, no action."""
     handler = MementoHandler()
     handler.setLevel(logging.DEBUG)
     deferror_handler(dict(isError=False, message=''))
     self.assertFalse(handler.check_error("error"))
开发者ID:CSRedRat,项目名称:magicicada-gui,代码行数:8,代码来源:test_logger.py

示例7: HeartbeatListenerTestCase

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]
class HeartbeatListenerTestCase(TestCase):
    """Tests for HeartbeatListener class."""

    def setUp(self):
        super(HeartbeatListenerTestCase, self).setUp()
        self.stdin = StringIO()
        self.stdout = StringIO()
        self.stderr = StringIO()
        self.mocker = Mocker()
        self.rpc = self.mocker.mock()
        self.listener = HeartbeatListener(1, 10, ['foo'], [], self.rpc,
                                          stdin=self.stdin, stdout=self.stdout,
                                          stderr=self.stderr)
        self.next_fail = {}
        self.handler = MementoHandler()
        self.listener.logger.addHandler(self.handler)
        self.listener.logger.setLevel(logging.DEBUG)
        self.handler.setLevel(logging.DEBUG)
        self.listener.logger.propagate = False
        self.processes = [dict(name="heartbeat", group="heartbeat", pid="101",
                               state=RUNNING)]
        self.handler.debug = True

    def tearDown(self):
        self.listener.logger.removeHandler(self.handler)
        self.handler.close()
        self.next_fail = None
        self.handler = None
        self.listener = None
        super(HeartbeatListenerTestCase, self).tearDown()

    def fail_next_stop(self, pname):
        """Make next stopProcess to fail."""
        expect(self.rpc.supervisor.stopProcess(pname)).throw(
            xmlrpclib.Fault(42, "Failed to stop the process."))

    def fail_next_start(self, pname):
        """Make next startProcess to fail."""
        expect(self.rpc.supervisor.startProcess(pname)).throw(
            xmlrpclib.Fault(42, "Failed to start the process."))

    def test_restart(self):
        """Test the restart method."""
        expect(self.rpc.supervisor.stopProcess("foo"))
        expect(self.rpc.supervisor.startProcess("foo"))
        with self.mocker:
            self.listener.restart("foo", "testing")
        self.assertTrue(self.handler.check_info("Restarting foo (last "
                                                "hearbeat: testing)"))

    def test_restart_fail_stop(self):
        """Test the restart method failing to stop the process."""
        self.fail_next_stop("foo")
        last = time.time()
        with self.mocker:
            try:
                self.listener.restart("foo", last)
            except xmlrpclib.Fault:
                msg = ("Failed to stop process %s (last heartbeat: %s), "
                       "exiting: %s") % \
                    ("foo", last, "<Fault 42: 'Failed to stop the process.'>")
                self.assertTrue(self.handler.check_error(msg))
            else:
                self.fail("Should get an xmlrpclib.Fault")

    def test_restart_fail_start(self):
        """Test the restart method failing to start the process."""
        expect(self.rpc.supervisor.stopProcess("foo"))
        self.fail_next_start("foo")
        last = time.time()
        with self.mocker:
            try:
                self.listener.restart("foo", last)
            except xmlrpclib.Fault:
                msg = (
                    'Failed to start process %s after stopping it, exiting: %s'
                ) % ("foo", "<Fault 42: 'Failed to start the process.'>")
                self.assertTrue(self.handler.check_error(msg))
            else:
                self.fail("Should get an xmlrpclib.Fault")

    def test_check_processes(self):
        """Test the check_processes method."""
        # add the fake process to the process list
        self.processes.append(dict(name="foo", group="foo", pid="42",
                                   state=RUNNING))
        self.processes.append(dict(name="bar", group="bar", pid="43",
                                   state=RUNNING))
        self.listener.processes = ['bar']
        # 2 process to restart
        self.listener.data['foo'] = {
            'time': time.time() - (self.listener.timeout + 2)}
        self.listener.data['bar'] = {
            'time': time.time() - (self.listener.timeout + 3)}
        self.listener.data['p-1'] = {
            'time': time.time() - (self.listener.timeout - 1)}
        expect(self.rpc.supervisor.getAllProcessInfo()).result(self.processes)
        expect(self.rpc.supervisor.stopProcess("foo:"))
        expect(self.rpc.supervisor.startProcess("foo:"))
        expect(self.rpc.supervisor.stopProcess("bar:bar"))
#.........这里部分代码省略.........
开发者ID:CSRedRat,项目名称:magicicada-server,代码行数:103,代码来源:test_heartbeat_listener.py

示例8: BaseTestCase

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]

#.........这里部分代码省略.........
        """Test that 'store' has 'items' as content."""
        if store is None:
            store = self.store
            assert store is not None, 'class must provide a store'

        msg = 'amount of rows for %s must be %s (got %s).'
        self.assertEqual(len(store), len(items),
                         msg % (store, len(items), len(store)))

        def unicodeize(elem):
            """Return the unicode repr of 'elem'."""
            if isinstance(elem, str):
                result = elem.decode('utf-8')
            else:
                result = elem
            return result

        def scan_tree(tree_iter, items):
            """Scan a whole tree."""
            msg = "row must be %r (got %r instead)"
            while tree_iter is not None:
                expected, children = items.pop()
                actual = store.get(tree_iter, *range(len(expected)))
                actual = map(unicodeize, actual)
                self.assertEqual(expected, actual,
                                 msg % (expected, actual))
                self.assertEqual(len(children),
                                 store.iter_n_children(tree_iter))

                if children:
                    child_iter = store.iter_children(tree_iter)
                    scan_tree(child_iter, children)

                tree_iter = store.iter_next(tree_iter)

        # assert rows content equal to items content
        root_iter = store.get_iter_first()
        tmp = list(reversed(items))
        scan_tree(root_iter, tmp)

    def debug_store(self):
        """Print the whole content of a store."""
        store_iter = self.store.get_iter_first()
        columns = self.store.get_n_columns()
        print '\nShowing contents of store:', self.store
        while store_iter is not None:
            print self.store.get(store_iter, *range(columns))
            store_iter = self.store.iter_next(store_iter)

    def assert_dialog_properties(self, dialog, title=None, modal=True,
                                 position=Gtk.WindowPosition.CENTER_ON_PARENT):
        """The dialog has correct properties."""
        msg = 'Must %sbe modal.'
        self.assertEqual(modal, dialog.get_modal(),
                         msg % ('' if modal else 'not '))

        actual_position = dialog.get_property('window-position')
        msg = 'dialog must have %s position (got %s instead).'
        self.assertEqual(position, actual_position,
                         msg % (position, actual_position))

        actual = dialog.get_title()
        msg = 'Title must be %r (got %r instead)'
        self.assertEqual(title, actual, msg % (title, actual))

        msg = 'Must not skip taskbar.'
        self.assertFalse(dialog.get_skip_taskbar_hint(), msg)

    def assert_function_logs(self, level, func, *args, **kwargs):
        """Check 'funcion' logs its inputs as 'level'."""
        name = func.__name__
        msg = '%s must be logged with level %r'
        try:
            func(*args, **kwargs)
        except Exception:  # pylint: disable=W0703
            self.assertTrue(self.memento.check_error(name),
                            'function (%s) must be logged as ERROR' % name)

        memento_func = getattr(self.memento, 'check_%s' % level.lower())
        self.assertTrue(memento_func(name), msg % (name, level))
        for arg in args:
            self.assertTrue(memento_func(str(arg)), msg % (arg, level))
        for key, val in kwargs.iteritems():
            arg = "'%s': %r" % (key, val)
            self.assertTrue(memento_func(arg), msg % (arg, level))

    def assert_method_called(self, obj, method, *args, **kwargs):
        """Check that obj.method(*args, **kwargs) was called."""
        self.assertEqual(getattr(obj, '_called')[method], [(args, kwargs)],
                         'Method %r was not called with the args %r and '
                         'kwargs %r' % (method, args, kwargs))

    def assert_methods_called(self, obj, methods):
        """Check that every method in 'methods' was called on 'obj'."""
        expected = dict((k, [((), {})]) for k in methods)
        self.assertEqual(getattr(obj, '_called'), expected)

    def assert_no_method_called(self, obj):
        """Check that obj.method was NOT called."""
        self.assertEqual(getattr(obj, '_called'), {})
开发者ID:CSRedRat,项目名称:magicicada-gui,代码行数:104,代码来源:__init__.py

示例9: NodeStructureTestCase

# 需要导入模块: from ubuntuone.devtools.handlers import MementoHandler [as 别名]
# 或者: from ubuntuone.devtools.handlers.MementoHandler import check_error [as 别名]

#.........这里部分代码省略.........
        expected = [('34', 'MakeDir', {'path': '/a/b/foo', '__done__': False})]
        self.assertEqual(node.operations, expected)
        self.assertEqual(node.done, False)
        self.assertEqual(len(node.children), 1)

        node = node.children['fighters']
        self.assertTrue(isinstance(node.last_modified, float))
        self.assertEqual(node.kind, KIND_FILE)
        p = '/a/b/foo/fighters'
        expected = [('67', 'MakeFile', {'path': p, '__done__': False}),
                    ('89', 'Unlink', {'path': p, '__done__': False})]
        self.assertEqual(node.operations, expected)
        self.assertEqual(node.done, False)
        self.assertEqual(len(node.children), 0)

    def test_finishing_nothing(self):
        """Finish something that is not there."""
        r = self.qc.remove('MakeDir', '34', {'path': '/a/bar'})
        self.assertEqual(r, None)
        self.assertTrue(self.handler.check_warning(
                        "Element ''", "['', 'a', 'bar']", 'not in children'))

    def test_operation_error_nothing(self):
        """Finish an operation that is not there."""
        # create a node and break it on purpose
        self.qc.add('MakeDir', '12', {'path': '/a'})
        self.assertEqual(len(self.qc._node_ops), 1)
        node = self.qc._node_ops[''].children['a']
        node.operations = []

        # remove the operation and check
        r = self.qc.remove('MakeDir', '12', {'path': '/a'})
        self.assertEqual(r, None)
        self.assertTrue(self.handler.check_error(
                        "found 0 times", "MakeDir", "12"))

    def test_operation_error_several(self):
        """Finish an operation that is more than once."""
        # create a node and break it on purpose
        self.qc.add('MakeDir', '12', {'path': '/a'})
        self.assertEqual(len(self.qc._node_ops), 1)
        node = self.qc._node_ops[''].children['a']
        node.operations = node.operations * 2

        # remove the operation and check
        r = self.qc.remove('MakeDir', '12', {'path': '/a'})
        self.assertEqual(r, None)
        self.assertTrue(self.handler.check_error(
                        "found 2 times", "MakeDir", "12"))

    def test_two_ops_finishing_one(self):
        """Add some nodes with different combinations."""
        # create two dirs
        self.qc.set_content([('MakeDir', '12', {'path': '/a/foo'}),
                             ('MakeDir', '34', {'path': '/a/bar'})])
        self.assertEqual(len(self.qc._node_ops), 1)

        # all inited properly
        root = self.qc._node_ops[''].children['a']
        self.assertEqual(root.last_modified, None)
        self.assertEqual(root.kind, KIND_DIR)
        self.assertEqual(root.operations, [])
        self.assertEqual(root.done, None)
        self.assertEqual(len(root.children), 2)

        node = root.children['foo']
开发者ID:CSRedRat,项目名称:magicicada-gui,代码行数:70,代码来源:test_queue_content.py


注:本文中的ubuntuone.devtools.handlers.MementoHandler.check_error方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。