id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
142,548
KelSolaar/Umbra
KelSolaar_Umbra/umbra/managers/patches_manager.py
umbra.managers.patches_manager.Patch
class Patch(foundations.data_structures.Structure): """ Defines a storage object for :class:`PatchesManager` class patch. """ def __init__(self, **kwargs): """ Initializes the class. :param \*\*kwargs: name, path, module, apply, uid. :type \*\*kwargs: dict """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) foundations.data_structures.Structure.__init__(self, **kwargs)
class Patch(foundations.data_structures.Structure): ''' Defines a storage object for :class:`PatchesManager` class patch. ''' def __init__(self, **kwargs): ''' Initializes the class. :param \*\*kwargs: name, path, module, apply, uid. :type \*\*kwargs: dict ''' pass
2
2
11
3
3
5
1
2
1
0
0
0
1
0
1
1
16
4
4
2
2
8
4
2
2
1
1
0
1
142,549
KelSolaar/Umbra
KelSolaar_Umbra/umbra/components/addons/projects_explorer/models.py
umbra.components.addons.projects_explorer.models.ProjectsProxyModel
class ProjectsProxyModel(QSortFilterProxyModel): """ Defines the proxy Model used by the :class:`umbra.components.factory.projects_explorer.projects_explorer.ProjectsExplorer` Component Interface class. """ def __init__(self, parent, *args, **kwargs): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) QSortFilterProxyModel.__init__(self, parent, *args, **kwargs) # --- Setting class attributes. --- color = "rgb({0}, {1}, {2})" self.__editor_node_format = "<span>{0}</span>" self.__file_node_format = "<span style=\"color: {0};\">{{0}}</span>".format(color.format(160, 160, 160)) self.__directory_node_format = "{0}" self.__project_node_format = "<b>{0}</b>" self.__default_project_node_format = "<b>Open Files</b>" def filterAcceptsRow(self, row, parent): """ Reimplements the :meth:`QSortFilterProxyModel.filterAcceptsRow` method. :param row: Source row. :type row: int :param parent: Source parent. :type parent: QModelIndex :return: Filter result :rtype: bool """ child = self.sourceModel().get_node(parent).child(row) if isinstance(child, EditorNode): return False return True def data(self, index, role=Qt.DisplayRole): """ Reimplements the :meth:`QSortFilterProxyModel.data` method. :param index: Index. :type index: QModelIndex :param role: Role. :type role: int :return: Data. :rtype: QVariant """ if role == Qt.DisplayRole: node = self.get_node(index) if node.family == "Editor": data = self.__editor_node_format.format(node.name) elif node.family == "File": data = self.__file_node_format.format(node.name) elif node.family == "Directory": data = self.__directory_node_format.format(node.name) elif node.family == "Project": if node is self.sourceModel().default_project_node: data = self.__default_project_node_format.format(node.name) else: data = self.__project_node_format.format(node.name) else: data = QVariant() return data else: return QSortFilterProxyModel.data(self, index, role) def get_node(self, index): """ Returns the Node at given index. :param index: Index. :type index: QModelIndex :return: Node. :rtype: AbstractCompositeNode """ index = self.mapToSource(index) if not index.isValid(): return self.sourceModel().root_node return index.internalPointer() or self.sourceModel().root_node def get_attribute(self, *args): """ Reimplements requisite method. """ pass
class ProjectsProxyModel(QSortFilterProxyModel): ''' Defines the proxy Model used by the :class:`umbra.components.factory.projects_explorer.projects_explorer.ProjectsExplorer` Component Interface class. ''' def __init__(self, parent, *args, **kwargs): ''' Initializes the class. :param parent: Object parent. :type parent: QObject :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* ''' pass def filterAcceptsRow(self, row, parent): ''' Reimplements the :meth:`QSortFilterProxyModel.filterAcceptsRow` method. :param row: Source row. :type row: int :param parent: Source parent. :type parent: QModelIndex :return: Filter result :rtype: bool ''' pass def data(self, index, role=Qt.DisplayRole): ''' Reimplements the :meth:`QSortFilterProxyModel.data` method. :param index: Index. :type index: QModelIndex :param role: Role. :type role: int :return: Data. :rtype: QVariant ''' pass def get_node(self, index): ''' Returns the Node at given index. :param index: Index. :type index: QModelIndex :return: Node. :rtype: AbstractCompositeNode ''' pass def get_attribute(self, *args): ''' Reimplements requisite method. ''' pass
6
6
18
3
8
8
3
1.02
1
1
1
0
5
5
5
5
101
18
41
15
35
42
35
15
29
7
1
3
13
142,550
KelSolaar/Umbra
KelSolaar_Umbra/umbra/tests/tests_umbra/tests_globals/tests_constants.py
umbra.tests.tests_umbra.tests_globals.tests_constants.TestConstants
class TestConstants(unittest.TestCase): """ Defines :class:`umbra.globals.constants.Constants` class units tests methods. """ def test_required_attributes(self): """ Tests presence of required attributes. """ required_attributes = ("application_name", "major_version", "minor_version", "change_version", "version", "logger", "verbosity_level", "verbosity_labels", "logging_default_formatter", "logging_separators", "default_codec", "codec_error", "application_directory", "provider_directory", "patches_directory", "settings_directory", "user_components_directory", "logging_directory", "io_directory", "preferences_directories", "factory_components_directory", "factory_addons_components_directory", "resources_directory", "patches_file", "settings_file", "logging_file", "libraries_directory", "default_timer_cycle", "null_object") for attribute in required_attributes: self.assertIn(attribute, Constants.__dict__) def test_application_name_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.application_name` attribute. """ self.assertRegexpMatches(Constants.application_name, "\w+") def test_major_version_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.major_version` attribute. """ self.assertRegexpMatches(Constants.version, "\d") def test_minor_version_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.minor_version` attribute. """ self.assertRegexpMatches(Constants.version, "\d") def test_change_version_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.change_version` attribute. """ self.assertRegexpMatches(Constants.version, "\d") def test_version_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.version` attribute. """ self.assertRegexpMatches(Constants.version, "\d\.\d\.\d") def test_logger_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.logger` attribute. """ self.assertRegexpMatches(Constants.logger, "\w+") def test_verbosity_level_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.verbosity_level` attribute. """ self.assertIsInstance(Constants.verbosity_level, int) self.assertGreaterEqual(Constants.verbosity_level, 0) self.assertLessEqual(Constants.verbosity_level, 4) def test_verbosity_labels_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.verbosity_labels` attribute. """ self.assertIsInstance(Constants.verbosity_labels, tuple) for label in Constants.verbosity_labels: self.assertIsInstance(label, unicode) def test_logging_default_formatter_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.logging_default_formatter` attribute. """ self.assertIsInstance(Constants.logging_default_formatter, unicode) def test_logging_separators_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.logging_separators` attribute. """ self.assertIsInstance(Constants.logging_separators, unicode) def test_default_codec_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.default_codec` attribute. """ valid_encodings = ("utf-8", "cp1252") self.assertIn(Constants.default_codec, valid_encodings) def test_encoding_error_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.codec_error` attribute. """ valid_encodings_errors = ("strict", "ignore", "replace", "xmlcharrefreplace") self.assertIn(Constants.codec_error, valid_encodings_errors) def test_application_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.application_directory` attribute. """ self.assertRegexpMatches(Constants.application_directory, "\w+") def test_provider_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.provider_directory` attribute. """ self.assertRegexpMatches(Constants.provider_directory, "\w+") def test_patches_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.patches_directory` attribute. """ self.assertRegexpMatches(Constants.patches_directory, "\w+") def test_settings_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.settings_directory` attribute. """ self.assertRegexpMatches(Constants.settings_directory, "\w+") def test_user_components_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.user_components_directory` attribute. """ self.assertRegexpMatches(Constants.user_components_directory, "\w+") def test_logging_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.logging_directory` attribute. """ self.assertRegexpMatches(Constants.logging_directory, "\w+") def test_io_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.io_directory` attribute. """ self.assertRegexpMatches(Constants.io_directory, "\w+") def test_preferences_directories_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.preferences_directories` attribute. """ self.assertIsInstance(Constants.preferences_directories, tuple) def test_factory_components_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.factory_components_directory` attribute. """ self.assertRegexpMatches(Constants.factory_components_directory, "\w+") def test_factory_addons_components_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.factory_addons_components_directory` attribute. """ self.assertRegexpMatches(Constants.factory_addons_components_directory, "\w+") def test_resources_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.resources_directory` attribute. """ self.assertRegexpMatches(Constants.resources_directory, "\w+") def test_patches_file_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.patches_file` attribute. """ self.assertRegexpMatches(Constants.patches_file, "\w+") def test_settings_file_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.settings_file` attribute. """ self.assertRegexpMatches(Constants.settings_file, "\w+") def test_logging_file_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.logging_file` attribute. """ self.assertRegexpMatches(Constants.logging_file, "\w+") def test_libraries_directory_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.libraries_directory` attribute. """ self.assertRegexpMatches(Constants.libraries_directory, "\w+") def test_default_timer_cycle_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.default_timer_cycle` attribute. """ self.assertIsInstance(Constants.default_timer_cycle, int) self.assertGreaterEqual(Constants.default_timer_cycle, 25) self.assertLessEqual(Constants.default_timer_cycle, 4 ** 32) def test_null_object_attribute(self): """ Tests :attr:`umbra.globals.constants.Constants.null_object` attribute. """ self.assertRegexpMatches(Constants.null_object, "\w+")
class TestConstants(unittest.TestCase): ''' Defines :class:`umbra.globals.constants.Constants` class units tests methods. ''' def test_required_attributes(self): ''' Tests presence of required attributes. ''' pass def test_application_name_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.application_name` attribute. ''' pass def test_major_version_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.major_version` attribute. ''' pass def test_minor_version_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.minor_version` attribute. ''' pass def test_change_version_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.change_version` attribute. ''' pass def test_version_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.version` attribute. ''' pass def test_logger_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.logger` attribute. ''' pass def test_verbosity_level_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.verbosity_level` attribute. ''' pass def test_verbosity_labels_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.verbosity_labels` attribute. ''' pass def test_logging_default_formatter_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.logging_default_formatter` attribute. ''' pass def test_logging_separators_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.logging_separators` attribute. ''' pass def test_default_codec_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.default_codec` attribute. ''' pass def test_encoding_error_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.codec_error` attribute. ''' pass def test_application_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.application_directory` attribute. ''' pass def test_provider_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.provider_directory` attribute. ''' pass def test_patches_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.patches_directory` attribute. ''' pass def test_settings_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.settings_directory` attribute. ''' pass def test_user_components_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.user_components_directory` attribute. ''' pass def test_logging_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.logging_directory` attribute. ''' pass def test_io_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.io_directory` attribute. ''' pass def test_preferences_directories_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.preferences_directories` attribute. ''' pass def test_factory_components_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.factory_components_directory` attribute. ''' pass def test_factory_addons_components_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.factory_addons_components_directory` attribute. ''' pass def test_resources_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.resources_directory` attribute. ''' pass def test_patches_file_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.patches_file` attribute. ''' pass def test_settings_file_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.settings_file` attribute. ''' pass def test_logging_file_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.logging_file` attribute. ''' pass def test_libraries_directory_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.libraries_directory` attribute. ''' pass def test_default_timer_cycle_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.default_timer_cycle` attribute. ''' pass def test_null_object_attribute(self): ''' Tests :attr:`umbra.globals.constants.Constants.null_object` attribute. ''' pass
31
31
8
1
3
3
1
0.9
1
3
1
0
30
0
30
102
259
63
103
36
72
93
71
36
40
2
2
1
32
142,551
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/views.py
umbra.ui.views.Mixin_AbstractWidget
class Mixin_AbstractWidget(Mixin_AbstractBase): """ Defines a mixin used to bring common capabilities in Application Widgets Views classes. """ pass
class Mixin_AbstractWidget(Mixin_AbstractBase): ''' Defines a mixin used to bring common capabilities in Application Widgets Views classes. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
3
0
0
0
6
6
1
2
1
1
3
2
1
1
0
2
0
0
142,552
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/views.py
umbra.ui.views.Abstract_QTreeWidget
class Abstract_QTreeWidget(QTreeWidget, Mixin_AbstractWidget): """ Defines a `QTreeWidget <http://doc.qt.nokia.com/qtreewidget.html>`_ subclass used as base by others Application Widgets Views classes. """ def __init__(self, parent=None, message=None): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param message: View default message when Model is empty. :type message: unicode """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) QTreeWidget.__init__(self, parent) Mixin_AbstractWidget.__init__(self, message)
class Abstract_QTreeWidget(QTreeWidget, Mixin_AbstractWidget): ''' Defines a `QTreeWidget <http://doc.qt.nokia.com/qtreewidget.html>`_ subclass used as base by others Application Widgets Views classes. ''' def __init__(self, parent=None, message=None): ''' Initializes the class. :param parent: Object parent. :type parent: QObject :param message: View default message when Model is empty. :type message: unicode ''' pass
2
2
14
3
4
7
1
2.2
2
0
0
0
1
0
1
7
20
4
5
2
3
11
5
2
3
1
3
0
1
142,553
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/views.py
umbra.ui.views.Abstract_QTreeView
class Abstract_QTreeView(QTreeView, Mixin_AbstractView): """ Defines a `QTreeView <http://doc.qt.nokia.com/qtreeview.html>`_ subclass used as base by others Application Views classes. """ def __init__(self, parent=None, read_only=False, message=None): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param read_only: View is read only. :type read_only: bool :param message: View default message when Model is empty. :type message: unicode """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) QTreeView.__init__(self, parent) Mixin_AbstractView.__init__(self, read_only, message)
class Abstract_QTreeView(QTreeView, Mixin_AbstractView): ''' Defines a `QTreeView <http://doc.qt.nokia.com/qtreeview.html>`_ subclass used as base by others Application Views classes. ''' def __init__(self, parent=None, read_only=False, message=None): ''' Initializes the class. :param parent: Object parent. :type parent: QObject :param read_only: View is read only. :type read_only: bool :param message: View default message when Model is empty. :type message: unicode ''' pass
2
2
16
3
4
9
1
2.6
2
0
0
4
1
0
1
19
22
4
5
2
3
13
5
2
3
1
3
0
1
142,554
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/views.py
umbra.ui.views.Abstract_QTableWidget
class Abstract_QTableWidget(QTableWidget, Mixin_AbstractWidget): """ Defines a `QTableWidget <http://doc.qt.nokia.com/qtablewidget.html>`_ subclass used as base by others Application Widgets Views classes. """ def __init__(self, parent=None, read_only=False, message=None): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param message: View default message when Model is empty. :type message: unicode """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) QTableWidget.__init__(self, parent) Mixin_AbstractWidget.__init__(self, message)
class Abstract_QTableWidget(QTableWidget, Mixin_AbstractWidget): ''' Defines a `QTableWidget <http://doc.qt.nokia.com/qtablewidget.html>`_ subclass used as base by others Application Widgets Views classes. ''' def __init__(self, parent=None, read_only=False, message=None): ''' Initializes the class. :param parent: Object parent. :type parent: QObject :param message: View default message when Model is empty. :type message: unicode ''' pass
2
2
14
3
4
7
1
2.2
2
0
0
0
1
0
1
7
20
4
5
2
3
11
5
2
3
1
3
0
1
142,555
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/views.py
umbra.ui.views.Abstract_QTableView
class Abstract_QTableView(QTableView, Mixin_AbstractView): """ Defines a `QTableView <http://doc.qt.nokia.com/qtableview.html>`_ subclass used as base by others Application Views classes. """ def __init__(self, parent=None, read_only=False, message=None): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param read_only: View is read only. :type read_only: bool :param message: View default message when Model is empty. :type message: unicode """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) QTableView.__init__(self, parent) Mixin_AbstractView.__init__(self, read_only, message)
class Abstract_QTableView(QTableView, Mixin_AbstractView): ''' Defines a `QTableView <http://doc.qt.nokia.com/qtableview.html>`_ subclass used as base by others Application Views classes. ''' def __init__(self, parent=None, read_only=False, message=None): ''' Initializes the class. :param parent: Object parent. :type parent: QObject :param read_only: View is read only. :type read_only: bool :param message: View default message when Model is empty. :type message: unicode ''' pass
2
2
16
3
4
9
1
2.6
2
0
0
0
1
0
1
19
22
4
5
2
3
13
5
2
3
1
3
0
1
142,556
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/views.py
umbra.ui.views.Abstract_QListWidget
class Abstract_QListWidget(QListWidget, Mixin_AbstractWidget): """ Defines a `QListWidget <http://doc.qt.nokia.com/qlistwidget.html>`_ subclass used as base by others Application Widgets Views classes. """ def __init__(self, parent=None, message=None): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param message: View default message when Model is empty. :type message: unicode """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) QListWidget.__init__(self, parent) Mixin_AbstractWidget.__init__(self, message)
class Abstract_QListWidget(QListWidget, Mixin_AbstractWidget): ''' Defines a `QListWidget <http://doc.qt.nokia.com/qlistwidget.html>`_ subclass used as base by others Application Widgets Views classes. ''' def __init__(self, parent=None, message=None): ''' Initializes the class. :param parent: Object parent. :type parent: QObject :param message: View default message when Model is empty. :type message: unicode ''' pass
2
2
14
3
4
7
1
2.2
2
0
0
0
1
0
1
7
20
4
5
2
3
11
5
2
3
1
3
0
1
142,557
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/views.py
umbra.ui.views.Abstract_QListView
class Abstract_QListView(QListView, Mixin_AbstractView): """ Defines a `QListView <http://doc.qt.nokia.com/qlistview.html>`_ subclass used as base by others Application Views classes. """ def __init__(self, parent=None, read_only=False, message=None): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param read_only: View is read only. :type read_only: bool :param message: View default message when Model is empty. :type message: unicode """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) QListView.__init__(self, parent) Mixin_AbstractView.__init__(self, read_only, message)
class Abstract_QListView(QListView, Mixin_AbstractView): ''' Defines a `QListView <http://doc.qt.nokia.com/qlistview.html>`_ subclass used as base by others Application Views classes. ''' def __init__(self, parent=None, read_only=False, message=None): ''' Initializes the class. :param parent: Object parent. :type parent: QObject :param read_only: View is read only. :type read_only: bool :param message: View default message when Model is empty. :type message: unicode ''' pass
2
2
16
3
4
9
1
2.6
2
0
0
0
1
0
1
19
22
4
5
2
3
13
5
2
3
1
3
0
1
142,558
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/nodes.py
umbra.ui.nodes.GraphModelNode
class GraphModelNode(AbstractCompositeNode, Mixin_GraphModelObject): """ Defines :class:`GraphModel` class base Node object. """ __family = "GraphModel" """ :param __family: Node family. :type __family: unicode """ def __init__(self, name=None, parent=None, children=None, roles=None, flags=None, **kwargs): """ Initializes the class. :param name: Node name. :type name: unicode :param parent: Node parent. :type parent: AbstractNode or AbstractCompositeNode :param children: Children. :type children: list :param roles: Roles. :type roles: dict :param flags: Flags. ( Qt.ItemFlag ) :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) AbstractCompositeNode.__init__(self, name, parent, children, **kwargs) Mixin_GraphModelObject.__init__(self) # --- Setting class attributes. --- self.roles = roles or {Qt.DisplayRole: self.name, Qt.EditRole: self.name} self.flags = flags or int(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) def __setattr__(self, attribute, value): """ Reimplements the :meth:`foundations.nodes.AbstractCompositeNode.__setattr__` method. :param attribute.: Attribute. :type attribute.: object :param value.: Value. :type value.: object """ current_value = getattr(self, attribute, None) AbstractCompositeNode.__setattr__(self, attribute, value) if not attribute in ("_GraphModelNode__name", "_GraphModelNode__roles", "_GraphModelNode__flags"): return trigger_model = getattr(self, "_Mixin_GraphModelObject__trigger_model", False) if trigger_model and value is not current_value: self.node_changed() __setitem__ = __setattr__ def node_changed(self): """ Triggers the host model(s) :meth:`umbra.ui.models.GraphModel.node_changed` method. :return: Method success. :rtype: bool """ for model in umbra.ui.models.GraphModel.find_model(self): model.node_changed(self) return True
class GraphModelNode(AbstractCompositeNode, Mixin_GraphModelObject): ''' Defines :class:`GraphModel` class base Node object. ''' def __init__(self, name=None, parent=None, children=None, roles=None, flags=None, **kwargs): ''' Initializes the class. :param name: Node name. :type name: unicode :param parent: Node parent. :type parent: AbstractNode or AbstractCompositeNode :param children: Children. :type children: list :param roles: Roles. :type roles: dict :param flags: Flags. ( Qt.ItemFlag ) :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* ''' pass def __setattr__(self, attribute, value): ''' Reimplements the :meth:`foundations.nodes.AbstractCompositeNode.__setattr__` method. :param attribute.: Attribute. :type attribute.: object :param value.: Value. :type value.: object ''' pass def node_changed(self): ''' Triggers the host model(s) :meth:`umbra.ui.models.GraphModel.node_changed` method. :return: Method success. :rtype: bool ''' pass
4
4
19
4
7
9
2
1.48
2
2
1
11
3
2
3
13
73
16
23
11
19
34
21
11
17
3
2
1
6
142,559
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/nodes.py
umbra.ui.nodes.GraphModelAttribute
class GraphModelAttribute(Attribute, Mixin_GraphModelObject): """ Defines a storage object for the :class:`GraphModelNode` class attributes. """ def __init__(self, name=None, value=None, roles=None, flags=None, **kwargs): """ Initializes the class. :param name: Attribute name. :type name: unicode :param value: Attribute value. :type value: object :param roles: Roles. :type roles: dict :param flags: Flags. :type flags: int :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) Attribute.__init__(self, name, value, **kwargs) Mixin_GraphModelObject.__init__(self) # --- Setting class attributes. --- self.roles = roles or {Qt.DisplayRole: value, Qt.EditRole: value} self.flags = flags or int(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled) def __setattr__(self, attribute, value): """ Reimplements the :meth:`foundations.nodes.Attribute.__setattr__` method. :param attribute: Attribute. :type attribute: object :param value: Value. :type value: object """ current_value = getattr(self, attribute, None) Attribute.__setattr__(self, attribute, value) if not attribute in ("_Attribute__name", "_Attribute__value", "_Attribute__roles", "_Attribute__flags"): return trigger_model = getattr(self, "_Mixin_GraphModelObject__trigger_model", False) if trigger_model and value is not current_value: self.attribute_changed() __setitem__ = __setattr__ def attribute_changed(self): """ Triggers the host model(s) :meth:`umbra.ui.models.GraphModel.attribute_changed` method. :return: Method success. :rtype: bool """ for model in umbra.ui.models.GraphModel.find_model(self): headers = model.horizontal_headers.values() if not self.name in headers: continue model.attribute_changed(model.find_node(self), headers.index(self.name)) return True
class GraphModelAttribute(Attribute, Mixin_GraphModelObject): ''' Defines a storage object for the :class:`GraphModelNode` class attributes. ''' def __init__(self, name=None, value=None, roles=None, flags=None, **kwargs): ''' Initializes the class. :param name: Attribute name. :type name: unicode :param value: Attribute value. :type value: object :param roles: Roles. :type roles: dict :param flags: Flags. :type flags: int :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* ''' pass def __setattr__(self, attribute, value): ''' Reimplements the :meth:`foundations.nodes.Attribute.__setattr__` method. :param attribute: Attribute. :type attribute: object :param value: Value. :type value: object ''' pass def attribute_changed(self): ''' Triggers the host model(s) :meth:`umbra.ui.models.GraphModel.attribute_changed` method. :return: Method success. :rtype: bool ''' pass
4
4
21
4
8
9
2
1.12
2
2
1
0
3
3
3
13
71
16
26
12
22
29
23
11
19
3
2
2
7
142,560
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/nodes.py
umbra.ui.nodes.DefaultNode
class DefaultNode(AbstractCompositeNode): """ | Defines the default Node used in :class:`GraphModel` class model. | This simple Node is used as an invisible root Node for :class:`GraphModel` class models. """ __family = "Default" """ :param __family: Node family. :type __family: unicode """ def __init__(self, name=None, parent=None, children=None, **kwargs): """ Initializes the class. :param name: Node name. :type name: unicode :param parent: Node parent. :type parent: AbstractCompositeNode :param children: Children. :type children: list :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) AbstractCompositeNode.__init__(self, name, parent, children, **kwargs)
class DefaultNode(AbstractCompositeNode): ''' | Defines the default Node used in :class:`GraphModel` class model. | This simple Node is used as an invisible root Node for :class:`GraphModel` class models. ''' def __init__(self, name=None, parent=None, children=None, **kwargs): ''' Initializes the class. :param name: Node name. :type name: unicode :param parent: Node parent. :type parent: AbstractCompositeNode :param children: Children. :type children: list :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* ''' pass
2
2
17
3
3
11
1
3.8
1
0
0
0
1
0
1
1
29
5
5
3
3
19
5
3
3
1
1
0
1
142,561
KelSolaar/Umbra
KelSolaar_Umbra/umbra/tests/tests_umbra/tests_exceptions.py
umbra.tests.tests_umbra.tests_exceptions.TestExceptions
class TestExceptions(unittest.TestCase): """ Defines :mod:`sibl_gui.exceptions` module exceptions classes units tests methods. """ def test_required_attributes(self): """ Tests presence of required attributes. """ required_attributes = ("value",) for exception in EXCEPTIONS: exception_instance = exception(None) for attribute in required_attributes: self.assertIn(attribute, dir(exception_instance)) def test__str__(self): """ Tests exceptions classes **__str__** method. """ for exception in EXCEPTIONS: exception_instance = exception("{0} Exception raised!".format(exception.__class__)) self.assertIsInstance(exception_instance.__str__(), str) exception_instance = exception([exception.__class__, "Exception raised!"]) self.assertIsInstance(exception_instance.__str__(), str) exception_instance = exception(0) self.assertIsInstance(exception_instance.__str__(), str)
class TestExceptions(unittest.TestCase): ''' Defines :mod:`sibl_gui.exceptions` module exceptions classes units tests methods. ''' def test_required_attributes(self): ''' Tests presence of required attributes. ''' pass def test__str__(self): ''' Tests exceptions classes **__str__** method. ''' pass
3
3
11
1
7
3
3
0.6
1
1
0
0
2
0
2
74
28
4
15
9
12
9
15
9
12
3
2
2
5
142,562
KelSolaar/Umbra
KelSolaar_Umbra/umbra/components/addons/tcp_server_ui/tcp_server_ui.py
umbra.components.addons.tcp_server_ui.tcp_server_ui.RequestsStackDataHandler
class RequestsStackDataHandler(SocketServer.BaseRequestHandler): """ Defines the default requests handler. """ codes = foundations.data_structures.Structure(request_end="<!RE>", server_shutdown="<!SS>") def handle(self): """ Reimplements the :meth:`SocketServer.BaseRequestHandler.handle` method. :return: Method success. :rtype: bool """ all_data = [] while True: data = self.request.recv(1024) if not data: break if self.codes.server_shutdown in data: return self.__server_shutdown() if self.codes.request_end in data: all_data.append(data[:data.find(self.codes.request_end)]) break all_data.append(data) if len(all_data) >= 2: tail = all_data[-2] + all_data[-1] if self.codes.server_shutdown in tail: return self.__server_shutdown() if self.codes.request_end in tail: all_data[-2] = tail[:tail.find(self.codes.request_end)] all_data.pop() break RuntimeGlobals.requests_stack.append("".join(all_data)) return True def __server_shutdown(self): """ Shutdowns the TCP Server. """ return self.container.stop(terminate=True)
class RequestsStackDataHandler(SocketServer.BaseRequestHandler): ''' Defines the default requests handler. ''' def handle(self): ''' Reimplements the :meth:`SocketServer.BaseRequestHandler.handle` method. :return: Method success. :rtype: bool ''' pass def __server_shutdown(self): ''' Shutdowns the TCP Server. ''' pass
3
3
21
5
12
4
5
0.41
1
1
1
0
2
0
2
6
50
12
27
7
24
11
26
7
23
8
1
3
9
142,563
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/languages.py
umbra.ui.languages.Language
class Language(foundations.data_structures.Structure): """ Defines a storage object for the :class:`Editor` class language description. """ def __init__(self, **kwargs): """ Initializes the class. :param \*\*kwargs: name, file, parser, extensions, highlighter, completer, pre_input_accelerators, post_input_accelerators, visual_accelerators, indent_marker, comment_marker, comment_block_marker_start, comment_block_marker_end, symbols_pairs, indentation_symbols, rules, tokens, theme. """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) foundations.data_structures.Structure.__init__(self, **kwargs)
class Language(foundations.data_structures.Structure): ''' Defines a storage object for the :class:`Editor` class language description. ''' def __init__(self, **kwargs): ''' Initializes the class. :param \*\*kwargs: name, file, parser, extensions, highlighter, completer, pre_input_accelerators, post_input_accelerators, visual_accelerators, indent_marker, comment_marker, comment_block_marker_start, comment_block_marker_end, symbols_pairs, indentation_symbols, rules, tokens, theme. ''' pass
2
2
12
3
3
6
1
2.25
1
0
0
0
1
0
1
1
17
4
4
2
2
9
4
2
2
1
1
0
1
142,564
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/common.py
umbra.ui.common.Location
class Location(foundations.data_structures.Structure): """ Defines a storage object for the :class:`SearchInFiles` class location. """ def __init__(self, **kwargs): """ Initializes the class. :param \*\*kwargs: directories, files, filters_in, filters_out, targets. :type \*\*kwargs: dict """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) foundations.data_structures.Structure.__init__(self, **kwargs)
class Location(foundations.data_structures.Structure): ''' Defines a storage object for the :class:`SearchInFiles` class location. ''' def __init__(self, **kwargs): ''' Initializes the class. :param \*\*kwargs: directories, files, filters_in, filters_out, targets. :type \*\*kwargs: dict ''' pass
2
2
11
3
3
5
1
2
1
0
0
0
1
0
1
1
16
4
4
2
2
8
4
2
2
1
1
0
1
142,565
KelSolaar/Umbra
KelSolaar_Umbra/umbra/tests/tests_umbra/tests_globals/tests_ui_constants.py
umbra.tests.tests_umbra.tests_globals.tests_ui_constants.TestUiConstants
class TestUiConstants(unittest.TestCase): """ Defines :class:`umbra.globals.ui_constants.UiConstants` class units tests methods. """ def test_required_attributes(self): """ Tests presence of required attributes. """ required_attributes = ("ui_file", "processing_ui_file", "reporter_ui_file", "windows_stylesheet_file", "darwin_stylesheet_file", "linux_stylesheet_file", "windows_full_screen_stylesheet_file", "darwin_full_screen_stylesheet_file", "linux_full_screen_stylesheet_file", "windows_style", "darwin_style", "linux_style", "settings_file", "layouts_file", "application_windows_icon", "splash_screen_image", "logo_image", "default_toolbar_icon_size", "custom_layouts_icon", "custom_layouts_hover_icon", "custom_layouts_active_icon", "miscellaneous_icon", "miscellaneous_hover_icon", "miscellaneous_active_icon", "development_icon", "development_hover_icon", "development_active_icon", "preferences_icon", "preferences_hover_icon", "preferences_active_icon", "startup_layout", "help_file", "api_file", "development_layout", "python_grammar_file", "logging_grammar_file", "text_grammar_file", "invalid_link_html_file", "crittercism_id") for attribute in required_attributes: self.assertIn(attribute, UiConstants.__dict__) def test_ui_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.ui_file` attribute. """ self.assertRegexpMatches(UiConstants.ui_file, "\w+") def test_processing_ui_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.processing_ui_file` attribute. """ self.assertRegexpMatches(UiConstants.processing_ui_file, "\w+") def test_reporter_ui_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.reporter_ui_file` attribute. """ self.assertRegexpMatches(UiConstants.reporter_ui_file, "\w+") def test_windows_stylesheet_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.windows_stylesheet_file` attribute. """ self.assertRegexpMatches(UiConstants.windows_stylesheet_file, "\w+") def test_darwin_stylesheet_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.darwin_stylesheet_file` attribute. """ self.assertRegexpMatches(UiConstants.darwin_stylesheet_file, "\w+") def test_linux_stylesheet_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.linux_stylesheet_file` attribute. """ self.assertRegexpMatches(UiConstants.linux_stylesheet_file, "\w+") def test_windows_full_screen_stylesheet_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.windows_full_screen_stylesheet_file` attribute. """ self.assertRegexpMatches(UiConstants.windows_full_screen_stylesheet_file, "\w+") def test_darwin_full_screen_stylesheet_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.darwin_full_screen_stylesheet_file` attribute. """ self.assertRegexpMatches(UiConstants.darwin_full_screen_stylesheet_file, "\w+") def test_linux_full_screen_stylesheet_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.linux_full_screen_stylesheet_file` attribute. """ self.assertRegexpMatches(UiConstants.linux_full_screen_stylesheet_file, "\w+") def test_windows_style_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.windows_style` attribute. """ self.assertRegexpMatches(UiConstants.windows_style, "\w+") def test_darwin_style_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.darwin_style` attribute. """ self.assertRegexpMatches(UiConstants.darwin_style, "\w+") def test_linux_style_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.linux_style` attribute. """ self.assertRegexpMatches(UiConstants.linux_style, "\w+") def test_settings_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.settings_file` attribute. """ self.assertRegexpMatches(UiConstants.settings_file, "\w+") def test_layouts_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.layouts_file` attribute. """ self.assertRegexpMatches(UiConstants.layouts_file, "\w+") def test_application_windows_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.application_windows_icon` attribute. """ self.assertRegexpMatches(UiConstants.application_windows_icon, "\w+") self.assertRegexpMatches(UiConstants.application_windows_icon, "\.[pP][nN][gG]$") def test_splashscreem_image_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.splash_screen_image` attribute. """ self.assertRegexpMatches(UiConstants.splash_screen_image, "\w+") self.assertRegexpMatches(UiConstants.splash_screen_image, "\.[bB][mM][pP]$|\.[jJ][pP][eE][gG]$|\.[jJ][pP][gG]|\.[pP][nN][gG]$") def test_logo_image_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.logo_image` attribute. """ self.assertRegexpMatches(UiConstants.logo_image, "\w+") self.assertRegexpMatches( UiConstants.logo_image, "\.[bB][mM][pP]$|\.[jJ][pP][eE][gG]$|\.[jJ][pP][gG]|\.[pP][nN][gG]$") def test_default_toolbar_icon_size_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.default_toolbar_icon_size` attribute. """ self.assertIsInstance(UiConstants.default_toolbar_icon_size, int) self.assertGreaterEqual(UiConstants.default_toolbar_icon_size, 8) self.assertLessEqual(UiConstants.default_toolbar_icon_size, 128) def test_custom_layouts_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.custom_layouts_icon` attribute. """ self.assertRegexpMatches(UiConstants.custom_layouts_icon, "\w+") def test_custom_layouts_hover_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.custom_layouts_hover_icon` attribute. """ self.assertRegexpMatches(UiConstants.custom_layouts_hover_icon, "\w+") def test_custom_layouts_active_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.custom_layouts_active_icon` attribute. """ self.assertRegexpMatches(UiConstants.custom_layouts_active_icon, "\w+") def test_miscellaneous_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.miscellaneous_icon` attribute. """ self.assertRegexpMatches(UiConstants.miscellaneous_icon, "\w+") def test_miscellaneous_hover_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.miscellaneous_hover_icon` attribute. """ self.assertRegexpMatches(UiConstants.miscellaneous_hover_icon, "\w+") def test_miscellaneous_active_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.miscellaneous_active_icon` attribute. """ self.assertRegexpMatches(UiConstants.miscellaneous_active_icon, "\w+") def test_development_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.development_icon` attribute. """ self.assertRegexpMatches(UiConstants.development_icon, "\w+") def test_development_hover_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.development_hover_icon` attribute. """ self.assertRegexpMatches(UiConstants.development_hover_icon, "\w+") def test_development_active_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.development_active_icon` attribute. """ self.assertRegexpMatches(UiConstants.development_active_icon, "\w+") def test_preferences_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.preferences_icon` attribute. """ self.assertRegexpMatches(UiConstants.preferences_icon, "\w+") def test_preferences_hover_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.preferences_hover_icon` attribute. """ self.assertRegexpMatches(UiConstants.preferences_hover_icon, "\w+") def test_preferences_active_icon_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.preferences_active_icon` attribute. """ self.assertRegexpMatches(UiConstants.preferences_active_icon, "\w+") def test_startup_layout_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.startup_layout` attribute. """ self.assertRegexpMatches(UiConstants.startup_layout, "\w+") def test_help_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.help_file` attribute. """ self.assertRegexpMatches(UiConstants.help_file, "(http|ftp|https)://([a-zA-Z0-9\-\.]+)/?") def test_api_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.api_file` attribute. """ self.assertRegexpMatches(UiConstants.api_file, "(http|ftp|https)://([a-zA-Z0-9\-\.]+)/?") def test_development_layout_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.development_layout` attribute. """ self.assertRegexpMatches(UiConstants.development_layout, "\w+") def test_python_grammar_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.python_grammar_file` attribute. """ self.assertRegexpMatches(UiConstants.python_grammar_file, "\w+") def test_logging_grammar_file_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.logging_grammar_file` attribute. """ self.assertRegexpMatches(UiConstants.logging_grammar_file, "\w+") def test_text_grammar_file_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.text_grammar_file` attribute. """ self.assertRegexpMatches(UiConstants.text_grammar_file, "\w+") def test_invalid_link_html_file_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.invalid_link_html_file` attribute. """ self.assertRegexpMatches(UiConstants.invalid_link_html_file, "\w+") def test_crittercism_id_attribute(self): """ Tests :attr:`umbra.globals.ui_constants.UiConstants.crittercism_id` attribute. """ self.assertRegexpMatches(UiConstants.crittercism_id, "\w+") self.assertEqual(UiConstants.crittercism_id, "51290b63421c983d17000490")
class TestUiConstants(unittest.TestCase): ''' Defines :class:`umbra.globals.ui_constants.UiConstants` class units tests methods. ''' def test_required_attributes(self): ''' Tests presence of required attributes. ''' pass def test_ui_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.ui_file` attribute. ''' pass def test_processing_ui_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.processing_ui_file` attribute. ''' pass def test_reporter_ui_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.reporter_ui_file` attribute. ''' pass def test_windows_stylesheet_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.windows_stylesheet_file` attribute. ''' pass def test_darwin_stylesheet_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.darwin_stylesheet_file` attribute. ''' pass def test_linux_stylesheet_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.linux_stylesheet_file` attribute. ''' pass def test_windows_full_screen_stylesheet_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.windows_full_screen_stylesheet_file` attribute. ''' pass def test_darwin_full_screen_stylesheet_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.darwin_full_screen_stylesheet_file` attribute. ''' pass def test_linux_full_screen_stylesheet_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.linux_full_screen_stylesheet_file` attribute. ''' pass def test_windows_style_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.windows_style` attribute. ''' pass def test_darwin_style_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.darwin_style` attribute. ''' pass def test_linux_style_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.linux_style` attribute. ''' pass def test_settings_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.settings_file` attribute. ''' pass def test_layouts_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.layouts_file` attribute. ''' pass def test_application_windows_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.application_windows_icon` attribute. ''' pass def test_splashscreem_image_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.splash_screen_image` attribute. ''' pass def test_logo_image_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.logo_image` attribute. ''' pass def test_default_toolbar_icon_size_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.default_toolbar_icon_size` attribute. ''' pass def test_custom_layouts_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.custom_layouts_icon` attribute. ''' pass def test_custom_layouts_hover_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.custom_layouts_hover_icon` attribute. ''' pass def test_custom_layouts_active_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.custom_layouts_active_icon` attribute. ''' pass def test_miscellaneous_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.miscellaneous_icon` attribute. ''' pass def test_miscellaneous_hover_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.miscellaneous_hover_icon` attribute. ''' pass def test_miscellaneous_active_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.miscellaneous_active_icon` attribute. ''' pass def test_development_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.development_icon` attribute. ''' pass def test_development_hover_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.development_hover_icon` attribute. ''' pass def test_development_active_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.development_active_icon` attribute. ''' pass def test_preferences_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.preferences_icon` attribute. ''' pass def test_preferences_hover_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.preferences_hover_icon` attribute. ''' pass def test_preferences_active_icon_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.preferences_active_icon` attribute. ''' pass def test_startup_layout_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.startup_layout` attribute. ''' pass def test_help_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.help_file` attribute. ''' pass def test_api_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.api_file` attribute. ''' pass def test_development_layout_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.development_layout` attribute. ''' pass def test_python_grammar_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.python_grammar_file` attribute. ''' pass def test_logging_grammar_file_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.logging_grammar_file` attribute. ''' pass def test_text_grammar_file_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.text_grammar_file` attribute. ''' pass def test_invalid_link_html_file_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.invalid_link_html_file` attribute. ''' pass def test_crittercism_id_attribute(self): ''' Tests :attr:`umbra.globals.ui_constants.UiConstants.crittercism_id` attribute. ''' pass
41
41
7
1
3
3
1
0.95
1
2
1
0
40
0
40
112
333
81
129
43
88
123
89
43
48
2
2
1
41
142,566
KelSolaar/Umbra
KelSolaar_Umbra/umbra/tests/tests_umbra/tests_globals/tests_runtime_globals.py
umbra.tests.tests_umbra.tests_globals.tests_runtime_globals.TestRuntimeGlobals
class TestRuntimeGlobals(unittest.TestCase): """ Defines :class:`umbra.globals.runtime_globals.RuntimeGlobals` class units tests methods. """ def test_required_attributes(self): """ Tests presence of required attributes. """ required_attributes = ("parameters", "arguments", "logging_console_handler", "logging_file_handler", "logging_session_handler", "logging_session_handler_stream", "logging_formatters", "logging_active_formatter", "verbosity_level", "logging_file", "requests_stack", "engine", "patches_manager", "components_manager", "actions_manager", "file_system_events_manager", "notifications_manager", "layouts_manager", "reporter", "application", "user_application_data_directory", "resources_directories", "ui_file", "patches_file", "settings_file", "settings", "last_browsed_path", "splashscreen_image", "splashscreen") for attribute in required_attributes: self.assertIn(attribute, RuntimeGlobals.__dict__) def test_resources_paths_attribute(self): """ Tests :attr:`umbra.globals.runtime_globals.RuntimeGlobals.resources_directories` attribute. """ self.assertIsInstance(RuntimeGlobals.resources_directories, list) def test_last_browsed_path(self): """ Tests :attr:`umbra.globals.runtime_globals.RuntimeGlobals.last_browsed_path` attribute. """ self.assertTrue(os.path.exists(RuntimeGlobals.last_browsed_path))
class TestRuntimeGlobals(unittest.TestCase): ''' Defines :class:`umbra.globals.runtime_globals.RuntimeGlobals` class units tests methods. ''' def test_required_attributes(self): ''' Tests presence of required attributes. ''' pass def test_resources_paths_attribute(self): ''' Tests :attr:`umbra.globals.runtime_globals.RuntimeGlobals.resources_directories` attribute. ''' pass def test_last_browsed_path(self): ''' Tests :attr:`umbra.globals.runtime_globals.RuntimeGlobals.last_browsed_path` attribute. ''' pass
4
4
16
1
12
3
1
0.32
1
2
1
0
3
0
3
75
56
7
37
6
33
12
9
6
5
2
2
1
4
142,567
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/delegates.py
umbra.ui.delegates.Style
class Style(foundations.data_structures.Structure): """ Defines a storage object for the :class:`RichText_QStyledItemDelegate` class style. """ def __init__(self, **kwargs): """ Initializes the class. :param \*\*kwargs: . :type \*\*kwargs: dict """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) foundations.data_structures.Structure.__init__(self, **kwargs)
class Style(foundations.data_structures.Structure): ''' Defines a storage object for the :class:`RichText_QStyledItemDelegate` class style. ''' def __init__(self, **kwargs): ''' Initializes the class. :param \*\*kwargs: . :type \*\*kwargs: dict ''' pass
2
2
11
3
3
5
1
2
1
0
0
0
1
0
1
1
16
4
4
2
2
8
4
2
2
1
1
0
1
142,568
KelSolaar/Umbra
KelSolaar_Umbra/umbra/ui/highlighters.py
umbra.ui.highlighters.Rule
class Rule(foundations.data_structures.Structure): """ Defines a storage object for highlighters rule. """ def __init__(self, **kwargs): """ Initializes the class. :param \*\*kwargs: pattern, format. :type \*\*kwargs: dict """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) foundations.data_structures.Structure.__init__(self, **kwargs)
class Rule(foundations.data_structures.Structure): ''' Defines a storage object for highlighters rule. ''' def __init__(self, **kwargs): ''' Initializes the class. :param \*\*kwargs: pattern, format. :type \*\*kwargs: dict ''' pass
2
2
11
3
3
5
1
2
1
0
0
0
1
0
1
1
16
4
4
2
2
8
4
2
2
1
1
0
1
142,569
Kellel/ProxyMiddleware
Kellel_ProxyMiddleware/ProxyMiddleware/ProxyMiddleware.py
ProxyMiddleware.ProxyMiddleware.TrailingSlash
class TrailingSlash(object): """ Trailing Slash -------------- Wrap a wsgi bottle application and attempt to serve the path as is. If this fails then attempt to serve the route with an appended trailing slash """ def __init__(self, wrap_app): self.wrap_app = wrap_app self.wrap_app = self.app = wrap_app def __call__(self, environ, start_response): try: self.app.router.match(environ) except HTTPError: PI = environ['PATH_INFO'] environ['PATH_INFO'] = PI + '/' try: self.app.router.match(environ) start_response('301 Redirect', [('Location', environ['SCRIPT_NAME'] + environ['PATH_INFO']),]) return [] except: environ['PATH_INFO'] = PI pass return self.wrap_app(environ, start_response)
class TrailingSlash(object): ''' Trailing Slash -------------- Wrap a wsgi bottle application and attempt to serve the path as is. If this fails then attempt to serve the route with an appended trailing slash ''' def __init__(self, wrap_app): pass def __call__(self, environ, start_response): pass
3
1
9
0
9
0
2
0.28
1
0
0
0
2
2
2
2
27
4
18
6
15
5
18
5
15
3
1
2
4
142,570
Kellel/ProxyMiddleware
Kellel_ProxyMiddleware/ProxyMiddleware/ProxyMiddleware.py
ProxyMiddleware.ProxyMiddleware.ReverseProxied
class ReverseProxied(object): """ Reverse Proxied --------------- Wrap a wsgi application such that the script name and path info are gleaned from the Nginx Reverse Proxy proxy_set_header X-SCRIPT-NAME /path; """ def __init__(self, wrap_app): self.wrap_app = wrap_app self.wrap_app = self.app = wrap_app def __call__ (self, environ, start_response): script_name = environ.get('HTTP_X_SCRIPT_NAME', '') if script_name: environ['SCRIPT_NAME'] = script_name path_info = environ['PATH_INFO'] if path_info.startswith(script_name): environ['PATH_INFO'] = path_info[len(script_name):] return self.wrap_app(environ, start_response)
class ReverseProxied(object): ''' Reverse Proxied --------------- Wrap a wsgi application such that the script name and path info are gleaned from the Nginx Reverse Proxy proxy_set_header X-SCRIPT-NAME /path; ''' def __init__(self, wrap_app): pass def __call__ (self, environ, start_response): pass
3
1
6
0
6
0
2
0.5
1
0
0
0
2
2
2
2
23
5
12
7
9
6
12
6
9
3
1
2
4
142,571
Kellel/ProxyMiddleware
Kellel_ProxyMiddleware/ProxyMiddleware/ProxyMiddleware.py
ProxyMiddleware.ProxyMiddleware.AddHeaderPlugin
class AddHeaderPlugin(object): name = "AddHeaderPlugin" api = 2 def __init__(self, headers): self.headers = headers def setup(self, app): pass def apply(self, callback, route): def wrapper(*args, **kwargs): for header, value in self.headers.items(): response.set_header(header, value) return callback(*args, **kwargs) return wrapper
class AddHeaderPlugin(object): def __init__(self, headers): pass def setup(self, app): pass def apply(self, callback, route): pass def wrapper(*args, **kwargs): pass
5
0
4
0
4
0
1
0
1
0
0
0
3
1
3
3
16
3
13
9
8
0
13
9
8
2
1
1
5
142,572
Kellel/ProxyMiddleware
Kellel_ProxyMiddleware/tests.py
tests.TestProxyMiddleware
class TestProxyMiddleware(unittest.TestCase): def setUp(self): self.wsgi_app = testing_app self.environ = { 'SCRIPT_NAME': "", 'PATH_INFO': "/path/to/test", 'HTTP_X_SCRIPT_NAME': "/path" } def test_reverseproxied(self): app = ReverseProxied(self.wsgi_app) newenv = app(self.environ, False) self.assertTrue(newenv['SCRIPT_NAME'] == "/path") self.assertTrue(newenv['PATH_INFO'] == "/to/test") def test_trailingslash(self): self.assertTrue(True)
class TestProxyMiddleware(unittest.TestCase): def setUp(self): pass def test_reverseproxied(self): pass def test_trailingslash(self): pass
4
0
4
0
3
0
1
0
1
1
1
0
3
2
3
75
14
3
11
8
7
0
11
8
7
1
2
0
3
142,573
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestGet
class TestGet(ModelTest): def setUp(self): super().setUp() self.model.add("testname") def test_get_top_level_item(self): assert self.model.get("1") == ["", "testname", 3, "", False, []] def test_get_second_level_item(self): self.model.add("testname2", parent="1") assert self.model.get("1.1") == ["1", "testname2", 3, "", False, []]
class TestGet(ModelTest): def setUp(self): pass def test_get_top_level_item(self): pass def test_get_second_level_item(self): pass
4
0
3
0
3
0
1
0
1
1
0
0
3
0
3
5
11
2
9
4
5
0
9
4
5
1
2
0
3
142,574
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestEdit
class TestEdit(ModelTest): def setUp(self): super().setUp() self.model.add("testname") def test_edit_name(self): self.model.edit("1", name="testname2") assert self.model == [["testname2", 3, "", False, []]] def test_edit_priority(self): self.model.edit("1", priority=4) assert self.model == [["testname", 4, "", False, []]] def test_edit_comment(self): self.model.edit("1", comment="testcomment") assert self.model == [["testname", 3, "testcomment", False, []]] def test_mark_as_done(self): self.model.edit("1", done=True) assert self.model == [["testname", 3, "", True, []]] def test_mark_as_undone(self): self.model.edit("1", done=True) self.model.edit("1", done=False) assert self.model == [["testname", 3, "", False, []]] def test_reparent(self): self.model.add("testname2", parent="1") self.model.add("testname3", parent="1.1") self.model.edit("1.1.1", parent="1") assert self.model == [["testname", 3, "", False, [ ["testname2", 3, "", False, []], ["testname3", 3, "", False, []] ]]] def test_reparent_to_top_level(self): self.model.add("testname2", parent="1") self.model.add("testname3", parent="1.1") self.model.edit("1.1.1", parent=-1) assert self.model == [ ["testname", 3, "", False, [ ["testname2", 3, "", False, []] ]], ["testname3", 3, "", False, []] ] def test_reparent_deeply_nested_item_to_same_parent(self): # corner case self.model.add("testname2", parent="1") self.model.add("testname3", parent="1.1") self.model.edit("1.1.1", parent="1.1") assert self.model == [ ["testname", 3, "", False, [ ["testname2", 3, "", False, [ ["testname3", 3, "", False, []] ]] ]] ] def test_edit_stability(self): # edit shouldn't move items around if not necessary self.model.add("testname2") self.model.edit("1", name="testname1", parent=-1) assert self.model == [ ["testname1", 3, "", False, []], ["testname2", 3, "", False, []] ]
class TestEdit(ModelTest): def setUp(self): pass def test_edit_name(self): pass def test_edit_priority(self): pass def test_edit_comment(self): pass def test_mark_as_done(self): pass def test_mark_as_undone(self): pass def test_reparent(self): pass def test_reparent_to_top_level(self): pass def test_reparent_deeply_nested_item_to_same_parent(self): pass def test_edit_stability(self): pass
11
0
6
0
5
0
1
0.04
1
1
0
0
10
0
10
12
66
9
55
11
44
2
39
11
28
1
2
0
10
142,575
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestBackup
class TestBackup(ModelTest): def test_should_create_backup_when_file_exists(self): self.model.add("testname1") self.model.add("testname2") assert os.path.exists(self.tmppath) assert json.loads(open(self.tmppath).read()) == { 'items': [["testname1", 3, "", False, []]], 'refs': {}, 'options': {} }
class TestBackup(ModelTest): def test_should_create_backup_when_file_exists(self): pass
2
0
9
0
9
0
1
0
1
0
0
0
1
0
1
3
10
0
10
2
8
0
6
2
4
1
2
0
1
142,576
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestAdd
class TestAdd(ModelTest): def test_add_top_level_item(self): self.model.add("testname") assert self.model == [["testname", 3, "", False, []]] def test_add_second_level_item(self): self.model.add("testname") self.model.add("testname2", parent="1") assert self.model == [["testname", 3, "", False, [ ["testname2", 3, "", False, []] ]]]
class TestAdd(ModelTest): def test_add_top_level_item(self): pass def test_add_second_level_item(self): pass
3
0
5
0
5
0
1
0
1
0
0
0
2
0
2
4
11
1
10
3
7
0
8
3
5
1
2
0
2
142,577
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestModify
class TestModify(ModifyTest): def test_purge_done_when_enabled(self): result = self.model.modify(purge=True) assert result == [["testname2", 3, "", False, []]] def test_purge_from_second_level(self): self.model.add("testname3", parent="1") result = self.model.modify(purge=True) assert result == [["testname2", 3, "", False, []]] def test_do_not_purge_when_disabled(self): result = self.model.modify() assert result == [ ["testname1", 4, "", True, []], ["testname2", 3, "", False, []] ] def test_sort_only_first_level_by_name(self): self.addSecondLevel() sort = ([], {1: [(0, True)]}) result = self.model.modify(sort=sort) assert result == [ ["testname2", 3, "", False, [ ["testname3", 2, "", False, []], ["testname4", 3, "", False, []] ]], ["testname1", 4, "", True, []] ] def test_sort_only_first_level_by_priority(self): self.addSecondLevel() sort = ([], {1: [(1, False)]}) result = self.model.modify(sort=sort) assert result == [ ["testname2", 3, "", False, [ ["testname3", 2, "", False, []], ["testname4", 3, "", False, []] ]], ["testname1", 4, "", True, []] ] def test_sort_only_second_level_by_name(self): self.addSecondLevel() sort = ([], {2: [(0, True)]}) result = self.model.modify(sort=sort) assert result == [ ["testname1", 4, "", True, []], ["testname2", 3, "", False, [ ["testname4", 3, "", False, []], ["testname3", 2, "", False, []] ]] ] def test_sort_only_second_level_by_priority(self): self.addSecondLevel() sort = ([], {2: [(1, True)]}) result = self.model.modify(sort=sort) assert result == [ ["testname1", 4, "", True, []], ["testname2", 3, "", False, [ ["testname4", 3, "", False, []], ["testname3", 2, "", False, []] ]] ] def test_sort_all_levels_by_name(self): self.addSecondLevel() self.addThirdLevel() sort = ([(0, True)], {}) result = self.model.modify(sort=sort) assert result == [ ["testname2", 3, "", False, [ ["testname4", 3, "", False, []], ["testname3", 2, "", False, [ ["testname6", 2, "", False, []], ["testname5", 3, "", False, []] ]] ]], ["testname1", 4, "", True, []] ] def test_sort_all_levels_by_priority(self): self.addSecondLevel() self.addThirdLevel() sort = ([(1, False)], {}) result = self.model.modify(sort=sort) assert result == [ ["testname2", 3, "", False, [ ["testname3", 2, "", False, [ ["testname6", 2, "", False, []], ["testname5", 3, "", False, []] ]], ["testname4", 3, "", False, []] ]], ["testname1", 4, "", True, []] ] def test_sort_all_levels_by_name_and_priority(self): self.addMore() sort = ([(0, True), (1, False)], {}) result = self.model.modify(sort=sort) assert result == [ ["testname2", 3, "", False, [ ["testname6", 1, "", False, []], ["testname5", 1, "", False, []], ["testname3", 2, "", False, []], ["testname4", 3, "", False, []] ]], ["testname1", 4, "", True, []], ["testname3", 5, "", False, []] ] def test_sort_first_level_by_name_and_third_level_by_priority(self): self.addSecondLevel() self.addThirdLevel() sort = ([], {1: [(0, True)], 3: [(1, False)]}) result = self.model.modify(sort=sort) assert result == [ ["testname2", 3, "", False, [ ["testname3", 2, "", False, [ ["testname6", 2, "", False, []], ["testname5", 3, "", False, []] ]], ["testname4", 3, "", False, []] ]], ["testname1", 4, "", True, []] ] def test_sort_second_level_by_priority_and_rest_by_name(self): self.addSecondLevel() self.addThirdLevel() sort = ([(0, True)], {2: [(1, True)]}) result = self.model.modify(sort=sort) assert result == [ ["testname2", 3, "", False, [ ["testname4", 3, "", False, []], ["testname3", 2, "", False, [ ["testname6", 2, "", False, []], ["testname5", 3, "", False, []] ]], ]], ["testname1", 4, "", True, []] ] def test_sort_second_level_by_name_and_priority(self): self.addMore() sort = ([], {2: [(0, True), (1, False)]}) result = self.model.modify(sort=sort) assert result == [ ["testname1", 4, "", True, []], ["testname2", 3, "", False, [ ["testname6", 1, "", False, []], ["testname5", 1, "", False, []], ["testname3", 2, "", False, []], ["testname4", 3, "", False, []] ]], ["testname3", 5, "", False, []] ] def test_sort_with_level_specified_as_string(self): # JSON corner case sort = ([], {"1": [(0, True)]}) result = self.model.modify(sort=sort) assert result == [ ["testname2", 3, "", False, []], ["testname1", 4, "", True, []] ] def test_done_all_levels(self): self.addSecondLevel() done = ([(None, None, True)], {}) result = self.model.modify(done=done) assert result == [ ["testname1", 4, "", True, []], ["testname2", 3, "", True, [ ["testname3", 2, "", True, []], ["testname4", 3, "", True, []] ]] ] def test_done_all_levels_by_regexp(self): self.addSecondLevel() self.addComments() done = ([(None, r'test.*[1|2|3]', True)], {}) result = self.model.modify(done=done) assert result == [ ["testname1", 4, "testcomment1", True, []], ["testname2", 3, "testcomment2", True, [ ["testname3", 2, "", True, []], ["testname4", 3, "", False, []] ]] ] def test_done_all_levels_comment_by_regexp(self): self.addSecondLevel() self.addComments() done = ([(2, r'test.*[2|3]', True)], {}) result = self.model.modify(done=done) assert result == [ ["testname1", 4, "testcomment1", True, []], ["testname2", 3, "testcomment2", True, [ ["testname3", 2, "", False, []], ["testname4", 3, "", False, []] ]] ] def test_done_first_level(self): self.addSecondLevel() done = ([(None, None, None)], {1: [(None, None, True)]}) result = self.model.modify(done=done) assert result == [ ["testname1", 4, "", True, []], ["testname2", 3, "", True, [ ["testname3", 2, "", False, []], ["testname4", 3, "", False, []] ]] ] def test_done_first_level_by_regexp(self): self.addSecondLevel() self.addComments() done = ([(None, None, None)], {1: [(None, r'test.*[2|3]', True)]}) result = self.model.modify(done=done) assert result == [ ["testname1", 4, "testcomment1", True, []], ["testname2", 3, "testcomment2", True, [ ["testname3", 2, "", False, []], ["testname4", 3, "", False, []] ]] ] def test_done_first_level_comment_by_regexp(self): self.addSecondLevel() self.addComments() done = ([(None, None, None)], {1: [(2, r'test.*[2|3]', True)]}) result = self.model.modify(done=done) assert result == [ ["testname1", 4, "testcomment1", True, []], ["testname2", 3, "testcomment2", True, [ ["testname3", 2, "", False, []], ["testname4", 3, "", False, []] ]] ]
class TestModify(ModifyTest): def test_purge_done_when_enabled(self): pass def test_purge_from_second_level(self): pass def test_do_not_purge_when_disabled(self): pass def test_sort_only_first_level_by_name(self): pass def test_sort_only_first_level_by_priority(self): pass def test_sort_only_second_level_by_name(self): pass def test_sort_only_second_level_by_priority(self): pass def test_sort_all_levels_by_name(self): pass def test_sort_all_levels_by_priority(self): pass def test_sort_all_levels_by_name_and_priority(self): pass def test_sort_first_level_by_name_and_third_level_by_priority(self): pass def test_sort_second_level_by_priority_and_rest_by_name(self): pass def test_sort_second_level_by_name_and_priority(self): pass def test_sort_with_level_specified_as_string(self): pass def test_done_all_levels(self): pass def test_done_all_levels_by_regexp(self): pass def test_done_all_levels_comment_by_regexp(self): pass def test_done_first_level(self): pass def test_done_first_level_by_regexp(self): pass def test_done_first_level_comment_by_regexp(self): pass
21
0
11
0
11
0
1
0
1
0
0
0
20
0
20
27
243
19
223
58
202
1
103
58
82
1
3
0
20
142,578
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.ModifyTest
class ModifyTest(ModelTest): def setUp(self): super().setUp() self.model.add("testname1", priority=4) self.model.add("testname2") self.model.edit("1", done=True) def addSecondLevel(self): self.model.add("testname3", priority=2, parent="2") self.model.add("testname4", parent="2") def addThirdLevel(self): self.model.add("testname5", parent="2.1") self.model.add("testname6", priority=2, parent="2.1") def addComments(self): self.model.edit("1", comment="testcomment1") self.model.edit("2", comment="testcomment2") def addMore(self): self.addSecondLevel() self.model.add("testname3", priority=5) self.model.add("testname5", priority=1, parent='2') self.model.add("testname6", priority=1, parent='2')
class ModifyTest(ModelTest): def setUp(self): pass def addSecondLevel(self): pass def addThirdLevel(self): pass def addComments(self): pass def addMore(self): pass
6
0
4
0
4
0
1
0
1
1
0
3
5
0
5
7
24
4
20
6
14
0
20
6
14
1
2
0
5
142,579
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestModifyInPlace
class TestModifyInPlace(ModifyTest): def test_if_changes_get_propagated_to_source_model(self): # We use purge here, but it doesn't matter. # Model.modifyInPlace calls Model.modify, so # see TestModify for different options tests. self.model.modifyInPlace(purge=True) assert self.model == [["testname2", 3, "", False, []]]
class TestModifyInPlace(ModifyTest): def test_if_changes_get_propagated_to_source_model(self): pass
2
0
6
0
3
3
1
0.75
1
0
0
0
1
0
1
8
7
0
4
2
2
3
4
2
2
1
3
0
1
142,580
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestOptions
class TestOptions(ModifyTest): def setUp(self): super().setUp() self.addSecondLevel() self.addThirdLevel() def getNewModel(self): model = Model() path = os.path.join(os.getcwd(), 'tests') model.setPath(os.path.join(path, '.td')) model.gpath = os.path.join(path, '.tdrc') return model def test_sort(self): self.model.setOptions(sort=([(1, False)], {})) assert list(self.getNewModel()) == [ ["testname2", 3, "", False, [ ["testname3", 2, "", False, [ ["testname6", 2, "", False, []], ["testname5", 3, "", False, []] ]], ["testname4", 3, "", False, []] ]], ["testname1", 4, "", True, []] ] def test_purge(self): self.model.setOptions(purge=True) assert list(self.getNewModel()) == [ ["testname2", 3, "", False, [ ["testname3", 2, "", False, [ ["testname5", 3, "", False, []], ["testname6", 2, "", False, []] ]], ["testname4", 3, "", False, []] ]] ] def test_done(self): self.model.setOptions(done=([(None, None, True)], {})) assert list(self.getNewModel()) == [ ["testname1", 4, "", True, []], ["testname2", 3, "", True, [ ["testname3", 2, "", True, [ ["testname5", 3, "", True, []], ["testname6", 2, "", True, []] ]], ["testname4", 3, "", True, []] ]] ] def test_global_only(self): self.model.setOptions(glob=True, sort=([(1, False)], {})) assert list(self.getNewModel()) == [ ["testname2", 3, "", False, [ ["testname3", 2, "", False, [ ["testname6", 2, "", False, []], ["testname5", 3, "", False, []] ]], ["testname4", 3, "", False, []] ]], ["testname1", 4, "", True, []] ] def test_local_before_global(self): self.model.add("testname10") self.model.edit("1", name="testname11") self.model.setOptions(sort=([(0, False)], {})) self.model.setOptions(glob=True, sort=([(0, True)], {})) assert list(self.getNewModel()) == [ ["testname10", 3, "", False, []], ["testname11", 4, "", True, []], ["testname2", 3, "", False, [ ["testname3", 2, "", False, [ ["testname5", 3, "", False, []], ["testname6", 2, "", False, []] ]], ["testname4", 3, "", False, []] ]] ]
class TestOptions(ModifyTest): def setUp(self): pass def getNewModel(self): pass def test_sort(self): pass def test_purge(self): pass def test_done(self): pass def test_global_only(self): pass def test_local_before_global(self): pass
8
0
10
0
10
0
1
0
1
3
1
0
7
0
7
14
80
6
74
10
66
0
29
10
21
1
3
0
7
142,581
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestExists
class TestExists(ModelTest): def test_existing_top_level_index(self): self.model.add("testname") assert self.model.exists("1") def test_existing_second_level_index(self): self.model.add("testname") self.model.add("testname2", parent="1") assert self.model.exists("1.1") def test_non_existing_top_level_index(self): assert not self.model.exists("1") def test_non_existing_second_level_index(self): self.model.add("testname") assert not self.model.exists("1.1")
class TestExists(ModelTest): def test_existing_top_level_index(self): pass def test_existing_second_level_index(self): pass def test_non_existing_top_level_index(self): pass def test_non_existing_second_level_index(self): pass
5
0
3
0
3
0
1
0
1
0
0
0
4
0
4
6
16
3
13
5
8
0
13
5
8
1
2
0
4
142,582
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.Get
class Get(object): """Handles keyboard input.""" TYPES = { "name": "any text (required)", "comment": "any text (<empty>)", "priority": "no/name (3/normal)", "parent": "index (<top level>)" } PRIORITIES = { "lowest": "1", "low": "2", "normal": "3", "high": "4", "highest": "5" } _LEN = 27 def __init__(self): """Creates new Get instance. Also sets readline hook. """ self.value = None readline.set_startup_hook(lambda: readline.insert_text( self.value is not None and str(self.value) or "" )) def input(self, field): """Gets user input for given field. Can be interrupted with ^C. :field: Field name. :returns: User input. """ try: desc = Get.TYPES[field] return input("{}|{}[{}]> ".format( field, "-" * (Get._LEN - len(field) - len(desc)), desc )) except KeyboardInterrupt: print() exit(0) def get(self, field, value=None): """Gets user input for given field and checks if it is valid. If input is invalid, it will ask the user to enter it again. Defaults values to empty or :value:. It does not check validity of parent index. It can only be tested further down the road, so for now accept anything. :field: Field name. :value: Default value to use for field. :returns: User input. """ self.value = value val = self.input(field) if field == 'name': while True: if val != '': break print("Name cannot be empty.") val = self.input(field) elif field == 'priority': if val == '': # Use default priority return None while True: if val in Get.PRIORITIES.values(): break c, val = val, Get.PRIORITIES.get(val) if val: break print("Unrecognized priority number or name [{}].".format(c)) val = self.input(field) val = int(val) return val
class Get(object): '''Handles keyboard input.''' def __init__(self): '''Creates new Get instance. Also sets readline hook. ''' pass def input(self, field): '''Gets user input for given field. Can be interrupted with ^C. :field: Field name. :returns: User input. ''' pass def get(self, field, value=None): '''Gets user input for given field and checks if it is valid. If input is invalid, it will ask the user to enter it again. Defaults values to empty or :value:. It does not check validity of parent index. It can only be tested further down the road, so for now accept anything. :field: Field name. :value: Default value to use for field. :returns: User input. ''' pass
4
4
21
3
12
6
4
0.37
1
3
0
0
3
1
3
3
82
13
51
11
47
19
35
11
31
9
1
3
12
142,583
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.View
class View(object): """Class used to display items on the screen.""" COLORS = [ None, '\033[34m', '\033[36m', '\033[37m', '\033[33m', '\033[31m' ] DIM = '\033[2m' BRIGHT = '\033[1m' RESET = '\033[0m' def __init__(self, model, **opts): """Creates new View instance. Displays the Model contents, basing on :opts:, and exits. :model: Model instance. :opts: Options defining how the View looks. """ colors = not opts.get("nocolor") def _show(submodel, offset): numoffset = len(str(len(list(submodel)))) - 1 for i, v in enumerate(submodel, start=1): (name, priority, comment, done, subitems) = v padding = " " * offset if i < 10: padding += " " * numoffset print("{}{}{}{}{}{}{}".format( colors and View.RESET or "", padding, colors and View.COLORS[priority] or "", colors and (done and View.DIM or View.BRIGHT) or "", i, done and '-' or '.', name )) padding += " " * (len(str(i)) + 1) if comment: print("{}{}({})".format( padding, colors and View.RESET or "", comment )) _show(subitems, offset + 2 + numoffset) _show(model, 0)
class View(object): '''Class used to display items on the screen.''' def __init__(self, model, **opts): '''Creates new View instance. Displays the Model contents, basing on :opts:, and exits. :model: Model instance. :opts: Options defining how the View looks. ''' pass def _show(submodel, offset): pass
3
2
28
2
24
3
3
0.18
1
3
0
0
1
0
1
1
45
6
33
12
30
6
20
12
17
4
1
2
5
142,584
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.EException
class EException(Exception): def __str__(self): return self.message
class EException(Exception): def __str__(self): pass
2
0
2
0
2
0
1
0
1
0
0
4
1
0
1
11
3
0
3
2
1
0
3
2
1
1
3
0
1
142,585
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.Arg
class Arg(object): """Main entry point. Handles patterns decoding and calling appropriate view/model manipulation methods. Also takes care of cmd arguments parsing, using Parser class. """ def __init__(self, model): """Creates new Arg instance. :model: Model instance. """ self.model = model Parser(self, sys.argv).rock() @logs def _getPattern(self, ipattern, done=None): """Parses sort pattern. :ipattern: A pattern to parse. :done: If :ipattern: refers to done|undone, use this to indicate proper state. :returns: A pattern suitable for Model.modify. """ if ipattern is None: return None if ipattern is True: if done is not None: return ([(None, None, done)], {}) # REMEMBER: This False is for sort reverse! return ([(0, False)], {}) def _getReverse(pm): return pm == '-' def _getIndex(k): try: return int(k) except ValueError: raise InvalidPatternError(k, "Invalid level number") def _getDone(p): v = p.split('=') if len(v) == 2: try: return (Model.indexes[v[0]], v[1], done) except KeyError: raise InvalidPatternError(v[0], 'Invalid field name') return (None, v[0], done) ipattern1 = list() ipattern2 = dict() for s in ipattern.split(','): if done is not None: v = done else: v = _getReverse(s[-1]) k = s.split(':') if len(k) == 1: if done is not None: ipattern1.append(_getDone(k[0])) continue ko = k[0][:-1] try: if len(k[0]) == 1: k = 0 else: k = Model.indexes[ko] except KeyError: k = _getIndex(k[0][:-1]) else: ipattern1.append((k, v)) continue v = (0, v) elif len(k) == 2: try: if done is not None: v = _getDone(k[1]) else: v = (Model.indexes[k[1][:-1]], v) k = _getIndex(k[0]) except KeyError: raise InvalidPatternError(k[1][:-1], 'Invalid field name') else: raise InvalidPatternError(s, 'Unrecognized token in') ipattern2.setdefault(k, []).append(v) return (ipattern1, ipattern2) def _getDone(self, done, undone): """Parses the done|undone state. :done: Done marking pattern. :undone: Not done marking pattern. :returns: Pattern for done|undone or None if neither were specified. """ if done: return self._getPattern(done, True) if undone: return self._getPattern(undone, False) def view(self, sort=None, purge=False, done=None, undone=None, **kwargs): """Handles the 'v' command. :sort: Sort pattern. :purge: Whether to purge items marked as 'done'. :done: Done pattern. :undone: Not done pattern. :kwargs: Additional arguments to pass to the View object. """ View(self.model.modify( sort=self._getPattern(sort), purge=purge, done=self._getDone(done, undone) ), **kwargs) def modify(self, sort=None, purge=False, done=None, undone=None): """Handles the 'm' command. :sort: Sort pattern. :purge: Whether to purge items marked as 'done'. :done: Done pattern. :undone: Not done pattern. """ self.model.modifyInPlace( sort=self._getPattern(sort), purge=purge, done=self._getDone(done, undone) ) def add(self, **args): """Handles the 'a' command. :args: Arguments supplied to the 'a' command. """ kwargs = self.getKwargs(args) if kwargs: self.model.add(**kwargs) def edit(self, **args): """Handles the 'e' command. :args: Arguments supplied to the 'e' command. """ if self.model.exists(args["index"]): values = dict(zip( ['parent', 'name', 'priority', 'comment', 'done'], self.model.get(args["index"]) )) kwargs = self.getKwargs(args, values) if kwargs: self.model.edit(args["index"], **kwargs) def rm(self, index): """Handles the 'r' command. :index: Index of the item to remove. """ if self.model.exists(index): self.model.remove(index) def done(self, index): """Handles the 'd' command. :index: Index of the item to mark as done. """ if self.model.exists(index): self.model.edit(index, done=True) def undone(self, index): """Handles the 'D' command. :index: Index of the item to mark as not done. """ if self.model.exists(index): self.model.edit(index, done=False) def options(self, glob=False, **args): """Handles the 'o' command. :glob: Whether to store specified options globally. :args: Arguments supplied to the 'o' command (excluding '-g'). """ kwargs = {} for argname, argarg in args.items(): if argname == "sort": argarg = self._getPattern(argarg) if argname not in ["done", "undone"]: kwargs[argname] = argarg if "done" in args or "undone" in args: kwargs["done"] = self._getDone( args.get("done"), args.get("undone") ) self.model.setOptions(glob=glob, **kwargs) def getKwargs(self, args, values={}, get=Get()): """Gets necessary data from user input. :args: Dictionary of arguments supplied in command line. :values: Default values dictionary, supplied for editing. :get: Object used to get values from user input. :returns: A dictionary containing data gathered from user input. """ kwargs = dict() for field in ['name', 'priority', 'comment', 'parent']: fvalue = args.get(field) or get.get(field, values.get(field)) if fvalue is not None: kwargs[field] = fvalue return kwargs
class Arg(object): '''Main entry point. Handles patterns decoding and calling appropriate view/model manipulation methods. Also takes care of cmd arguments parsing, using Parser class. ''' def __init__(self, model): '''Creates new Arg instance. :model: Model instance. ''' pass @logs def _getPattern(self, ipattern, done=None): '''Parses sort pattern. :ipattern: A pattern to parse. :done: If :ipattern: refers to done|undone, use this to indicate proper state. :returns: A pattern suitable for Model.modify. ''' pass def _getReverse(pm): pass def _getIndex(k): pass def _getDone(p): pass def _getDone(p): '''Parses the done|undone state. :done: Done marking pattern. :undone: Not done marking pattern. :returns: Pattern for done|undone or None if neither were specified. ''' pass def view(self, sort=None, purge=False, done=None, undone=None, **kwargs): '''Handles the 'v' command. :sort: Sort pattern. :purge: Whether to purge items marked as 'done'. :done: Done pattern. :undone: Not done pattern. :kwargs: Additional arguments to pass to the View object. ''' pass def modify(self, sort=None, purge=False, done=None, undone=None): '''Handles the 'm' command. :sort: Sort pattern. :purge: Whether to purge items marked as 'done'. :done: Done pattern. :undone: Not done pattern. ''' pass def add(self, **args): '''Handles the 'a' command. :args: Arguments supplied to the 'a' command. ''' pass def edit(self, **args): '''Handles the 'e' command. :args: Arguments supplied to the 'e' command. ''' pass def rm(self, index): '''Handles the 'r' command. :index: Index of the item to remove. ''' pass def done(self, index): '''Handles the 'd' command. :index: Index of the item to mark as done. ''' pass def undone(self, index): '''Handles the 'D' command. :index: Index of the item to mark as not done. ''' pass def options(self, glob=False, **args): '''Handles the 'o' command. :glob: Whether to store specified options globally. :args: Arguments supplied to the 'o' command (excluding '-g'). ''' pass def getKwargs(self, args, values={}, get=Get()): '''Gets necessary data from user input. :args: Dictionary of arguments supplied in command line. :values: Default values dictionary, supplied for editing. :get: Object used to get values from user input. :returns: A dictionary containing data gathered from user input. ''' pass
17
13
14
2
9
4
3
0.47
1
11
5
0
12
1
12
12
221
42
122
33
105
57
103
32
87
13
1
4
44
142,586
KenjiTakahashi/td
KenjiTakahashi_td/tests/mocks.py
tests.mocks.ArgMock
class ArgMock(object): def __init__(self): self.model = ModelMock() def view(self): pass def modify(self): pass def add(self): pass def edit(self): pass def rm(self): pass def done(self): pass def undone(self): pass def options(self): pass
class ArgMock(object): def __init__(self): pass def view(self): pass def modify(self): pass def add(self): pass def edit(self): pass def rm(self): pass def done(self): pass def undone(self): pass def options(self): pass
10
0
2
0
2
0
1
0
1
1
1
0
9
1
9
9
27
8
19
11
9
0
19
11
9
1
1
0
9
142,587
KenjiTakahashi/td
KenjiTakahashi_td/tests/mocks.py
tests.mocks.GetMock
class GetMock(object): def get(self, field, value): return value if value is not None else "mock"
class GetMock(object): def get(self, field, value): pass
2
0
2
0
2
0
2
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
2
1
0
2
142,588
KenjiTakahashi/td
KenjiTakahashi_td/tests/mocks.py
tests.mocks.HandlerMock
class HandlerMock(logging.Handler): def __init__(self): super(HandlerMock, self).__init__() self.message = None logging.getLogger('td').addHandler(self) def emit(self, record): self.message = str(record.msg) def assertLogged(self, message): assert self.message == message
class HandlerMock(logging.Handler): def __init__(self): pass def emit(self, record): pass def assertLogged(self, message): pass
4
0
3
0
3
0
1
0
1
2
0
0
3
1
3
23
11
2
9
5
5
0
9
5
5
1
3
0
3
142,589
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.NotEnoughArgumentsError
class NotEnoughArgumentsError(EException): def __init__(self, name): self.message = "{}: Not enough arguments.".format(name)
class NotEnoughArgumentsError(EException): def __init__(self, name): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
12
3
0
3
3
1
0
3
3
1
1
4
0
1
142,590
KenjiTakahashi/td
KenjiTakahashi_td/tests/mocks.py
tests.mocks.ModelMock
class ModelMock(object): def __init__(self): self.modify_val = False self.modifyInPlace_val = False self.add_val = False self.edit_val = False self.rm_val = False self.done_val = False self.undone_val = False self.options_val = False def get(self, index): return [1, 1, 1, 1, 1] def exists(self, index): return True def modify(self, sort, purge, done): self.modify_val = True def modifyInPlace(self, sort, purge, done): self.modifyInPlace_val = True def add(self, name, priority, comment, parent): self.add_val = True def edit( self, index=None, name=None, priority=None, comment=None, done=None, parent=None ): self.edit_val = True if done is True: self.done_val = True elif done is False: self.undone_val = True def remove(self, index): self.rm_val = True def setOptions(self, glob, **kwargs): self.options_val = True
class ModelMock(object): def __init__(self): pass def get(self, index): pass def exists(self, index): pass def modify(self, sort, purge, done): pass def modifyInPlace(self, sort, purge, done): pass def add(self, name, priority, comment, parent): pass def edit( self, index=None, name=None, priority=None, comment=None, done=None, parent=None ): pass def remove(self, index): pass def setOptions(self, glob, **kwargs): pass
10
0
4
0
4
0
1
0
1
0
0
0
9
8
9
9
41
8
33
21
20
0
29
18
19
3
1
1
11
142,591
KenjiTakahashi/td
KenjiTakahashi_td/tests/mocks.py
tests.mocks.StdoutMock
class StdoutMock(object): def __init__(self): sys.stdout = StringIO() self.argv = sys.argv def undo(self): sys.argv = self.argv sys.stdout = sys.__stdout__ def resetArgv(self): sys.argv = ['td'] def addArgs(self, *args): sys.argv.extend(args) def assertEqual(self, msg): assert msg == sys.stdout.getvalue()
class StdoutMock(object): def __init__(self): pass def undo(self): pass def resetArgv(self): pass def addArgs(self, *args): pass def assertEqual(self, msg): pass
6
0
2
0
2
0
1
0
1
0
0
0
5
1
5
5
17
4
13
7
7
0
13
7
7
1
1
0
5
142,592
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_main.py
tests.test_main.TestArg
class TestArg(object): def setUp(self): self.mock = StdoutMock() self.model = ModelMock() self.mock.resetArgv() def tearDown(self): self.mock.undo() def test_view(self): Arg(self.model) assert self.model.modify_val is True def test_modify(self): self.mock.addArgs("m", "-s", "sp", "-p", "-d", "dp", "-D", "Dp") Arg(self.model) assert self.model.modifyInPlace_val is True def test_add(self): self.mock.addArgs("a", "1.1", "-n", "n", "-p", "1", "-c", "c") Arg(self.model) assert self.model.add_val is True def test_edit(self): self.mock.addArgs( "e", "1.1", "--parent", "2.2", "-n", "n", "-p", "1", "-c", "c" ) Arg(self.model) assert self.model.edit_val is True def test_rm(self): self.mock.addArgs("r", "1.1") Arg(self.model) assert self.model.rm_val is True def test_done(self): self.mock.addArgs("d", "1.1") Arg(self.model) assert self.model.done_val is True def test_undone(self): self.mock.addArgs("D", "1.1") Arg(self.model) assert self.model.undone_val is True def test_options(self): self.mock.addArgs("o", "-g", "-s", "sp", "-p", "-d", "dp", "-D", "Dp") Arg(self.model) assert self.model.options_val is True def test_options_sort(self): self.mock.addArgs("o", "-s") Arg(self.model) assert self.model.options_val is True def test_options_purge(self): self.mock.addArgs("o", "-p") Arg(self.model) assert self.model.options_val is True def test_options_done(self): self.mock.addArgs("o", "-d") Arg(self.model) assert self.model.options_val is True def test_options_undone(self): self.mock.addArgs("o", "-D") Arg(self.model) assert self.model.options_val is True def test_getKwargs(self): arg = Arg.__new__(Arg) result = arg.getKwargs({"priority": 3}, {"comment": "test"}, GetMock()) assert result == { "name": "mock", "comment": "test", "priority": 3, "parent": "mock" }
class TestArg(object): def setUp(self): pass def tearDown(self): pass def test_view(self): pass def test_modify(self): pass def test_add(self): pass def test_edit(self): pass def test_rm(self): pass def test_done(self): pass def test_undone(self): pass def test_options(self): pass def test_options_sort(self): pass def test_options_purge(self): pass def test_options_done(self): pass def test_options_undone(self): pass def test_getKwargs(self): pass
16
0
4
0
4
0
1
0
1
4
4
0
15
2
15
15
80
14
66
20
50
0
58
20
42
1
1
0
15
142,593
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_main.py
tests.test_main.TestArg_getPattern
class TestArg_getPattern(object): def setUp(self): self.arg = Arg.__new__(Arg) # Don't do this at home self.handler = HandlerMock() def test_sort_all_levels(self): result = self.arg._getPattern(True) assert result == ([(0, False)], {}) def test_sort_one_specific_level(self): result = self.arg._getPattern("1+") assert result == ([], {1: [(0, False)]}) def test_sort_two_specific_levels(self): result = self.arg._getPattern("1+,2-") assert result == ([], {1: [(0, False)], 2: [(0, True)]}) def test_sort_all_levels_and_specific_level(self): result = self.arg._getPattern("+,1+") assert result == ([(0, False)], {1: [(0, False)]}) def test_sort_all_levels_by_priority(self): result = self.arg._getPattern("priority+") assert result == ([(1, False)], {}) def test_sort_all_levels_by_name_and_priority(self): result = self.arg._getPattern("-,priority+") assert result == ([(0, True), (1, False)], {}) def test_sort_all_levels_by_state_and_priority(self): result = self.arg._getPattern("state-,priority+") assert result == ([(3, True), (1, False)], {}) def test_sort_specific_level_by_priority(self): result = self.arg._getPattern("1:priority+") assert result == ([], {1: [(1, False)]}) def test_sort_specific_level_by_name_and_priority(self): result = self.arg._getPattern("1-,1:priority+") assert result == ([], {1: [(0, True), (1, False)]}) def test_sort_specific_level_by_state_and_priority(self): result = self.arg._getPattern("1:state-,1:priority+") assert result == ([], {1: [(3, True), (1, False)]}) def test_done_all(self): result = self.arg._getPattern(True, done=True) assert result == ([(None, None, True)], {}) def test_done_all_by_regexp(self): result = self.arg._getPattern("test.*[1-9]", done=True) assert result == ([(None, r'test.*[1-9]', True)], {}) def test_done_all_by_comment_regexp(self): result = self.arg._getPattern("comment=test.*[1-9]", done=True) assert result == ([(2, r'test.*[1-9]', True)], {}) def test_done_specific_level_by_regexp(self): result = self.arg._getPattern("1:test.*[1-9]", done=True) assert result == ([], {1: [(None, r'test.*[1-9]', True)]}) def test_done_specific_level_by_comment_regexp(self): result = self.arg._getPattern("1:comment=test.*[1-9]", done=True) assert result == ([], {1: [(2, r'test.*[1-9]', True)]}) def test_passing_invalid_level_without_index(self): self.arg._getPattern("a+") self.handler.assertLogged('Invalid level number: a') def test_passing_invalid_level_with_index(self): self.arg._getPattern("a:name+") self.handler.assertLogged('Invalid level number: a') def test_passing_invalid_index_name(self): self.arg._getPattern("1:nema+") self.handler.assertLogged('Invalid field name: nema') def test_passing_too_much_data(self): self.arg._getPattern("1:name:sth") self.handler.assertLogged('Unrecognized token in: 1:name:sth') def test_passing_invalid_index_name_with_done(self): self.arg._getPattern("nema=.*", done=True) self.handler.assertLogged('Invalid field name: nema') def test_empty_should_stay_empty(self): result = self.arg._getPattern(None) assert result is None
class TestArg_getPattern(object): def setUp(self): pass def test_sort_all_levels(self): pass def test_sort_one_specific_level(self): pass def test_sort_two_specific_levels(self): pass def test_sort_all_levels_and_specific_level(self): pass def test_sort_all_levels_by_priority(self): pass def test_sort_all_levels_by_name_and_priority(self): pass def test_sort_all_levels_by_state_and_priority(self): pass def test_sort_specific_level_by_priority(self): pass def test_sort_specific_level_by_name_and_priority(self): pass def test_sort_specific_level_by_state_and_priority(self): pass def test_done_all(self): pass def test_done_all_by_regexp(self): pass def test_done_all_by_comment_regexp(self): pass def test_done_specific_level_by_regexp(self): pass def test_done_specific_level_by_comment_regexp(self): pass def test_passing_invalid_level_without_index(self): pass def test_passing_invalid_level_with_index(self): pass def test_passing_invalid_index_name(self): pass def test_passing_too_much_data(self): pass def test_passing_invalid_index_name_with_done(self): pass def test_empty_should_stay_empty(self): pass
23
0
3
0
3
0
1
0.01
1
2
2
0
22
2
22
22
88
21
67
41
44
1
67
41
44
1
1
0
22
142,594
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_main.py
tests.test_main.TestGet
class TestGet(object): def setUp(self): self.mock = StdoutMock() self.get = Get() Get.input = self.func self.i = True self.v = "" def tearDown(self): self.mock.undo() def func(self, f): if self.i: self.i = False return self.v return "1" def test_correct_name(self): self.v = "test" result = self.get.get("name") assert result == "test" def test_empty_name(self): self.get.get("name") self.mock.assertEqual("Name cannot be empty.\n") def test_correct_comment(self): self.v = "test" result = self.get.get("comment") assert result == "test" def test_parent(self): # Anything is correct here. See docstring in the code. self.v = "1.1" result = self.get.get("parent") assert result == "1.1" def test_correct_priority_names(self): for n, ne in enumerate(["lowest", "low", "normal", "high", "highest"]): self.i = True self.v = ne result = self.get.get("priority") assert result == n + 1 def test_incorrect_priority_name(self): self.v = "the highest" self.get.get("priority") self.mock.assertEqual( "Unrecognized priority number or name [the highest].\n" ) def test_correct_priority_numbers(self): for n in range(1, 6): self.i = True self.v = str(n) result = self.get.get("priority") assert result == n def t_incorrect_priority_numbers(self, n): self.v = str(n) self.get.get("priority") self.mock.assertEqual( "Unrecognized priority number or name [{}].\n".format(n) ) def test_incorrect_priority_number0(self): self.t_incorrect_priority_numbers(0) def test_incorrect_priority_number6(self): self.t_incorrect_priority_numbers(6) def test_empty_priority(self): result = self.get.get("priority") assert result is None
class TestGet(object): def setUp(self): pass def tearDown(self): pass def func(self, f): pass def test_correct_name(self): pass def test_empty_name(self): pass def test_correct_comment(self): pass def test_parent(self): pass def test_correct_priority_names(self): pass def test_incorrect_priority_name(self): pass def test_correct_priority_numbers(self): pass def t_incorrect_priority_numbers(self, n): pass def test_incorrect_priority_number0(self): pass def test_incorrect_priority_number6(self): pass def test_empty_priority(self): pass
15
0
4
0
4
0
1
0.02
1
5
2
0
14
4
14
14
74
13
60
27
45
1
56
27
41
2
1
1
17
142,595
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_main.py
tests.test_main.TestParser_part
class TestParser_part(object): def setUp(self): self.mock = StdoutMock() self.handler = HandlerMock() self.out1 = None self.out2 = None def tearDown(self): self.mock.undo() def func1(self, test=None, sort=None): self.out1 = test def func2(self, test1=None, test2=None): self.out2 = (test1, test2) def test_help_message(self): parser = Parser("", ["td", "-h"]) parser._part("test", "", {}, "help") self.mock.assertEqual("help\n") def test_one_argument(self): parser = Parser("", ["td", "-t", "value"]) parser._part("test", self.func1, {"-t": ("test", True)}, "") assert self.out1 == "value" def test_argument_without_value(self): parser = Parser("", ["td", "-b"]) parser._part("test", self.func1, {"-b": ("test", False)}, "") assert self.out1 is True def test_two_arguments(self): # It should break by induction further on. parser = Parser("", ["td", "-t1", "value1", "-t2", "value2"]) parser._part("test", self.func2, { "-t1": ("test1", True), "-t2": ("test2", True) }, "") self.out2 == ("value1", "value2") def test_one_argument_for_two_arguments_func(self): parser = Parser("", ["td", "-t2", "value2"]) parser._part("test", self.func2, { "-t1": ("test1", True), "-t2": ("test2", True) }, "") self.out2 == (None, "value2") def test_no_arguments(self): parser = Parser("", ["td"]) parser._part("test", self.func1, {}, "", test=True) assert self.out1 is True def test_missing_argument(self): parser = Parser("", ["td", "-t"]) parser._part("test", "", {"-t": ("test", True)}, "") self.handler.assertLogged("test: Not enough arguments.") def test_wrong_argument(self): parser = Parser("", ["td", "-y"]) parser._part("test", "", {"-t": ("test", True)}, "") self.handler.assertLogged("test: Unrecognized argument [-y].") def test_sort_with_no_arguments(self): # If no arguments are supplied, it should use default. # Applies to done/undone too. parser = Parser("", ["td", "-s"]) parser._part("test", self.func1, {"-s": ("sort", True)}, "", test=True) assert self.out1 is True
class TestParser_part(object): def setUp(self): pass def tearDown(self): pass def func1(self, test=None, sort=None): pass def func2(self, test1=None, test2=None): pass def test_help_message(self): pass def test_one_argument(self): pass def test_argument_without_value(self): pass def test_two_arguments(self): pass def test_one_argument_for_two_arguments_func(self): pass def test_no_arguments(self): pass def test_missing_argument(self): pass def test_wrong_argument(self): pass def test_sort_with_no_arguments(self): pass
14
0
4
0
4
0
1
0.06
1
3
3
0
13
4
13
13
67
12
52
27
38
3
48
27
34
1
1
0
13
142,596
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.TestRemove
class TestRemove(ModelTest): def test_remove_item(self): self.model.add("testname") self.model.add("testname2", parent="1") self.model.remove("1") assert self.model == [] def test_remove_child_item(self): self.model.add("testname") self.model.add("testname2", parent="1") self.model.remove("1.1") assert self.model == [["testname", 3, "", False, []]] def test_remove_non_existing_item(self): handler = HandlerMock() self.model.add("testname") self.model.remove("1.1") handler.assertLogged('No item found at index [1.1].')
class TestRemove(ModelTest): def test_remove_item(self): pass def test_remove_child_item(self): pass def test_remove_non_existing_item(self): pass
4
0
5
0
5
0
1
0
1
1
1
0
3
0
3
5
18
2
16
5
12
0
16
5
12
1
2
0
3
142,597
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_model.py
tests.test_model.ModelTest
class ModelTest(object): def setUp(self): self.model = Model() path = os.path.join(os.getcwd(), 'tests') self.model.setPath(os.path.join(path, '.td')) self.model.gpath = os.path.join(path, '.tdrc') self.tmppath = os.path.join(path, '.td~') def tearDown(self): try: os.remove(self.model.path) os.remove(self.tmppath) os.remove(self.model.gpath) except OSError: pass
class ModelTest(object): def setUp(self): pass def tearDown(self): pass
3
0
7
0
7
0
2
0
1
2
1
7
2
2
2
2
15
1
14
6
11
0
14
6
11
2
1
1
3
142,598
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.Parser
class Parser(object): """Parses command line arguments and runs appropriate Arg methods.""" def __init__(self, arg, argv): """Creates new Parser instance. First element of :argv: should be irrelevant (e.g. apps' name), because it will be stripped off. :arg: Arg instance. :argv: A list from which to get arguments. """ self.arg = arg self.argv = deque(argv[1:]) @logs def _part(self, name, func, args, help, **kwargs): """Parses arguments of a single command (e.g. 'v'). If :args: is empty, it assumes that command takes no further arguments. :name: Name of the command. :func: Arg method to execute. :args: Dictionary of CLI arguments pointed at Arg method arguments. :help: Commands' help text. :kwargs: Additional arguments for :func:. """ while self.argv: arg = self.argv.popleft() if arg == "-h" or arg == "--help": print(help) return try: argname, argarg = args[arg] kwargs[argname] = argarg and self.argv.popleft() or True except KeyError: raise UnrecognizedArgumentError(name, arg) except IndexError: valids = ["-s", "--sort", "-d", "--done", "-D", "--undone"] if arg not in valids: raise NotEnoughArgumentsError(name) kwargs[argname] = True func(**kwargs) @logs def rock(self): """Starts and does the parsing.""" if not self.argv: self.arg.view() while(self.argv): arg = self.argv.popleft() if arg == "-h" or arg == "--help": print( """Usage: td [-h (--help)] [-v (--version)] [command]""" """, where [command] is one of:\n\n""" """v (view)\tChanges the way next output""" """ will look like. See [td v -h].\n""" """m (modify)\tApplies one time changes to""" """ the database. See [td m -h].\n""" """o (options)\tSets persistent options, applied""" """ on every next execution. See [td o -h].\n""" """a (add)\t\tAdds new item. See [td a -h].\n""" """e (edit)\tEdits existing item. See [td e -h].\n""" """r (rm)\t\tRemoves existing item. See [td r -h].\n""" """d (done)\tMarks items as done. See [td d -h].\n""" """D (undone)\tMarks items as not done. See [td D -h].\n""" """\nAdditional options:\n""" """ -h (--help)\tShows this screen.\n""" """ -v (--version)Shows version number.""" ) elif arg == "-v" or arg == "--version": print("td :: {}".format(__version__)) elif arg == "v" or arg == "view": self._part("view", self.arg.view, { "--no-color": ("nocolor", False), "-s": ("sort", True), "--sort": ("sort", True), "-p": ("purge", False), "--purge": ("purge", False), "-d": ("done", True), "--done": ("done", True), "-D": ("undone", True), "--undone": ("undone", True) }, """Usage: td v [-h (--help)] [command(s)]""" """, where [command(s)] are any of:\n\n""" """-s (--sort) <pattern>\tSorts the output using""" """ <pattern>.\n""" """-p (--purge)\t\tHides items marked as done.\n""" """-d (--done) <pattern>\tDisplays items matching""" """ <pattern> as done.\n""" """-D (--undone) <pattern>\tDisplays items matching""" """ <pattern> as not done.\n""" """--no-color\t\tDo not add color codes to the output.\n""" """\nAdditional options:\n""" """ -h (--help)\t\tShows this screen.""" ) elif arg == "m" or arg == "modify": self._part("modify", self.arg.modify, { "-s": ("sort", True), "--sort": ("sort", True), "-p": ("purge", False), "--purge": ("purge", False), "-d": ("done", True), "--done": ("done", True), "-D": ("undone", True), "--undone": ("undone", True) }, """Usage: td m [-h (--help)] [command(s)]""" """, where [command(s)] are any of:\n\n""" """-s (--sort) <pattern>\tSorts database using""" """ <pattern>.\n""" """-p (--purge)\t\tRemoves items marked as done.\n""" """-d (--done) <pattern>\tMarks items matching""" """ <pattern> as done.\n""" """-D (--undone) <pattern>\tMarks items matching""" """ <pattern> as not done.\n""" """\nAdditional options:\n""" """ -h (--help)\t\tShows this screen.""" ) elif arg == "a" or arg == "add": args = dict() if self.argv and self.arg.model.exists(self.argv[0]): args["parent"] = self.argv.popleft() self._part("add", self.arg.add, { "-n": ("name", True), "--name": ("name", True), "-p": ("priority", True), "--priority": ("priority", True), "-c": ("comment", True), "--comment": ("comment", True) }, """Usage: td a [-h (--help)] [parent] [command(s)]""" """, where [command(s)] are any of:\n\n""" """-n (--name) <text>\t\tSets item's name.\n""" """-p (--priority) <no|name>\tSets item's priority.\n""" """-c (--comment) <text>\t\tSets item's comment.\n""" """\nIf [parent] index is specified, new item will""" """ become it's child.\n""" """If any of the arguments is omitted,""" """ this command will launch an interactive session""" """ letting the user supply the rest of them.\n""" """\nAdditional options:\n""" """ -h (--help)\t\t\tShows this screen.""", **args ) elif arg == "e" or arg == "edit": if not self.argv: raise NotEnoughArgumentsError("edit") args = dict() if self.argv[0] not in ["-h", "--help"]: args["index"] = self.argv.popleft() self._part("edit", self.arg.edit, { "--parent": ("parent", True), "-n": ("name", True), "--name": ("name", True), "-p": ("priority", True), "--priority": ("priority", True), "-c": ("comment", True), "--comment": ("comment", True) }, """Usage: td e [-h (--help)] <index> [command(s)]""" """, where [command(s)] are any of:\n\n""" """--parent <index>\t\tChanges item's parent.\n""" """-n (--name) <text>\t\tChanges item's name.\n""" """-p (--priority) <no|name>\tChanges item's priority.\n""" """-c (--comment) <text>\t\tChanges item's comment.\n""" """\nIndex argument is required and has to point at""" """ an existing item.\n""" """If any of the arguments is omitted, it will launch""" """ an interactive session letting the user supply the""" """ rest of them.\n""" """\nAdditions options:\n""" """ -h (--help)\t\t\tShows this screen.""", **args ) elif arg == "r" or arg == "rm": args = dict() if not self.argv: raise NotEnoughArgumentsError("rm") elif self.argv[0] not in ["-h", "--help"]: args["index"] = self.argv.popleft() self._part("rm", self.arg.rm, { }, """Usage: td r [-h (--help)] <index>\n\n""" """Index argument is required and has to point at""" """ an existing item.\n""" """\nAdditions options:\n""" """ -h (--help)\tShows this screen.""", **args ) elif arg == "d" or arg == "done": args = dict() if not self.argv: raise NotEnoughArgumentsError("done") elif self.argv[0] not in ["-h", "--help"]: args["index"] = self.argv.popleft() self._part("done", self.arg.done, { }, """Usage: td d [-h (--help)] <index>\n\n""" """Index argument is required and has to point at""" """ an existing item.\n""" """\nAdditional options:\n""" """ -h (--help)\tShows this screen.""", **args ) elif arg == "D" or arg == "undone": args = dict() if not self.argv: raise NotEnoughArgumentsError("undone") elif self.argv[0] not in ["-h", "--help"]: args["index"] = self.argv.popleft() self._part("undone", self.arg.undone, { }, """Usage: td D [-h (--help)] <index>\n\n""" """Index argument is required and has to point at""" """ an existing item.\n""" """\nAdditional options:\n""" """ -h (--help)\tShows this screen.""", **args ) elif arg == "o" or arg == "options": self._part("options", self.arg.options, { "-g": ("glob", False), "--global": ("glob", False), "-s": ("sort", True), "--sort": ("sort", True), "-p": ("purge", False), "--purge": ("purge", False), "-d": ("done", True), "--done": ("done", True), "-D": ("undone", True), "--undone": ("undone", True) }, """Usage: td o [-h (--help)] [command(s)]""" """, where [command(s)] are any of:\n\n""" """-g (--global)\t\tApply specified options to all""" """ ToDo lists (store in ~/.tdrc).\n""" """-s (--sort) <pattern>\tAlways sorts using""" """ <pattern>.\n""" """-p (--purge)\t\tAlways removes items marked""" """as done.\n""" """-d (--done) <pattern>\tAlways marks items maching""" """ <pattern> as done.\n""" """-D (--undone) <pattern>\tAlways marks items maching""" """ <pattern> as not done.\n""" """\nAdditional options:\n""" """ -h (--help)\t\tShows this screen.""" ) else: raise UnrecognizedCommandError("td", arg)
class Parser(object): '''Parses command line arguments and runs appropriate Arg methods.''' def __init__(self, arg, argv): '''Creates new Parser instance. First element of :argv: should be irrelevant (e.g. apps' name), because it will be stripped off. :arg: Arg instance. :argv: A list from which to get arguments. ''' pass @logs def _part(self, name, func, args, help, **kwargs): '''Parses arguments of a single command (e.g. 'v'). If :args: is empty, it assumes that command takes no further arguments. :name: Name of the command. :func: Arg method to execute. :args: Dictionary of CLI arguments pointed at Arg method arguments. :help: Commands' help text. :kwargs: Additional arguments for :func:. ''' pass @logs def rock(self): '''Starts and does the parsing.''' pass
6
4
76
2
69
5
10
0.08
1
6
3
0
3
2
3
3
234
9
209
13
203
16
58
11
54
22
1
3
29
142,599
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.UnrecognizedArgumentError
class UnrecognizedArgumentError(EException): def __init__(self, name, arg): self.message = "{}: Unrecognized argument [{}].".format(name, arg)
class UnrecognizedArgumentError(EException): def __init__(self, name, arg): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
12
3
0
3
3
1
0
3
3
1
1
4
0
1
142,600
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.UnrecognizedCommandError
class UnrecognizedCommandError(EException): def __init__(self, name, cmd): self.message = "{}: Unrecognized command [{}].".format(name, cmd)
class UnrecognizedCommandError(EException): def __init__(self, name, cmd): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
12
3
0
3
3
1
0
3
3
1
1
4
0
1
142,601
KenjiTakahashi/td
KenjiTakahashi_td/td/main.py
td.main.InvalidPatternError
class InvalidPatternError(EException): def __init__(self, k, msg): self.message = "{}: {}".format(msg, k)
class InvalidPatternError(EException): def __init__(self, k, msg): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
12
3
0
3
3
1
0
3
3
1
1
4
0
1
142,602
KenjiTakahashi/td
KenjiTakahashi_td/tests/test_main.py
tests.test_main.TestParserrock
class TestParserrock(object): def setUp(self): self.mock = StdoutMock() self.handler = HandlerMock() self.parser = Parser(ArgMock(), ["td"]) self.parser._part = self.mock_part self.out = False def tearDown(self): self.mock.undo() def mock_part(self, *args, **kwargs): self.out = True def do_part(self, *n): self.parser.argv = deque(n) self.parser.rock() def assert_part(self, *n): self.do_part(*n) assert self.out is True def test_v(self): self.assert_part("v") def test_view(self): self.assert_part("view") def test_m(self): self.assert_part("m") def test_modify(self): self.assert_part("modify") def test_a(self): self.assert_part("a") def test_add(self): self.assert_part("add") def test_e_without_index(self): self.do_part("e") self.handler.assertLogged("edit: Not enough arguments.") def test_e(self): self.assert_part("e", "1.1") def test_edit(self): self.assert_part("edit", "1.1") def test_r_without_index(self): self.do_part("r") self.handler.assertLogged("rm: Not enough arguments.") def test_r(self): self.assert_part("r", "1.1") def test_rm(self): self.assert_part("rm", "1.1") def test_d_without_index(self): self.do_part("d") self.handler.assertLogged("done: Not enough arguments.") def test_d(self): self.assert_part("d", "1.1") def test_done(self): self.assert_part("done", "1.1") def test_D_without_index(self): self.do_part("D") self.handler.assertLogged("undone: Not enough arguments.") def test_D(self): self.assert_part("D", "1.1") def test_undone(self): self.assert_part("undone", "1.1") def test_o(self): self.assert_part("o") def test_options(self): self.assert_part("options") def test_add_parent(self): # It deserves a separate test self.assert_part("a", "1.1") def test_wrong_command(self): self.do_part("dang") self.handler.assertLogged("td: Unrecognized command [dang].")
class TestParserrock(object): def setUp(self): pass def tearDown(self): pass def mock_part(self, *args, **kwargs): pass def do_part(self, *n): pass def assert_part(self, *n): pass def test_v(self): pass def test_view(self): pass def test_m(self): pass def test_modify(self): pass def test_a(self): pass def test_add(self): pass def test_e_without_index(self): pass def test_e_without_index(self): pass def test_edit(self): pass def test_r_without_index(self): pass def test_r_without_index(self): pass def test_rm(self): pass def test_d_without_index(self): pass def test_d_without_index(self): pass def test_done(self): pass def test_D_without_index(self): pass def test_D_without_index(self): pass def test_undone(self): pass def test_o(self): pass def test_options(self): pass def test_add_parent(self): pass def test_wrong_command(self): pass
28
0
2
0
2
0
1
0.02
1
4
4
0
27
4
27
27
93
26
66
32
38
1
66
32
38
1
1
0
27
142,603
KenjiTakahashi/td
KenjiTakahashi_td/td/model.py
td.model.NoItemError
class NoItemError(Exception): def __init__(self, k): self.message = "No item found at index [{}].".format(k) def __str__(self): return self.message
class NoItemError(Exception): def __init__(self, k): pass def __str__(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
1
2
12
6
1
5
4
2
0
5
4
2
1
3
0
2
142,604
KenjiTakahashi/td
KenjiTakahashi_td/td/model.py
td.model.Model
class Model(UserList): """A holder for all the td data. It keeps the actual data, the references and permanent options and provides an interface to manipulate them. """ indexes = { "name": 0, "priority": 1, "comment": 2, "state": 3 } priorities = [None, "lowest", "low", "medium", "high", "highest"] def setPath(self, path): """Sets permanent storage path. :path: New permanent storage path. """ self.path = path @save @load def add(self, name, priority=3, comment="", parent=""): """Adds new item to the model. Name argument may contain (ref:) syntax, which will be stripped down as needed. :parent: should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :name: Name (with refs). :priority: Item's priority. :comment: Comment. :parent: Item's parent ("" for top-level item). """ item = [name, priority, comment, False, []] data = self.data for c in self._split(parent): data = data[int(c) - 1][4] data.append(item) @save @load def edit( self, index, name=None, priority=None, comment=None, done=None, parent=None ): """Modifies :index: to specified data. Every argument, which is not None, will get changed. If parent is not None, the item will get reparented. Use parent=-1 or parent='' for reparenting to top-level. :index: Index of the item to edit. :name: New name. :priority: New priority. :comment: New comment. :done: Done mark. :parent: New parent. """ if parent == -1: parent = '' parent = self._split(parent) index = self._split(index) item = self.data for j, c in enumerate(index): item = item[int(c) - 1] if j + 1 != len(index): item = item[4] if name is not None: item[0] = name if priority is not None: item[1] = priority if comment is not None: item[2] = comment if done is not None: item[3] = done if parent is not None and parent != index[:-1]: parentitem = self.data for c in parent: parentitem = parentitem[int(c) - 1][4] parentitem.append(item) parent = index[:-1] parentitem = self.data for c in parent: parentitem = parentitem[int(c) - 1][4] parentitem.remove(item) @save @load @logs def remove(self, index): """Removes specified item from the model. :index: Should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :index: Item's index. """ data = self.data index = self._split(index) for j, c in enumerate(index): i = int(c) - 1 if j + 1 == len(index): try: del data[i] except IndexError: raise NoItemError('.'.join(index)) else: data = data[i][4] @load def exists(self, index): """Checks whether :index: exists in the Model. :index: Index to look for. :returns: True if :index: exists in the Model, False otherwise. """ data = self.data try: for c in self._split(index): i = int(c) - 1 data = data[i][4] except Exception: return False return True @load def get(self, index): """Gets data values for specified :index:. :index: Index for which to get data. :returns: A list in form [parent, name, priority, comment, done, children]. """ data = self.data index2 = self._split(index) for c in index2[:-1]: i = int(c) - 1 data = data[i][4] return [index[:-2] or ""] + data[int(index[-1]) - 1] def _modifyInternal(self, *, sort=None, purge=False, done=None): """Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whether to reverse or not, <index> are one of Model.indexes and <level_index> indicate a number of level to sort. Of course, the lists above may contain multiple items. :done: patterns looks similar to :sort:, except that it has additional <regexp> values and that True|False means to mark as done|undone. @note: Should not be used directly. It was defined here, because :save: decorator needs undecorated version of Model.modify. :sort: Pattern on which to sort the database. :purge: Whether to purge done items. :done: Pattern on which to mark items as done/undone. :returns: New database, modified according to supplied arguments. """ sortAll, sortLevels = sort is not None and sort or ([], {}) doneAll, doneLevels = done is not None and done or ([], {}) def _mark(v, i): if done is None: return v[:4] def _mark_(index, regexp, du): if du is None: return v[:4] if index is None: for v_ in v[:3]: if regexp is None or re.match(regexp, str(v_)): return v[:3] + [du] return v[:4] if regexp is None or re.match(regexp, str(v[index])): return v[:3] + [du] try: for doneLevel in doneLevels[i]: result = _mark_(*doneLevel) if result is not None: return result except KeyError: pass for doneAll_ in doneAll: result = _mark_(*doneAll_) if result is None: return v[:4] return result def _modify(submodel, i): _new = list() for v in submodel: if purge: if not v[3]: _new.append(_mark(v, i) + [_modify(v[4], i + 1)]) else: _new.append(_mark(v, i) + [_modify(v[4], i + 1)]) levels = sortLevels.get(i) or sortLevels.get(str(i)) for index, reverse in levels or sortAll: _new = sorted(_new, key=lambda e: e[index], reverse=reverse) return _new return _modify(self.data, 1) @load def modify(self, *, sort=None, purge=False, done=None): """Calls Model._modifyInternal after loading the database.""" return self._modifyInternal(sort=sort, purge=purge, done=done) @save def modifyInPlace(self, *, sort=None, purge=False, done=None): """Like Model.modify, but changes existing database instead of returning a new one.""" self.data = self.modify(sort=sort, purge=purge, done=done) @save @load def setOptions(self, glob=False, **kwargs): """Set option(s). :glob: If True, stores specified options globally. :kwargs: Dictionary of options and values to set. """ if glob: self.globalOptions.update(kwargs) else: self.options.update(kwargs) @load def __iter__(self): return super().__iter__() def _split(self, index): """Splits :index: by '.', removing empty strings. If None is supplied, None is returned. :index: Index to split. :returns: :index: split by '.' or empty list, if there are no items. """ if index is None: return None split = index.split('.') if split == ['']: return [] return split
class Model(UserList): '''A holder for all the td data. It keeps the actual data, the references and permanent options and provides an interface to manipulate them. ''' def setPath(self, path): '''Sets permanent storage path. :path: New permanent storage path. ''' pass @save @load def add(self, name, priority=3, comment="", parent=""): '''Adds new item to the model. Name argument may contain (ref:) syntax, which will be stripped down as needed. :parent: should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :name: Name (with refs). :priority: Item's priority. :comment: Comment. :parent: Item's parent ("" for top-level item). ''' pass @save @load def edit( self, index, name=None, priority=None, comment=None, done=None, parent=None ): '''Modifies :index: to specified data. Every argument, which is not None, will get changed. If parent is not None, the item will get reparented. Use parent=-1 or parent='' for reparenting to top-level. :index: Index of the item to edit. :name: New name. :priority: New priority. :comment: New comment. :done: Done mark. :parent: New parent. ''' pass @save @load @logs def remove(self, index): '''Removes specified item from the model. :index: Should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :index: Item's index. ''' pass @load def exists(self, index): '''Checks whether :index: exists in the Model. :index: Index to look for. :returns: True if :index: exists in the Model, False otherwise. ''' pass @load def get(self, index): '''Gets data values for specified :index:. :index: Index for which to get data. :returns: A list in form [parent, name, priority, comment, done, children]. ''' pass def _modifyInternal(self, *, sort=None, purge=False, done=None): '''Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whether to reverse or not, <index> are one of Model.indexes and <level_index> indicate a number of level to sort. Of course, the lists above may contain multiple items. :done: patterns looks similar to :sort:, except that it has additional <regexp> values and that True|False means to mark as done|undone. @note: Should not be used directly. It was defined here, because :save: decorator needs undecorated version of Model.modify. :sort: Pattern on which to sort the database. :purge: Whether to purge done items. :done: Pattern on which to mark items as done/undone. :returns: New database, modified according to supplied arguments. ''' pass def _mark(v, i): pass def _mark_(index, regexp, du): pass def _modifyInternal(self, *, sort=None, purge=False, done=None): pass @load def modify(self, *, sort=None, purge=False, done=None): '''Calls Model._modifyInternal after loading the database.''' pass @save def modifyInPlace(self, *, sort=None, purge=False, done=None): '''Like Model.modify, but changes existing database instead of returning a new one.''' pass @save @load def setOptions(self, glob=False, **kwargs): '''Set option(s). :glob: If True, stores specified options globally. :kwargs: Dictionary of options and values to set. ''' pass @load def __iter__(self): pass def _split(self, index): '''Splits :index: by '.', removing empty strings. If None is supplied, None is returned. :index: Index to split. :returns: :index: split by '.' or empty list, if there are no items. ''' pass
30
12
18
2
12
4
3
0.47
1
9
1
0
12
2
12
87
262
45
148
59
115
69
123
47
107
11
8
3
50
142,605
KennethWilke/PingdomLib
KennethWilke_PingdomLib/pingdomlib/contact.py
pingdomlib.contact.PingdomContact
class PingdomContact(object): """Class representing a pingdom contact Attributes: * id -- Contact identifier * name -- Contact name * email -- Contact email * cellphone -- Contact cellphone * countryiso -- Cellphone country ISO code * defaultsmsprovider -- Default SMS provider * twitteruser -- Twitter username * directtwitter -- Send tweets as direct messages * iphonetokens -- List of iPhone tokens * androidtokens -- List of android tokens * paused -- True if contact is paused """ def __init__(self, instantiator, contactinfo=dict()): self.pingdom = instantiator self.__addDetails__(contactinfo) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['name', 'email', 'cellphone', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser', 'iphonetokens', 'androidtokens', 'paused']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __addDetails__(self, contactinfo): """Fills attributes from a dictionary""" # Auto-load instance attributes from passed in dictionary for key in contactinfo: object.__setattr__(self, key, contactinfo[key]) def modify(self, **kwargs): """Modify a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser', 'name']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of <PingdomContact>.modify()\n') response = self.pingdom.request('PUT', 'notification_contacts/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Deletes a contact. CANNOT BE REVERSED! Returns status message""" response = self.pingdom.request('DELETE', 'notification_contacts/%s' % self.id) return response.json()['message']
class PingdomContact(object): '''Class representing a pingdom contact Attributes: * id -- Contact identifier * name -- Contact name * email -- Contact email * cellphone -- Contact cellphone * countryiso -- Cellphone country ISO code * defaultsmsprovider -- Default SMS provider * twitteruser -- Twitter username * directtwitter -- Send tweets as direct messages * iphonetokens -- List of iPhone tokens * androidtokens -- List of android tokens * paused -- True if contact is paused ''' def __init__(self, instantiator, contactinfo=dict()): pass def __setattr__(self, key, value): pass def __addDetails__(self, contactinfo): '''Fills attributes from a dictionary''' pass def modify(self, **kwargs): '''Modify a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String ''' pass def delete(self): '''Deletes a contact. CANNOT BE REVERSED! Returns status message''' pass
6
4
15
3
5
7
2
1.68
1
1
0
0
5
1
5
5
98
23
28
11
22
47
22
11
16
3
1
2
10
142,606
KennethWilke/PingdomLib
KennethWilke_PingdomLib/pingdomlib/check.py
pingdomlib.check.PingdomCheck
class PingdomCheck(object): """Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from """ _detail_keys = ['name', 'resolution', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'paused', 'contactids', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'use_legacy_notifications', 'lastresponsetime', 'probe_filters',] def __init__(self, instantiator, checkinfo=dict()): self.pingdom = instantiator self.__addDetails__(checkinfo) def __getattr__(self, attr): # Pull variables from pingdom if unset if attr in self._detail_keys: self.getDetails() return getattr(self, attr) else: raise AttributeError("'PingdomCheck' object has no attribute '%s'" % attr) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def __str__(self): return "<PingdomCheck (%s)%s is '%s'>" % (self.id, self.name, self.status) def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwargs: if key not in ['limit', 'offset', 'from', 'to']: sys.stderr.write('%s not a valid argument for analysis()\n' % key) response = self.pingdom.request('GET', 'analysis/%s' % self.id, kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']] def __addDetails__(self, checkinfo): """Fills attributes from a dictionary, uses special handling for the 'type' key""" # Auto-load instance attributes from passed in dictionary for key in checkinfo: if key == 'type': if checkinfo[key] in checktypes: self.type = checkinfo[key] else: # Take key from type dict, convert to string for type self.type = checkinfo[key].iterkeys().next() # Take value from type dict, store to member of new attrib object.__setattr__(self, self.type, checkinfo[key].itervalues().next()) else: # Store other key value pairs as attributes object.__setattr__(self, key, checkinfo[key]) # back-fill missing keys (if any) missing_keys = list(set(self._detail_keys) - set(checkinfo.keys())) for key in missing_keys: object.__setattr__(self, key, None) if 'status' in checkinfo and checkinfo['status'] == 'paused': object.__setattr__(self, 'paused', True) else: object.__setattr__(self, 'paused', False) def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check'] def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status', 'lasterrortime', 'lasttesttime', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'additionalurls', 'stringtosend', 'stringtoexpect', 'expectedip', 'nameserver', 'use_legacy_notifications', 'host', 'alert_policy', 'autoresolve', 'probe_filters']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True: raise Exception("Cannot set legacy parameter when use_legacy_notifications is not True") kwargs["use_legacy_notifications"] = True response = self.pingdom.request("PUT", 'checks/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation""" response = self.pingdom.request("DELETE", "checks/%s" % self.id) return response.json()['message'] def averages(self, **kwargs): """Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary'] def hoursofday(self, **kwargs): """Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'uselocaltime']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.hoursofday()\n') response = self.pingdom.request('GET', 'summary.hoursofday/%s' % self.id, kwargs) return response.json()['hoursofday'] def outages(self, **kwargs): """Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.outages()\n') response = self.pingdom.request('GET', 'summary.outage/%s' % self.id, kwargs) return response.json()['summary']['states'] def performance(self, **kwargs): """For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'resolution', 'includeuptime', 'probes', 'order']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.performance()\n') response = self.pingdom.request('GET', 'summary.performance/%s' % self.id, kwargs) return response.json()['summary'] def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period.""" args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes'] def results(self, **kwargs): """Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhanled parameters for key in kwargs: if key not in ['from', 'to', 'probes', 'status', 'limit', 'offset', 'includeanalysis', 'maxresponse', 'minresponse']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.results()\n') response = self.pingdom.request('GET', 'results/%s' % self.id, kwargs) return response.json() def publishPublicReport(self): """Activate public report for this check. Returns status message""" response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message'] def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
class PingdomCheck(object): '''Class representing a check in pingdom Attributes: * id -- Check identifier * name -- Check name * type -- Check type * lasterrortime -- Timestamp of last error (if any). Format is UNIX timestamp * lasttesttime -- Timestamp of last test (if any). Format is UNIX timestamp * lastresponsetime -- Response time (in milliseconds) of last test * status -- Current status of check * resolution -- How often should the check be tested. In minutes * hostname -- Target host * created -- Creation time. Format is UNIX timestamp * contactids -- Identifiers s of contact who should receive alerts * sendtoemail -- Send alerts as email * sendtosms -- Send alerts as SMS * sendtotwitter -- Send alerts through Twitter * sendtoiphone -- Send alerts to iPhone * sendtoandroid -- Send alerts to Android * sendnotificationwhendown -- Send notification when down this many times * notifyagainevery -- Notify again every n result * notifywhenbackup -- Notify when back up again * use_legacy_notifications -- Use the old notifications instead of BeepManager * probe_filters -- What region should the probe check from ''' def __init__(self, instantiator, checkinfo=dict()): pass def __getattr__(self, attr): pass def __setattr__(self, key, value): pass def __str__(self): pass def getAnalyses(self, **kwargs): '''Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * time_from -- Return only results with timestamp of first test greater or equal to this value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated the confirmation test 'timeconfrimtest' : <Integer> Time of the confirmation test that perfromed the error analysis }, ... ] ''' pass def __addDetails__(self, checkinfo): '''Fills attributes from a dictionary, uses special handling for the 'type' key''' pass def getDetails(self): '''Update check details, returns dictionary of details''' pass def modify(self, **kwargs): '''Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General parameters: * name -- Check name Type: String * host - Target host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * sendtotwitter -- Send alerts through Twitter Type: Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notifywhenbackup -- Notify when back up again Type: Boolean * use_legacy_notifications -- Use old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password for HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String DNS check options: * expectedip -- Expected IP Type: String * nameserver -- Nameserver to check Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: user:password Type: String * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean ''' pass def delete(self): '''Deletes the check from pingdom, CANNOT BE REVERSED! Returns status message of operation''' pass def averages(self, **kwargs): '''Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False Returned structure: { 'responsetime' : { 'to' : <Integer> Start time of period 'from' : <Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } ''' pass def hoursofday(self, **kwargs): '''Returns the average response time for each hour of the day (0-23) for a specific check over a selected time period. I.e. it shows you what an average day looks like during that time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * uselocaltime -- If true, use the user's local time zone for results (from and to parameters should still be specified in UTC). If false, use UTC for results. Type: Boolean Default: False Returned structure: [ { 'hour' : <Integer> Hour of day (0-23). Please note that if data is missing for an individual hour, it's entry will not be included in the result. 'avgresponse': <Integer> Average response time(in milliseconds) for this hour of the day }, ... ] ''' pass def outages(self, **kwargs): '''Get a list of status changes for a specified check and time period. If order is speficied to descending, the list is ordered by newest first. (Default is ordered by oldest first.) Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: One week earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * order -- Sorting order of outages. Ascending or descending Type: String ['asc', 'desc'] Default: asc Returned structure: [ { 'status' : <String> Interval status 'timefrom' : <Integer> Interval start. Format is UNIX timestamp 'timeto' : <Integer> Interval end. Format is UNIX timestamp }, ... ] ''' pass def performance(self, **kwargs): '''For a given interval in time, return a list of sub intervals with the given resolution. Useful for generating graphs. A sub interval may be a week, a day or an hour depending on the choosen resolution Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 10 intervals earlier than 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * resolution -- Inteval size Type: String ['hour', 'day', 'week'] Default: hour * includeuptime -- Include uptime information Type: Boolean Default: False * probes -- Filter to only use results from a list of probes. Format is a comma separated list of probe identifiers. Can not be used if includeuptime is set to true. Also note that this can cause intervals to be omitted, since there may be no results from the desired probes in them. Type: String Default: All probes * order -- Sorting order of sub intervals. Ascending or descending. Type: String ['asc', 'desc'] Default: asc Returned structure: { <RESOLUTION> : [ { 'starttime' : <Integer> Hour interval start. Format UNIX timestamp 'avgresponse' : <Integer> Average response time for this interval in milliseconds 'uptime' : <Integer> Total uptime for this interval in seconds 'downtime' : <Integer> Total downtime for this interval in seconds 'unmonitored' : <Integer> Total unmonitored time for this interval in seconds }, ... ] } ''' pass def probes(self, fromtime, totime=None): '''Get a list of probes that performed tests for a specified check during a specified period.''' pass def results(self, **kwargs): '''Return a list of raw test results for a specified check Optional Parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 1 day prior to 'to' * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -- Filter to only show results from a list of probes. Format is a comma separated list of probe identifiers Type: String Default: All probes * status -- Filter to only show results with specified statuses. Format is a comma separated list of (down, up, unconfirmed, unknown) Type: String Default: All statuses * limit -- Number of results to show Type: Integer (max 1000) Default: 1000 * offset -- Number of results to skip Type: Integer (max 43200) Default: 0 * includeanalysis -- Attach available root cause analysis identifiers to corresponding results Type: Boolean Default: False * maxresponse -- Maximum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None * minresponse -- Minimum response time (ms). If set, specified interval must not be larger than 31 days. Type: Integer Default: None Returned structure: { 'results' : [ { 'probeid' : <Integer> Probe identifier 'time' : <Integer> Time when test was performed. Format is UNIX timestamp 'status' : <String> Result status ['up', 'down', 'unconfirmed_down', 'unknown'] 'responsetime' : <Integer> Response time in milliseconds Will be 0 if no response was received 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'analysisid' : <Integer> Analysis identifier }, ... ], 'activeprobes' : <Integer List> Probe identifiers in result set } ''' pass def publishPublicReport(self): '''Activate public report for this check. Returns status message''' pass def removePublicReport(self): '''Deactivate public report for this check. Returns status message''' pass
18
14
40
8
10
22
3
2.21
1
6
1
0
17
2
17
17
742
161
181
43
163
400
133
43
115
6
1
3
54
142,607
KennethWilke/PingdomLib
KennethWilke_PingdomLib/pingdomlib/pingdom.py
pingdomlib.pingdom.Pingdom
class Pingdom(object): """Main connection object to interact with pingdom Attributes: * pushChanges -- This boolean controls if changes are automatically pushed to pingdom * shortlimit -- String containing short api rate limit details * longlimit -- String containing long api rate limit details """ def __init__(self, username, password, apikey, accountemail=None, pushchanges=True, server=server_address): self.pushChanges = pushchanges self.username = username self.password = password self.apikey = apikey self.accountemail = accountemail self.url = '%s/api/%s/' % (server, api_version) self.shortlimit = '' self.longlimit = '' @staticmethod def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lower() def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self.accountemail: headers.update({'Account-Email': self.accountemail}) # Method selection handling if method.upper() == 'GET': response = requests.get(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'POST': response = requests.post(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid method in pingdom request") # Store pingdom api limits self.shortlimit = response.headers.get( 'Req-Limit-Short', self.shortlimit) self.longlimit = response.headers.get( 'Req-Limit-Long', self.longlimit) # Verify OK response if response.status_code != 200: sys.stderr.write('ERROR from %s: %d' % (response.url, response.status_code)) sys.stderr.write('Returned data: %s\n' % response.json()) response.raise_for_status() return response def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) return response.json()['actions'] def alerts(self, **parameters): """A short-hand version of 'actions', returns list of alerts. See parameters for actions()""" return self.actions(**parameters)['alerts'] def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None """ # Warn user about unhandled parameters for key in parameters: if key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']] def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check def getResults(self, checkid): """ Returns detailed results for a specified check id.""" response = self.request('GET','results/%s' % checkid) return response.json() def newCheck(self, name, host, checktype='http', **kwargs): """Creates a new check with settings specified by provided parameters. Provide new check name, hostname and type along with any additional optional parameters passed as keywords. Returns new PingdomCheck instance Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional parameters: * paused -- Check should be paused Type: Boolean Default: False * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] Default: 5 * contactids -- Comma separated list of contact IDs Type: String Default: None * sendtoemail -- Send alerts as email Type: Boolean Default: False * sendtosms -- Send alerts as SMS Type: Boolean Default: False * sendtotwitter -- Send alerts through Twitter Type: Boolean Default: False * sendtoiphone -- Send alerts to iPhone Type: Boolean Default: False * sendtoandroid -- Send alerts to Android Type: Boolean Default: False * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer Default: 2 * notifyagainevery -- Set how many results to wait for in between notices Type: Integer Default: 0 * notifywhenbackup -- Notify when back up again Type: Boolean Default: True * use_legacy_notifications -- Use the old notifications instead of BeepManager Type: Boolean Default: False HTTP check options: * url -- Target path on server Type: String Default: / * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String Default: None * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String Default: None * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String Default: None * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String Default: None HTTPCustom check options: * url -- Target path on server Type: String Mandatory * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String Default: None TCP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None DNS check options: * expectedip -- Expected IP Type: String Mandatory * nameserver -- Nameserver to check Type: String Mandatory UDP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None SMTP check options: * port -- Target server port Type: Integer Default: 25 * auth -- Username and password for target SMTP authentication. Example: user:password Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False POP3 check options: * port -- Target server port Type: Integer Default: 110 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False IMAP check options: * port -- Target server port Type: Integer Default: 143 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata', 'use_legacy_notifications']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'url', 'encryption', 'port', 'auth', 'additionalurls', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['alert_policy', 'autoresolve', 'paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'expectedip', 'nameserver', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtosend', 'stringtoexpect', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'auth', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendtoandroid', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'type', 'hostname', 'port', 'stringtoexpect', 'encryption', 'use_legacy_notifications']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of newCheck() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in newCheck()") parameters = {'name': name, 'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request("POST", 'checks', parameters) return self.getCheck(checkinfo.json()['check']['id']) def modifyChecks(self, **kwargs): """Pause or change resolution for multiple checks in one bulk call. Parameters: * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * checkids -- Comma-separated list of identifiers for checks to be modified. Invalid check identifiers will be ignored. Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'checkids']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newCheck()\n') return self.request("PUT", "checks", kwargs).json()['message'] def deleteChecks(self, checkids): """Deletes a list of checks, CANNOT BE REVERSED! Provide a comma-separated list of checkid's to delete """ return self.request("DELETE", "checks", {'delcheckids': checkids}).json()['message'] def credits(self): """Gets credits list""" return self.request("GET", "credits").json()['credits'] def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes'] def references(self): """Get a reference of regions, timezones and date/time/number formats and their identifiers. Returned structure: { 'regions' : [ { 'id' : <Integer> Region identifier 'description' : <String> Region description 'countryid' : <Integer> Corresponding country identifier 'datetimeformatid' : <Integer> Corresponding datetimeformat identifier 'numberformatid' : <Integer> Corresponding numberformat identifer 'timezoneid' : <Integer> Corresponding timezone identifier }, ... ], 'timezones' : [ { 'id' : <Integer> Time zone identifier 'description' : <String> Time zone description }, ... ], 'datetimeformats' : [ { 'id' : <Integer> Date/time format identifer 'description' : <String> Date/time format description }, ... ], 'numberformats' : [ { 'id' : <Integer> Number format identifier 'description' : <String> Number format description }, ... ], 'countries' : [ { 'id' : <Integer> Country id 'iso' : <String> Country ISO code }, ... ], 'phonecodes' : [ { 'countryid' : <Integer> Country id 'name' : <String> Country name 'phonecode' : <String> Area phone code }, ... ] }""" return self.request("GET", "reference").json() def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ response = self.request('GET', 'traceroute', {'host': host, 'probeid': probeid}) return response.json()['traceroute'] def servertime(self): """Get the current time of the API server in UNIX format""" return self.request('GET', 'servertime').json()['servertime'] def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']] def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()['contact'] return PingdomContact(self, contactinfo) def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message'] def deleteContacts(self, contactids): """Deletes a list of contacts. CANNOT BE REVERSED! Provide a comma-separated list of contactid's to delete Returns status message """ return self.request("DELETE", "notification_contacts", {'delcheckids': contactids}).json()['message'] def singleTest(self, host, checktype, **kwargs): """Performs a single test using a specified Pingdom probe against a specified target. Please note that this method is meant to be used sparingly, not to set up your own monitoring solution. Provide hostname and check type, followed by any optional arguments. Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional arguments: * probeid -- Probe to use for check Type: Integer Default: A random probe See newCheck() docstring for type-specific arguments Returned structure: { 'status' : <String> Test result status ['up, 'down'] 'responsetime' : <Integer> Response time in milliseconds 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'probeid' : <Integer> Probe identifier 'probedesc' : <String> Probe description } """ if checktype == 'http': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'shouldcontain', 'shouldnotcontain', 'postdata']: if key.startswith('requestheader') is not True: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'http'\n") elif checktype == 'httpcustom': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'url', 'encryption', 'port', 'auth', 'additionalurls']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'httpcustom'\n") elif checktype == 'tcp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'tcp'\n") elif checktype == 'ping': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'ping'\n") elif checktype == 'dns': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'expectedip', 'nameserver']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'dns'\n") elif checktype == 'udp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtosend', 'stringtoexpect']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'udp'\n") elif checktype == 'smtp': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'auth', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'smtp'\n") elif checktype == 'pop3': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'pop3'\n") elif checktype == 'imap': # Warn user about unhandled parameters for key in kwargs: if key not in ['probeid', 'port', 'stringtoexpect', 'encryption']: sys.stderr.write("'%s'" % key + ' is not a valid ' + 'argument of singleTest() for type ' + "'imap'\n") else: raise Exception("Invalid checktype in singleTest()") parameters = {'host': host, 'type': checktype} for key, value in kwargs.iteritems(): parameters[key] = value checkinfo = self.request('GET', "single", parameters) return checkinfo.json()['result'] def getSettings(self): """Returns all account-specific settings. Returned structure: { 'firstname' : <String> First name 'lastname' : <String> Last name 'company' : <String> Company 'email' : <String> Email 'phone' : <String> Phone 'phonecountryiso' : <String> Phone country ISO code 'cellphone' : <String> Cellphone 'cellphonecountryiso' : <String> Cellphone country ISO code 'address' : <String> Address line 1 'address2' : <String> Address line 2 'zip' : <String> Zip, postal code or equivalent 'location' : <String> City / location 'state' : <String> State or equivalent 'autologout' : <Boolean> Enable auto-logout 'country' : { 'name' : <String> Country name 'iso' : <String> Country ISO-code 'countryid' : <Integer> Country identifier } 'vatcode' : <String> For certain EU countries, VAT-code 'region' : <String> Region 'regionid' : <Integer> Region identifier, see reference 'accountcreated' : <Integer> Account creation timestamp 'timezone' : { 'id' : <String> Timezone name 'description' : <String> Timezone description 'timezoneid' : <Integer> Timezone identifier } 'dateformat' : <String> Date format 'timeformat' : <String> Time format 'datetimeformatid' : <Integer> Date/time format identifier 'numberformat' : <String> Number format 'numberformatexample' : <String> Example of number presentation 'numberformatid' : <Integer> Number format identifier 'publicreportscode' : <String> URL code 'settingssaved' : <Boolean> True if user has saved initial settings in control panel } """ return self.request('GET', 'settings').json()['settings'] def modifySettings(self, **kwargs): """Modify account-specific settings. Returns status message for operation Optional parameters: * firstname -- First name Type: String * lastname -- Last name Type: String * company -- Company Type: String * email -- Email (Please note that your email is used for authentication purposes such as using this API or logging into the Pingdom Panel) Type: String * cellphone -- Cellphone (without country code) (Requires cellcountrycode and cellcountryiso) Type: String * cellcountrycode -- Cellphone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * cellcountryiso -- Cellphone country ISO code, for example US(USA) or SE (Sweden) Type: String * phone -- Phone (without country code) (Requires phonecountrycode and phonecountryiso) Type: String * phonecountrycode -- Phone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * phonecountryiso -- Phone country ISO code, for example US (USA) or SE (Sweden) Type: String * address -- Address line 1 Type: String * address2 -- Address line 2 Type: String * zip -- Zip, postal code or equivalent Type: String * location -- City / location Type: String * state -- State, province or equivalent Type: String * countryiso -- Country ISO code, for example US (USA) or SE (Sweden) Type: String * vatcode -- For certain EU countries, VAT-code. Example: SE123456789 Type: String * autologout -- Enable auto-logout Type: Boolean * regionid -- Region identifier, for localization purposes. 0 for "Custom"/none. See the API resource "Reference" for more information Type: Integer * timezoneid -- Time zone identifier. See the API resource "Reference" for more information Type: Integer * datetimeformatid -- Date/time format identifier. See the API resource "Reference" for more information Type: Integer * numberformatid -- Number format identifier. See the API resource "Reference" for more information Type: Integer * pubrcustomdesign -- Use custom design for public reports Type: Boolean * pubrtextcolor -- Public reports, custom text color (Example: FEFFFE or 99CC00) Type: String * pubrbackgroundcolor -- Public reports, background color (Example: FEFFFE or 99CC00) Type: String * pubrlogourl -- Public reports, URL to custom logotype. This parameter is currently disabled for public use. (Example: stats.pingdom.com/images/logo.png) Type: String * pubrmonths -- Public reports, nuber of months to show Type: String ['none', 'all', '3'] * pubrshowoverview -- Public reports, enable overview Type: Boolean * pubrcustomdomain -- Public reports, custom domain. Must be a DNS CNAME with target stats.pingdom.com Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['firstname', 'lastname', 'company', 'email', 'cellphone', 'cellcountrycode', 'cellcountryiso', 'phone', 'phonecountrycode', 'phonecountryiso', 'address', 'address2', 'zip', 'location', 'state', 'countryiso', 'vatcode', 'autologout', 'regionid', 'timezoneid', 'datetimeformatid', 'numberformatid', 'pubrcustomdesign', 'pubrtextcolor', 'pubrbackgroundcolor', 'pubrlogourl', 'pubrmonths', 'pubrshowoverview', 'pubrcustomdomain']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of modifySettings()\n') return self.request('PUT', 'settings', kwargs).json()['message'] def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.email', parameters).json()['message'] def getPublicReports(self): """Returns a list of public (web-based) reports Returned structure: [ { 'checkid' : <Integer> Check identifier 'checkname' : <String> Check name 'reporturl' : <String> URL to report }, ... ] """ return self.request('GET', 'reports.public').json()['public'] def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer """ # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n') parameters = {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message']
class Pingdom(object): '''Main connection object to interact with pingdom Attributes: * pushChanges -- This boolean controls if changes are automatically pushed to pingdom * shortlimit -- String containing short api rate limit details * longlimit -- String containing long api rate limit details ''' def __init__(self, username, password, apikey, accountemail=None, pushchanges=True, server=server_address): pass @staticmethod def _serializeBooleans(params): '''"Convert all booleans to lowercase strings''' pass def request(self, method, url, parameters=dict()): '''Requests wrapper function''' pass def actions(self, **parameters): '''Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } ''' pass def alerts(self, **parameters): '''A short-hand version of 'actions', returns list of alerts. See parameters for actions()''' pass def getChecks(self, **parameters): '''Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None ''' pass def getChecks(self, **parameters): '''Returns a detailed description of a specified check.''' pass def getResults(self, checkid): ''' Returns detailed results for a specified check id.''' pass def newCheck(self, name, host, checktype='http', **kwargs): '''Creates a new check with settings specified by provided parameters. Provide new check name, hostname and type along with any additional optional parameters passed as keywords. Returns new PingdomCheck instance Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional parameters: * paused -- Check should be paused Type: Boolean Default: False * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] Default: 5 * contactids -- Comma separated list of contact IDs Type: String Default: None * sendtoemail -- Send alerts as email Type: Boolean Default: False * sendtosms -- Send alerts as SMS Type: Boolean Default: False * sendtotwitter -- Send alerts through Twitter Type: Boolean Default: False * sendtoiphone -- Send alerts to iPhone Type: Boolean Default: False * sendtoandroid -- Send alerts to Android Type: Boolean Default: False * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer Default: 2 * notifyagainevery -- Set how many results to wait for in between notices Type: Integer Default: 0 * notifywhenbackup -- Notify when back up again Type: Boolean Default: True * use_legacy_notifications -- Use the old notifications instead of BeepManager Type: Boolean Default: False HTTP check options: * url -- Target path on server Type: String Default: / * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * shouldcontain -- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String Default: None * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String Default: None * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server Type: String Default: None * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String Default: None HTTPCustom check options: * url -- Target path on server Type: String Mandatory * encryption -- Use SSL/TLS Type: Boolean Default: False * port -- Target server port Type: Integer Default: 80 * auth -- Username and password for HTTP authentication Example: user:password Type: String Default: None * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String Default: None TCP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None DNS check options: * expectedip -- Expected IP Type: String Mandatory * nameserver -- Nameserver to check Type: String Mandatory UDP check options: * port -- Target server port Type: Integer Mandatory * stringtosend -- String to send Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None SMTP check options: * port -- Target server port Type: Integer Default: 25 * auth -- Username and password for target SMTP authentication. Example: user:password Type: String Default: None * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False POP3 check options: * port -- Target server port Type: Integer Default: 110 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False IMAP check options: * port -- Target server port Type: Integer Default: 143 * stringtoexpect -- String to expect in response Type: String Default: None * encryption -- Use connection encryption Type: Boolean Default: False ''' pass def modifyChecks(self, **kwargs): '''Pause or change resolution for multiple checks in one bulk call. Parameters: * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * checkids -- Comma-separated list of identifiers for checks to be modified. Invalid check identifiers will be ignored. Type: String ''' pass def deleteChecks(self, checkids): '''Deletes a list of checks, CANNOT BE REVERSED! Provide a comma-separated list of checkid's to delete ''' pass def credits(self): '''Gets credits list''' pass def probes(self, **kwargs): '''Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] ''' pass def references(self): '''Get a reference of regions, timezones and date/time/number formats and their identifiers. Returned structure: { 'regions' : [ { 'id' : <Integer> Region identifier 'description' : <String> Region description 'countryid' : <Integer> Corresponding country identifier 'datetimeformatid' : <Integer> Corresponding datetimeformat identifier 'numberformatid' : <Integer> Corresponding numberformat identifer 'timezoneid' : <Integer> Corresponding timezone identifier }, ... ], 'timezones' : [ { 'id' : <Integer> Time zone identifier 'description' : <String> Time zone description }, ... ], 'datetimeformats' : [ { 'id' : <Integer> Date/time format identifer 'description' : <String> Date/time format description }, ... ], 'numberformats' : [ { 'id' : <Integer> Number format identifier 'description' : <String> Number format description }, ... ], 'countries' : [ { 'id' : <Integer> Country id 'iso' : <String> Country ISO code }, ... ], 'phonecodes' : [ { 'countryid' : <Integer> Country id 'name' : <String> Country name 'phonecode' : <String> Area phone code }, ... ] }''' pass def traceroute(self, host, probeid): '''Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } ''' pass def servertime(self): '''Get the current time of the API server in UNIX format''' pass def getContacts(self, **kwargs): '''Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] ''' pass def newContact(self, name, **kwargs): '''Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String ''' pass def modifyContacts(self, contactids, paused): '''Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message ''' pass def deleteContacts(self, contactids): '''Deletes a list of contacts. CANNOT BE REVERSED! Provide a comma-separated list of contactid's to delete Returns status message ''' pass def singleTest(self, host, checktype, **kwargs): '''Performs a single test using a specified Pingdom probe against a specified target. Please note that this method is meant to be used sparingly, not to set up your own monitoring solution. Provide hostname and check type, followed by any optional arguments. Types available: * http * httpcustom * tcp * ping * dns * udp * smtp * pop3 Optional arguments: * probeid -- Probe to use for check Type: Integer Default: A random probe See newCheck() docstring for type-specific arguments Returned structure: { 'status' : <String> Test result status ['up, 'down'] 'responsetime' : <Integer> Response time in milliseconds 'statusdesc' : <String> Short status description 'statusdesclong' : <String> Long status description 'probeid' : <Integer> Probe identifier 'probedesc' : <String> Probe description } ''' pass def getSettings(self): '''Returns all account-specific settings. Returned structure: { 'firstname' : <String> First name 'lastname' : <String> Last name 'company' : <String> Company 'email' : <String> Email 'phone' : <String> Phone 'phonecountryiso' : <String> Phone country ISO code 'cellphone' : <String> Cellphone 'cellphonecountryiso' : <String> Cellphone country ISO code 'address' : <String> Address line 1 'address2' : <String> Address line 2 'zip' : <String> Zip, postal code or equivalent 'location' : <String> City / location 'state' : <String> State or equivalent 'autologout' : <Boolean> Enable auto-logout 'country' : { 'name' : <String> Country name 'iso' : <String> Country ISO-code 'countryid' : <Integer> Country identifier } 'vatcode' : <String> For certain EU countries, VAT-code 'region' : <String> Region 'regionid' : <Integer> Region identifier, see reference 'accountcreated' : <Integer> Account creation timestamp 'timezone' : { 'id' : <String> Timezone name 'description' : <String> Timezone description 'timezoneid' : <Integer> Timezone identifier } 'dateformat' : <String> Date format 'timeformat' : <String> Time format 'datetimeformatid' : <Integer> Date/time format identifier 'numberformat' : <String> Number format 'numberformatexample' : <String> Example of number presentation 'numberformatid' : <Integer> Number format identifier 'publicreportscode' : <String> URL code 'settingssaved' : <Boolean> True if user has saved initial settings in control panel } ''' pass def modifySettings(self, **kwargs): '''Modify account-specific settings. Returns status message for operation Optional parameters: * firstname -- First name Type: String * lastname -- Last name Type: String * company -- Company Type: String * email -- Email (Please note that your email is used for authentication purposes such as using this API or logging into the Pingdom Panel) Type: String * cellphone -- Cellphone (without country code) (Requires cellcountrycode and cellcountryiso) Type: String * cellcountrycode -- Cellphone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * cellcountryiso -- Cellphone country ISO code, for example US(USA) or SE (Sweden) Type: String * phone -- Phone (without country code) (Requires phonecountrycode and phonecountryiso) Type: String * phonecountrycode -- Phone country code, for example 1 (USA) or 46 (Sweden) Type: Integer * phonecountryiso -- Phone country ISO code, for example US (USA) or SE (Sweden) Type: String * address -- Address line 1 Type: String * address2 -- Address line 2 Type: String * zip -- Zip, postal code or equivalent Type: String * location -- City / location Type: String * state -- State, province or equivalent Type: String * countryiso -- Country ISO code, for example US (USA) or SE (Sweden) Type: String * vatcode -- For certain EU countries, VAT-code. Example: SE123456789 Type: String * autologout -- Enable auto-logout Type: Boolean * regionid -- Region identifier, for localization purposes. 0 for "Custom"/none. See the API resource "Reference" for more information Type: Integer * timezoneid -- Time zone identifier. See the API resource "Reference" for more information Type: Integer * datetimeformatid -- Date/time format identifier. See the API resource "Reference" for more information Type: Integer * numberformatid -- Number format identifier. See the API resource "Reference" for more information Type: Integer * pubrcustomdesign -- Use custom design for public reports Type: Boolean * pubrtextcolor -- Public reports, custom text color (Example: FEFFFE or 99CC00) Type: String * pubrbackgroundcolor -- Public reports, background color (Example: FEFFFE or 99CC00) Type: String * pubrlogourl -- Public reports, URL to custom logotype. This parameter is currently disabled for public use. (Example: stats.pingdom.com/images/logo.png) Type: String * pubrmonths -- Public reports, nuber of months to show Type: String ['none', 'all', '3'] * pubrshowoverview -- Public reports, enable overview Type: Boolean * pubrcustomdomain -- Public reports, custom domain. Must be a DNS CNAME with target stats.pingdom.com Type: Boolean ''' pass def getEmailReports(self): '''Returns a list of PingdomEmailReport instances.''' pass def newEmailReport(self, name, **kwargs): '''Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String ''' pass def getPublicReports(self): '''Returns a list of public (web-based) reports Returned structure: [ { 'checkid' : <Integer> Check identifier 'checkname' : <String> Check name 'reporturl' : <String> URL to report }, ... ] ''' pass def getSharedReports(self): '''Returns a list of PingdomSharedReport instances''' pass def newSharedReport(self, checkid, **kwargs): '''Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer ''' pass
30
28
44
8
13
23
4
1.78
1
8
4
0
27
8
28
28
1,275
242
372
75
341
661
202
73
173
30
1
4
117
142,608
KennethWilke/PingdomLib
KennethWilke_PingdomLib/pingdomlib/analysis.py
pingdomlib.analysis.PingdomAnalysis
class PingdomAnalysis(object): """Class representing a root cause analysis""" def __init__(self, instantiator, analysis): self.pingdom = instantiator.pingdom self.checkid = instantiator.id self.id = analysis['id'] self.timefirsttest = analysis['timefirsttest'] self.timeconfirmtest = analysis['timeconfirmtest'] def getDetails(self): response = self.pingdom.request('GET', 'analysis/%s/%s' % (self.checkid, self.id)) self.details = response.text return self.details def __getattr__(self, attr): if attr == 'details': return self.getDetails()
class PingdomAnalysis(object): '''Class representing a root cause analysis''' def __init__(self, instantiator, analysis): pass def getDetails(self): pass def __getattr__(self, attr): pass
4
1
5
0
5
0
1
0.07
1
0
0
0
3
6
3
3
19
3
15
11
11
1
14
11
10
2
1
1
4
142,609
KennethWilke/PingdomLib
KennethWilke_PingdomLib/pingdomlib/reports.py
pingdomlib.reports.PingdomSharedReport
class PingdomSharedReport(object): """Class represening a pingdom shared report Attributes: * id -- Banner identifier * name -- Banner name * checkid -- Check identifier * auto -- Automatic period activated * type -- Banner type * url -- Banner URL * fromyear -- Period start: year * frommonth -- Period start: month * fromday -- Period start: day * toyear -- Period end: year * tomonth -- Period end: month * today -- Period end: day """ def __init__(self, instantiator, reportdetails): self.pingdom = instantiator for key in reportdetails: setattr(self, key, reportdetails[key]) def delete(self): """Delete this email report""" response = self.pingdom.request('DELETE', 'reports.shared/%s' % self.id) return response.json()['message']
class PingdomSharedReport(object): '''Class represening a pingdom shared report Attributes: * id -- Banner identifier * name -- Banner name * checkid -- Check identifier * auto -- Automatic period activated * type -- Banner type * url -- Banner URL * fromyear -- Period start: year * frommonth -- Period start: month * fromday -- Period start: day * toyear -- Period end: year * tomonth -- Period end: month * today -- Period end: day ''' def __init__(self, instantiator, reportdetails): pass def delete(self): '''Delete this email report''' pass
3
2
6
1
4
1
2
1.78
1
0
0
0
2
1
2
2
31
6
9
6
6
16
8
6
5
2
1
1
3
142,610
KennethWilke/PingdomLib
KennethWilke_PingdomLib/pingdomlib/reports.py
pingdomlib.reports.PingdomEmailReport
class PingdomEmailReport(object): """Class represening a pingdom email report Attributes: * id -- Subscription identifier * name -- Subscription name * checkid -- Check identifier for check subscriptions * frequency -- Report frequency * additionalemails -- List additional receiving email addressse * contactids -- List of identifiers for receiving contacts """ def __init__(self, instantiator, reportdetails): self.pingdom = instantiator for key in reportdetails: object.__setattr__(self, key, reportdetails[key]) def __setattr__(self, key, value): # Autopush changes to attributes if key in ['id', 'name', 'checkid', 'frequency', 'contactids', 'additionalemails']: if self.pingdom.pushChanges: self.modify(**{key: value}) else: object.__setattr__(self, key, value) object.__setattr__(self, key, value) def modify(self, **kwargs): """Modify this email report Parameters: * name -- Check name Type: String * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional recipient email addresses Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['name', 'checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomEmailReport>.modify()\n') response = self.pingdom.request("PUT", 'reports.email/%s' % self.id, kwargs) return response.json()['message'] def delete(self): """Delete this email report""" response = self.pingdom.request('DELETE', 'reports.email/%s' % self.id) return response.json()['message']
class PingdomEmailReport(object): '''Class represening a pingdom email report Attributes: * id -- Subscription identifier * name -- Subscription name * checkid -- Check identifier for check subscriptions * frequency -- Report frequency * additionalemails -- List additional receiving email addressse * contactids -- List of identifiers for receiving contacts ''' def __init__(self, instantiator, reportdetails): pass def __setattr__(self, key, value): pass def modify(self, **kwargs): '''Modify this email report Parameters: * name -- Check name Type: String * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional recipient email addresses Type: String ''' pass def delete(self): '''Delete this email report''' pass
5
3
14
3
6
5
2
1.12
1
0
0
0
4
1
4
4
70
17
25
10
20
28
20
10
15
3
1
2
9
142,611
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_juman_wrapper_python2.py
test.test_juman_wrapper_python2.TestJumanWrapperPython2
class TestJumanWrapperPython2(unittest.TestCase): def setUp(self): pass def test_juman_wrapper(self): try: from pyknp import Juman juman = Juman(command='juman', jumanpp=False) result = juman.analysis(u"これはペンです。") logger.debug(','.join(mrph.midasi for mrph in result)) for mrph in result.mrph_list(): assert isinstance(mrph, pyknp.Morpheme) logger.debug(u"見出し:%s, 読み:%s, 原形:%s, 品詞:%s, 品詞細分類:%s, 活用型:%s, 活用形:%s, 意味情報:%s, 代表表記:%s" \ % (mrph.midasi, mrph.yomi, mrph.genkei, mrph.hinsi, mrph.bunrui, mrph.katuyou1, mrph.katuyou2, mrph.imis, mrph.repname)) except ImportError: logger.debug('skip test_juman_wrapper') def test_tokenize(self): """This test case checks juman_wrapper.tokenize """ logger.debug (u'Tokenize Test') test_sentence = u"紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" juman_wrapper = JumanWrapper() token_objects = juman_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True) assert isinstance(token_objects, TokenizedSenetence) for t_obj in token_objects.tokenized_objects: assert isinstance(t_obj, TokenizedResult) logger.debug(u"word_surafce:{}, word_stem:{}, pos_tuple:{}, misc_info:{}".format( t_obj.word_surface, t_obj.word_stem, ' '.join(t_obj.tuple_pos), t_obj.misc_info )) assert isinstance(t_obj.word_surface, string_types) assert isinstance(t_obj.word_stem, string_types) assert isinstance(t_obj.tuple_pos, tuple) assert isinstance(t_obj.misc_info, dict) token_objects_list = token_objects.convert_list_object() assert isinstance(token_objects_list, list) logger.debug('-'*30) for stem_posTuple in token_objects_list: assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, string_types) assert isinstance(word_posTuple, tuple) logger.debug(u'word_stem:{} word_pos:{}'.format(word_stem, ' '.join(word_posTuple))) def test_filter_pos(self): """ """ logger.debug (u'Filtering Test. POS condition is only 名詞') test_sentence = u"紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" juman_wrapper = JumanWrapper() token_objects = juman_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True ) pos_condition = [(u'名詞', )] filtered_result = juman_wrapper.filter( parsed_sentence=token_objects, pos_condition=pos_condition ) assert isinstance(filtered_result, FilteredObject) for t_obj in filtered_result.tokenized_objects: assert isinstance(t_obj, TokenizedResult) logger.debug(u"word_surafce:{}, word_stem:{}, pos_tuple:{}, misc_info:{}".format( t_obj.word_surface, t_obj.word_stem, ' '.join(t_obj.tuple_pos), t_obj.misc_info )) assert isinstance(t_obj.word_surface, string_types) assert isinstance(t_obj.word_stem, string_types) assert isinstance(t_obj.tuple_pos, tuple) assert isinstance(t_obj.misc_info, dict) assert t_obj.tuple_pos[0] == u'名詞' logger.debug('-'*30) for stem_posTuple in filtered_result.convert_list_object(): assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, string_types) assert isinstance(word_posTuple, tuple) logger.debug(u'word_stem:{} word_pos:{}'.format(word_stem, ' '.join(word_posTuple))) def test_stopwords(self): stopword = [u'AV', u'女優'] logger.debug (u'Stopwords Filtering Test. Stopwords is {}'.format(u','.join(stopword))) test_sentence = u"紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" juman_wrapper = JumanWrapper() token_objects = juman_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True ) filtered_result = juman_wrapper.filter( parsed_sentence=token_objects, stopwords=stopword ) check_flag = True for stem_posTuple in filtered_result.convert_list_object(): assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, string_types) assert isinstance(word_posTuple, tuple) logger.debug(u'word_stem:{} word_pos:{}'.format(word_stem, ' '.join(word_posTuple))) if word_stem in stopword: check_flag = False assert check_flag def test_juman_server_mode(self): ### test with server mode ### ### Attention: this method causes Error if you don't start JUMAN SERVER mode ### test_sentence = u"紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" juman_wrapper = JumanWrapper(server='localhost', port=32000) token_objects = juman_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True) self.assertTrue(isinstance(token_objects, TokenizedSenetence)) list_tokens = juman_wrapper.tokenize(sentence=test_sentence, return_list=True, is_feature=True) self.assertTrue(isinstance(list_tokens, list))
class TestJumanWrapperPython2(unittest.TestCase): def setUp(self): pass def test_juman_wrapper(self): pass def test_tokenize(self): '''This test case checks juman_wrapper.tokenize ''' pass def test_filter_pos(self): ''' ''' pass def test_stopwords(self): pass def test_juman_server_mode(self): pass
7
2
22
3
19
1
2
0.05
1
8
4
0
6
0
6
78
140
20
114
40
106
6
86
40
78
3
2
2
14
142,612
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_filter_python3.py
test.test_filter_python3.TestFilter
class TestFilter(unittest.TestCase): def setUp(self): '''紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優みたいだ。''' self.test_senetence = '紗倉 まなは、日本のAV女優みたいで、うつくしい。そこで、ぼくはその1枚のはなやかな作品を見たいと思った。' self.stopword = ['AV', '女優'] self.pos_condition = [('名詞', '一般',), ('名詞', '固有名詞'), ('形容詞', '自立',), ('助詞', '格助詞', '引用')] self.path_user_dict = os.path.join(os.path.dirname(__file__), 'resources/test/userdict.csv') def test_filtering(self): mecab_obj = MecabWrapper(dictType='ipadic') tokenized_sentence = mecab_obj.tokenize(sentence=self.test_senetence,is_feature=True).\ filter(pos_condition=self.pos_condition, stopwords=self.stopword) assert isinstance(tokenized_sentence, TokenizedSenetence) seq_except_pos = [('動詞',), ('名詞', '代名詞'), ('名詞', '接尾')] seq_match_pos = [('名詞',), ('名詞', '固有名詞',), ('形容詞',), ('形容詞', '自立'),('助詞', '格助詞', '引用')] for token_obj in tokenized_sentence.tokenized_objects: assert isinstance(token_obj, TokenizedResult) pos_tuple = token_obj.tuple_pos # 結果に入っているべきではない品詞 # for except_pos in seq_except_pos: self.assertTrue(not set(except_pos).issubset(set(pos_tuple))) # 結果に入っているべき品詞 # bool_any = any(set(match_pos).issubset(set(pos_tuple)) for match_pos in seq_match_pos) self.assertTrue(bool_any) # stopwordsのチェック self.assertTrue(token_obj.word_stem not in self.stopword)
class TestFilter(unittest.TestCase): def setUp(self): '''紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優みたいだ。''' pass def test_filtering(self): pass
3
1
14
2
10
2
2
0.19
1
4
3
0
2
4
2
74
30
5
21
15
18
4
20
15
17
3
2
2
4
142,613
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_filter_python2.py
test.test_filter_python2.TestFilter
class TestFilter(unittest.TestCase): def setUp(self): '''紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優みたいだ。''' self.test_senetence = u'紗倉 まなは、日本のAV女優みたいで、うつくしい。\nそこで、ぼくはその1枚のはなやかな作品を見たいと思った。' self.stopword = ['AV'] self.pos_condition = [('名詞', '一般',), ('名詞', '固有名詞'), ('形容詞', '自立',), ('助詞', '格助詞', '引用')] self.path_user_dict = os.path.join(os.path.dirname(__file__), 'resources/test/userdict.csv') def test_filtering(self): mecab_obj = MecabWrapper(dictType='ipadic') tokenized_sentence = mecab_obj.tokenize(sentence=self.test_senetence,is_feature=True).\ filter(pos_condition=self.pos_condition, stopwords=self.stopword) assert isinstance(tokenized_sentence, TokenizedSenetence) seq_except_pos = [(u'動詞',), (u'名詞', u'代名詞'), (u'名詞', u'接尾')] seq_match_pos = [(u'名詞',), (u'名詞', u'固有名詞',), (u'形容詞',), (u'形容詞', u'自立'),(u'助詞', u'格助詞', u'引用')] for token_obj in tokenized_sentence.tokenized_objects: assert isinstance(token_obj, TokenizedResult) pos_tuple = token_obj.tuple_pos # 結果に入っているべきではない品詞 # for except_pos in seq_except_pos: self.assertTrue(not set(except_pos).issubset(set(pos_tuple))) # 結果に入っているべき品詞 # bool_any = any(set(match_pos).issubset(set(pos_tuple)) for match_pos in seq_match_pos) self.assertTrue(bool_any)
class TestFilter(unittest.TestCase): def setUp(self): '''紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優みたいだ。''' pass def test_filtering(self): pass
3
1
13
2
10
2
2
0.15
1
4
3
0
2
4
2
74
27
4
20
15
17
3
19
15
16
3
2
2
4
142,614
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/common/test_server_handler.py
test.common.test_server_handler.TestServerHandler
class TestServerHandler(unittest.TestCase): @classmethod def setUpClass(cls): if six.PY3: cls.test_senetence = '紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優。' else: cls.test_senetence = u'紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優。' cls.jumanpp_command = "/usr/local/bin/jumanpp" def test_jumanpp_process_hanlder_normal(self): """It tests jumanpp process handler""" # normal test # jumanpp_process_handler = sever_handler.JumanppHnadler(jumanpp_command=self.jumanpp_command) result_jumanpp_analysis = jumanpp_process_handler.query(input_string=self.test_senetence) self.assertTrue(isinstance(result_jumanpp_analysis,six.text_type)) ## stop process ## jumanpp_process_handler.stop_process() ## delete instance ## del jumanpp_process_handler def test_jumanpp_process_handler_timeout_exception(self): """It tests the case which causes timeout exception""" with self.assertRaises(Exception) as exc: jumanpp_process_handler = sever_handler.JumanppHnadler(jumanpp_command=self.jumanpp_command, timeout_second=1) result_jumanpp_analysis = jumanpp_process_handler.query(input_string=self.test_senetence*100) exception_message = exc.exception jumanpp_process_handler.stop_process() def test_jumanpp_process_handler_init_exception(self): with self.assertRaises(Exception) as exc: jumanpp_process_handler = sever_handler.JumanppHnadler(jumanpp_command='hoge', timeout_second=1) exception_message = exc.exception def test_jumanpp_process_handler_huge_request(self): """It tests the case where a user sends too much request""" input_huge_request = [self.test_senetence] * 100 jumanpp_process_handler = sever_handler.JumanppHnadler(jumanpp_command=self.jumanpp_command) seq_result_jumanpp_analysis = [jumanpp_process_handler.query(input_string=sentence) for sentence in input_huge_request] self.assertTrue(isinstance(seq_result_jumanpp_analysis, list))
class TestServerHandler(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_jumanpp_process_hanlder_normal(self): '''It tests jumanpp process handler''' pass def test_jumanpp_process_handler_timeout_exception(self): '''It tests the case which causes timeout exception''' pass def test_jumanpp_process_handler_init_exception(self): pass def test_jumanpp_process_handler_huge_request(self): '''It tests the case where a user sends too much request''' pass
7
3
7
0
6
1
1
0.19
1
3
1
0
4
1
5
77
44
6
32
19
25
6
27
16
21
2
2
1
6
142,615
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/object_models.py
JapaneseTokenizer.object_models.WrapperBase
class WrapperBase(object): def tokenize(self, sentence, normalize, is_feature, is_surface, return_list, func_normalizer=None): # type: (text_type, bool, bool, bool, bool, Callable[[text_type], text_type])->None """* What you can do""" raise NotImplemented def filter(self, parsed_sentence, pos_condition=None, stopwords=None): raise NotImplemented
class WrapperBase(object): def tokenize(self, sentence, normalize, is_feature, is_surface, return_list, func_normalizer=None): '''* What you can do''' pass def filter(self, parsed_sentence, pos_condition=None, stopwords=None): pass
3
1
6
0
5
1
1
0.18
1
0
0
4
2
0
2
2
14
1
11
9
2
2
5
3
2
1
1
0
2
142,616
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py
JapaneseTokenizer.mecab_wrapper.mecab_wrapper.MecabWrapper
class MecabWrapper(WrapperBase): def __init__(self, dictType, pathUserDictCsv=None, path_mecab_config=None, path_dictionary=None, string_encoding='utf-8'): # type: (text_type, text_type, text_type, text_type, text_type)->None """ :param dictType: a dictionary type called by mecab :param pathUserDictCsv: path to your original dictionary file :param path_mecab_config: path to 'mecab_config' command. It's automatically detected if not give :param path_dictionary: path to a dictionary which you want to use. If not given, it's automatically detected :param string_encoding: encoding option to parse command line result. This is mainly used for python2.x """ self.string_encoding = string_encoding self._dictType = dictType self._pathUserDictCsv = pathUserDictCsv self._path_dictionary = path_dictionary if path_mecab_config is None: self._path_mecab_config = self.__get_path_to_mecab_config() else: self._path_mecab_config = path_mecab_config if self._path_dictionary is not None: assert os.path.exists(self._path_dictionary), 'Path dictionary is NOT exist.' self._mecab_dictionary_path = None else: self._mecab_dictionary_path = self.__check_mecab_dict_path() logger.info("mecab dictionary path is detected under {}".format(self._mecab_dictionary_path)) self.mecabObj = self.__CallMecab() assert dictType in ["neologd", "all", "ipadic", "ipaddic", "user", "", "jumandic", "unidic", None], \ 'Dictionary Type Error. Your dict = {} is NOT available.' if dictType == 'all': logger.error('dictionary type "all" is deprecated from version1.6') raise Exception('dictionary type "all" is deprecated from version1.6') if dictType == 'user': logger.error('dictionary type "user" is deprecated from version1.6. You just give path to dictionary csv.') raise Exception('dictionary type "all" is deprecated from version1.6. You just give path to dictionary csv.') if pathUserDictCsv is not None and isinstance(pathUserDictCsv, text_type) and pathUserDictCsv != '': assert os.path.exists(pathUserDictCsv), \ 'Your user dictionary does NOT exist. Path={}'.format(pathUserDictCsv) def __get_path_to_mecab_config(self): """You get path into mecab-config """ if six.PY2: path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']) path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '') else: path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']).decode(self.string_encoding) path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '') logger.info(msg='mecab-config is detected at {}'.format(path_mecab_config_dir)) return path_mecab_config_dir def __check_mecab_dict_path(self): """check path to dict of Mecab in system environment """ mecab_dic_cmd = "echo `{} --dicdir`".format(os.path.join(self._path_mecab_config, 'mecab-config')) try: if six.PY2: path_mecab_dict = subprocess.check_output( mecab_dic_cmd, shell=True ).strip('\n') else: path_mecab_dict = subprocess.check_output(mecab_dic_cmd, shell=True).decode(self.string_encoding).strip('\n') except subprocess.CalledProcessError: logger.error("{}".format(mecab_dic_cmd)) raise subprocess.CalledProcessError(returncode=-1, cmd="Failed to execute mecab-config command") if path_mecab_dict == '': raise SystemError("""mecab dictionary path is not found with following command: {} You are not able to use additional dictionary. Still you are able to call mecab default dictionary""".format(mecab_dic_cmd)) return path_mecab_dict def __check_mecab_libexe(self): mecab_libexe_cmd = "echo `{} --libexecdir`".format(os.path.join(self._path_mecab_config, 'mecab-config')) try: if six.PY2: path_mecab_libexe = subprocess.check_output( mecab_libexe_cmd, shell=True ).strip('\n') else: path_mecab_libexe = subprocess.check_output(mecab_libexe_cmd, shell=True).decode(self.string_encoding).strip('\n') except subprocess.CalledProcessError: logger.error("{}".format(mecab_libexe_cmd)) raise subprocess.CalledProcessError(returncode=-1, cmd="Failed to execute mecab-config --libexecdir") if path_mecab_libexe == '': raise SystemError("""Mecab config is not callable with following command: {} You are not able to compile your user dictionary. Still, you are able to use default mecab dictionary.""".format(mecab_libexe_cmd)) return path_mecab_libexe def __CallMecab(self): if self._path_dictionary is not None and self._mecab_dictionary_path is None: logger.debug('Use dictionary you specified.') cmMecabInitialize = '-d {}'.format(self._path_dictionary) elif self._dictType == 'neologd': # use neologd logger.debug('Use neologd additional dictionary') cmMecabInitialize = '-d {}'.format(os.path.join(self._mecab_dictionary_path, "mecab-ipadic-neologd")) elif self._dictType == 'ipadic' or self._dictType == 'ipaddic': # use ipadic logger.debug('Use ipadic dictionary') cmMecabInitialize = '-d {}'.format(os.path.join(self._mecab_dictionary_path, "ipadic")) elif six.PY2 is False and self._dictType == 'jumandic': # use jumandic. This is impossible to call in Python2.x logger.debug('Use jumandic dictionary') cmMecabInitialize = '-d {}'.format(os.path.join(self._mecab_dictionary_path, "jumandic")) elif six.PY2 and self._dictType == 'jumandic': raise Exception('In python2.x, impossible to call jumandic.') else: logger.debug('Use no default dictionary') cmMecabInitialize = '' # execute compile if user dictionary is given if self._pathUserDictCsv is not None: logger.debug('Use User dictionary') pathUserDict = self.__CompileUserdict() cmMecabInitialize += ' -u {}'.format(pathUserDict) if six.PY2: cmMecabCall = "-Ochasen {}".format(cmMecabInitialize) else: cmMecabCall = "{}".format(cmMecabInitialize) logger.debug(msg="mecab initialized with {}".format(cmMecabCall)) try: mecabObj = MeCab.Tagger(cmMecabCall) except Exception as e: logger.error(e.args) logger.error("Possibly Path to userdict is invalid. Check the path") raise subprocess.CalledProcessError(returncode=-1, cmd="Failed to initialize Mecab object") return mecabObj def __CompileUserdict(self): """* What you can do """ path_mecab_dict = self.__check_mecab_dict_path() path_mecab_libexe = self.__check_mecab_libexe() cmCompileDict = u'{0}/mecab-dict-index -d {1}/ipadic -u {2} -f utf-8 -t utf-8 {3} > /dev/null'.format(path_mecab_libexe, path_mecab_dict, self._pathUserDictCsv.replace("csv", "dict"), self._pathUserDictCsv) logger.debug(msg="compiling mecab user dictionary with: {}".format(cmCompileDict)) try: subprocess.call( cmCompileDict , shell=True ) except OSError as e: logger.error('type:' + str(type(e))) logger.error('args:' + str(e.args)) sys.exit('Failed to compile mecab userdict. System ends') return self._pathUserDictCsv.replace("csv", "dict") def __feature_parser(self, uni_feature, word_surface): """ Parse the POS feature output by Mecab :param uni_feature unicode: :return ( (pos1, pos2, pos3), word_stem ): """ list_feature_items = uni_feature.split((',')) # if word has no feature at all if len(list_feature_items)==1: return ('*'), ('*') pos1 = list_feature_items[0] pos2 = list_feature_items[1] pos3 = list_feature_items[2] tuple_pos = ( pos1, pos2, pos3 ) # if without constraint(output is normal mecab dictionary like) if len(list_feature_items) == 9: word_stem = list_feature_items[6] # if with constraint(output format depends on Usedict.txt) else: word_stem = word_surface return tuple_pos, word_stem def __postprocess_analyzed_result(self, string_mecab_parsed_result, is_feature, is_surface): # type: (text_type,bool,bool)->List[TokenizedResult] """Extract surface word and feature from analyzed lines. Extracted results are returned with list, whose elements are TokenizedResult class [TokenizedResult] """ assert isinstance(string_mecab_parsed_result, str) check_tab_separated_line = lambda x: True if '\t' in x else False tokenized_objects = [ self.__result_parser(analyzed_line=analyzed_line, is_feature=is_feature, is_surface=is_surface) for analyzed_line in string_mecab_parsed_result.split('\n') if not analyzed_line=='EOS' and check_tab_separated_line(analyzed_line) ] assert isinstance(tokenized_objects, list) return tokenized_objects def __result_parser(self, analyzed_line, is_feature, is_surface): # type: (text_type,bool,bool)->TokenizedResult """Extract surface word and feature from analyzed line. Extracted elements are returned with TokenizedResult class """ assert isinstance(analyzed_line, str) assert isinstance(is_feature, bool) assert isinstance(is_surface, bool) surface, features = analyzed_line.split('\t', 1) tuple_pos, word_stem = self.__feature_parser(features, surface) tokenized_obj = TokenizedResult( node_obj=None, analyzed_line=analyzed_line, tuple_pos=tuple_pos, word_stem=word_stem, word_surface=surface, is_feature=is_feature, is_surface=is_surface ) return tokenized_obj def tokenize(self, sentence, normalized=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=normalize_text): # type: (text_type, bool, bool, bool, bool, Callable[[str], str])->Union[List[str], TokenizedSenetence] """* What you can do - Call mecab tokenizer, and return tokenized objects """ if six.PY2 and isinstance(sentence, str): sentence = sentence.decode(self.string_encoding) else: pass # decide normalization function depending on dictType if func_normalizer is None and self._dictType == 'neologd' and is_neologdn_valid: normalized_sentence = neologdn.normalize(sentence) elif func_normalizer is None and self._dictType == 'neologd' and is_neologdn_valid == False: raise Exception("You could not call neologd dictionary bacause you do NOT install the package neologdn.") elif func_normalizer == normalize_text: normalized_sentence = normalize_text(sentence, dictionary_mode=self._dictType) elif func_normalizer is None: normalized_sentence = sentence else: normalized_sentence = func_normalizer(sentence) # don't delete this variable. The variable "encoded_text" protects sentence from deleting if six.PY2: encoded_text = normalized_sentence.encode(self.string_encoding) else: encoded_text = normalized_sentence if six.PY2: tokenized_objects = [] node = self.mecabObj.parseToNode(encoded_text) node = node.next while node.next is not None: word_surface = node.surface.decode(self.string_encoding) tuple_pos, word_stem = self.__feature_parser(node.feature.decode(self.string_encoding), word_surface) tokenized_obj = TokenizedResult( node_obj=node, tuple_pos=tuple_pos, word_stem=word_stem, word_surface=word_surface, is_feature=is_feature, is_surface=is_surface ) tokenized_objects.append(tokenized_obj) node = node.next tokenized_sentence = TokenizedSenetence( sentence=sentence, tokenized_objects=tokenized_objects) else: parsed_result = self.mecabObj.parse(encoded_text) tokenized_objects = self.__postprocess_analyzed_result( string_mecab_parsed_result=parsed_result, is_feature=is_feature, is_surface=is_surface ) tokenized_sentence = TokenizedSenetence( sentence=sentence, tokenized_objects=tokenized_objects ) # type: TokenizedSenetence if return_list: return tokenized_sentence.convert_list_object() else: return tokenized_sentence def filter(self, parsed_sentence, pos_condition=None, stopwords=None): # type: (TokenizedSenetence, List[Tuple[str,...]], List[str]) -> FilteredObject assert isinstance(parsed_sentence, TokenizedSenetence) assert isinstance(pos_condition, (type(None), list)) assert isinstance(stopwords, (type(None), list)) return parsed_sentence.filter(pos_condition, stopwords)
class MecabWrapper(WrapperBase): def __init__(self, dictType, pathUserDictCsv=None, path_mecab_config=None, path_dictionary=None, string_encoding='utf-8'): ''' :param dictType: a dictionary type called by mecab :param pathUserDictCsv: path to your original dictionary file :param path_mecab_config: path to 'mecab_config' command. It's automatically detected if not give :param path_dictionary: path to a dictionary which you want to use. If not given, it's automatically detected :param string_encoding: encoding option to parse command line result. This is mainly used for python2.x ''' pass def __get_path_to_mecab_config(self): '''You get path into mecab-config ''' pass def __check_mecab_dict_path(self): '''check path to dict of Mecab in system environment ''' pass def __check_mecab_libexe(self): pass def __CallMecab(self): pass def __CompileUserdict(self): '''* What you can do ''' pass def __feature_parser(self, uni_feature, word_surface): ''' Parse the POS feature output by Mecab :param uni_feature unicode: :return ( (pos1, pos2, pos3), word_stem ): ''' pass def __postprocess_analyzed_result(self, string_mecab_parsed_result, is_feature, is_surface): '''Extract surface word and feature from analyzed lines. Extracted results are returned with list, whose elements are TokenizedResult class [TokenizedResult] ''' pass def __result_parser(self, analyzed_line, is_feature, is_surface): '''Extract surface word and feature from analyzed line. Extracted elements are returned with TokenizedResult class ''' pass def tokenize(self, sentence, normalized=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=normalize_text): '''* What you can do - Call mecab tokenizer, and return tokenized objects ''' pass def filter(self, parsed_sentence, pos_condition=None, stopwords=None): pass
12
8
27
3
20
4
4
0.19
1
10
2
0
11
7
11
13
309
42
225
63
203
43
157
51
145
10
2
2
43
142,617
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/datamodels.py
JapaneseTokenizer.datamodels.FilteredObject
class FilteredObject(TokenizedSenetence): def __init__(self, sentence, tokenized_objects, pos_condition, stopwords): # type: (str, List[TokenizedResult], List[str, ...], List[str])->None super(FilteredObject, self).__init__( sentence=sentence, tokenized_objects=tokenized_objects ) self.pos_condition=pos_condition self.stopwords=stopwords
class FilteredObject(TokenizedSenetence): def __init__(self, sentence, tokenized_objects, pos_condition, stopwords): pass
2
0
8
0
7
1
1
0.13
1
1
0
0
1
2
1
7
9
0
8
4
6
1
5
4
3
1
2
0
1
142,618
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/juman_wrapper/juman_wrapper.py
JapaneseTokenizer.juman_wrapper.juman_wrapper.JumanWrapper
class JumanWrapper(WrapperBase): def __init__(self, command='juman', server=None, port=32000, timeout=30, rcfile=None, option='-e2 -B', pattern='EOS', is_use_pyknp=False, **args): # type: (text_type, text_type, int, int, text_type, Union[bytes, text_type], Union[bytes, text_type], bool, **str)->None """* Class to call Juman tokenizer """ self.timeout = timeout self.pattern = pattern self.option = option self.command = command if not rcfile is None and not os.path.exists(rcfile): raise FileExistsError('rcfile does not exist at {}'.format(rcfile)) if not server is None: # It converts from str into bytes only for sever mode # self.option = self.option.encode('utf-8') # type: Union[str,bytes] self.pattern = self.pattern.encode('utf-8') # type: Union[str,bytes] else: pass # check os # if os.name == 'nt': if not is_use_pyknp: logger.warning(msg='It forces is_use_pyknp = True on Windows.') else: pass self.is_use_pyknp = True else: pass if server is not None: # use server mode # self.juman = pyknp.Juman(command=command, server=server, port=port, timeout=self.timeout, rcfile=rcfile, option=option, pattern=pattern, jumanpp=False, **args) if six.PY3: # It overwrites juman_lines() method # self.juman.juman_lines = self.__monkey_patch_juman_lines elif is_use_pyknp and server is None: # use unix process with pyknp self.juman = pyknp.Juman(command=command, server=server, port=port, timeout=self.timeout, rcfile=rcfile, option=option, pattern=pattern, jumanpp=False, **args) else: # use unix process with pexpect(RECOMMENDED) # self.juman = JumanppHnadler(jumanpp_command=command, option=self.option, pattern=self.pattern, timeout_second=self.timeout) def __del__(self): if hasattr(self, "juman"): if isinstance(self.juman, JumanppHnadler): self.juman.stop_process() def __monkey_patch_juman_lines(self, input_str): # type: (text_type)->text_type """* What you can do - It overwrites juman_line() method because this method causes TypeError in python3 """ assert isinstance(self.juman, pyknp.Juman) if not self.juman.socket and not self.juman.subprocess: if self.juman.server is not None: self.juman.socket = MonkeyPatchSocket(self.juman.server, self.juman.port, b"RUN -e2\n") else: command = "%s %s" % (self.juman.command, self.juman.option) if self.juman.rcfile: command += " -r %s" % self.juman.rcfile self.juman.subprocess = pyknp.Subprocess(command) if self.juman.socket: return self.juman.socket.query(input_str, pattern=self.juman.pattern) return self.juman.subprocess.query(input_str, pattern=self.juman.pattern) def __extract_morphological_information(self, mrph_object, is_feature, is_surface): """This method extracts morphlogical information from token object. """ assert isinstance(mrph_object, pyknp.Morpheme) assert isinstance(is_feature, bool) assert isinstance(is_surface, bool) surface = mrph_object.midasi word_stem = mrph_object.genkei tuple_pos = (mrph_object.hinsi, mrph_object.bunrui) misc_info = { 'katuyou1': mrph_object.katuyou1, 'katuyou2': mrph_object.katuyou2, 'imis': mrph_object.imis, 'repname': mrph_object.repname } token_object = TokenizedResult( node_obj=None, tuple_pos=tuple_pos, word_stem=word_stem, word_surface=surface, is_feature=is_feature, is_surface=is_surface, misc_info=misc_info ) return token_object def call_juman_interface(self, input_str): # type: (text_type)->MList if isinstance(self.juman, pyknp.Juman): result = self.juman.analysis(input_str) return result elif isinstance(self.juman, JumanppHnadler): try: result_analysis = self.juman.query(input_str) except UnicodeDecodeError: logger.warning(msg="Process is down by some reason. It restarts process automatically.") self.juman.restart_process() result_analysis = self.juman.query(input_string=input_str) return MList(result_analysis) else: raise Exception('Not defined.') def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): # type: (text_preprocess, bool, bool, bool, bool, Callable[[str], text_type])->Union[List[text_type], TokenizedSenetence] """This method returns tokenized result. If return_list==True(default), this method returns list whose element is tuple consisted with word_stem and POS. If return_list==False, this method returns TokenizedSenetence object. """ assert isinstance(normalize, bool) assert isinstance(sentence, text_type) normalized_sentence = func_normalizer(sentence) result = self.call_juman_interface(normalized_sentence) token_objects = [ self.__extract_morphological_information( mrph_object=morph_object, is_surface=is_surface, is_feature=is_feature ) for morph_object in result] if return_list: tokenized_objects = TokenizedSenetence( sentence=sentence, tokenized_objects=token_objects ) return tokenized_objects.convert_list_object() else: tokenized_objects = TokenizedSenetence( sentence=sentence, tokenized_objects=token_objects) return tokenized_objects def filter(self, parsed_sentence, pos_condition=None, stopwords=None): # type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type])->FilteredObject assert isinstance(parsed_sentence, TokenizedSenetence) assert isinstance(pos_condition, (type(None), list)) assert isinstance(stopwords, (type(None), list)) return parsed_sentence.filter(pos_condition, stopwords)
class JumanWrapper(WrapperBase): def __init__(self, command='juman', server=None, port=32000, timeout=30, rcfile=None, option='-e2 -B', pattern='EOS', is_use_pyknp=False, **args): '''* Class to call Juman tokenizer ''' pass def __del__(self): pass def __monkey_patch_juman_lines(self, input_str): '''* What you can do - It overwrites juman_line() method because this method causes TypeError in python3 ''' pass def __extract_morphological_information(self, mrph_object, is_feature, is_surface): '''This method extracts morphlogical information from token object. ''' pass def call_juman_interface(self, input_str): pass def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): '''This method returns tokenized result. If return_list==True(default), this method returns list whose element is tuple consisted with word_stem and POS. If return_list==False, this method returns TokenizedSenetence object. ''' pass def filter(self, parsed_sentence, pos_condition=None, stopwords=None): pass
8
4
24
2
19
3
3
0.18
1
10
4
0
7
6
7
9
173
18
133
41
110
24
78
26
70
8
2
3
24
142,619
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/datamodels.py
JapaneseTokenizer.datamodels.TokenizedSenetence
class TokenizedSenetence(object): def __init__(self, sentence, tokenized_objects, string_encoding='utf-8'): # type: (text_type, List[TokenizedResult], text_type)->None """* Parameters - sentence: sentence - tokenized_objects: list of TokenizedResult object - string_encoding: Encoding type of string type. This option is used only under python2.x """ assert isinstance(sentence, text_type) assert isinstance(tokenized_objects, list) self.sentence = sentence self.tokenized_objects = tokenized_objects self.string_encoding = string_encoding def __extend_token_object(self, token_object, is_denormalize=True, func_denormalizer=denormalize_text): # type: (TokenizedResult,bool,Callable[[str],str])->Tuple """This method creates dict object from token object. """ assert isinstance(token_object, TokenizedResult) if is_denormalize: if token_object.is_feature == True: if token_object.is_surface == True: token = (func_denormalizer(token_object.word_surface), token_object.tuple_pos) else: token = (func_denormalizer(token_object.word_stem), token_object.tuple_pos) else: if token_object.is_surface == True: token = func_denormalizer(token_object.word_surface) else: token = func_denormalizer(token_object.word_stem) else: if token_object.is_feature == True: if token_object.is_surface == True: token = (token_object.word_surface, token_object.tuple_pos) else: token = (token_object.word_stem, token_object.tuple_pos) else: if token_object.is_surface == True: token = token_object.word_surface else: token = token_object.word_stem return token def convert_list_object(self, is_denormalize=True, func_denormalizer=denormalize_text): # type: (bool,Callable[[str],str])->List[Union[str, Tuple[str,...]]] """* What you can do - You extract string object from TokenizedResult object * Args - is_denormalize: boolen object. True; it makes denormalize string - func_denormalizer: callable object. de-normalization function. """ sentence_in_list_obj = [ self.__extend_token_object(token_object,is_denormalize,func_denormalizer) for token_object in self.tokenized_objects ] return sentence_in_list_obj def __convert_string_type(self, p_c_tuple): # type: (Tuple[text_type,...])->Tuple[text_type] """* What you can do - it normalizes string types into str """ if not isinstance(p_c_tuple, tuple): raise Exception('Pos condition expects tuple of string. However = {}'.format(p_c_tuple)) converted = [text_type] * len(p_c_tuple) for i, pos_element in enumerate(p_c_tuple): if six.PY2 and isinstance(pos_element, str): """str into unicode if python2.x""" converted[i] = pos_element.decode(self.string_encoding) elif six.PY2 and isinstance(pos_element, text_type): converted[i] = pos_element elif six.PY3: converted[i] = pos_element else: raise Exception() return tuple(converted) def __check_pos_condition(self, pos_condistion): # type: (List[Tuple[text_type, ...]])->List[Tuple[text_type, ...]] """* What you can do - Check your pos condition - It converts character type into unicode if python version is 2.x """ assert isinstance(pos_condistion, list) return [self.__convert_string_type(p_c_tuple) for p_c_tuple in pos_condistion] def filter(self, pos_condition=None, stopwords=None, is_normalize=True, func_normalizer=normalize_text, check_field_name='stem'): # type: (List[Tuple[text_type,...]], List[text_type], bool, Callable[[text_type], text_type],text_type)->FilteredObject """* What you can do - It filters out token which does NOT meet the conditions (stopwords & part-of-speech tag) - Under python2.x, pos_condition & stopwords are converted into unicode type. * Parameters - pos_condition: list of part-of-speech(pos) condition. The pos condition is tuple is variable length. You can specify hierarchical structure of pos condition with variable tuple. The hierarchy of pos condition follows definition of dictionary. - For example, in mecab you can take words with 名詞 if ('名詞',) - For example, in mecab you can take words with 名詞-固有名詞 if ('名詞', '固有名詞') - stopwords: list of word which you would like to remove - is_normalize: Boolean flag for normalize stopwords. - func_normalizer: Function object for normalization. The function object must be the same one as when you use tokenize. - check_field_name: Put field name to check if stopword or NOT. Kytea does not have stem form of word, put 'surface' instead. * Example >>> pos_condition = [('名詞', '一般'), ('形容詞', '自立'), ('助詞', '格助詞', '一般')] >>> stopwords = ['これ', 'それ'] """ assert isinstance(pos_condition, (type(None), list)) assert isinstance(stopwords, (type(None), list)) if stopwords is None: s_words = [] elif six.PY2 and all((isinstance(s, str) for s in stopwords)): """under python2.x, from str into unicode""" if is_normalize: s_words = [func_normalizer(s.decode(self.string_encoding)) for s in stopwords] else: s_words = [s.decode(self.string_encoding) for s in stopwords] else: if is_normalize: s_words = [func_normalizer(s) for s in stopwords] else: s_words = stopwords if pos_condition is None: p_condition = [] else: p_condition = self.__check_pos_condition(pos_condition) filtered_object = filter_words( tokenized_obj=self, valid_pos=p_condition, stopwords=s_words, check_field_name=check_field_name ) assert isinstance(filtered_object, FilteredObject) return filtered_object
class TokenizedSenetence(object): def __init__(self, sentence, tokenized_objects, string_encoding='utf-8'): '''* Parameters - sentence: sentence - tokenized_objects: list of TokenizedResult object - string_encoding: Encoding type of string type. This option is used only under python2.x ''' pass def __extend_token_object(self, token_object, is_denormalize=True, func_denormalizer=denormalize_text): '''This method creates dict object from token object. ''' pass def convert_list_object(self, is_denormalize=True, func_denormalizer=denormalize_text): '''* What you can do - You extract string object from TokenizedResult object * Args - is_denormalize: boolen object. True; it makes denormalize string - func_denormalizer: callable object. de-normalization function. ''' pass def __convert_string_type(self, p_c_tuple): '''* What you can do - it normalizes string types into str ''' pass def __check_pos_condition(self, pos_condistion): '''* What you can do - Check your pos condition - It converts character type into unicode if python version is 2.x ''' pass def filter(self, pos_condition=None, stopwords=None, is_normalize=True, func_normalizer=normalize_text, check_field_name='stem'): '''* What you can do - It filters out token which does NOT meet the conditions (stopwords & part-of-speech tag) - Under python2.x, pos_condition & stopwords are converted into unicode type. * Parameters - pos_condition: list of part-of-speech(pos) condition. The pos condition is tuple is variable length. You can specify hierarchical structure of pos condition with variable tuple. The hierarchy of pos condition follows definition of dictionary. - For example, in mecab you can take words with 名詞 if ('名詞',) - For example, in mecab you can take words with 名詞-固有名詞 if ('名詞', '固有名詞') - stopwords: list of word which you would like to remove - is_normalize: Boolean flag for normalize stopwords. - func_normalizer: Function object for normalization. The function object must be the same one as when you use tokenize. - check_field_name: Put field name to check if stopword or NOT. Kytea does not have stem form of word, put 'surface' instead. * Example >>> pos_condition = [('名詞', '一般'), ('形容詞', '自立'), ('助詞', '格助詞', '一般')] >>> stopwords = ['これ', 'それ'] ''' pass
7
6
25
3
15
8
4
0.49
1
8
2
1
6
3
6
6
158
21
92
26
76
45
59
17
52
8
1
3
23
142,620
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_juman_wrapper_python3.py
test.test_juman_wrapper_python3.TestJumanWrapperPython3
class TestJumanWrapperPython3(unittest.TestCase): def setUp(self): # this is under MacOSX10 self.path_to_juman_command = '/usr/local/bin/juman' if not os.path.exists(self.path_to_juman_command): self.path_to_juman_command = 'juman' def test_juman_wrapper(self): try: juman = Juman(command=self.path_to_juman_command) result = juman.analysis("これはペンです。") logger.debug(','.join(mrph.midasi for mrph in result)) for mrph in result.mrph_list(): assert isinstance(mrph, pyknp.Morpheme) logger.debug("見出し:%s, 読み:%s, 原形:%s, 品詞:%s, 品詞細分類:%s, 活用型:%s, 活用形:%s, 意味情報:%s, 代表表記:%s" \ % (mrph.midasi, mrph.yomi, mrph.genkei, mrph.hinsi, mrph.bunrui, mrph.katuyou1, mrph.katuyou2, mrph.imis, mrph.repname)) except ImportError: print('skip test_juman_wrapper') def test_tokenize(self): """This test case checks juman_wrapper.tokenize """ logger.debug('Tokenize Test') test_sentence = "紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" juman_wrapper = JumanWrapper(command=self.path_to_juman_command) token_objects = juman_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True) assert isinstance(token_objects, TokenizedSenetence) for t_obj in token_objects.tokenized_objects: assert isinstance(t_obj, TokenizedResult) logger.debug("word_surafce:{}, word_stem:{}, pos_tuple:{}, misc_info:{}".format( t_obj.word_surface, t_obj.word_stem, ' '.join(t_obj.tuple_pos), t_obj.misc_info )) assert isinstance(t_obj.word_surface, str) assert isinstance(t_obj.word_stem, str) assert isinstance(t_obj.tuple_pos, tuple) assert isinstance(t_obj.misc_info, dict) token_objects_list = token_objects.convert_list_object() assert isinstance(token_objects_list, list) logger.debug('-'*30) for stem_posTuple in token_objects_list: assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, str) assert isinstance(word_posTuple, tuple) logger.debug('word_stem:{} word_pos:{}'.format(word_stem, ' '.join(word_posTuple))) def test_filter_pos(self): """POS filteringのテスト """ logger.debug('Filtering Test. POS condition is only 名詞') test_sentence = "紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" juman_wrapper = JumanWrapper(command=self.path_to_juman_command) token_objects = juman_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True) pos_condition = [('名詞', )] filtered_result = juman_wrapper.filter( parsed_sentence=token_objects, pos_condition=pos_condition ) assert isinstance(filtered_result, FilteredObject) for t_obj in filtered_result.tokenized_objects: assert isinstance(t_obj, TokenizedResult) logger.debug("word_surafce:{}, word_stem:{}, pos_tuple:{}, misc_info:{}".format( t_obj.word_surface, t_obj.word_stem, ' '.join(t_obj.tuple_pos), t_obj.misc_info )) assert isinstance(t_obj.word_surface, str) assert isinstance(t_obj.word_stem, str) assert isinstance(t_obj.tuple_pos, tuple) assert isinstance(t_obj.misc_info, dict) assert t_obj.tuple_pos[0] == '名詞' logger.debug('-'*30) for stem_posTuple in filtered_result.convert_list_object(): assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, str) assert isinstance(word_posTuple, tuple) logger.debug('word_stem:{} word_pos:{}'.format(word_stem, ' '.join(word_posTuple))) def test_stopwords(self): """stopword除去のテスト""" stopword = ['AV', '女優'] logger.debug ('Stopwords Filtering Test. Stopwords is {}'.format(','.join(stopword))) test_sentence = "紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" juman_wrapper = JumanWrapper(command=self.path_to_juman_command) token_objects = juman_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True ) filtered_result = juman_wrapper.filter( parsed_sentence=token_objects, stopwords=stopword ) check_flag = True for stem_posTuple in filtered_result.convert_list_object(): assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, str) assert isinstance(word_posTuple, tuple) logger.debug('word_stem:{} word_pos:{}'.format(word_stem, ' '.join(word_posTuple))) if word_stem in stopword: check_flag = False assert check_flag def test_juman_severmode(self): """* What you can do - juman server modeのテストを実施する """ logger.debug('Tokenize test with server mode') test_sentence = "紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" # check socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = 'localhost' PORT = 32000 try: s.connect((HOST, PORT)) s.close() except: logger.warning("SKip server mode test because server is not working.") else: juman_wrapper = JumanWrapper(command=self.path_to_juman_command, server=HOST, port=PORT) token_objects = juman_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True) assert isinstance(token_objects, TokenizedSenetence) test_sentence = "ペルシア語(ペルシアご、ペルシア語: فارسی‌‎, پارسی‌; Fārsī, Pārsī)は、イランを中心とする中東地域で話される言語。" juman_wrapper = JumanWrapper(command=self.path_to_juman_command, server=HOST, port=PORT) list_token = juman_wrapper.tokenize(sentence=test_sentence, return_list=True, is_feature=True) assert isinstance(list_token, list)
class TestJumanWrapperPython3(unittest.TestCase): def setUp(self): pass def test_juman_wrapper(self): pass def test_tokenize(self): '''This test case checks juman_wrapper.tokenize ''' pass def test_filter_pos(self): '''POS filteringのテスト ''' pass def test_stopwords(self): '''stopword除去のテスト''' pass def test_juman_severmode(self): '''* What you can do - juman server modeのテストを実施する ''' pass
7
4
24
2
21
2
3
0.08
1
10
4
0
6
1
6
78
151
16
125
43
118
10
99
43
92
3
2
2
16
142,621
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/common/sever_handler.py
JapaneseTokenizer.common.sever_handler.JumanppHnadler
class JumanppHnadler(UnixProcessHandler): def __init__(self, jumanpp_command, option = None, pattern = 'EOS', timeout_second = 10): # type: (text_type,text_type,text_type,int)->None super(JumanppHnadler, self).__init__(command=jumanpp_command, option=option, pattern=pattern, timeout_second=timeout_second) def launch_jumanpp_process(self, command): # type: (text_type)->None return self.launch_process(command)
class JumanppHnadler(UnixProcessHandler): def __init__(self, jumanpp_command, option = None, pattern = 'EOS', timeout_second = 10): pass def launch_jumanpp_process(self, command): pass
3
0
5
0
4
1
1
0.22
1
1
0
0
2
0
2
10
13
2
9
7
2
2
5
3
2
1
2
0
2
142,622
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/common/sever_handler.py
JapaneseTokenizer.common.sever_handler.ProcessDownException
class ProcessDownException(Exception): pass
class ProcessDownException(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
142,623
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/datamodels.py
JapaneseTokenizer.datamodels.TokenizedResult
class TokenizedResult(object): def __init__(self, node_obj, tuple_pos, word_stem, word_surface, is_feature=True, is_surface=False, misc_info=None, analyzed_line=None): # type: (Optional[Node], Tuple[text_type, ...], str, str, bool, bool, Optional[Dict[str, Any]], str)->None assert isinstance(node_obj, (Node, type(None))) assert isinstance(tuple_pos, (string_types, tuple)) assert isinstance(word_stem, (string_types)) assert isinstance(word_surface, text_type) assert isinstance(misc_info, (type(None), dict)) self.node_obj = node_obj self.word_stem = word_stem self.word_surface = word_surface self.is_surface = is_surface self.is_feature = is_feature self.misc_info = misc_info self.analyzed_line = analyzed_line if isinstance(tuple_pos, tuple): self.tuple_pos = tuple_pos elif isinstance(tuple_pos, string_types): self.tuple_pos = ('*', ) else: raise Exception('Error while parsing feature object. {}'.format(tuple_pos))
class TokenizedResult(object): def __init__(self, node_obj, tuple_pos, word_stem, word_surface, is_feature=True, is_surface=False, misc_info=None, analyzed_line=None): pass
2
0
30
2
27
1
3
0.04
1
4
0
0
1
8
1
1
31
2
28
18
18
1
18
10
16
3
1
1
3
142,624
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/common/sever_handler.py
JapaneseTokenizer.common.sever_handler.UnixProcessHandler
class UnixProcessHandler(object): def __init__(self, command, option=None, pattern='EOS', timeout_second=10): # type: (text_type,text_type,text_type,int)->None """* Get communication with unix process using pexpect module.""" self.command = command self.timeout_second = timeout_second self.pattern = pattern self.option = option self.launch_process(command) def __del__(self): if hasattr(self, "process_analyzer"): self.process_analyzer.kill(sig=9) def launch_process(self, command): # type: (Union[bytes,text_type])->None """* What you can do - It starts process and keep it. """ if not self.option is None: command_plus_option = self.command + " " + self.option else: command_plus_option = self.command if six.PY3: if shutil.which(command) is None: raise Exception("No command at {}".format(command)) else: self.process_analyzer = pexpect.spawnu(command_plus_option) self.process_id = self.process_analyzer.pid else: doc_command_string = "echo '' | {}".format(command) command_check = os.system(doc_command_string) if not command_check == 0: raise Exception("No command at {}".format(command)) else: self.process_analyzer = pexpect.spawnu(command_plus_option) self.process_id = self.process_analyzer.pid def restart_process(self): # type: ()->None if not self.option is None: command_plus_option = self.command + " " + self.option else: command_plus_option = self.command self.process_analyzer.kill(sig=9) self.process_analyzer = pexpect.spawnu(command_plus_option) self.process_id = self.process_analyzer.pid def stop_process(self): # type: ()->bool """* What you can do - You're able to stop the process which this instance has now. """ if hasattr(self, "process_analyzer"): self.process_analyzer.kill(sig=9) else: pass return True def __query(self, input_string): # type: (text_type)->text_type """* What you can do - It takes the result of Juman++ - This function monitors time which takes for getting the result. """ signal.signal(signal.SIGALRM, self.__notify_handler) signal.alarm(self.timeout_second) self.process_analyzer.sendline(input_string) buffer = "" while True: line_string = self.process_analyzer.readline() # type: text_type if line_string.strip() == input_string: """Skip if process returns the same input string""" continue elif line_string.strip() == self.pattern: buffer += line_string signal.alarm(0) return buffer else: buffer += line_string def __notify_handler(self, signum, frame): raise ProcessDownException("""It takes longer time than {time} seconds. You're able to try, 1. Change your setting of 'timeout_second' parameter 2. Run restart_process() method when the exception happens.""".format(**{"time": self.timeout_second})) def query(self, input_string): # type: (text_type)->text_type return self.__query(input_string=input_string)
class UnixProcessHandler(object): def __init__(self, command, option=None, pattern='EOS', timeout_second=10): '''* Get communication with unix process using pexpect module.''' pass def __del__(self): pass def launch_process(self, command): '''* What you can do - It starts process and keep it. ''' pass def restart_process(self): pass def stop_process(self): '''* What you can do - You're able to stop the process which this instance has now. ''' pass def __query(self, input_string): '''* What you can do - It takes the result of Juman++ - This function monitors time which takes for getting the result. ''' pass def __notify_handler(self, signum, frame): pass def query(self, input_string): pass
9
4
11
0
8
2
2
0.28
1
2
1
1
8
6
8
8
96
10
68
25
55
19
54
21
45
5
1
2
18
142,625
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/kytea_wrapper/kytea_wrapper.py
JapaneseTokenizer.kytea_wrapper.kytea_wrapper.KyteaWrapper
class KyteaWrapper(WrapperBase): def __init__(self, option_string='-deftag UNKNOWN!!'): # type: (string_types)->None # option string is argument of Kytea. assert isinstance(option_string, string_types) self.kytea = Mykytea.Mykytea(option_string) def __list_tags(self, t): def convert(t2): return (t2[0], t2[1]) return [(word.surface, [[convert(t2) for t2 in t1] for t1 in word.tag]) for word in t] def __check_char_set(self, input_char): # type: (text_type) -> text_type if six.PY2 and isinstance(input_char, str): return input_char.decode('utf-8') elif isinstance(input_char, text_type): return input_char else: raise Exception('nor unicode, str') def __extract_morphological_information(self, kytea_tags_tuple, is_feature): # type: (Tuple[text_type,List[Any]], bool) -> TokenizedResult """This method extracts morphlogical information from token object. """ assert isinstance(kytea_tags_tuple, tuple) assert isinstance(is_feature, bool) surface = self.__check_char_set(kytea_tags_tuple[0]) # NOTE: kytea does NOT show word stem. Put blank string instead. if six.PY2: word_stem = ''.decode('utf-8') else: word_stem = '' pos_tuple = kytea_tags_tuple[1][0] pos = self.__check_char_set(pos_tuple[0][0]) pos_score = float(pos_tuple[0][1]) yomi_tuple = kytea_tags_tuple[1][1] yomi = self.__check_char_set(yomi_tuple[0][0]) yomi_score = float(yomi_tuple[0][1]) tuple_pos = (pos, ) misc_info = { 'pos_score': pos_score, 'pos': pos, 'yomi': yomi, 'yomi_score': yomi_score } token_object = TokenizedResult( node_obj=None, tuple_pos=tuple_pos, word_stem=word_stem, word_surface=surface, is_feature=is_feature, is_surface=True, misc_info=misc_info ) return token_object def call_kytea_tokenize_api(self, sentence): """ """ result = self.kytea.getTagsToString(sentence) assert isinstance(result, text_type) return result def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): # type: (text_type, bool, bool, bool, bool, Callable[[str],str]) -> Union[List[str], TokenizedSenetence] """This method returns tokenized result. If return_list==True(default), this method returns list whose element is tuple consisted with word_stem and POS. If return_list==False, this method returns TokenizedSenetence object. """ assert isinstance(normalize, bool) assert isinstance(sentence, text_type) normalized_sentence = func_normalizer(sentence) if six.PY2: normalized_sentence = normalized_sentence.encode('utf-8') result = self.__list_tags(self.kytea.getTags(normalized_sentence)) token_objects = [ self.__extract_morphological_information( kytea_tags_tuple=kytea_tags, is_feature=is_feature ) for kytea_tags in result] if return_list: tokenized_objects = TokenizedSenetence( sentence=sentence, tokenized_objects=token_objects ) return tokenized_objects.convert_list_object() else: tokenized_objects = TokenizedSenetence( sentence=sentence, tokenized_objects=token_objects) return tokenized_objects def filter(self, parsed_sentence, pos_condition=None, stopwords=None): assert isinstance(parsed_sentence, TokenizedSenetence) assert isinstance(pos_condition, (type(None), list)) assert isinstance(stopwords, (type(None), list)) return parsed_sentence.filter(pos_condition, stopwords, check_field_name='surface')
class KyteaWrapper(WrapperBase): def __init__(self, option_string='-deftag UNKNOWN!!'): pass def __list_tags(self, t): pass def convert(t2): pass def __check_char_set(self, input_char): pass def __extract_morphological_information(self, kytea_tags_tuple, is_feature): '''This method extracts morphlogical information from token object. ''' pass def call_kytea_tokenize_api(self, sentence): ''' ''' pass def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): '''This method returns tokenized result. If return_list==True(default), this method returns list whose element is tuple consisted with word_stem and POS. If return_list==False, this method returns TokenizedSenetence object. ''' pass def filter(self, parsed_sentence, pos_condition=None, stopwords=None): pass
9
3
14
2
11
2
2
0.17
1
9
2
0
7
1
7
9
117
19
84
32
70
14
52
26
43
3
2
1
13
142,626
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_jumanpp_wrapper_python2.py
test.test_jumanpp_wrapper_python2.TestJumanppWrapperPython2
class TestJumanppWrapperPython2(unittest.TestCase): def setUp(self): # this is under MacOSX10 self.path_to_juman_command = '/usr/local/bin/jumanpp' if not os.path.exists(self.path_to_juman_command): self.path_to_juman_command = 'jumanpp' def test_JumanppClient(self): test_sentence = u'外国人参政権を欲しい。' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = 'localhost' PORT = 12000 try: s.connect((HOST, PORT)) s.close() except: logger.warning("SKip server mode test because server is not working.") else: client_obj = JumanppClient(hostname='localhost', port=12000) res = client_obj.query(sentence=test_sentence, pattern=r'EOS') del res def test_jumanpp_servermode(self): ### test with list return object ### test_sentence = u'外国人参政権を欲しい。' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = 'localhost' PORT = 12000 try: s.connect((HOST, PORT)) s.close() except: logger.warning("SKip server mode test because server is not working.") else: jumanpp_tokenizer = JumanppWrapper(server='localhost', port=12000) list_tokens = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=True) assert isinstance(list_tokens, list) ### test with TokenizedSenetence return object ### tokenized_obj = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=False) assert isinstance(tokenized_obj, TokenizedSenetence) ### test with TokenizedSenetence return object and filter by chain expression ### pos_condtion = [('名詞', )] filtered_res = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=False).filter(pos_condition=pos_condtion) assert isinstance(filtered_res, FilteredObject) assert isinstance(filtered_res.convert_list_object(), list) def test_jumanpp_servermode_stress(self): ### test with severmode with much stress ### test_sentence = u'外国人参政権を欲しい。' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = 'localhost' PORT = 12000 try: s.connect((HOST, PORT)) s.close() except: logger.warning("SKip server mode test because server is not working.") else: jumanpp_tokenizer = JumanppWrapper(server='localhost', port=12000) for i in range(0, 1000): list_tokens = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=True) assert isinstance(list_tokens, list) assert u'外国' in test_sentence del jumanpp_tokenizer def test_jumanpp_localmode_pyexpect(self): test_sentence = u'外国人参政権を欲しい。' jumanpp_tokenizer = JumanppWrapper(command=self.path_to_juman_command, is_use_pyknp=False) self.assertTrue(isinstance(jumanpp_tokenizer.jumanpp_obj, JumanppHnadler)) list_tokens = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=True) assert isinstance(list_tokens, list) jumanpp_tokenizer = JumanppWrapper(command=self.path_to_juman_command, is_use_pyknp=False) self.assertTrue(isinstance(jumanpp_tokenizer.jumanpp_obj, JumanppHnadler)) tokenized_obj = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=False) assert isinstance(tokenized_obj, TokenizedSenetence) def test_jumanpp_huge_amount_text(self): """pexpectを利用した大量テキスト処理 & テキスト処理中のプロセス再起動""" logger.info('under testing of processing huge amount of text...') seq_test_sentence = [u'外国人参政権を欲しい。'] * 500 jumanpp_tokenizer = JumanppWrapper(is_use_pyknp=False, command=self.path_to_juman_command) self.assertTrue(isinstance(jumanpp_tokenizer.jumanpp_obj, JumanppHnadler)) for i, test_s in enumerate(seq_test_sentence): tokenized_obj = jumanpp_tokenizer.tokenize(sentence=test_s) self.assertTrue(isinstance(tokenized_obj, TokenizedSenetence)) if not i == 0 and i % 100 == 0: """強制的にプロセスを殺して再起動""" logger.info('It forces stop unix process.') jumanpp_tokenizer.jumanpp_obj.restart_process() else: pass
class TestJumanppWrapperPython2(unittest.TestCase): def setUp(self): pass def test_JumanppClient(self): pass def test_jumanpp_servermode(self): pass def test_jumanpp_servermode_stress(self): pass def test_jumanpp_localmode_pyexpect(self): pass def test_jumanpp_huge_amount_text(self): '''pexpectを利用した大量テキスト処理 & テキスト処理中のプロセス再起動''' pass
7
1
15
1
13
1
2
0.09
1
9
5
0
6
1
6
78
94
9
78
38
71
7
79
38
72
3
2
2
13
142,627
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_kytea_wrapper_python2.py
test.test_kytea_wrapper_python2.TestKyteaWrapperPython2
class TestKyteaWrapperPython2(unittest.TestCase): def setUp(self): pass def test_tokenization(self): input_sentence = u"紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" kytea_wrapper = KyteaWrapper() tokenized_result = kytea_wrapper.tokenize( sentence=input_sentence, normalize=True, return_list=False, is_feature=True ) assert isinstance(tokenized_result, TokenizedSenetence) for t_obj in tokenized_result.tokenized_objects: assert isinstance(t_obj, TokenizedResult) print('-'*30) tokenized_result_list = tokenized_result.convert_list_object() assert isinstance(tokenized_result_list, list) for t_obj_tuple in tokenized_result_list: assert isinstance(t_obj_tuple, tuple) def test_filter_pos(self): """ """ print (u'Filtering Test. POS condition is only 名詞') test_sentence = u"紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" kytea_wrapper = KyteaWrapper() tokenized_result = kytea_wrapper.tokenize( sentence=test_sentence, normalize=True, return_list=False, is_feature=True ) pos_condition = [(u'名詞', )] filtered_result = kytea_wrapper.filter( parsed_sentence=tokenized_result, pos_condition=pos_condition ) assert isinstance(filtered_result, FilteredObject) for t_obj in filtered_result.tokenized_objects: assert isinstance(t_obj, TokenizedResult) assert isinstance(t_obj.word_surface, unicode) assert isinstance(t_obj.word_stem, unicode) assert isinstance(t_obj.tuple_pos, tuple) assert isinstance(t_obj.misc_info, dict) assert t_obj.tuple_pos[0] == u'名詞' print('-'*30) for stem_posTuple in filtered_result.convert_list_object(): assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, unicode) assert isinstance(word_posTuple, tuple) def test_stopwords(self): stopword = [u'女優'] print (u'Stopwords Filtering Test. Stopwords is {}'.format(u','.join(stopword))) test_sentence = u"紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" kytea_wrapper = KyteaWrapper() token_objects = kytea_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True ) filtered_result = kytea_wrapper.filter( parsed_sentence=token_objects, stopwords=stopword ) check_flag = True print('-'*30) for stem_posTuple in filtered_result.convert_list_object(): assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, unicode) assert isinstance(word_posTuple, tuple) if word_stem in stopword: check_flag = False assert check_flag
class TestKyteaWrapperPython2(unittest.TestCase): def setUp(self): pass def test_tokenization(self): pass def test_filter_pos(self): ''' ''' pass def test_stopwords(self): pass
5
1
20
2
18
1
3
0.03
1
7
4
0
4
0
4
76
86
10
74
29
69
2
55
29
50
3
2
2
10
142,628
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_kytea_wrapper_python3.py
test.test_kytea_wrapper_python3.TestKyteaWrapperPython3
class TestKyteaWrapperPython3(unittest.TestCase): def setUp(self): pass def test_tokenization(self): input_sentence = "紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" kytea_wrapper = KyteaWrapper() tokenized_result = kytea_wrapper.tokenize( sentence=input_sentence, normalize=True, return_list=False, is_feature=True ) assert isinstance(tokenized_result, TokenizedSenetence) for t_obj in tokenized_result.tokenized_objects: assert isinstance(t_obj, TokenizedResult) #print('-'*30) tokenized_result_list = tokenized_result.convert_list_object() assert isinstance(tokenized_result_list, list) for t_obj_tuple in tokenized_result_list: assert isinstance(t_obj_tuple, tuple) def test_filter_pos(self): """ """ # 'Filtering Test. POS condition is only 名詞') test_sentence = "紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" kytea_wrapper = KyteaWrapper() tokenized_result = kytea_wrapper.tokenize( sentence=test_sentence, normalize=True, return_list=False, is_feature=True ) pos_condition = [('名詞', )] filtered_result = kytea_wrapper.filter( parsed_sentence=tokenized_result, pos_condition=pos_condition ) assert isinstance(filtered_result, FilteredObject) for t_obj in filtered_result.tokenized_objects: assert isinstance(t_obj, TokenizedResult) assert isinstance(t_obj.word_surface, str) assert isinstance(t_obj.word_stem, str) assert isinstance(t_obj.tuple_pos, tuple) assert isinstance(t_obj.misc_info, dict) assert t_obj.tuple_pos[0] == '名詞' for stem_posTuple in filtered_result.convert_list_object(): assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, str) assert isinstance(word_posTuple, tuple) def test_stopwords(self): stopword = ['女優'] # ('Stopwords Filtering Test. Stopwords is {}'.format(','.join(stopword))) test_sentence = "紗倉 まな(さくら まな、1993年3月23日 - )は、日本のAV女優。" kytea_wrapper = KyteaWrapper() token_objects = kytea_wrapper.tokenize(sentence=test_sentence, return_list=False, is_feature=True ) filtered_result = kytea_wrapper.filter( parsed_sentence=token_objects, stopwords=stopword ) check_flag = True for stem_posTuple in filtered_result.convert_list_object(): assert isinstance(stem_posTuple, tuple) word_stem = stem_posTuple[0] word_posTuple = stem_posTuple[1] assert isinstance(word_stem, str) assert isinstance(word_posTuple, tuple) if word_stem in stopword: check_flag = False assert check_flag
class TestKyteaWrapperPython3(unittest.TestCase): def setUp(self): pass def test_tokenization(self): pass def test_filter_pos(self): ''' ''' pass def test_stopwords(self): pass
5
1
19
1
17
1
3
0.07
1
8
4
0
4
0
4
76
82
9
68
29
63
5
50
29
45
3
2
2
10
142,629
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_mecab_wrapper_python2.py
test.test_mecab_wrapper_python2.TestMecabWrapperPython2
class TestMecabWrapperPython2(unittest.TestCase): def setUp(self): self.test_senetence = u'紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優。' self.test_sentence2 = u'午前零時。午前3時。3時。' self.path_user_dict = os.path.join(os.path.dirname(__file__), 'resources/test/userdict.csv') def test_neologd_parse(self): """* Test case - neologd辞書で正しく分割できることを確認する """ mecab_obj = MecabWrapper(dictType='neologd') parsed_obj = mecab_obj.tokenize(sentence=self.test_senetence) self.assertTrue(parsed_obj, TokenizedSenetence) self.assertTrue(isinstance(parsed_obj.convert_list_object(), list)) self.assertTrue(all(isinstance(mrph, string_types) for mrph in parsed_obj.convert_list_object())) parsed_obj = mecab_obj.tokenize(sentence=self.test_sentence2) self.assertTrue(parsed_obj, TokenizedSenetence) self.assertTrue(isinstance(parsed_obj.convert_list_object(), list)) self.assertTrue(all(isinstance(mrph, string_types) for mrph in parsed_obj.convert_list_object())) def test_default_parse(self): """* Test case - デフォルトの状態で動作を確認する """ dictType = "ipadic" mecab_obj = MecabWrapper(dictType=dictType) assert isinstance(mecab_obj, MecabWrapper) parsed_obj = mecab_obj.tokenize(sentence=self.test_senetence, return_list=True) assert isinstance(parsed_obj, list) if python_version >= (3, 0, 0): for morph in parsed_obj: assert isinstance(morph, str) else: for morph in parsed_obj: assert isinstance(morph, string_types) def test_init_userdict(self): # test when user dictionary is called mecab_obj = MecabWrapper(dictType='ipadic', pathUserDictCsv=self.path_user_dict) assert isinstance(mecab_obj, MecabWrapper) parsed_obj = mecab_obj.tokenize(sentence=self.test_senetence, return_list=True) is_ok = False for morph in parsed_obj: if u'さくらまな' == morph: is_ok = True else: pass assert is_ok def test_parse_jumandic(self): with self.assertRaises(Exception): mecab_obj = MecabWrapper(dictType='jumandic') assert isinstance(mecab_obj, MecabWrapper) def test_init_alldict(self): """* Test case - すべての辞書を利用した場合の動作を確認する """ with self.assertRaises(Exception): mecab_obj = MecabWrapper(dictType='all', pathUserDictCsv=self.path_user_dict) assert isinstance(mecab_obj, MecabWrapper)
class TestMecabWrapperPython2(unittest.TestCase): def setUp(self): pass def test_neologd_parse(self): '''* Test case - neologd辞書で正しく分割できることを確認する ''' pass def test_default_parse(self): '''* Test case - デフォルトの状態で動作を確認する ''' pass def test_init_userdict(self): pass def test_parse_jumandic(self): pass def test_init_alldict(self): '''* Test case - すべての辞書を利用した場合の動作を確認する ''' pass
7
3
9
0
8
2
2
0.22
1
5
2
0
6
3
6
78
62
6
46
22
39
10
45
22
38
4
2
2
11
142,630
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_mecab_wrapper_python3.py
test.test_mecab_wrapper_python3.TestMecabWrapperPython3
class TestMecabWrapperPython3(unittest.TestCase): def setUp(self): self.test_senetence = '紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優。' self.test_sentence2 = '午前零時。午前3時。3時。' self.path_user_dict = os.path.join(os.path.dirname(__file__), 'resources/test/userdict.csv') def test_neologd_parse(self): # test using neologd dictionary mecab_obj = MecabWrapper(dictType='neologd') parsed_obj = mecab_obj.tokenize(sentence=self.test_senetence) self.assertTrue(parsed_obj, TokenizedSenetence) self.assertTrue(isinstance(parsed_obj.convert_list_object(), list)) self.assertTrue(all(isinstance(mrph, str) for mrph in parsed_obj.convert_list_object())) parsed_obj = mecab_obj.tokenize(sentence=self.test_sentence2) self.assertTrue(parsed_obj, TokenizedSenetence) self.assertTrue(isinstance(parsed_obj.convert_list_object(), list)) self.assertTrue(all(isinstance(mrph, str) for mrph in parsed_obj.convert_list_object())) def test_default_parse(self): # test default status dictType = "ipadic" mecab_obj = MecabWrapper(dictType=dictType) assert isinstance(mecab_obj, MecabWrapper) parsed_obj = mecab_obj.tokenize(sentence=self.test_senetence, return_list=True) assert isinstance(parsed_obj, list) for morph in parsed_obj: assert isinstance(morph, str) parsed_obj = mecab_obj.tokenize(sentence=self.test_sentence2, return_list=True) assert isinstance(parsed_obj, list) for morph in parsed_obj: assert isinstance(morph, str) def test_parse_jumandic(self): mecab_obj = MecabWrapper(dictType='jumandic') assert isinstance(mecab_obj, MecabWrapper) parsed_obj = mecab_obj.tokenize(sentence=self.test_senetence, return_list=False) assert isinstance(parsed_obj, TokenizedSenetence) for tokenized_obj in parsed_obj.tokenized_objects: if tokenized_obj.word_stem == '女優': # ドメイン:文化・芸術 is special output only in Jumandic assert 'ドメイン:文化・芸術' in tokenized_obj.analyzed_line def test_parse_userdic(self): pass def test_parse_dictionary_path(self): # put path to dictionary and parse sentence. path_default_ipadic = '/usr/local/lib/mecab/dic/mecab-ipadic-neologd' if os.path.exists(path_default_ipadic): mecab_obj = MecabWrapper(dictType=None, path_dictionary=path_default_ipadic) assert mecab_obj._path_dictionary == path_default_ipadic parsed_obj = mecab_obj.tokenize(sentence=self.test_senetence, return_list=False) assert isinstance(parsed_obj, TokenizedSenetence) def test_init_userdict(self): # this test should be error response. mecab_obj = MecabWrapper(dictType='ipadic', pathUserDictCsv=self.path_user_dict) assert isinstance(mecab_obj, MecabWrapper) parsed_obj = mecab_obj.tokenize(sentence=self.test_senetence, return_list=False) assert isinstance(parsed_obj, TokenizedSenetence) is_ok = False for tokenized_obj in parsed_obj.tokenized_objects: if tokenized_obj.word_stem == 'さくらまな': is_ok = True assert is_ok
class TestMecabWrapperPython3(unittest.TestCase): def setUp(self): pass def test_neologd_parse(self): pass def test_default_parse(self): pass def test_parse_jumandic(self): pass def test_parse_userdic(self): pass def test_parse_dictionary_path(self): pass def test_init_userdict(self): pass
8
0
9
1
8
1
2
0.09
1
4
2
0
7
3
7
79
69
10
54
27
46
5
54
27
46
3
2
2
14
142,631
Kensuke-Mitsuzawa/JapaneseTokenizers
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/juman_wrapper/juman_wrapper.py
JapaneseTokenizer.juman_wrapper.juman_wrapper.MonkeyPatchSocket
class MonkeyPatchSocket(object): """* Class for overwriting pyknp.Socket because it is only for python2.x""" def __init__(self, hostname, port, option=None): try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((hostname, port)) except: raise if option is not None: self.sock.send(option) data = b"" while b"OK" not in data: # while isinstance(data, bytes) and b"OK" not in data: data = self.sock.recv(1024) def __del__(self): if self.sock: self.sock.close() def query(self, sentence, pattern): # type: (str,str)->str assert (isinstance(sentence, six.text_type)) sentence_bytes = sentence.encode('utf-8').strip() pattern_bytes = pattern.encode('utf-8') self.sock.sendall(sentence_bytes + b"\n") data = self.sock.recv(1024) assert isinstance(data, bytes) recv = data while not re.search(pattern_bytes, recv): data = self.sock.recv(1024) recv = recv + data return recv.strip().decode('utf-8')
class MonkeyPatchSocket(object): '''* Class for overwriting pyknp.Socket because it is only for python2.x''' def __init__(self, hostname, port, option=None): pass def __del__(self): pass def query(self, sentence, pattern): pass
4
1
10
0
9
1
3
0.11
1
2
0
0
3
1
3
3
33
3
27
10
23
3
27
10
23
4
1
1
8
142,632
Kensuke-Mitsuzawa/JapaneseTokenizers
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kensuke-Mitsuzawa_JapaneseTokenizers/JapaneseTokenizer/jumanpp_wrapper/jumanpp_wrapper.py
JapaneseTokenizer.jumanpp_wrapper.jumanpp_wrapper.JumanppWrapper
class JumanppWrapper(WrapperBase): """Class for Juman++""" def __init__(self, command='jumanpp', timeout=30, pattern=r'EOS', server=None, port=12000, is_use_pyknp=False, ** args): # type: (text_type,int,text_type,text_type,bool) """* What you can do - You can select backend process of jumanpp. - jumanpp-pexpect: It calls jumanpp on your local machine. It keeps jumanpp process running. - jumanpp-pyknp: It calls jumanpp on your local machine. It launches jumanpp process everytime you call. Thus, this is slower than jumanpp-pexpect - jumanpp-server: It calls jumannpp on somewhere else. Keep mind, you have jumanpp sever process somewhere. * Parameters - timeout: Time to wait from jumanpp process. - is_use_pyknp: bool flag to decide if you use pyknp as backend process. If True; you use pyknp. False; you use pexpect. pexpect is much faster than you use pyknp. You can not use pexpect if you're using it on Windowns - server: hostname where jumanpp is running - port: port number where jumanpp is running """ self.eos_pattern = pattern self.is_use_pyknp = is_use_pyknp if six.PY2: self.dummy_text = 'これはダミーテキストです'.decode('utf-8') elif six.PY3: self.dummy_text = 'これはダミーテキストです' if not server is None: pattern = pattern.encode('utf-8') else: pass if os.name == 'nt': """It forces to use pyknp if it runs on Windows.""" if not self.is_use_pyknp: logger.warning( msg="You're not able to use pexpect in Windows. It forced to set is_use_pyknp = True") else: pass self.is_use_pyknp = True else: pass if server is None and self.is_use_pyknp: # jumanpp-pexpect # logger.debug('jumanpp wrapper is initialized with pyknp package') self.jumanpp_obj = Juman( command=command, timeout=timeout, pattern=pattern, jumanpp=True, **args) elif server is None: # jumanpp-pexpect # logger.debug( 'jumanpp wrapper is initialized with pexpect unix handler') self.jumanpp_obj = JumanppHnadler( jumanpp_command=command, timeout_second=timeout, pattern=pattern) # type: JumanppHnadler # put dummy sentence to avoid exception just after command initialization # res = self.jumanpp_obj.query(self.dummy_text) else: # jumanpp-server # self.jumanpp_obj = JumanppClient( hostname=server, port=port, timeout=timeout) def __del__(self): if hasattr(self, "jumanpp_obj"): if isinstance(self.jumanpp_obj, JumanppClient): self.jumanpp_obj.sock.close() elif isinstance(self.jumanpp_obj, JumanppHnadler): self.jumanpp_obj.stop_process() else: del self.jumanpp_obj else: pass def call_juman_interface(self, input_str): # type: (text_type) -> MList """* What you can do - You call Juman tokenizer interface. * Output - pyknp.MList """ if isinstance(self.jumanpp_obj, Juman): ml_token_object = self.jumanpp_obj.analysis(input_str=input_str) elif isinstance(self.jumanpp_obj, JumanppHnadler): try: result_token = self.jumanpp_obj.query(input_string=input_str) except ProcessDownException: """Unix process is down by any reason.""" logger.warning( "Re-starting unix process because it takes longer time than {} seconds...".format(self.jumanpp_obj.timeout_second)) self.jumanpp_obj.restart_process() self.jumanpp_obj.query(self.dummy_text) result_token = self.jumanpp_obj.query(input_string=input_str) ml_token_object = MList(result_token) except UnicodeDecodeError: logger.warning( msg="Process is down by some reason. It restarts process automatically.") self.jumanpp_obj.restart_process() self.jumanpp_obj.query(self.dummy_text) result_token = self.jumanpp_obj.query(input_string=input_str) ml_token_object = MList(result_token) else: ml_token_object = MList(result_token) elif isinstance(self.jumanpp_obj, JumanppClient): server_response = self.jumanpp_obj.query( sentence=input_str, pattern=self.eos_pattern) ml_token_object = MList(server_response) else: raise Exception('Not defined') return ml_token_object @on_timeout(limit=60) def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): # type: (text_type, bool, bool, bool, bool, Callable[[text_type], text_type]) -> Union[TokenizedSenetence, List[text_type]] """* What you can do - """ if normalize: normalized_sentence = func_normalizer(sentence) else: normalized_sentence = sentence ml_token_object = self.call_juman_interface(normalized_sentence) token_objects = [ juman_utils.extract_morphological_information( mrph_object=morph_object, is_surface=is_surface, is_feature=is_feature ) for morph_object in ml_token_object] if return_list: tokenized_objects = TokenizedSenetence( sentence=sentence, tokenized_objects=token_objects) return tokenized_objects.convert_list_object() else: tokenized_objects = TokenizedSenetence( sentence=sentence, tokenized_objects=token_objects) return tokenized_objects def filter(self, parsed_sentence, pos_condition=None, stopwords=None): # type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type]) -> FilteredObject assert isinstance(parsed_sentence, TokenizedSenetence) assert isinstance(pos_condition, (type(None), list)) assert isinstance(stopwords, (type(None), list)) return parsed_sentence.filter(pos_condition, stopwords)
class JumanppWrapper(WrapperBase): '''Class for Juman++''' def __init__(self, command='jumanpp', timeout=30, pattern=r'EOS', server=None, port=12000, is_use_pyknp=False, ** args): '''* What you can do - You can select backend process of jumanpp. - jumanpp-pexpect: It calls jumanpp on your local machine. It keeps jumanpp process running. - jumanpp-pyknp: It calls jumanpp on your local machine. It launches jumanpp process everytime you call. Thus, this is slower than jumanpp-pexpect - jumanpp-server: It calls jumannpp on somewhere else. Keep mind, you have jumanpp sever process somewhere. * Parameters - timeout: Time to wait from jumanpp process. - is_use_pyknp: bool flag to decide if you use pyknp as backend process. If True; you use pyknp. False; you use pexpect. pexpect is much faster than you use pyknp. You can not use pexpect if you're using it on Windowns - server: hostname where jumanpp is running - port: port number where jumanpp is running ''' pass def __del__(self): pass def call_juman_interface(self, input_str): '''* What you can do - You call Juman tokenizer interface. * Output - pyknp.MList ''' pass @on_timeout(limit=60) def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): '''* What you can do - ''' pass def filter(self, parsed_sentence, pos_condition=None, stopwords=None): pass
7
4
30
2
22
6
4
0.29
1
8
4
0
5
4
5
7
159
17
111
31
92
32
69
18
63
8
2
2
22
142,633
Kensuke-Mitsuzawa/JapaneseTokenizers
Kensuke-Mitsuzawa_JapaneseTokenizers/test/test_jumanpp_wrapper_python3.py
test.test_jumanpp_wrapper_python3.TestJumanppWrapperPython3
class TestJumanppWrapperPython3(unittest.TestCase): def setUp(self): # this is under MacOSX10 self.path_to_juman_command = '/usr/local/bin/jumanpp' if not os.path.exists(self.path_to_juman_command): self.path_to_juman_command = 'jumanpp' def test_JumanppClient(self): test_sentence = '外国人参政権を欲しい。' # check socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = 'localhost' PORT = 12000 try: s.connect((HOST, PORT)) s.close() except: logger.warning("SKip server mode test because server is not working.") else: jumanpp_tokenizer = JumanppWrapper(server=HOST, port=PORT) client_obj = JumanppClient(hostname='localhost', port=12000) res = client_obj.query(sentence=test_sentence, pattern=rb'EOS') del res def test_jumanpp_servermode(self): ### test with list return object ### test_sentence = '外国人参政権を欲しい。' # check socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = 'localhost' PORT = 12000 try: s.connect((HOST, PORT)) s.close() except: logger.warning(msg='SKip server mode test because server is not working.') else: jumanpp_tokenizer = JumanppWrapper(server=HOST, port=PORT) list_tokens = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=True) assert isinstance(list_tokens, list) ### test with TokenizedSenetence return object ### tokenized_obj = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=False) assert isinstance(tokenized_obj, TokenizedSenetence) ### test with TokenizedSenetence return object and filter by chain expression ### pos_condtion = [('名詞',)] filtered_res = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=False).filter( pos_condition=pos_condtion) assert isinstance(filtered_res, FilteredObject) assert isinstance(filtered_res.convert_list_object(), list) def test_jumanpp_servermode_stress(self): ### test with severmode with much stress ### test_sentence = '外国人参政権を欲しい。' # check socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = 'localhost' PORT = 12000 try: s.connect((HOST, PORT)) s.close() except: logger.warning(msg='SKip server mode test because server is not working.') else: jumanpp_tokenizer = JumanppWrapper(server='localhost', port=12000) for i in range(0, 1000): list_tokens = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=True) assert isinstance(list_tokens, list) assert '外国' in test_sentence del jumanpp_tokenizer def test_jumanpp_localmode_pyexpect(self): """pexpectを使ったプロセス呼び出しのテスト""" test_sentence = '外国人参政権を欲しい。' jumanpp_tokenizer = JumanppWrapper(is_use_pyknp=False, command=self.path_to_juman_command) self.assertTrue(isinstance(jumanpp_tokenizer.jumanpp_obj, JumanppHnadler)) list_tokens = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=True) assert isinstance(list_tokens, list) jumanpp_tokenizer = JumanppWrapper(is_use_pyknp=False, command=self.path_to_juman_command) self.assertTrue(isinstance(jumanpp_tokenizer.jumanpp_obj, JumanppHnadler)) tokenized_obj = jumanpp_tokenizer.tokenize(sentence=test_sentence, return_list=False) assert isinstance(tokenized_obj, TokenizedSenetence) def test_jumanpp_huge_amount_text(self): """pexpectを利用した大量テキスト処理 & テキスト処理中のプロセス再起動""" logger.info('under testing of processing huge amount of text...') seq_test_sentence = ['外国人参政権を欲しい。'] * 500 jumanpp_tokenizer = JumanppWrapper(is_use_pyknp=False, command=self.path_to_juman_command) self.assertTrue(isinstance(jumanpp_tokenizer.jumanpp_obj, JumanppHnadler)) for i, test_s in enumerate(seq_test_sentence): tokenized_obj = jumanpp_tokenizer.tokenize(sentence=test_s) self.assertTrue(isinstance(tokenized_obj, TokenizedSenetence)) if not i == 0 and i % 100 == 0: """強制的にプロセスを殺して再起動""" logger.info('It forces stop unix process.') jumanpp_tokenizer.jumanpp_obj.restart_process() else: pass
class TestJumanppWrapperPython3(unittest.TestCase): def setUp(self): pass def test_JumanppClient(self): pass def test_jumanpp_servermode(self): pass def test_jumanpp_servermode_stress(self): pass def test_jumanpp_localmode_pyexpect(self): '''pexpectを使ったプロセス呼び出しのテスト''' pass def test_jumanpp_huge_amount_text(self): '''pexpectを利用した大量テキスト処理 & テキスト処理中のプロセス再起動''' pass
7
2
16
1
13
2
2
0.14
1
9
5
0
6
1
6
78
100
9
80
39
73
11
80
39
73
3
2
2
13
142,634
Kentzo/Power
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kentzo_Power/power/__init__.py
power.get_power_management_class.PowerManagement
class PowerManagement(PowerManagementPlatform): def __init__(self, *args, **kwargs): super(PowerManagement, self).__init__(*args, **kwargs) from power.common import PowerManagementNoop self._noop = PowerManagementNoop() def add_observer(self, observer): try: return super(PowerManagement, self).add_observer(observer) except: warnings.warn("{0}.add_observer raised:\n{1}".format( PowerManagementPlatform.__name__, traceback.format_exc()), category=RuntimeWarning) return self._noop.add_observer(observer) def remove_observer(self, observer): try: return super(PowerManagement, self).remove_observer(observer) except: warnings.warn("{0}.remove_observer raised:\n{1}".format( PowerManagementPlatform.__name__, traceback.format_exc()), category=RuntimeWarning) return self._noop.remove_observer(observer) def get_providing_power_source_type(self): try: return super(PowerManagement, self).get_providing_power_source_type() except: warnings.warn("{0}.get_providing_power_source_type raised:\n{1}".format( PowerManagementPlatform.__name__, traceback.format_exc()), category=RuntimeWarning) return self._noop.get_providing_power_source_type() def get_time_remaining_estimate(self): try: return super(PowerManagement, self).get_time_remaining_estimate() except: warnings.warn("{0}.get_time_remaining_estimate raised:\n{1}".format( PowerManagementPlatform.__name__, traceback.format_exc()), category=RuntimeWarning) return self._noop.get_time_remaining_estimate() def get_low_battery_warning_level(self): try: return super(PowerManagement, self).get_low_battery_warning_level() except: warnings.warn("{0}.get_low_battery_warning_level raised:\n{1}".format( PowerManagementPlatform.__name__, traceback.format_exc()), category=RuntimeWarning) return self._noop.get_low_battery_warning_level()
class PowerManagement(PowerManagementPlatform): def __init__(self, *args, **kwargs): pass def add_observer(self, observer): pass def remove_observer(self, observer): pass def get_providing_power_source_type(self): pass def get_time_remaining_estimate(self): pass def get_low_battery_warning_level(self): pass
7
0
6
0
6
0
2
0
1
3
1
0
6
1
6
6
41
6
35
9
27
0
35
9
27
2
1
1
11
142,635
Kentzo/Power
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kentzo_Power/power/darwin.py
power.darwin.PowerSourcesNotificationsObserver
class PowerSourcesNotificationsObserver(NSObject): """ Manages NSThread instance which is used to run NSRunLoop with only source - IOPSNotificationCreateRunLoopSource. Thread is automatically spawned when first observer is added and stopped when last observer is removed. Does not keep strong references to observers. @note: Method names break PEP8 convention to conform PyObjC naming conventions """ def init(self): self = objc.super(PowerSourcesNotificationsObserver, self).init() if self is not None: self._weak_observers = [] self._thread = None self._lock = objc.object_lock(self) return self def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarget_selector_object_( self, 'runPowerNotificationsThread', None) self._thread.start() def stopThread(self): """Stops spawned NSThread.""" if self._thread is not None: self.performSelector_onThread_withObject_waitUntilDone_( 'stopPowerNotificationsThread', self._thread, None, objc.YES) self._thread = None def runPowerNotificationsThread(self): """Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.""" pool = NSAutoreleasePool.alloc().init() @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_source_notification(context): with self._lock: for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource( on_power_source_notification, None) CFRunLoopAddSource(NSRunLoop.currentRunLoop( ).getCFRunLoop(), self._source, kCFRunLoopDefaultMode) while not NSThread.currentThread().isCancelled(): NSRunLoop.currentRunLoop().runMode_beforeDate_( NSDefaultRunLoopMode, NSDate.distantFuture()) del pool def stopPowerNotificationsThread(self): """Removes the only source from NSRunLoop and cancels thread.""" assert NSThread.currentThread() == self._thread CFRunLoopSourceInvalidate(self._source) self._source = None NSThread.currentThread().cancel() def addObserver_(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() """ with self._lock: self._weak_observers.append(weakref.ref(observer)) if len(self._weak_observers) == 1: self.startThread() def removeObserver_(self, observer): """ Removes an observer. @param observer: Previously added observer """ with self._lock: self._weak_observers.remove(weakref.ref(observer)) if len(self._weak_observers) == 0: self.stopThread()
class PowerSourcesNotificationsObserver(NSObject): ''' Manages NSThread instance which is used to run NSRunLoop with only source - IOPSNotificationCreateRunLoopSource. Thread is automatically spawned when first observer is added and stopped when last observer is removed. Does not keep strong references to observers. @note: Method names break PEP8 convention to conform PyObjC naming conventions ''' def init(self): pass def startThread(self): '''Spawns new NSThread to handle notifications.''' pass def stopThread(self): '''Stops spawned NSThread.''' pass def runPowerNotificationsThread(self): '''Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.''' pass @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_source_notification(context): pass def stopPowerNotificationsThread(self): '''Removes the only source from NSRunLoop and cancels thread.''' pass def addObserver_(self, observer): ''' Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() ''' pass def removeObserver_(self, observer): ''' Removes an observer. @param observer: Previously added observer ''' pass
10
7
9
1
6
2
2
0.39
1
1
0
0
7
4
7
7
76
12
46
17
36
18
45
16
36
3
1
3
16
142,636
Kentzo/Power
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kentzo_Power/power/darwin.py
power.darwin.PowerManagement
class PowerManagement(common.PowerManagementBase): notifications_observer = PowerSourcesNotificationsObserver.alloc().init() def __init__(self, cf_run_loop=None): """ @param cf_run_loop: If provided, all notifications are posted within this loop """ super(PowerManagement, self).__init__() self._cf_run_loop = cf_run_loop def on_power_source_notification(self): """ Called in response to IOPSNotificationCreateRunLoopSource() event. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_sources_change(self) observer.on_time_remaining_change(self) def get_providing_power_source_type(self): """ Uses IOPSCopyPowerSourcesInfo and IOPSGetProvidingPowerSourceType to get providing power source type. """ blob = IOPSCopyPowerSourcesInfo() type = IOPSGetProvidingPowerSourceType(blob) return POWER_TYPE_MAP[type] def get_low_battery_warning_level(self): """ Uses IOPSGetBatteryWarningLevel to get battery warning level. """ warning_level = IOPSGetBatteryWarningLevel() return WARNING_LEVEL_MAP[warning_level] def get_time_remaining_estimate(self): """ In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate. """ if IOPSGetTimeRemainingEstimate is not None: # Mac OS X 10.7+ estimate = float(IOPSGetTimeRemainingEstimate()) if estimate == -1.0: return common.TIME_REMAINING_UNKNOWN elif estimate == -2.0: return common.TIME_REMAINING_UNLIMITED else: return estimate / 60.0 else: # Mac OS X 10.6 warnings.warn( "IOPSGetTimeRemainingEstimate is not preset", RuntimeWarning) blob = IOPSCopyPowerSourcesInfo() type = IOPSGetProvidingPowerSourceType(blob) if type == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED else: estimate = 0.0 for source in IOPSCopyPowerSourcesList(blob): description = IOPSGetPowerSourceDescription(blob, source) if kIOPSIsPresentKey in description and description[kIOPSIsPresentKey] and kIOPSTimeToEmptyKey in description and description[kIOPSTimeToEmptyKey] > 0.0: estimate += float(description[kIOPSTimeToEmptyKey]) if estimate > 0.0: return float(estimate) else: return common.TIME_REMAINING_UNKNOWN def add_observer(self, observer): """ Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ """ super(PowerManagement, self).add_observer(observer) if len(self._weak_observers) == 1: if not self._cf_run_loop: PowerManagement.notifications_observer.addObserver_(self) else: @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_sources_change(context): self.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource( on_power_sources_change, None) CFRunLoopAddSource(self._cf_run_loop, self._source, kCFRunLoopDefaultMode) def remove_observer(self, observer): """ Stops thread and invalidates source. """ super(PowerManagement, self).remove_observer(observer) if len(self._weak_observers) == 0: if not self._cf_run_loop: PowerManagement.notifications_observer.removeObserver_(self) else: CFRunLoopSourceInvalidate(self._source) self._source = None
class PowerManagement(common.PowerManagementBase): def __init__(self, cf_run_loop=None): ''' @param cf_run_loop: If provided, all notifications are posted within this loop ''' pass def on_power_source_notification(self): ''' Called in response to IOPSNotificationCreateRunLoopSource() event. ''' pass def get_providing_power_source_type(self): ''' Uses IOPSCopyPowerSourcesInfo and IOPSGetProvidingPowerSourceType to get providing power source type. ''' pass def get_low_battery_warning_level(self): ''' Uses IOPSGetBatteryWarningLevel to get battery warning level. ''' pass def get_time_remaining_estimate(self): ''' In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate. ''' pass def add_observer(self, observer): ''' Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ ''' pass @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_sources_change(context): pass def remove_observer(self, observer): ''' Stops thread and invalidates source. ''' pass
10
7
12
0
8
4
3
0.48
1
3
0
0
7
2
7
14
99
9
62
23
52
30
54
22
45
8
2
4
21
142,637
Kentzo/Power
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kentzo_Power/power/win32.py
power.win32.SYSTEM_POWER_STATUS
class SYSTEM_POWER_STATUS(ctypes.Structure): _fields_ = [ ('ACLineStatus', ctypes.c_ubyte), ('BatteryFlag', ctypes.c_ubyte), ('BatteryLifePercent', ctypes.c_ubyte), ('Reserved1', ctypes.c_ubyte), ('BatteryLifeTime', wintypes.DWORD), ('BatteryFullLifeTime', wintypes.DWORD) ]
class SYSTEM_POWER_STATUS(ctypes.Structure): pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9
0
9
2
8
0
2
2
1
0
0
0
0
142,638
Kentzo/Power
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kentzo_Power/tests/test_common.py
tests.test_common.TestPowerManagementCommon.test_fallback_usage_error.PowerManagementFaulty
class PowerManagementFaulty(power.common.PowerManagementBase): def add_observer(self, observer): raise RuntimeError() def remove_observer(self, observer): raise RuntimeError() def get_providing_power_source_type(self): raise RuntimeError() def get_time_remaining_estimate(self): raise RuntimeError() def get_low_battery_warning_level(self): raise RuntimeError()
class PowerManagementFaulty(power.common.PowerManagementBase): def add_observer(self, observer): pass def remove_observer(self, observer): pass def get_providing_power_source_type(self): pass def get_time_remaining_estimate(self): pass def get_low_battery_warning_level(self): pass
6
0
2
0
2
0
1
0
1
1
0
0
5
0
5
12
15
4
11
6
5
0
11
6
5
1
2
0
5
142,639
Kentzo/Power
Kentzo_Power/power/freebsd.py
power.freebsd.PowerManagement
class PowerManagement(common.PowerManagementBase): @staticmethod def power_source_type(): """ FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported """ try: supply=int(subprocess.check_output(["sysctl","-n","hw.acpi.acline"])) except: return common.POWER_TYPE_AC if supply == 1: return common.POWER_TYPE_AC elif supply == 0: return common.POWER_TYPE_BATTERY else: raise RuntimeError("Unknown power source type!") @staticmethod def is_ac_online(): """ @return: True if ac is online. Otherwise False """ try: supply=int(subprocess.check_output(["sysctl","-n","hw.acpi.acline"])) except: return True return supply == 1 @staticmethod def is_battery_present(): """ TODO @return: True if battery is present. Otherwise False """ return False @staticmethod def is_battery_discharging(): """ TODO @return: True if ac is online. Otherwise False """ return False @staticmethod def get_battery_state(): """ TODO @return: Tuple (energy_full, energy_now, power_now) """ energy_now = float(100.0) power_now = float(100.0) energy_full = float(100.0) return energy_full, energy_now, power_now def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") return common.POWER_TYPE_AC def get_low_battery_warning_level(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. """ all_energy_full = [] all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.LOW_BATTERY_WARNING_NONE elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_full.append(energy_full) all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) try: total_percentage = sum(all_energy_full) / sum(all_energy_now) total_time = sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) if total_time <= 10.0: return common.LOW_BATTERY_WARNING_FINAL elif total_percentage <= 22.0: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE except ZeroDivisionError as e: warnings.warn("Unable to calculate low battery level: {0}".format(e), category=RuntimeWarning) return common.LOW_BATTERY_WARNING_NONE def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN def add_observer(self, observer): warnings.warn("Current system does not support observing.") pass def remove_observer(self, observer): warnings.warn("Current system does not support observing.") pass
class PowerManagement(common.PowerManagementBase): @staticmethod def power_source_type(): ''' FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported ''' pass @staticmethod def is_ac_online(): ''' @return: True if ac is online. Otherwise False ''' pass @staticmethod def is_battery_present(): ''' TODO @return: True if battery is present. Otherwise False ''' pass @staticmethod def is_battery_discharging(): ''' TODO @return: True if ac is online. Otherwise False ''' pass @staticmethod def get_battery_state(): ''' TODO @return: Tuple (energy_full, energy_now, power_now) ''' pass def get_providing_power_source_type(self): ''' Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. ''' pass def get_low_battery_warning_level(self): ''' Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. ''' pass def get_time_remaining_estimate(self): ''' Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. ''' pass def add_observer(self, observer): pass def remove_observer(self, observer): pass
16
8
14
0
10
4
3
0.34
1
6
0
0
5
0
10
17
162
21
105
35
89
36
89
28
78
9
2
3
33
142,640
Kentzo/Power
Kentzo_Power/power/linux.py
power.linux.PowerManagement
class PowerManagement(common.PowerManagementBase): @staticmethod def power_source_type(supply_path): """ @param supply_path: Path to power supply @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported """ with open(os.path.join(supply_path, 'type'), 'r') as type_file: type = type_file.readline().strip() if type == 'Mains': return common.POWER_TYPE_AC elif type == 'UPS': return common.POWER_TYPE_UPS elif type == 'Battery': return common.POWER_TYPE_BATTERY else: raise RuntimeError("Type of {path} ({type}) is not supported".format(path=supply_path, type=type)) @staticmethod def is_ac_online(supply_path): """ @param supply_path: Path to power supply @return: True if ac is online. Otherwise False """ with open(os.path.join(supply_path, 'online'), 'r') as online_file: return online_file.readline().strip() == '1' @staticmethod def is_battery_present(supply_path): """ @param supply_path: Path to power supply @return: True if battery is present. Otherwise False """ with open(os.path.join(supply_path, 'present'), 'r') as present_file: return present_file.readline().strip() == '1' @staticmethod def is_battery_discharging(supply_path): """ @param supply_path: Path to power supply @return: True if ac is online. Otherwise False """ with open(os.path.join(supply_path, 'status'), 'r') as status_file: return status_file.readline().strip() == 'Discharging' @staticmethod def get_battery_state(supply_path): """ @param supply_path: Path to power supply @return: Tuple (energy_full, energy_now, power_now) """ try: energy_now_file = open(os.path.join(supply_path, 'energy_now'), 'r') except IOError: energy_now_file = open(os.path.join(supply_path, 'charge_now'), 'r') try: energy_full_file = open(os.path.join(supply_path, 'energy_full'), 'r') except IOError: energy_full_file = open(os.path.join(supply_path, 'charge_full'), 'r') try: with open(os.path.join(supply_path, 'power_now'), 'r') as power_now_file: power_now = float(power_now_file.readline().strip()) except IOError: with open(os.path.join(supply_path, 'voltage_now'), 'r') as voltage_now_file: with open(os.path.join(supply_path, 'current_now'), 'r') as current_now_file: power_now = float(current_now_file.readline().strip()) * float(voltage_now_file.readline().strip()) / 10000000 with energy_now_file: with energy_full_file: energy_now = float(energy_now_file.readline().strip()) energy_full = float(energy_full_file.readline().strip()) return energy_full, energy_now, power_now def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) return common.POWER_TYPE_AC def get_low_battery_warning_level(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. """ all_energy_full = [] all_energy_now = [] all_power_now = [] for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.LOW_BATTERY_WARNING_NONE elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): energy_full, energy_now, power_now = self.get_battery_state(supply_path) all_energy_full.append(energy_full) all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) try: total_percentage = sum(all_energy_full) / sum(all_energy_now) total_time = sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) if total_time <= 10.0: return common.LOW_BATTERY_WARNING_FINAL elif total_percentage <= 22.0: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE except ZeroDivisionError as e: warnings.warn("Unable to calculate low battery level: {0}".format(e), category=RuntimeWarning) return common.LOW_BATTERY_WARNING_NONE def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_energy_not_discharging = [] all_power_now = [] for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): energy_full, energy_now, power_now = self.get_battery_state(supply_path) all_energy_now.append(energy_now) all_power_now.append(power_now) elif self.is_battery_present(supply_path) and not self.is_battery_discharging(supply_path): energy_now = self.get_battery_state(supply_path)[1] all_energy_not_discharging.append(energy_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)])\ + sum(all_energy_not_discharging) / (sum(all_power_now) / len(all_power_now)) * 60.0 except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN def add_observer(self, observer): warnings.warn("Current system does not support observing.") pass def remove_observer(self, observer): warnings.warn("Current system does not support observing.") pass
class PowerManagement(common.PowerManagementBase): @staticmethod def power_source_type(supply_path): ''' @param supply_path: Path to power supply @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported ''' pass @staticmethod def is_ac_online(supply_path): ''' @param supply_path: Path to power supply @return: True if ac is online. Otherwise False ''' pass @staticmethod def is_battery_present(supply_path): ''' @param supply_path: Path to power supply @return: True if battery is present. Otherwise False ''' pass @staticmethod def is_battery_discharging(supply_path): ''' @param supply_path: Path to power supply @return: True if ac is online. Otherwise False ''' pass @staticmethod def get_battery_state(supply_path): ''' @param supply_path: Path to power supply @return: Tuple (energy_full, energy_now, power_now) ''' pass def get_providing_power_source_type(self): ''' Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. ''' pass def get_low_battery_warning_level(self): ''' Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. ''' pass def get_time_remaining_estimate(self): ''' Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. ''' pass def add_observer(self, observer): pass def remove_observer(self, observer): pass
16
8
17
1
13
4
4
0.27
1
5
0
0
5
0
10
17
185
15
134
51
118
36
115
36
104
10
2
4
40
142,641
Kentzo/Power
Kentzo_Power/power/win32.py
power.win32.PowerManagement
class PowerManagement(common.PowerManagementBase): def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(ctypes.pointer(power_status)): raise ctypes.WinError() return POWER_TYPE_MAP[power_status.ACLineStatus] def get_low_battery_warning_level(self): """ Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(ctypes.pointer(power_status)): raise ctypes.WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.LOW_BATTERY_WARNING_NONE else: if power_status.BatteryLifeTime != -1 and power_status.BatteryLifeTime <= 600: return common.LOW_BATTERY_WARNING_FINAL elif power_status.BatteryLifePercent <= 22: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(ctypes.pointer(power_status)): raise ctypes.WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED elif power_status.BatteryLifeTime == -1: return common.TIME_REMAINING_UNKNOWN else: return float(power_status.BatteryLifeTime) / 60.0 def add_observer(self, observer): warnings.warn("Current system does not support observing.") pass def remove_observer(self, observer): warnings.warn("Current system does not support observing.") pass
class PowerManagement(common.PowerManagementBase): def get_providing_power_source_type(self): ''' Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. ''' pass def get_low_battery_warning_level(self): ''' Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures. ''' pass def get_time_remaining_estimate(self): ''' Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime ''' pass def add_observer(self, observer): pass def remove_observer(self, observer): pass
6
3
10
1
7
2
3
0.31
1
2
1
0
5
0
5
12
54
8
35
9
29
11
30
9
24
5
2
2
13
142,642
Kentzo/Power
Kentzo_Power/setup.py
setup.PyTest
class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to pytest")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = '' def run_tests(self): import shlex #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(shlex.split(self.pytest_args)) sys.exit(errno)
class PyTest(TestCommand): def initialize_options(self): pass def run_tests(self): pass
3
0
5
0
4
1
1
0.1
1
0
0
0
2
1
2
2
13
2
10
8
5
1
10
8
5
1
1
0
2
142,643
Kentzo/Power
Kentzo_Power/tests/observer.py
tests.observer.TestObserver
class TestObserver(power.PowerManagementObserver): def on_power_sources_change(self, power_management): print("on_power_sources_change") def on_time_remaining_change(self, power_management): print("on_time_remaining_change")
class TestObserver(power.PowerManagementObserver): def on_power_sources_change(self, power_management): pass def on_time_remaining_change(self, power_management): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
2
6
1
5
3
2
0
5
3
2
1
1
0
2
142,644
Kentzo/Power
Kentzo_Power/tests/test_common.py
tests.test_common.TestPowerManagementCommon
class TestPowerManagementCommon(unittest.TestCase): def test_get_low_battery_warningLevel(self): level = power.PowerManagement().get_low_battery_warning_level() self.assertIsNotNone(level) self.assertIsInstance(level, int) self.assertIn(level, [power.LOW_BATTERY_WARNING_NONE, power.LOW_BATTERY_WARNING_EARLY, power.LOW_BATTERY_WARNING_FINAL]) def test_get_remaining_estimate(self): estimate = power.PowerManagement().get_time_remaining_estimate() self.assertIsNotNone(estimate) self.assertIsInstance(estimate, float) self.assertTrue(estimate == power.TIME_REMAINING_UNKNOWN or estimate == power.TIME_REMAINING_UNLIMITED or estimate >= 0.0) def test_get_providing_power_source(self): type = power.PowerManagement().get_providing_power_source_type() self.assertIsNotNone(type) self.assertIsInstance(type, int) self.assertIn(type, [power.POWER_TYPE_AC, power.POWER_TYPE_BATTERY, power.POWER_TYPE_UPS]) def test_fallback_unsupported_platform(self): with mock.patch('sys.platform', 'planb'): self.assertEqual(power.get_power_management_class(), power.common.PowerManagementNoop) def test_fallback_importError(self): with mock.patch('power.get_platform_power_management_class', side_effect=RuntimeError): self.assertEqual(power.get_power_management_class(), power.common.PowerManagementNoop) def test_fallback_usage_error(self): class PowerManagementFaulty(power.common.PowerManagementBase): def add_observer(self, observer): raise RuntimeError() def remove_observer(self, observer): raise RuntimeError() def get_providing_power_source_type(self): raise RuntimeError() def get_time_remaining_estimate(self): raise RuntimeError() def get_low_battery_warning_level(self): raise RuntimeError() with mock.patch('power.get_platform_power_management_class', return_value=PowerManagementFaulty): c = power.get_power_management_class() self.assertTrue(issubclass(c, PowerManagementFaulty)) with self.assertWarns(RuntimeWarning): pm = c() self.assertEqual(pm.get_providing_power_source_type(), power.POWER_TYPE_AC)
class TestPowerManagementCommon(unittest.TestCase): def test_get_low_battery_warningLevel(self): pass def test_get_remaining_estimate(self): pass def test_get_providing_power_source(self): pass def test_fallback_unsupported_platform(self): pass def test_fallback_importError(self): pass def test_fallback_usage_error(self): pass class PowerManagementFaulty(power.common.PowerManagementBase): def add_observer(self, observer): pass def remove_observer(self, observer): pass def get_providing_power_source_type(self): pass def get_time_remaining_estimate(self): pass def get_low_battery_warning_level(self): pass
13
0
5
1
4
0
1
0
1
6
2
0
6
0
6
78
51
11
40
18
27
0
40
18
27
1
2
2
11
142,645
Kentzo/Power
Kentzo_Power/power/common.py
power.common.PowerManagementNoop
class PowerManagementNoop(PowerManagementBase): """ No-op subclass of PowerManagement. It operates like AC is always attached and power sources are never changed. """ def get_providing_power_source_type(self): """ @return: Always POWER_TYPE_AC """ return POWER_TYPE_AC def get_low_battery_warning_level(self): """ @return: Always LOW_BATTERY_WARNING_NONE """ return LOW_BATTERY_WARNING_NONE def get_time_remaining_estimate(self): """ @return: Always TIME_REMAINING_UNLIMITED """ return TIME_REMAINING_UNLIMITED def add_observer(self, observer): """ Does nothing. """ pass def remove_observer(self, observer): """ Does nothing. """ pass def remove_all_observers(self): """ Does nothing. """ pass
class PowerManagementNoop(PowerManagementBase): ''' No-op subclass of PowerManagement. It operates like AC is always attached and power sources are never changed. ''' def get_providing_power_source_type(self): ''' @return: Always POWER_TYPE_AC ''' pass def get_low_battery_warning_level(self): ''' @return: Always LOW_BATTERY_WARNING_NONE ''' pass def get_time_remaining_estimate(self): ''' @return: Always TIME_REMAINING_UNLIMITED ''' pass def add_observer(self, observer): ''' Does nothing. ''' pass def remove_observer(self, observer): ''' Does nothing. ''' pass def remove_all_observers(self): ''' Does nothing. ''' pass
7
7
5
0
2
3
1
1.69
1
0
0
0
6
0
6
13
40
5
13
7
6
22
13
7
6
1
2
0
6
142,646
Kentzo/git-archive-all
Kentzo_git-archive-all/test_git_archive_all.py
test_git_archive_all.Record
class Record: def __init__(self, kind, contents, excluded=False): self.kind = kind self.contents = contents self.excluded = excluded def __getitem__(self, item): return self.contents[item] def __setitem__(self, key, value): self.contents[key] = value
class Record: def __init__(self, kind, contents, excluded=False): pass def __getitem__(self, item): pass def __setitem__(self, key, value): pass
4
0
3
0
3
0
1
0
0
0
0
0
3
3
3
3
11
2
9
7
5
0
9
7
5
1
0
0
3
142,647
Kentzo/git-archive-all
Kentzo_git-archive-all/setup.py
setup.PyTest
class PyTest(TestCommand): user_options = [("pytest-args=", "a", "Arguments to pass to pytest")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = "" def run_tests(self): import shlex # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(shlex.split(self.pytest_args)) sys.exit(errno)
class PyTest(TestCommand): def initialize_options(self): pass def run_tests(self): pass
3
0
6
1
4
1
1
0.1
1
0
0
0
2
1
2
2
15
4
10
8
5
1
10
8
5
1
1
0
2