id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
11,600
__init__.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/filesystem_notifications/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import sys try: if sys.platform == 'win32': from ninja_ide.core.file_handling.filesystem_notifications import windows source = windows elif sys.platform == 'darwin': from ninja_ide.core.file_handling.filesystem_notifications import darwin source = darwin elif sys.platform.startswith("linux"): from ninja_ide.core.file_handling.filesystem_notifications import linux source = linux else: # Aything we do not have a clue how to handle from ninja_ide.core.file_handling.filesystem_notifications import openbsd source = openbsd except BaseException: from ninja_ide.core.file_handling.filesystem_notifications import openbsd source = openbsd NinjaFileSystemWatcher = source.NinjaFileSystemWatcher()
1,526
Python
.py
36
38.583333
81
0.748148
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,601
base_watcher.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/filesystem_notifications/base_watcher.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. # import os from PyQt4.QtCore import QObject from PyQt4.QtCore import SIGNAL, QThread from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.core.file_handling.filesystem_notifications.Watcher') DEBUG = logger.debug ADDED = 1 MODIFIED = 2 DELETED = 3 RENAME = 4 REMOVE = 5 def do_stat(file_path): status = None try: status = os.stat(file_path) except OSError: pass return status class SingleFileWatcher(QThread): def __init__(self, callback): self._watches = dict() self._do_run = True self._emit_call = callback super(SingleFileWatcher, self).__init__() def stop_running(self): self._do_run = False def add_watch(self, file_to_watch): status = do_stat(file_to_watch) # only add if the file still exists if (file_to_watch not in self._watches) and status: self._watches[file_to_watch] = do_stat(file_to_watch) elif not status: self._emit_call(DELETED, file_to_watch) def is_empty(self): return len(self._watches) == 0 def del_watch(self, file_to_unwatch): if file_to_unwatch in self._watches: self._watches.pop(file_to_unwatch) def tick(self): keys = list(self._watches.keys()) for each_file in keys: status = do_stat(each_file) if not status: self._emit_call(DELETED, each_file) self.del_watch(each_file) if status.st_mtime > self._watches[each_file].st_mtime: self._emit_call(MODIFIED, each_file) self._watches[each_file] = status def run(self): while self._do_run: self.tick() QThread.msleep(1000) self.deleteLater() class BaseWatcher(QObject): ############################################################################### # SIGNALS # ############################################################################### def __init__(self): super(BaseWatcher, self).__init__() self._single_file_watcher = None self.allow_kill = True def add_file_watch(self, file_path): if not self._single_file_watcher: self._single_file_watcher = \ SingleFileWatcher(self._emit_signal_on_change) self.connect(self._single_file_watcher, SIGNAL("destroyed(QObject*)"), self.on_destroy) self._single_file_watcher.start() self._single_file_watcher.add_watch(file_path) def remove_file_watch(self, file_path): if self._single_file_watcher: self._single_file_watcher.del_watch(file_path) if self._single_file_watcher.is_empty() and self.allow_kill: self._single_file_watcher.stop_running() self._single_file_watcher.quit() def on_destroy(self): self._single_file_watcher.wait() self._single_file_watcher = None def shutdown_notification(self): if hasattr(self, "_single_file_watcher") and self._single_file_watcher: self._single_file_watcher.stop_running() self._single_file_watcher.quit() def _emit_signal_on_change(self, event, path): DEBUG("About to emit the signal" + repr(event))
4,017
Python
.py
101
32.455446
85
0.616431
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,602
darwin.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/filesystem_notifications/darwin.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from ninja_ide.core.file_handling.filesystem_notifications import base_watcher from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.core.file_handling.filesystem_notifications.darwin') DEBUG = logger.debug ADDED = base_watcher.ADDED DELETED = base_watcher.DELETED REMOVE = base_watcher.REMOVE RENAME = base_watcher.RENAME MODIFIED = base_watcher.MODIFIED class NinjaFileSystemWatcher(base_watcher.BaseWatcher): def __init__(self): super(NinjaFileSystemWatcher, self).__init__() # self.event_mapping = { # fsevents.IN_CREATE: ADDED, # fsevents.IN_MODIFY: MODIFIED, # fsevents.IN_DELETE: DELETED, # fsevents.IN_MOVED_FROM: REMOVE, # fsevents.IN_MOVED_TO: ADDED} def shutdown_notification(self): pass # except: def add_watch(self, path): pass # stream = fsevents.Stream(self._emit_signal_on_change, # path, file_events=True) def remove_watch(self, path): pass # except: def _emit_signal_on_change(self, event): pass
1,821
Python
.py
47
34.531915
84
0.719796
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,603
openbsd.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/filesystem_notifications/openbsd.py
# -*- coding: utf-8 *-* from ninja_ide.core.file_handling.filesystem_notifications import base_watcher from PyQt4.QtCore import SIGNAL class NinjaFileSystemWatcher(base_watcher.BaseWatcher): def __init__(self): self.watching_paths = {} super(NinjaFileSystemWatcher, self).__init__() self._ignore_hidden = ('.git', '.hg', '.svn', '.bzr') def add_watch(self, path): pass def remove_watch(self, path): pass def shutdown_notification(self): base_watcher.BaseWatcher.shutdown_notification(self) def _emit_signal_on_change(self, event, path): self.emit(SIGNAL("fileChanged(int, QString)"), event, path)
680
Python
.py
16
36.3125
78
0.675799
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,604
plugins_manager.py
ninja-ide_ninja-ide/ninja_ide/core/encapsulated_env/plugins_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtCore import QObject from ninja_ide.gui.ide import IDE class PluginsManager(QObject): def __init__(self): super(PluginsManager, self).__init__() def get_activated_plugins(self): qsettings = IDE.ninja_settings() return qsettings.value('plugins/registry/activated', []) def get_failstate_plugins(self): qsettings = IDE.ninja_settings() return qsettings.value('plugins/registry/failure', []) def get_to_activate_plugins(self): qsettings = IDE.ninja_settings() return qsettings.value('plugins/registry/toactivate', []) def set_to_activate_plugins(self, to_activate): qsettings = IDE.ninja_settings() qsettings.setValue('plugins/registry/toactivate', to_activate) def set_activated_plugins(self, activated): qsettings = IDE.ninja_settings() qsettings.setValue('plugins/registry/activated', activated) def set_failstate_plugins(self, failure): qsettings = IDE.ninja_settings() qsettings.setValue('plugins/registry/failure', failure) def activate_plugin(self, plugin): """ Receives PluginMetadata instance and activates its given plugin BEWARE: We do not do any kind of checking about if the plugin is actually installed. """ plugin_name = plugin.name to_activate = self.get_to_activate_plugins() to_activate.append(plugin_name) self.set_to_activate_plugins(to_activate) self.__activate_plugin(plugin, plugin_name) def load_all_plugins(self): to_activate = self.get_to_activate_plugins() for each_plugin in to_activate: self.__activate_plugin(__import__(each_plugin), each_plugin) def __activate_plugin(self, plugin, plugin_name): """ Receives the actual plugin module and tries activate or marks as failure """ activated = self.get_activated_plugins() failure = self.get_failstate_plugins() try: plugin.activate() except Exception: # This plugin can no longer be activated if plugin_name in activated: activated.remove(plugin_name) if plugin_name not in failure: failure.append(plugin_name) else: activated.append(plugin_name) if plugin_name in failure: failure.remove(plugin_name) finally: self.set_activated_plugins(activated) self.set_failstate_plugins(failure)
3,254
Python
.py
76
35.355263
72
0.673095
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,605
nenvironment.py
ninja-ide_ninja-ide/ninja_ide/core/encapsulated_env/nenvironment.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. ############################################################################### # Virtualenv bootstraping ############################################################################### from PyQt4.QtCore import QObject, SIGNAL, QThread from pip import main as pipmain from ninja_ide.resources import HOME_NINJA_PATH import os import sys from virtualenv import create_environment # This is here only for reference purposes # def create_environment(home_dir, site_packages=False, clear=False, # prompt=None, search_dirs=None, never_download=False, from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.core.encapsulated_env.nenvironement') # FIXME: Nothing is being printed, idk why DEBUG = logger.debug def debug(x): print(x) DEBUG = debug NINJA_ENV_NAME = "venv" NINJA_ENV = os.path.join(HOME_NINJA_PATH, NINJA_ENV_NAME) NINJA_ENV_BIN = os.path.join(NINJA_ENV, "bin") if not os.path.isdir(NINJA_ENV): create_environment(NINJA_ENV) if not os.path.isdir(NINJA_ENV_BIN): NINJA_ENV_BIN = os.path.join(NINJA_ENV, "Scripts") NINJA_ENV_ACTIVATE = os.path.join(NINJA_ENV_BIN, "activate_this.py") exec(compile(open(NINJA_ENV_ACTIVATE).read(), NINJA_ENV_ACTIVATE, 'exec'), dict(__file__=NINJA_ENV_ACTIVATE)) ############################################################################### try: from pip.backwardcompat import xmlrpclib except BaseException: if sys.version_info[0] >= 3: import xmlrpc else: import xmlrpclib try: from pip.util import get_installed_distributions except BaseException: from pip.utils import get_installed_distributions PLUGIN_QUERY = {"keywords": "ninja_ide plugin"} class AsyncRunner(QThread): """ Run in a QThread the given callable. SIGNALS: @threadEnded() @threadFailed(const QString&) @threadFinished(PyQt_PyObject) """ def __init__(self, runable): self.__runable = runable self.__args = [] self.__kwargs = {} self.__finished = False self.__iserror = False self.__errmsg = "" super(AsyncRunner, self).__init__() self.connect(self, SIGNAL("threadEnded()"), self._success_finish) self.connect(self, SIGNAL("threadFailed(const QString&)"), self._fail_finish) def _success_finish(self): self.__finished = True self.wait() self.emit(SIGNAL("threadFinished(PyQt_PyObject)"), self.status) def _fail_finish(self, errmsg): self.__finished = True self.__iserror = True self.__errmsg = errmsg self.wait() self.emit(SIGNAL("threadFinished(PyQt_PyObject)"), self.status) def status(self): """ Return status of running process. finished: this indicates if running or not, no result info exit_state: 0 success, 1 error exit_msg: only populated on error """ return {"finished": self.__finished, "exit_state": self.__iserror, "exit_msg": self.__errmsg} def __call__(self, *args, **kwargs): """ Usually called as a decorator, it is interesting to return a reference to this runner so the caller can check on status or at least subscribe """ self.__args = args self.__kwargs = kwargs self.start() return self def run(self): try: self.__runable(*self.__args, **self.__kwargs) self.emit(SIGNAL("threadEnded()")) except Exception as e: if hasattr(e, "message"): errmsg = e.message else: # Python 3 errmsg = str(e) self.emit(SIGNAL("threadFailed(QString)"), errmsg) def make_async(func): """Decorate methods to be run as Qthreads""" def make_me_async(*args, **kwargs): async_func = AsyncRunner(func) async_func(*args, **kwargs) return async_func return make_me_async class NenvEggSearcher(QObject): """ SIGNALS: @searchTriggered() @searchCompleted(PyQt_PyObject) """ def __init__(self): super(NenvEggSearcher, self).__init__() self.search_url = "https://pypi.python.org/pypi" self.__pypi = None @property def pypi(self): """I want to delay doing this, since might not be necessary""" if self.__pypi is None: self.__pypi = xmlrpclib.ServerProxy(self.search_url) return self.__pypi @make_async def do_search(self): self.emit(SIGNAL("searchTriggered()")) plugins_found = self.pypi.search(PLUGIN_QUERY, "and") self.emit(SIGNAL("searchCompleted(PyQt_PyObject)"), self.__iterate_results(plugins_found)) def __iterate_results(self, result_list): for each_plugin in result_list: yield PluginMetadata.from_result(each_plugin, self.pypi) def export_env(self): """ This should wrap pip freeze in the future iterates over pip installed packages, local and not local returns tuples version, name """ for each_distribution in get_installed_distributions(): yield each_distribution.version, each_distribution.key class PluginMetadata(QObject): """ Hold all available metadata for a given plugin, default instance is created by from_result factory which returns a shallow instance, only holding the data from a result (name, summary, version). To obtain full data call inflate. SIGNALS: @willInflatePluginMetadata() @pluginMetadataInflated() @pluginInstalled(PyQt_PyObject) """ @classmethod def from_result(cls, r, pypi): return cls(name=r["name"], summary=r["summary"], version=r["version"], pypi=pypi) def __init__(self, name, summary, version, pypi, shallow=True, **kwargs): # shallow attributes self.name = name self.summary = summary self.version = version self.pypi = pypi # Set manually to bind in the ui after inflate self.identifier = 0 # Inflated attributes (zeroed, declared here just for doc purposes) self.stable_version = "" self.author = "" # used by store self.author_email = "" # used by store self.maintainer = "" self.maintainer_email = "" self.home_page = "" # used by store self.license = "" # used by store self.description = "" # used by store self.keywords = "" # used by store self.platform = "" self.download_url = "" # used by store # (list of classifier strings) self.classifiers = [] # used by store self.requires = "" self.requires_dist = "" self.provides = "" self.provides_dist = "" self.requires_external = "" self.requires_python = "" self.obsoletes = "" self.obsoletes_dist = "" self.project_url = "" # (URL of the packages.python.org docs if they've been supplied) self.docs_url = "" # internal attributes self.shallow = shallow super(PluginMetadata, self).__init__() if kwargs: for each_kwarg, each_value in kwargs: setattr(self, each_kwarg, each_value) self.shallow = False def activate(self): imported_plugin = __import__(self.name) imported_plugin.activate() @make_async def inflate(self): """ Fill extra attributes of a shallow object """ if self.shallow: self.emit(SIGNAL("willInflatePluginMetadata()")) rdata = self.pypi.release_data(self.name, self.version) for each_arg, each_value in rdata.items(): setattr(self, each_arg, each_value) self.emit(SIGNAL("pluginMetadataInflated(PyQt_PyObject)"), self) self.shallow = False @make_async def install(self): """ Install this package in the current env. We always specify the version, we cant be sure we are the latest one or that the user wants to install any other available. """ pkg_string = "%s==%s" % (self.name, self.version) pipmain(["install", "-q", pkg_string]) self.emit(SIGNAL("pluginInstalled(PyQt_PyObject)"), self) @make_async def reinstall(self): pipmain(["install", "-q", "--force-reinstall", self.name]) self.emit(SIGNAL("pluginInstalled(PyQt_PyObject)"), self) @make_async def upgrade(self): pipmain(["install", "-q", "--ugprade", self.name]) self.emit(SIGNAL("pluginInstalled(PyQt_PyObject)"), self) @make_async def remove(self): pipmain(["uninstall", "-q", "-y", self.name]) class BasePlugin(QObject): """ A base from which every plugin should inherit """ def __init__(self, name): super(BasePlugin, self).__init__() def activate(self): pass # This is how the directory structure should look """ ninja_ide/ __init__.py contrib/ __init__.py plugins/ __init__.py yourpluginname/ __init__.py yourcode.py """
10,023
Python
.py
269
30.02974
79
0.612744
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,606
ntemplate_registry.py
ninja-ide_ninja-ide/ninja_ide/core/template_registry/ntemplate_registry.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os from PyQt5.QtCore import QObject from ninja_ide.gui.ide import IDE class ConflictingTypeForCategory(Exception): def __init__(self, project_type, category): self.__project_type = project_type self.__category = category super(ConflictingTypeForCategory, self).__init__() def __repr__(self): return "%s already has a type %s" % (self.__project_type, self.__category) def message(self): return repr(self) class NTemplateRegistry(QObject): """ Hold refere """ def __init__(self): self.__project_types = {} self.__types_by_category = {} super(NTemplateRegistry, self).__init__() IDE.register_service("template_registry", self) def register_project_type(self, project_type): if project_type.compound_name() in self.__project_types.keys(): raise ConflictingTypeForCategory( project_type.type_name, project_type.category ) else: self.__project_types[project_type.compound_name()] = project_type # This is here mostly for convenience self.__types_by_category.setdefault( project_type.category, []).append(project_type) def list_project_types(self): return self.__project_types.keys() def list_project_categories(self): return self.__types_by_category.keys() def list_templates_for_cateogory(self, category): return self.__types_by_category.get(category, []) def get_project_type(self, project_type): return self.__project_types.get(project_type, None) @classmethod def create_compound_name(cls, type_name, category): return "%s_%s" % (type_name, category) class BaseProjectType(QObject): """ Any Project type defined should inherit from this. The only mandatory method is create_layout """ type_name = "No Type" layout_version = "0.0" category = "No Category" encoding_string = {} single_line_comment = {} description = "No Description" def __init__(self, name, path, licence_text, licence_short_name="GPLv3", base_encoding="utf-8"): self.name = name self.path = path self.base_encoding = base_encoding self.licence_short_name = licence_short_name self.licence_text = licence_text super(BaseProjectType, self).__init__() @classmethod def compound_name(cls): return NTemplateRegistry.create_compound_name( cls.type_name, cls.category) @classmethod def register(cls): """ Just a convenience method that registers a given type """ tr = IDE.get_service("template_registry") try: tr.register_project_type(cls) except ConflictingTypeForCategory: pass finally: return tr.get_project_type(cls.compound_name()) def _create_path(self, path=None): path = path if path else self.path full_path = os.path.expanduser(path) split_path = full_path.split(os.path.sep) full_path = "" for each_folder in split_path: if each_folder: full_path += each_folder + "/" else: full_path += "/" if not os.path.exists(full_path): os.mkdir(full_path) @classmethod def wizard_pages(cls): """Return the pages to be displayed in the wizard.""" raise NotImplementedError("%s lacks wizard_pages" % cls.__name__) @classmethod def from_dict(cls, results): """Create an instance from this project type using the wizard result""" raise NotImplementedError("%s lacks from_dict" % cls.__name__) def get_file_extension(self, filename): _, extension = os.path.splitext(filename) return extension[1:] def init_file(self, fd, filepath): """ Adds encoding line and licence if possible """ ext = self.get_file_extension(filepath) if self.base_encoding and (ext in self.encoding_string): fd.write(self.encoding_string[ext] % self.base_encoding + '\n') if self.licence_text and (ext in self.single_line_comment): for each_line in self.licence_text.splitlines(): fd.write(self.single_line_comment[ext] + each_line + '\n') def _create_file(self, path, content): with open(path, "w") as writable: self.init_file(writable, path) writable.write(content) def create_layout(self, wizard): """ Create set of folders and files required for this project bootstrap """ raise NotImplementedError("%s lacks create_layout" % self.__class__.__name__) def update_layout(self): """ If you must (notice the version attribute) you can update a given project environment. You should save versions somehow in said project """ pass def get_project_api(self): """ Here we expect you to return a QMenu with wathever you need inside. Bare in mind that we will add this to the context menu on the project tree but we might use it elsewere, not guaranteed. """ pass def get_project_file_api(self): """ This is exactly the same as 'get_project_api' but for files. You should return a tuple containing: (evaluate_pertinence_function, QMenu) Where evaluate_pertinence is a function that will receive the file path and return True/False if the QMenu is apt for said file. """ pass def get_project_wizard_pages(self): pass def wizard_callback(self): pass def _open_project(self, path): """Open Project based on path into Explorer""" projects_explorer = IDE.get_service("projects_explorer") projects_explorer.open_project_folder(path) template_registry = NTemplateRegistry()
6,884
Python
.py
172
31.47093
79
0.626555
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,607
bundled_project_types.py
ninja-ide_ninja-ide/ninja_ide/core/template_registry/bundled_project_types.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os from ninja_ide.core.template_registry.ntemplate_registry import BaseProjectType SETUP_PY_FILE = """ # BEWARE: This is a minimal version you will most likely need to extend it from setuptools import setup, find_packages setup( name='%s', version='1.0', packages=find_packages(), )""" BASIC_HELLO = """ # This is a sample yet useful program, for python 3 def hello_world(): print("hello world, this is %s's main") """ class PythonVenvProject(BaseProjectType): type_name = "Basic Python Project with Venv" layout_version = "0.1" category = "Python" class PythonProject(BaseProjectType): type_name = "Basic Python Project" layout_version = "0.1" category = "Python" encoding_string = {"py": "# -*- coding: %s -*-"} single_line_comment = {"py": "# "} description = \ """A plugin that creates the layout for a basic python project """ def __init__(self, *args, **kwargs): super(PythonProject, self).__init__(*args, **kwargs) def create_layout(self): """ Create set of folders and files required for a basic python project """ full_path = os.path.expanduser(self.path) split_path = full_path.split(os.path.sep) full_path = "" for each_folder in split_path: if each_folder: full_path += each_folder + "/" else: full_path += "/" if not os.path.exists(full_path): os.mkdir(full_path) # Create a single init file filepath = os.path.join(self.path, "__init__.py") with open(filepath, "w") as base_init: self.init_file(base_init, filepath) # Create a setup.py filepath = os.path.join(self.path, "setup.py") with open(filepath, "w") as base_setup: self.init_file(base_setup, filepath) base_setup.write(SETUP_PY_FILE % self.name) # Create a basic main file filepath = os.path.join(self.path, "main.py") with open(filepath, "w") as base_main: self.init_file(base_main, filepath) base_main.write(BASIC_HELLO % self.name) def get_project_api(self): """ Here we expect you to return a QMenu with wathever you need inside. Bare in mind that we will add this to the context menu on the project tree but we might use it elsewere, not guaranteed. """ pass def get_project_file_api(self): """ This is exactly the same as 'get_project_api' but for files. You should return a tuple containing: (evaluate_pertinence_function, QMenu) Where evaluate_pertinence is a function that will receive the file path and return True/False if the QMenu is apt for said file. """ pass def get_project_wizard_pages(self): return [] def wizard_callback(self): pass @classmethod def wizard_pages(csl): from PyQt5.QtWidgets import ( QWizardPage, QVBoxLayout, QLineEdit, QGridLayout, QLabel, ) p = QWizardPage() vbox = QGridLayout(p) vbox.addWidget(QLabel("Location:"), 0, 0) line = QLineEdit() vbox.addWidget(line, 0, 1) vbox.addWidget(QLabel("Interpreter:"), 1, 0) line_interpreter = QLineEdit() vbox.addWidget(line_interpreter, 1, 1) return [p] class DjangoProject(BaseProjectType): type_name = "Django Project" layout_version = "0.1" category = "Django" description = "Lalalallaal django" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class PyQtProject(BaseProjectType): type_name = "PyQt Project" layout_version = "0.1" category = "PyQt" description = "Lalallaal PyQt" @classmethod def wizard_pages(cls): from PyQt5.QtWidgets import QWizardPage p = QWizardPage() p.setTitle("PPPPPP") p.setSubTitle("Pyqslaldsald ") return [p] class GitProject(BaseProjectType): type_name = "Git" layout_version = "0.1" category = "Clone Project" description = "Clones a Git repository" # Register bundled projects PythonProject.register() PythonVenvProject.register() DjangoProject.register() PyQtProject.register() GitProject.register()
5,060
Python
.py
138
30.210145
79
0.648721
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,608
__bundled_project_types.py
ninja-ide_ninja-ide/ninja_ide/core/template_registry/__bundled_project_types.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os from ninja_ide.core.template_registry.ntemplate_registry import BaseProjectType SETUP_PY_FILE = """ # BEWARE: This is a minimal version you will most likely need to extend it from setuptools import setup, find_packages setup( name='%s', version='1.0', packages=find_packages(), )""" BASIC_HELLO = """ # This is a sample yet useful program, for python 3 def hello_world(): print("hello world, this is %s's main") """ class PythonVenvProject(BaseProjectType): type_name = "Basic Python Project with Venv" layout_version = "0.1" category = "Python" class PythonProject(BaseProjectType): type_name = "Basic Python Project" layout_version = "0.1" category = "Python" encoding_string = {"py": "# -*- coding: %s -*-"} single_line_comment = {"py": "# "} description = \ """This wizard will create a basic Python project. """ def __init__(self, *args, **kwargs): super(PythonProject, self).__init__(*args, **kwargs) def create_layout(self): """ Create set of folders and files required for a basic python project """ # Create project path project_path = os.path.join(self.path, self.name) self._create_path(project_path) # Create a single init file filepath = os.path.join(project_path, "__init__.py") with open(filepath, "w") as base_init: self.init_file(base_init, filepath) # Create a setup.py filepath = os.path.join(project_path, "setup.py") with open(filepath, "w") as base_setup: self.init_file(base_setup, filepath) base_setup.write(SETUP_PY_FILE % self.name) # Create a basic main file filepath = os.path.join(project_path, "main.py") with open(filepath, "w") as base_main: self.init_file(base_main, filepath) base_main.write(BASIC_HELLO % self.name) from ninja_ide.tools import json_manager project = {} project["name"] = self.name project["license"] = self.license_text json_manager.create_ninja_project(project_path, self.name, project) def get_project_api(self): """ Here we expect you to return a QMenu with wathever you need inside. Bare in mind that we will add this to the context menu on the project tree but we might use it elsewere, not guaranteed. """ pass def get_project_file_api(self): """ This is exactly the same as 'get_project_api' but for files. You should return a tuple containing: (evaluate_pertinence_function, QMenu) Where evaluate_pertinence is a function that will receive the file path and return True/False if the QMenu is apt for said file. """ pass def get_project_wizard_pages(self): return [] def wizard_callback(self): pass @classmethod def wizard_pages(cls): from PyQt5.QtWidgets import ( QWizardPage, QVBoxLayout, QLineEdit, QGridLayout, QLabel, QStyle, QFileDialog, QFrame, QComboBox ) from PyQt5.QtGui import QIcon from ninja_ide.tools import ui_tools from ninja_ide.utils import utils class Page(QWizardPage): def __init__(self): super().__init__() vbox = QVBoxLayout(self) self.setTitle("Python Project") frame = QFrame() frame.setLineWidth(2) vbox.addStretch(1) frame.setFrameShape(QFrame.StyledPanel) vbox.addWidget(frame) box = QGridLayout(frame) box.addWidget(QLabel("Project Name:"), 0, 0) self._line_project_name = QLineEdit() self.registerField("name*", self._line_project_name) box.addWidget(self._line_project_name, 0, 1) box.addWidget(QLabel("Create in:"), 1, 0) self.line = QLineEdit() self.registerField("path", self.line) choose_dir_action = self.line.addAction( QIcon(self.style().standardPixmap( self.style().SP_DirIcon)), QLineEdit.TrailingPosition) box.addWidget(self.line, 1, 1) box.addWidget(QLabel("Interpreter:"), 2, 0) line_interpreter = QComboBox() line_interpreter.setEditable(True) line_interpreter.addItems(utils.get_python()) box.addWidget(line_interpreter, 2, 1) choose_dir_action.triggered.connect(self._choose_dir) self.line.setText(utils.get_home_dir()) def _choose_dir(self): directory = QFileDialog.getExistingDirectory( self, "Choose Directory", "~") if directory: self.line.setText(directory) return [Page()] class DjangoProject(BaseProjectType): type_name = "Django Project" layout_version = "0.1" category = "Django" description = "Lalalallaal django" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class PyQtProject(BaseProjectType): type_name = "PyQt Project" layout_version = "0.1" category = "PyQt" description = "Lalallaal PyQt" @classmethod def wizard_pages(cls): from PyQt5.QtWidgets import QWizardPage p = QWizardPage() p.setTitle("PPPPPP") p.setSubTitle("Pyqslaldsald ") return [p] class GitProject(BaseProjectType): type_name = "Git" layout_version = "0.1" category = "Clone Project" description = "Clones a Git repository" # Register bundled projects PythonProject.register() PythonVenvProject.register() DjangoProject.register() PyQtProject.register() GitProject.register()
6,611
Python
.py
166
31.463855
79
0.627907
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,609
python_project_type.py
ninja-ide_ninja-ide/ninja_ide/core/template_registry/bundled_project_types/python_project_type.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os from ninja_ide import translations from ninja_ide.tools import json_manager from ninja_ide.core.template_registry.bundled_project_types import initial_page from ninja_ide.core.template_registry.ntemplate_registry import BaseProjectType SETUP_PY_FILE = """ # BEWARE: This is a minimal version you will most likely need to extend it from setuptools import setup, find_packages setup( name='%s', version='1.0', packages=find_packages(), ) """ BASIC_HELLO = """ # This is a sample yet useful program, for python 3 def hello_world(): print("hello world, this is %s's main") """ class PythonProject(BaseProjectType): type_name = "Basic Python Project" layout_version = "0.1" category = "Python" encoding_string = {"py": "# -*- coding: %s -*-"} single_line_comment = {"py": "# "} description = "This wizard will create a basic Python project." def create_layout(self, wizard): """ Create set of folders and files required for a basic python project """ # Create project path project_path = os.path.join(self.path, self.name) self._create_path(project_path) # Create a single init file filepath = os.path.join(project_path, "__init__.py") with open(filepath, "w") as base_init: self.init_file(base_init, filepath) # Create a setup.py filepath = os.path.join(project_path, "setup.py") with open(filepath, "w") as base_setup: self.init_file(base_setup, filepath) base_setup.write(SETUP_PY_FILE % self.name) # Create a basic main file filepath = os.path.join(project_path, "main.py") with open(filepath, "w") as base_main: self.init_file(base_main, filepath) base_main.write(BASIC_HELLO % self.name) # Create .nja file project = {} project["name"] = self.name project["project-type"] = self.category project["mainFile"] = "main.py" project["description"] = wizard.field("description") json_manager.create_ninja_project(project_path, self.name, project) # Open project in Explorer self._open_project(project_path) @classmethod def wizard_pages(cls): return (InitialPage(),) class InitialPage(initial_page.InitialPage): def __init__(self): super().__init__() self.setTitle(translations.TR_WIZARD_PYTHON_PROJECT_TITLE) self.setSubTitle(translations.TR_WIZARD_PYTHON_PROJECT_SUBTITLE) PythonProject.register()
3,256
Python
.py
81
34.765432
79
0.681876
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,610
__init__.py
ninja-ide_ninja-ide/ninja_ide/core/template_registry/bundled_project_types/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from . import python_project_type # noqa from . import pyqt_project_type # noqa
775
Python
.py
18
42
70
0.759259
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,611
initial_page.py
ninja-ide_ninja-ide/ninja_ide/core/template_registry/bundled_project_types/initial_page.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. """ This page is common in all projects """ import sys import os from PyQt5.QtWidgets import ( QWizardPage, QVBoxLayout, QComboBox, QFrame, QPlainTextEdit, QLabel, QGridLayout, QLineEdit, QFileDialog ) from ninja_ide.core.file_handling import file_manager from ninja_ide import translations from ninja_ide.tools import utils # http://opensource.org/licenses/alphabetical LICENSES = ( 'Academic Free License', 'Apache License 2.0', 'Apple Public Source License', 'Artistic License', 'Artistic license', 'Common Development and Distribution License', 'Common Public Attribution License', 'Eclipse Public License', 'Educational Community License', 'European Union Public License', 'GNU Affero General Public License', 'GNU General Public License v2', 'GNU General Public License v3', 'GNU Lesser General Public License 2.1', 'GNU Lesser General Public License 3.0', 'MIT license', 'Microsoft Public License', 'Microsoft Reciprocal License', 'Mozilla Public License 1.1', 'Mozilla Public License 2.0', 'NASA Open Source Agreement', 'New BSD License 3-Clause', 'Non-Profit Open Software License', 'Old BSD License 2-Clause', 'Open Software License', 'Other', 'Other Open Source', 'PHP License', 'PostgreSQL License', 'Proprietary', 'Python Software License', 'Simple Public License', 'W3C License', 'Zope Public License', 'zlib license') class InitialPage(QWizardPage): def __init__(self): super().__init__() vbox = QVBoxLayout(self) frame = QFrame(self) vbox.addStretch(1) frame.setFrameShape(QFrame.StyledPanel) vbox.addWidget(frame) # Fields fields_box = QGridLayout(frame) # Project name fields_box.addWidget(QLabel(translations.TR_WIZARD_PROJECT_NAME), 0, 0) self._line_project_name = QLineEdit("untitled") self.registerField("name*", self._line_project_name) fields_box.addWidget(self._line_project_name, 0, 1) # Project location fields_box.addWidget( QLabel(translations.TR_WIZARD_PROJECT_LOCATION), 1, 0) self._line_location = QLineEdit() self._line_location.setReadOnly(True) self._line_location.setText(utils.get_home_dir()) self.registerField("path", self._line_location) choose_dir_act = self._line_location.addAction( self.style().standardIcon( self.style().SP_DirIcon), QLineEdit.TrailingPosition) fields_box.addWidget(self._line_location, 1, 1) # Project description fields_box.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 2, 0) self._txt_desciption = QPlainTextEdit() fields_box.addWidget(self._txt_desciption, 2, 1) self.registerField("description", self._txt_desciption) # Project license fields_box.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 3, 0) combo_license = QComboBox() combo_license.addItems(LICENSES) combo_license.setCurrentIndex(12) fields_box.addWidget(combo_license, 3, 1) self.registerField("license", combo_license, property="currentText") # Project interpreter fields_box.addWidget( QLabel(translations.TR_WIZARD_PROJECT_INTERPRETER), 4, 0) combo_interpreter = QComboBox() combo_interpreter.addItems(utils.get_python()) combo_interpreter.setCurrentText(sys.executable) fields_box.addWidget(combo_interpreter, 4, 1) self.registerField("interpreter", combo_interpreter) # Connections self._line_project_name.textChanged.connect(self._on_text_changed) choose_dir_act.triggered.connect(self._choose_dir) def _choose_dir(self): dirname = QFileDialog.getExistingDirectory( self, translations.TR_WIZARD_CHOOSE_DIR, utils.get_home_dir()) if dirname: self._line_location.setText(dirname) @property def location(self): return self._line_location.text() @property def project_name(self): return self._line_project_name.text() def _on_text_changed(self): ok = self.validate() if not ok: self._line_project_name.setStyleSheet("background-color: red") else: self._line_project_name.setStyleSheet("background-color: none;") def validate(self): ok = True project_path = os.path.join(self.location, self.project_name) if file_manager.folder_exists(project_path): ok = False return ok def isComplete(self): val = super().isComplete() return val and self.validate()
5,393
Python
.py
128
35.609375
79
0.687476
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,612
pyqt_project_type.py
ninja-ide_ninja-ide/ninja_ide/core/template_registry/bundled_project_types/pyqt_project_type.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os from PyQt5.QtWidgets import ( QWizardPage, QVBoxLayout, QFrame, QLineEdit, QLabel, QComboBox, QGridLayout ) from ninja_ide import translations from ninja_ide.core.template_registry.ntemplate_registry import BaseProjectType from ninja_ide.core.template_registry.bundled_project_types import initial_page from ninja_ide.tools import json_manager MAIN = """ import sys from PyQt5.QtWidgets import QApplication from {module} import {classname} if __name__ == "__main__": app = QApplication(sys.argv) widget = {classname}() widget.show() sys.exit(app.exec_()) """ WIDGET = """ from PyQt5.QtWidgets import {baseclass} class {classname}({baseclass}): def __init__(self, parent=None): super().__init__(parent) """ class PyQtWidgetsProject(BaseProjectType): type_name = "PyQt Widgets Application" layout_version = "0.1" category = "PyQt" description = "Creates a PyQt application for the desktop." @classmethod def wizard_pages(cls): return [InitialPage(), SecondPage()] def create_layout(self, wizard): base_class = wizard.field("base_class") class_name = wizard.field("class_name").title() module = base_class.lower()[1:] # Create project path project_path = os.path.join(self.path, self.name) self._create_path(project_path) # Create main file filepath = os.path.join(project_path, "main.py") with open(filepath, "w") as base_main: self.init_file(base_main, filepath) base_main.write(MAIN.format(module=module, classname=class_name)) # Create widget file filepath = os.path.join(project_path, module + ".py") with open(filepath, "w") as widget_file: self.init_file(widget_file, filepath) widget_file.write( WIDGET.format(baseclass=base_class, classname=class_name)) # Create ninja project file project = {} project["name"] = self.name project["project-type"] = self.category project["mainFile"] = "main.py" json_manager.create_ninja_project(project_path, self.name, project) self._open_project(project_path) class InitialPage(initial_page.InitialPage): def __init__(self): super().__init__() self.setTitle(translations.TR_WIZARD_PYQT_PROJECT_TITLE) self.setSubTitle(translations.TR_WIZARD_PYQT_PROJECT_SUBTITLE) class SecondPage(QWizardPage): def __init__(self): super().__init__() self.setTitle(translations.TR_WIZARD_PYQT_PROJECT_TITLE_SECOND_PAGE) self.setSubTitle( translations.TR_WIZARD_PYQT_PROJECT_SUBTITLE_SECOND_PAGE) vbox = QVBoxLayout(self) frame = QFrame(self) frame.setFrameShape(QFrame.StyledPanel) vbox.addWidget(frame) # Fields fields_box = QGridLayout(frame) fields_box.addWidget( QLabel(translations.TR_WIZARD_PYQT_CLASS_NAME), 0, 0) self._line_class_name = QLineEdit() self.registerField("class_name*", self._line_class_name) fields_box.addWidget(self._line_class_name, 0, 1) fields_box.addWidget( QLabel(translations.TR_WIZARD_PYQT_BASE_CLASS), 1, 0) self._combo_class_name = QComboBox() self._combo_class_name.addItems(["QWidget", "QMainWindow", "QDialog"]) self.registerField( "base_class", self._combo_class_name, property="currentText") fields_box.addWidget(self._combo_class_name, 1, 1) fields_box.addWidget( QLabel(translations.TR_WIZARD_PYQT_WIDGET_FILE), 2, 0) self._line_widget_file = QLineEdit() self._line_widget_file.setReadOnly(True) fields_box.addWidget(self._line_widget_file, 2, 1) self._combo_class_name.currentTextChanged.connect( self.__update_line_widget) self.__update_line_widget(self._combo_class_name.currentText()) def __update_line_widget(self, text): text = text.lower()[1:] + ".py" self._line_widget_file.setText(text) PyQtWidgetsProject.register()
4,843
Python
.py
120
33.941667
79
0.674473
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,613
__init__.py
ninja-ide_ninja-ide/ninja_tests/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import QApplication import pytest app = QApplication([])
770
Python
.py
19
39.526316
70
0.768309
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,614
test_indenter.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/test_indenter.py
import pytest from PyQt5.QtWidgets import QPlainTextEdit from ninja_ide.gui.editor.indenter import base class DummyEditor(QPlainTextEdit): def __enter__(self): self.textCursor().beginEditBlock() def __exit__(self, exc_type, exc_value, traceback): self.textCursor().endEditBlock() @pytest.fixture def code_editor(): editor = DummyEditor() indenter = base.BasicIndenter(editor) return editor, indenter @pytest.mark.parametrize( 'text, expected', [ (' def foo():', ' def foo():\n '), (' def foo():', ' def foo():\n '), ('def foo():', 'def foo():\n'), (' def foo():', ' def foo():\n ') ] ) def test_basic_indenter(code_editor, text, expected): editor, indenter = code_editor editor.setPlainText(text) cursor = editor.textCursor() cursor.movePosition(cursor.EndOfLine) editor.setTextCursor(cursor) indenter.indent_block(cursor) assert editor.toPlainText() == expected @pytest.mark.parametrize( 'text, use_tab, expected', [ (' def foo():', False, ' def foo():\n '), ('\tdef foo():', True, '\tdef foo():\n\t') ] ) def test_text(code_editor, text, use_tab, expected): editor, indenter = code_editor editor.setPlainText(text) cursor = editor.textCursor() cursor.movePosition(cursor.EndOfLine) editor.setTextCursor(cursor) indenter.use_tabs = use_tab if use_tab: text = '\t' else: text = ' ' assert indenter.text() == text indenter.indent_block(cursor) assert editor.toPlainText() == expected @pytest.mark.parametrize( 'text, width, expected, use_tab', [ ('def foo():', 4, 'def foo(): ', False), ('def foo():', 2, 'def foo(): ', False), ('def foooo():', 4, 'def foooo(): ', False), ('def foo():', 1, 'def foo():\t', True) ] ) def test_indent(code_editor, text, width, expected, use_tab): editor, indenter = code_editor editor.setPlainText(text) cursor = editor.textCursor() cursor.movePosition(cursor.EndOfLine) editor.setTextCursor(cursor) indenter.width = width indenter.use_tabs = use_tab indenter.indent() assert editor.toPlainText() == expected @pytest.mark.parametrize( 'text, n, expected', [ ('ninja\nide', 1, ' ninja\n ide'), ('ninja\nide', 2, ' ninja\n ide'), ('ninja', 4, ' ninja') ] ) def test_indent_selection(code_editor, text, n, expected): editor, indenter = code_editor editor.setPlainText(text) editor.selectAll() for i in range(n): indenter.indent_selection() assert editor.toPlainText() == expected
2,747
Python
.py
85
27.117647
68
0.610964
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,615
_test_autocomplete_braces.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/_test_autocomplete_braces.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import pytest from unittest.mock import Mock from ninja_ide import resources from ninja_ide.gui.editor import editor from PyQt5.QtGui import QTextDocument from PyQt5.QtCore import Qt # FIXME: use mock from ninja_ide.gui.explorer.tabs import bookmark_manager # noqa resources.COLOR_SCHEME = {"colors": []} @pytest.fixture def editor_bot(qtbot): editable = Mock() editable.document = QTextDocument() _editor = editor.create_editor(editable) return _editor @pytest.mark.parametrize( "text, expected_text, column", [ ("[", "[]", 1), ("{", "{}", 1), ("(", "()", 1) ]) def test_close_braces(qtbot, editor_bot, text, expected_text, column): qtbot.keyClicks(editor_bot, text) assert editor_bot.text == expected_text _, col = editor_bot.cursor_position assert col == column @pytest.mark.parametrize( "text, expected_text, column", [ ("[]", "[]", 2), ("{}", "{}", 2), ("()", "()", 2) ]) def test_close_braces2(qtbot, editor_bot, text, expected_text, column): qtbot.keyClicks(editor_bot, text) assert editor_bot.text == expected_text _, col = editor_bot.cursor_position assert col == column @pytest.mark.parametrize( "text, expected_text, column", [ ("[[[[[[[[[[", "[[[[[[[[[[]]]]]]]]]]", 10), ("{{{{{{{{{{", "{{{{{{{{{{}}}}}}}}}}", 10), ("((((((((((", "(((((((((())))))))))", 10) ]) def test_close_braces3(qtbot, editor_bot, text, expected_text, column): qtbot.keyClicks(editor_bot, text) assert editor_bot.text == expected_text _, col = editor_bot.cursor_position assert col == column def test_close_braces4(editor_bot, qtbot): editor_bot.text = "test content" cursor = editor_bot.textCursor() cursor.movePosition(cursor.EndOfBlock) editor_bot.setTextCursor(cursor) # Press '(' qtbot.keyPress(editor_bot, Qt.Key_ParenLeft) assert editor_bot.text == "test content()" def test_close_braces5(editor_bot, qtbot): editor_bot.text = "test content" cursor = editor_bot.textCursor() cursor.movePosition(cursor.EndOfBlock) cursor.movePosition(cursor.Left) editor_bot.setTextCursor(cursor) # Press '(' qtbot.keyPress(editor_bot, Qt.Key_ParenLeft) assert editor_bot.text == "test conten(t" if __name__ == "__main__": pytest.main()
3,061
Python
.py
86
31.604651
71
0.661137
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,616
test_python_indenter.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/test_python_indenter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from ninja_ide.gui.editor.base import BaseTextEditor from ninja_ide.gui.editor.indenter.python_indenter import PythonIndenter def make_editor(): editor = BaseTextEditor() indenter = PythonIndenter(editor) return editor, indenter def make_indent(text): editor, indenter = make_editor() editor.text = text cursor = editor.textCursor() cursor.movePosition(cursor.End) editor.setTextCursor(cursor) indenter.indent_block(cursor) return editor.text def test_1(): assert make_indent('def foo():') == 'def foo():\n ' def test_2(): text = make_indent('def foo():\n pass') assert text == 'def foo():\n pass\n' def test_3(): text = make_indent('def foo():\n def inner():') assert text == 'def foo():\n def inner():\n ' def test_4(): text = make_indent("def foo():\n def inner():\n pass") assert text == 'def foo():\n def inner():\n pass\n ' def test_5(): text = make_indent("lista = [23,") assert text == 'lista = [23,\n ' def test_6(): text = make_indent('def foo(*args,') assert text == 'def foo(*args,\n ' def test_7(): a_text = "def foo(arg1,\n arg2, arg3):" text = make_indent(a_text) assert text == 'def foo(arg1,\n arg2, arg3):\n ' def test_8(): a_text = """# Comment class A(object): def __init__(self): self._val = 0 def foo(self): def bar(arg1, arg2):""" text = make_indent(a_text) expected = """# Comment class A(object): def __init__(self): self._val = 0 def foo(self): def bar(arg1, arg2): """ assert text == expected def test_9(): a_text = """# comment lista = [32, 3232332323, [3232,""" text = make_indent(a_text) expected = """# comment lista = [32, 3232332323, [3232, """ assert text == expected def test_10(): # Hang indent # text = make_indent('tupla = (') # assert text == 'tupla = (\n ' pass def test_11(): a_text = "def foo():\n def inner():\n return foo()" text = make_indent(a_text) expected = "def foo():\n def inner():\n return foo()\n " assert text == expected def test_12(): a_text = """if __name__ == "__main__": nombre = input('Nombre: ') print(nombre)""" text = make_indent(a_text) expected = """if __name__ == "__main__": nombre = input('Nombre: ') print(nombre) """ assert text == expected def test_13(): a_text = "d = []" editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 1, 5 indenter.indent_block(editor.textCursor()) expected = "d = [\n \n]" assert editor.text == expected def test_14(): a_text = "d = ['one', 'two']" editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 1, 5 indenter.indent_block(editor.textCursor()) expected = "d = [\n 'one', 'two']" assert editor.text == expected def test_15(): """ { { }, | <-- cursor } """ a_text = "{\n {\n },\n}" editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 2, 6 indenter.indent_block(editor.textCursor()) expected = '{\n {\n },\n \n}' assert editor.text == expected assert editor.cursor_position == (3, 4) def test_16(): """ x = [0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11] """ a_text = "x = [0, 1, 2," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 1, 13 indenter.indent_block(editor.textCursor()) expected = "x = [0, 1, 2,\n " assert editor.text == expected def test_22(): """ x = [0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11] """ a_text = "x = [0, 1, 2,\n [3, 4, 5," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 2, 14 indenter.indent_block(editor.textCursor()) expected = "x = [0, 1, 2,\n [3, 4, 5,\n " assert editor.text == expected def test_23(): """ x = [0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11] """ a_text = "x = [0, 1, 2,\n [3, 4, 5,\n 6, 7, 8]," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 3, 15 indenter.indent_block(editor.textCursor()) expected = "x = [0, 1, 2,\n [3, 4, 5,\n 6, 7, 8],\n " assert editor.text == expected def test_24(): """ x = [ 0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11 ] """ a_text = "x = [\n 0, 1, 2, [3, 4, 5," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 1, 22 indenter.indent_block(editor.textCursor()) expected = "x = [\n 0, 1, 2, [3, 4, 5,\n " assert editor.text == expected def test_25(): """ x = [ 0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11 ] """ a_text = "x = [\n 0, 1, 2, [3, 4, 5,\n 6, 7, 8]," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 2, 23 indenter.indent_block(editor.textCursor()) expected = "x = [\n 0, 1, 2, [3, 4, 5,\n 6, 7, 8],\n " assert editor.text == expected def test_26(): expected = 'def foo():\n {}\n' for kw in ('break', 'continue', 'raise', 'pass', 'return'): assert make_indent('def foo():\n {}'.format(kw)) == expected.format(kw)
6,477
Python
.py
207
25.661836
82
0.540058
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,617
_test_autocomplete_quotes.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/_test_autocomplete_quotes.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import pytest from unittest.mock import Mock from ninja_ide.gui.editor import editor from PyQt5.QtGui import QTextDocument from PyQt5.QtCore import Qt @pytest.fixture def editor_bot(qtbot): editable = Mock() editable.document = QTextDocument() _editor = editor.create_editor(editable) return _editor @pytest.mark.parametrize( "text, expected_text, column", [ ("'", "''", 1), ("''", "''", 2), ('"', '""', 1), ('""', '""', 2), ("''''", "''''''", 3), ('""""', '""""""', 3) ]) def test_close_quotes(qtbot, editor_bot, text, expected_text, column): qtbot.keyClicks(editor_bot, text) assert editor_bot.text == expected_text _, col = editor_bot.cursor_position assert col == column def test_autocomplete_single_selection(editor_bot, qtbot): editor_bot.text = 'ninja-ide rocks!' editor_bot.selectAll() qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) assert editor_bot.text == '"ninja-ide rocks!"' def test_autocomplete_multiline_selection(editor_bot, qtbot): editor_bot.text = 'ninja-ide rocks!\nholaaaa\nkokoko' editor_bot.selectAll() qtbot.keyPress(editor_bot, Qt.Key_Apostrophe) assert editor_bot.text == "'ninja-ide rocks!\nholaaaa\nkokoko'" def test_autocomplete_multiline_selection2(editor_bot, qtbot): editor_bot.text = 'ninja-ide rocks!\nholaaaa\nkokoko' editor_bot.selectAll() for i in range(5): qtbot.keyPress(editor_bot, Qt.Key_Apostrophe) assert editor_bot.text == "'''''ninja-ide rocks!\nholaaaa\nkokoko'''''" def test_autocomplete_triple_double_quotes(editor_bot, qtbot): qtbot.keyPress(editor_bot, Qt.Key_Return) qtbot.keyPress(editor_bot, Qt.Key_Return) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) assert editor_bot.text == '\n\n""""""' _, col = editor_bot.cursor_position assert col == 3 def test_autocomplete_triple_double_quotes2(editor_bot, qtbot): qtbot.keyPress(editor_bot, Qt.Key_Return) qtbot.keyPress(editor_bot, Qt.Key_Return) for i in range(4): qtbot.keyPress(editor_bot, Qt.Key_Space) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) assert editor_bot.text == '\n\n """"""' _, col = editor_bot.cursor_position assert col == 7 def test_last(editor_bot, qtbot): editor_bot.text = "class NINJA(object):\n " cur = editor_bot.textCursor() cur.movePosition(cur.End) editor_bot.setTextCursor(cur) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) qtbot.keyPress(editor_bot, Qt.Key_QuoteDbl) assert editor_bot.text == 'class NINJA(object):\n """"""' _, col = editor_bot.cursor_position assert col == 7 editor_bot.textCursor().insertText('docstring') assert editor_bot.text == 'class NINJA(object):\n """docstring"""' if __name__ == "__main__": pytest.main()
3,923
Python
.py
96
36.614583
75
0.691296
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,618
test_code_editor.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/test_code_editor.py
import pytest from PyQt5.QtGui import QTextCursor from ninja_ide.gui.editor.base import CodeEditor @pytest.fixture def code_editor(): editor = CodeEditor() editor.text = "NINJA-IDE is not just another IDE" return editor def test_find_match(code_editor): assert code_editor.find_match('IDE') is True _, col = code_editor.cursor_position assert col == 9 def test_find_match_cs(code_editor): assert code_editor.find_match('JUST', True) is False def test_find_match_wo(code_editor): assert code_editor.find_match('ju', whole_word=True) is False def test_replace_match(code_editor): code_editor.find_match('just') code_editor.replace_match( word_old='just', word_new='JUST' ) assert code_editor.text == 'NINJA-IDE is not JUST another IDE' def test_replace_all(code_editor): code_editor.replace_all( word_old='IDE', word_new='Integrated Development Environment' ) assert code_editor.text == ( 'NINJA-Integrated Development Environment is not just another ' 'Integrated Development Environment')
1,111
Python
.py
31
30.903226
71
0.712008
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,619
__init__.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
692
Python
.py
16
42.25
70
0.760355
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,620
test_editor.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/test_editor.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import pytest from PyQt5.QtGui import QTextCursor from ninja_ide.gui.editor import base @pytest.fixture def editor_fixture(): editor = base.BaseTextEditor() return editor @pytest.fixture def editor_with_text(editor_fixture): editor_fixture.setPlainText("this\nis\an\nexample") editor_fixture.moveCursor(QTextCursor.Start) return editor_fixture def test_selected_text(editor_with_text): cursor = editor_with_text.textCursor() cursor.movePosition(cursor.Right, cursor.KeepAnchor, 4) editor_with_text.setTextCursor(cursor) assert editor_with_text.has_selection() assert editor_with_text.selected_text() == 'this' def test_selection_range(editor_with_text): cursor = editor_with_text.textCursor() cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor, 2) editor_with_text.setTextCursor(cursor) assert editor_with_text.selection_range() == (0, 1) cursor.movePosition(QTextCursor.Right, QTextCursor. KeepAnchor) editor_with_text.setTextCursor(cursor) assert editor_with_text.selection_range() == (0, 2) @pytest.mark.parametrize( 'text, lineno, expected', [ ('ninja\nIDE\n\nis awesome!', 2, ''), ('ninja\nIDE\n\nis awesome!', 0, 'ninja'), ('ninja\nIDE\n\nis awesome!', 3, 'is awesome!'), ('ninja\nIDE\n\nis awesome!', -1, 'ninja') ] ) def test_line_text(editor_fixture, text, lineno, expected): editor_fixture.text = text editor_fixture.cursor_position = lineno, 0 assert editor_fixture.line_text(lineno) == expected @pytest.mark.parametrize( 'text, expected', [ ('asd ldsaj lkaskdj hakjshdkjh asd', 1), ('as\n\n\nd ld\nsaj l\nkaskdj hakjshdkjh asd', 6), ('asd ldsaj lkaskdj ha\nkj\nshdkjh asd', 3) ] ) def test_line_count(editor_fixture, text, expected): editor_fixture.text = text assert editor_fixture.line_count() == expected def test_insert_text(editor_fixture): assert editor_fixture.text == '' editor_fixture.insert_text("inserting text") assert editor_fixture.text == 'inserting text' editor_fixture.setReadOnly(True) editor_fixture.insert_text("INSERTING TEXt") assert editor_fixture.text == 'inserting text' @pytest.mark.parametrize( 'text, position, expected', [ ('hola como estas', (0, 0), 'hola'), ('hola\n como \nestas', (2, 3), 'estas'), ('hola\n aaa ssss wwww como estas', (1, 17), 'como') ] ) def test_get_right_word(editor_fixture, text, position, expected): editor_fixture.text = text editor_fixture.cursor_position = position assert editor_fixture.cursor_position == position @pytest.mark.parametrize( 'text, position, expected', [ ('hola como estas', (0, 0), 'h'), ('hola\n como \nestas', (2, 3), 'a'), ('hola\n aaa ssss wwww como estas', (1, 17), 'm') ] ) def test_get_right_character(editor_fixture, text, position, expected): editor_fixture.text = text editor_fixture.cursor_position = position assert editor_fixture.get_right_character() == expected @pytest.mark.parametrize( 'text, lineno, up, expected', [ ('ninja\nIDE\n\nis awesome!!!\n!', 0, False, 'IDE\nninja\n\nis awesome!!!\n!'), ('ninja\nIDE\n\nis awesome!!!\n!', 3, True, 'ninja\nIDE\nis awesome!!!\n\n!') ] ) def test_move_up_down(editor_fixture, text, lineno, up, expected): editor_fixture.text = text editor_fixture.cursor_position = lineno, 0 editor_fixture.move_up_down(up) assert editor_fixture.text == expected @pytest.mark.parametrize( 'text, range_, up, expected', [ ('ninja is not just\nanother\nide\nprint', (0, 1), False, 'ide\nninja is not just\nanother\nprint'), ('ninja is not just\nanother\nide\nprint', (2, 1), True, 'another\nide\nninja is not just\nprint') ] ) def test_move_up_down_selection(editor_fixture, text, range_, up, expected): editor_fixture.text = text start, end = range_ editor_fixture.cursor_position = start, 0 cursor = editor_fixture.textCursor() if up: cursor.movePosition(QTextCursor.EndOfLine) cursor.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.Up, QTextCursor.KeepAnchor, abs(end - start)) else: cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor, end - start) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) editor_fixture.setTextCursor(cursor) editor_fixture.move_up_down(up) assert editor_fixture.text == expected @pytest.mark.parametrize( 'text, lineno, n, expected', [ ('example\ntext', 0, 1, 'example\nexample\ntext'), ('example\ntext', 1, 1, 'example\ntext\ntext'), ('example\ntext', 1, 3, 'example\ntext\ntext\ntext\ntext') ] ) def test_duplicate_line(editor_fixture, text, lineno, n, expected): editor_fixture.text = text editor_fixture.cursor_position = lineno, 0 for i in range(n): editor_fixture.duplicate_line() assert editor_fixture.text == expected @pytest.mark.parametrize( 'text, _range, n, expected', [ ('exa\nmple\ntext\n!!', (0, 1), 1, 'exa\nmple\nexa\nmple\ntext\n!!'), ('exa\nmple\ntext\n!!', (0, 1), 4, 'exa\nmple\nexa\nmple\nexa\nmple\nexa\nmple\nexa\nmple\ntext\n!!'), # noqa ] ) def test_duplicate_line_selection(editor_fixture, text, _range, n, expected): editor_fixture.text = text cursor = editor_fixture.textCursor() start, end = _range editor_fixture.cursor_position = start, 0 cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor, end - start) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) editor_fixture.setTextCursor(cursor) for i in range(n): editor_fixture.duplicate_line() assert editor_fixture.text == expected @pytest.mark.parametrize( 'text, position, expected', [ ('hola\ncomo\nestas\n ', (0, 4), 'hola'), ('hola\ncomo\nestas\n ', (2, 1), 'estas'), ('hola\ncomo\nestas\n ', (0, 1), 'hola'), ('hola\ncomo\nestas\n ', (1, 3), 'como'), ('hola\ncomo\nestas\n ', (3, 2), '') ] ) def test_word_under_cursor(editor_fixture, text, position, expected): editor_fixture.text = text editor_fixture.cursor_position = position cursor = editor_fixture.word_under_cursor() assert not cursor.isNull() assert cursor.selectedText() == expected
7,204
Python
.py
183
34.502732
118
0.684406
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,621
__test_marker_area.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/side_areas/__test_marker_area.py
from ninja_tests.gui import editor editor_ref = editor.create_editor() widget = editor_ref.side_widgets.get("MarkerWidget") def test_1(qtbot): widget.add_bookmark(2) widget.add_bookmark(5) assert widget.bookmarks == [2, 5] def test_2(qtbot): for i in range(100): editor_ref.textCursor().insertBlock() widget.add_bookmark(57) widget.add_bookmark(20) widget.add_bookmark(5) widget.add_bookmark(97) widget.add_bookmark(100) editor_ref.cursor_position = 16, 0 widget.next_bookmark() line, _ = editor_ref.cursor_position assert line == 20 widget.previous_bookmark() line, _ = editor_ref.cursor_position assert line == 5 def test_3(): for i in range(190): editor_ref.textCursor().insertBlock() widget.add_bookmark(20) widget.add_bookmark(5) widget.add_bookmark(54) widget.add_bookmark(124) widget.add_bookmark(189) editor_ref.cursor_position = 130, 0 widget.next_bookmark() line, _ = editor_ref.cursor_position assert line == 189 widget.previous_bookmark() line, _ = editor_ref.cursor_position assert line == 124 widget.next_bookmark() widget.next_bookmark() widget.next_bookmark() line, _ = editor_ref.cursor_position assert line == 5
1,289
Python
.py
42
25.904762
52
0.68629
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,622
__init__.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/side_areas/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. # from ninja_ide.gui.editor.side_area import marker_widget # # Need COLOR_SCHEME # from ninja_ide import resources # from ninja_ide.tools import json_manager # all_schemes = json_manager.load_editor_schemes() # resources.COLOR_SCHEME = all_schemes["Ninja Dark"] # def get_marker_area(): # # editor = create_editor() # return marker_widget.MarkerWidget()
1,058
Python
.py
25
41.16
70
0.756074
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,623
__test_plugin_interfaces.py
ninja-ide_ninja-ide/ninja_tests/core/__test_plugin_interfaces.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import unittest from ninja_ide.core.plugin_interfaces import implements from ninja_ide.core.plugin_interfaces import MethodNotImplemented class A(object): def _a_private_method(self): pass def one(self): pass def two(self): pass class B(object): pass class C(object): def one(self): pass def two(self): pass class PluginInterfacesTestCase(unittest.TestCase): def test_implements_decorator(self): a_implement = implements(A) self.assertRaises(MethodNotImplemented, a_implement, B) self.assertEqual(a_implement(C), C) if __name__ == '__main__': unittest.main()
1,401
Python
.py
41
30.463415
70
0.726394
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,624
__test_file_handling_nvirtualfilesystem.py
ninja-ide_ninja-ide/ninja_tests/core/__test_file_handling_nvirtualfilesystem.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from PyQt4.QtCore import QObject import unittest import os #import tempfile #from ninja_ide.core.file_handling.nfile import NFile from ninja_ide.core.file_handling import nfilesystem NVirtualFileSystem = nfilesystem.NVirtualFileSystem CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) class FakeNProject(QObject): def __init__(self, path): self.path = path super(FakeNProject, self).__init__() class FakeNFile(QObject): def __init__(self, path=""): self.path = path super(FakeNFile, self).__init__() nfilesystem.NFile = FakeNFile class NVirtualFileSystemTestCase(unittest.TestCase): """Test NVirtualFileSystem API works""" def test_supports_adding_nproject(self): nvfs = NVirtualFileSystem() project_path = "a given path" project = FakeNProject(project_path) nvfs.open_project(project) self.assertIn(project_path, nvfs._NVirtualFileSystem__projects) def test_adding_repeated_nproject_is_ignored(self): nvfs = NVirtualFileSystem() project_path = "a given path" project = FakeNProject(project_path) project2 = FakeNProject(project_path) self.assertNotEqual(project, project2) nvfs.open_project(project) self.assertIn(project_path, nvfs._NVirtualFileSystem__projects) nvfs.open_project(project2) self.assertEqual(nvfs._NVirtualFileSystem__projects[project_path], project) def test_files_get_attached_to_project(self): nvfs = NVirtualFileSystem() project_path = "a given path" project = FakeNProject(project_path) nvfs.get_file(project_path) nvfs.open_project(project) nfile = nvfs._NVirtualFileSystem__tree[project_path] self.assertEqual(project, nvfs._NVirtualFileSystem__reverse_project_map[nfile]) def test_close_file_is_handled(self): pass if __name__ == '__main__': unittest.main()
2,769
Python
.py
67
35.761194
77
0.708271
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,625
__test_plugin_manager.py
ninja-ide_ninja-ide/ninja_tests/core/__test_plugin_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import unittest import os from ninja_ide.core.plugin_manager import PluginManager CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) PLUGIN_NOT_VALID_NAME = 'test_NOT_plugin.plugin' PLUGIN_VALID_NAME = 'test_plugin.plugin' class PluginManagerTestCase(unittest.TestCase): def setUp(self): global CURRENT_DIR plugin_dir = os.path.join(CURRENT_DIR, 'plugins') self.pm = PluginManager(plugin_dir, None) def test_discover(self): self.assertEqual(len(self.pm), 0) self.pm.discover() self.assertEqual(len(self.pm), 1) def test_magic_method_contains(self): global PLUGIN_VALID_NAME, PLUGIN_NOT_VALID_NAME self.pm.discover() self.assertEqual(PLUGIN_VALID_NAME in self.pm, True) self.assertEqual(PLUGIN_NOT_VALID_NAME in self.pm, False) def test_magic_method_getitem(self): global PLUGIN_VALID_NAME, PLUGIN_NOT_VALID_NAME self.pm.discover() self.assertTrue(self.pm['test_plugin.plugin']) self.assertRaises(KeyError, self.pm.__getitem__, PLUGIN_NOT_VALID_NAME) if __name__ == '__main__': unittest.main()
1,872
Python
.py
44
38.340909
79
0.720176
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,626
__test_file_manager.py
ninja-ide_ninja-ide/ninja_tests/core/__test_file_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import unittest import os from ninja_ide.core.file_handling import file_manager CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) class FileManagerTestCase(unittest.TestCase): def setUp(self): global CURRENT_DIR self.examples_dir = os.path.join(CURRENT_DIR, 'examples') def test_read_file_content(self): filename = os.path.join(self.examples_dir, 'file_for_tests.py') content = file_manager.read_file_content(filename) expected = ("# -*- coding: utf-8 -*-\n\nprint 'testing'\n" "print 'ñandú testing'\n").encode('utf-8') self.assertEqual(content, expected) if __name__ == '__main__': unittest.main()
1,472
Python
.py
34
39.558824
71
0.716491
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,627
test_file_handling_nfile.py
ninja-ide_ninja-ide/ninja_tests/core/test_file_handling_nfile.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os import tempfile import pytest from ninja_ide.core.file_handling import nfile from ninja_ide.core.file_handling.file_manager import NinjaNoFileNameException from ninja_ide.core.file_handling.file_manager import NinjaIOException CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) # Test Nfile API works def test_knows_if_exists(): """If the file exists, can NFile tell?""" temp_file = tempfile.NamedTemporaryFile() existing_nfile = nfile.NFile(temp_file.name) assert existing_nfile._exists() def test_knows_if_doesnt_exists(): """If the file does not exists, can NFile tell?""" temp_file = tempfile.NamedTemporaryFile() existing_nfile = nfile.NFile(temp_file.name) temp_file.close() assert not existing_nfile._exists() def test_save_no_filename_raises(): """If there is no filename associated to the nfile we should get error""" no_filename_file = nfile.NFile() with pytest.raises(NinjaNoFileNameException) as info: no_filename_file.save("dumb content") assert str(info.value) == "I am asked to write a file but no one told me"\ " where" def test_creates_if_doesnt_exist(): temp_name = tempfile.NamedTemporaryFile().name assert not os.path.exists(temp_name) a_nfile = nfile.NFile(temp_name) a_nfile.save("empty content") assert os.path.exists(temp_name) def test_actual_content_is_saved(): content = "empty content" temp_name = tempfile.NamedTemporaryFile().name assert not os.path.exists(temp_name) a_nfile = nfile.NFile(temp_name) a_nfile.save(content) a_file = open(temp_name) a_file_content = a_file.read() assert a_file_content == content a_file.close() def test_saves_to_filepath(): temp_name = tempfile.NamedTemporaryFile().name assert not os.path.exists(temp_name) a_nfile = nfile.NFile(temp_name) assert not os.path.exists(a_nfile.file_path) a_nfile.save("content") assert os.path.exists(a_nfile.file_path) def test_path_overrides_filepath(): temp_name = tempfile.NamedTemporaryFile().name temp_name_path = tempfile.NamedTemporaryFile().name temp_name_path = "%s_really_unique" % temp_name_path assert temp_name != temp_name_path assert not temp_name == temp_name_path a_nfile = nfile.NFile(temp_name) assert not os.path.exists(a_nfile.file_path) a_nfile.save("content", path=temp_name_path) assert not os.path.exists(temp_name) assert os.path.exists(temp_name_path) def test_path_is_set_as_new_nfile_filepath(): temp_name = tempfile.NamedTemporaryFile().name temp_name_path = tempfile.NamedTemporaryFile().name temp_name_path = "%s_really_unique" % temp_name_path assert temp_name != temp_name_path a_nfile = nfile.NFile(temp_name) assert temp_name_path != a_nfile.file_path new_nfile = a_nfile.save("content", path=temp_name_path) assert temp_name_path == new_nfile.file_path assert temp_name != a_nfile.file_path def test_copy_flag_saves_to_path_only(): temp_name = tempfile.NamedTemporaryFile().name temp_name_path = tempfile.NamedTemporaryFile().name temp_name_path = u"%s_really_unique" % temp_name_path assert temp_name != temp_name_path a_nfile = nfile.NFile(temp_name) a_nfile.save("content", path=temp_name_path) assert not os.path.exists(temp_name) assert os.path.exists(temp_name_path) def test_file_is_read_properly(): to_load_file = tempfile.NamedTemporaryFile() load_text = "Something to load" to_load_file.write(load_text.encode()) to_load_file.seek(0) a_nfile = nfile.NFile(to_load_file.name) content = a_nfile.read() assert content == load_text def test_file_read_blows_when_nonexistent_path(): a_nfile = nfile.NFile() with pytest.raises(NinjaNoFileNameException): a_nfile.read() def test_file_read_blows_on_nonexistent_file(): temp_name = tempfile.NamedTemporaryFile().name a_nfile = nfile.NFile(temp_name) with pytest.raises(NinjaIOException): a_nfile.read() def test_file_is_moved(): temp_name = tempfile.NamedTemporaryFile().name new_temp_name = "%s_new" % temp_name test_content = "zero" temp_file = open(temp_name, "w") temp_file.write(test_content) temp_file.close() a_nfile = nfile.NFile(temp_name) a_nfile.move(new_temp_name) assert os.path.exists(new_temp_name) read_test_content = open(new_temp_name, "r") assert read_test_content.read() == test_content read_test_content.close() assert not os.path.exists(temp_name) def test_move_changes_filepath(): temp_name = tempfile.NamedTemporaryFile().name new_temp_name = "%s_new" % temp_name test_content = "zero" temp_file = open(temp_name, "w") temp_file.write(test_content) temp_file.close() a_nfile = nfile.NFile(temp_name) a_nfile.move(new_temp_name) assert a_nfile.file_path == new_temp_name def test_filepath_changes_even_if_inexistent(): temp_name = tempfile.NamedTemporaryFile().name a_nfile = nfile.NFile() a_nfile.move(temp_name) assert a_nfile.file_path == temp_name
5,848
Python
.py
141
37.06383
78
0.713858
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,628
__init__.py
ninja-ide_ninja-ide/ninja_tests/core/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
692
Python
.py
16
42.25
70
0.760355
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,629
__test_plugin.py
ninja-ide_ninja-ide/ninja_tests/core/plugins/test_plugin/__test_plugin.py
# -*- coding: utf-8 -*- from ninja_ide.core import plugin class TestPlugin(plugin.Plugin): pass
103
Python
.py
4
23
33
0.71875
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,630
setup.py
ninja-ide_ninja-ide/build_files/installer/windows/setup.py
#********************************************* # Auto-Generated With py2Nsis #********************************************* from setuptools import find_packages packages = find_packages(exclude=["tests"]) import warnings #ignore the sets DeprecationWarning warnings.simplefilter('ignore', DeprecationWarning) import py2exe warnings.resetwarnings() from distutils.core import setup target = { 'script' : "ninja-ide.py", 'version' : "2.1", 'company_name' : "", 'copyright' : "GPL", 'name' : "Ninja", 'dest_base' : "Ninja", 'icon_resources': [(1, "ninja.ico")] } setup( data_files = [], zipfile = None, options = { "py2exe": { "compressed": 0, "optimize": 0, "includes": ['sip', 'PyQt4.QtNetwork', 'win32com'], "excludes": ['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl', 'Tkconstants', 'Tkinter'], "packages": packages, "bundle_files": 1, "dist_dir": "dist", "xref": False, "skip_archive": False, "ascii": False, "custom_boot_script": '', } }, console = [], windows = [target], service = [], com_server = [], ctypes_com_server = [] )
1,372
Python
.py
44
24.159091
169
0.510313
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,631
typing_performance.py
ninja-ide_ninja-ide/ninja_profiling/typing_performance.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import sys from unittest import mock import time from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QTimer from PyQt5.QtCore import Qt from PyQt5.QtTest import QTest sys.path.append("..") from ninja_ide.tools import json_manager from ninja_ide import resources from ninja_ide.core.file_handling import nfile from ninja_ide.gui.editor import neditable from ninja_ide.gui.editor.editor import NEditor from ninja_ide.gui.syntax_registry import syntax_registry # noqa from ninja_ide.gui.ide import IDE json_manager.load_syntax() themes = json_manager.load_editor_schemes() resources.COLOR_SCHEME = themes["Ninja Dark"] qapp = QApplication(sys.argv) IDE.register_service("ide", mock.Mock()) ninja_editor = NEditor(neditable=neditable.NEditable(nfile.NFile())) ninja_editor.side_widgets.remove("CodeFoldingWidget") ninja_editor.side_widgets.remove("MarkerWidget") ninja_editor.side_widgets.remove("TextChangeWidget") ninja_editor.side_widgets.update_viewport() ninja_editor.side_widgets.resize() ninja_editor.register_syntax_for() ninja_editor.showMaximized() click_times = {} with open(sys.argv[1]) as fp: text = fp.read() def click(key): clock_before = time.clock() if isinstance(key, str): QTest.keyClicks(ninja_editor, key) else: QTest.keyClick(ninja_editor, key) while qapp.hasPendingEvents(): qapp.processEvents() clock_after = time.clock() ms = int((clock_after - clock_before) * 100) click_times[ms] = click_times.get(ms, 0) + 1 def test(): clock_before = time.clock() for line in text.splitlines(): indent_width = len(line) - len(line.lstrip()) while ninja_editor.textCursor().positionInBlock() > indent_width: click(Qt.Key_Backspace) for i in range( indent_width - ninja_editor.textCursor().positionInBlock()): click(Qt.Key_Space) line = line[indent_width:] for char in line: click(char) click(Qt.Key_Enter) clock_after = time.clock() typing_time = clock_after - clock_before print("Typed {} chars in {} sec. {} ms per character".format( len(text), typing_time, typing_time * 1000 / len(text))) print("Time per click: Count of clicks") click_time_keys = sorted(click_times.keys()) for click_time_key in click_time_keys: print(" %5dms: %4d" % ( click_time_key, click_times[click_time_key])) qapp.quit() QTimer.singleShot(0, test) qapp.exec_()
3,231
Python
.py
84
34.547619
76
0.71909
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,632
test_python_indenter.py
ninja-ide_ninja-ide/ninja_tests/gui/editor/test_python_indenter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from ninja_ide.gui.editor.base import BaseTextEditor from ninja_ide.gui.editor.indenter.python_indenter import PythonIndenter def make_editor(): editor = BaseTextEditor() indenter = PythonIndenter(editor) return editor, indenter def make_indent(text): editor, indenter = make_editor() editor.text = text cursor = editor.textCursor() cursor.movePosition(cursor.End) editor.setTextCursor(cursor) indenter.indent_block(cursor) return editor.text def test_1(): assert make_indent('def foo():') == 'def foo():\n ' def test_2(): text = make_indent('def foo():\n pass') assert text == 'def foo():\n pass\n' def test_3(): text = make_indent('def foo():\n def inner():') assert text == 'def foo():\n def inner():\n ' def test_4(): text = make_indent("def foo():\n def inner():\n pass") assert text == 'def foo():\n def inner():\n pass\n ' def test_5(): text = make_indent("lista = [23,") assert text == 'lista = [23,\n ' def test_6(): text = make_indent('def foo(*args,') assert text == 'def foo(*args,\n ' def test_7(): a_text = "def foo(arg1,\n arg2, arg3):" text = make_indent(a_text) assert text == 'def foo(arg1,\n arg2, arg3):\n ' def test_8(): a_text = """# Comment class A(object): def __init__(self): self._val = 0 def foo(self): def bar(arg1, arg2):""" text = make_indent(a_text) expected = """# Comment class A(object): def __init__(self): self._val = 0 def foo(self): def bar(arg1, arg2): """ assert text == expected def test_9(): a_text = """# comment lista = [32, 3232332323, [3232,""" text = make_indent(a_text) expected = """# comment lista = [32, 3232332323, [3232, """ assert text == expected def test_10(): # Hang indent # text = make_indent('tupla = (') # assert text == 'tupla = (\n ' pass def test_11(): a_text = "def foo():\n def inner():\n return foo()" text = make_indent(a_text) expected = "def foo():\n def inner():\n return foo()\n " assert text == expected def test_12(): a_text = """if __name__ == "__main__": nombre = input('Nombre: ') print(nombre)""" text = make_indent(a_text) expected = """if __name__ == "__main__": nombre = input('Nombre: ') print(nombre) """ assert text == expected def test_13(): a_text = "d = []" editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 1, 5 indenter.indent_block(editor.textCursor()) expected = "d = [\n \n]" assert editor.text == expected def test_14(): a_text = "d = ['one', 'two']" editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 1, 5 indenter.indent_block(editor.textCursor()) expected = "d = [\n 'one', 'two']" assert editor.text == expected def test_15(): """ { { }, | <-- cursor } """ a_text = "{\n {\n },\n}" editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 2, 6 indenter.indent_block(editor.textCursor()) expected = '{\n {\n },\n \n}' assert editor.text == expected assert editor.cursor_position == (3, 4) def test_16(): """ x = [0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11] """ a_text = "x = [0, 1, 2," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 1, 13 indenter.indent_block(editor.textCursor()) expected = "x = [0, 1, 2,\n " assert editor.text == expected def test_22(): """ x = [0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11] """ a_text = "x = [0, 1, 2,\n [3, 4, 5," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 2, 14 indenter.indent_block(editor.textCursor()) expected = "x = [0, 1, 2,\n [3, 4, 5,\n " assert editor.text == expected def test_23(): """ x = [0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11] """ a_text = "x = [0, 1, 2,\n [3, 4, 5,\n 6, 7, 8]," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 3, 15 indenter.indent_block(editor.textCursor()) expected = "x = [0, 1, 2,\n [3, 4, 5,\n 6, 7, 8],\n " assert editor.text == expected def test_24(): """ x = [ 0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11 ] """ a_text = "x = [\n 0, 1, 2, [3, 4, 5," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 1, 22 indenter.indent_block(editor.textCursor()) expected = "x = [\n 0, 1, 2, [3, 4, 5,\n " assert editor.text == expected def test_25(): """ x = [ 0, 1, 2, [3, 4, 5, 6, 7, 8], 9, 10, 11 ] """ a_text = "x = [\n 0, 1, 2, [3, 4, 5,\n 6, 7, 8]," editor, indenter = make_editor() editor.text = a_text editor.cursor_position = 2, 23 indenter.indent_block(editor.textCursor()) expected = "x = [\n 0, 1, 2, [3, 4, 5,\n 6, 7, 8],\n " assert editor.text == expected def test_26(): expected = 'def foo():\n {}\n' for kw in ('break', 'continue', 'raise', 'pass', 'return'): assert make_indent('def foo():\n {}'.format(kw)) == expected.format(kw)
6,477
Python
.pyt
207
25.661836
82
0.540058
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,633
conftest.py
andreafrancia_trash-cli/conftest.py
def pytest_configure(config): config.addinivalue_line( "markers", "slow: tests that uses the filesystem" )
123
Python
.py
4
25.75
57
0.689076
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,634
setup.py
andreafrancia_trash-cli/setup.py
# Copyright (C) 2007-2021 Andrea Francia Trivolzio(PV) Italy from setuptools import setup setup()
99
Python
.py
3
31.666667
60
0.810526
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,635
test_parsing_trashinfo_contents.py
andreafrancia_trash-cli/tests/test_trashcli_lib/test_parsing_trashinfo_contents.py
# Copyright (C) 2011 Andrea Francia Trivolzio(PV) Italy import unittest from datetime import datetime from tests.support.py2mock import MagicMock from trashcli.parse_trashinfo.parse_path import parse_path from trashcli.parse_trashinfo.parse_trashinfo import ParseTrashInfo from trashcli.parse_trashinfo.maybe_parse_deletion_date import \ maybe_parse_deletion_date, unknown_date from trashcli.parse_trashinfo.parse_original_location import \ parse_original_location from trashcli.parse_trashinfo.parser_error import ParseError from trashcli.parse_trashinfo.parse_deletion_date import parse_deletion_date class TestParseTrashInfo(unittest.TestCase): def test_it_should_parse_date(self): out = MagicMock() parser = ParseTrashInfo(on_deletion_date=out) parser.parse_trashinfo('[Trash Info]\n' 'Path=foo\n' 'DeletionDate=1970-01-01T00:00:00\n') out.assert_called_with(datetime(1970, 1, 1, 0, 0, 0)) def test_it_should_parse_path(self): out = MagicMock() parser = ParseTrashInfo(on_path=out) parser.parse_trashinfo('[Trash Info]\n' 'Path=foo\n' 'DeletionDate=1970-01-01T00:00:00\n') out.assert_called_with('foo') class TestParseDeletionDate(unittest.TestCase): def test1(self): assert parse_deletion_date('DeletionDate=2000-12-31T23:59:58') == \ datetime(2000, 12, 31, 23, 59, 58) def test2(self): assert parse_deletion_date('DeletionDate=2000-12-31T23:59:58\n') == \ datetime(2000, 12, 31, 23, 59, 58) def test3(self): assert parse_deletion_date( '[Trash Info]\nDeletionDate=2000-12-31T23:59:58') == \ datetime(2000, 12, 31, 23, 59, 58) def test_two_deletion_dates(self): assert parse_deletion_date('DeletionDate=2000-01-01T00:00:00\n' 'DeletionDate=2000-12-31T00:00:00\n') == \ datetime(2000, 1, 1, 0, 0) class Test_maybe_parse_deletion_date(unittest.TestCase): def test_on_trashinfo_without_date_parse_to_unknown_date(self): assert (unknown_date == maybe_parse_deletion_date(a_trashinfo_without_deletion_date())) def test_on_trashinfo_with_date_parse_to_date(self): from datetime import datetime example_date_as_string = '2001-01-01T00:00:00' same_date_as_datetime = datetime(2001, 1, 1) assert (same_date_as_datetime == maybe_parse_deletion_date( make_trashinfo(example_date_as_string))) def test_on_trashinfo_with_invalid_date_parse_to_unknown_date(self): invalid_date = 'A long time ago' assert (unknown_date == maybe_parse_deletion_date(make_trashinfo(invalid_date))) def test_how_to_parse_original_path(): assert 'foo.txt' == parse_path('Path=foo.txt') assert '/path/to/be/escaped' == parse_path( 'Path=%2Fpath%2Fto%2Fbe%2Fescaped') class TestTrashInfoParser(unittest.TestCase): def test_1(self): assert '/foo.txt' == parse_original_location("[Trash Info]\n" "Path=/foo.txt\n", '/') def test_it_raises_error_on_parsing_original_location(self): with self.assertRaises(ParseError): parse_original_location(an_empty_trashinfo(), '/') def a_trashinfo_without_deletion_date(): return ("[Trash Info]\n" "Path=foo.txt\n") def make_trashinfo(date): return ("[Trash Info]\n" "Path=foo.txt\n" "DeletionDate=%s" % date) def an_empty_trashinfo(): return ''
3,777
Python
.py
78
38.064103
79
0.631608
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,636
test_trash_dir_reader.py
andreafrancia_trash-cli/tests/test_trashcli_lib/test_trash_dir_reader.py
# Copyright (C) 2011 Andrea Francia Trivolzio(PV) Italy import unittest from tests.support.fakes.fake_file_system import FakeFileSystem from trashcli.lib.trash_dir_reader import TrashDirReader class TestTrashDirReader(unittest.TestCase): def setUp(self): self.fs = FakeFileSystem() self.trash_dir = TrashDirReader(self.fs) def test(self): self.fs.create_fake_file('/info/foo.trashinfo') result = list(self.trash_dir.list_orphans('/')) assert [] == result def test2(self): self.fs.create_fake_file('/files/foo') result = list(self.trash_dir.list_orphans('/')) assert ['/files/foo'] == result
677
Python
.py
16
35.9375
63
0.689708
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,637
test_trash_dir_scanner.py
andreafrancia_trash-cli/tests/test_trashcli_lib/trash_dir_scanner/test_trash_dir_scanner.py
import unittest from tests.support.py2mock import Mock from trashcli.fstab.volume_listing import VolumesListing from trashcli.lib.dir_checker import DirChecker from trashcli.lib.user_info import SingleUserInfoProvider from trashcli.trash_dirs_scanner import TrashDirsScanner, trash_dir_found class TestTrashDirScanner(unittest.TestCase): def test_scan_trash_dirs(self): volumes_listing = Mock(spec=VolumesListing) user_info_provider = SingleUserInfoProvider() dir_checker = Mock(spec=DirChecker) scanner = TrashDirsScanner( user_info_provider, volumes_listing=volumes_listing, top_trash_dir_rules=Mock(), dir_checker=dir_checker ) dir_checker.is_dir.return_value = True volumes_listing.list_volumes.return_value = ['/vol', '/vol2'] result = list(scanner.scan_trash_dirs({'HOME': '/home/user'}, 123)) self.assertEqual( [(trash_dir_found, ('/home/user/.local/share/Trash', '/')), (trash_dir_found, ('/vol/.Trash-123', '/vol')), (trash_dir_found, ('/vol2/.Trash-123', '/vol2'))], result)
1,153
Python
.py
24
40.041667
75
0.673197
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,638
test_top_trash_dir_rules.py
andreafrancia_trash-cli/tests/test_trashcli_lib/trash_dir_scanner/test_top_trash_dir_rules.py
import unittest from tests.support.py2mock import Mock, call from trashcli.trash_dirs_scanner import ( TopTrashDirRules, top_trash_dir_does_not_exist, top_trash_dir_invalid_because_not_sticky, top_trash_dir_invalid_because_parent_is_symlink, top_trash_dir_valid, ) class TestTopTrashDirRules(unittest.TestCase): def setUp(self): self.fs = Mock(spec=['exists', 'is_sticky_dir', 'is_symlink']) self.rules = TopTrashDirRules(self.fs) def test_path_not_exists(self): self.fs.exists.return_value = False result = self.rules.valid_to_be_read("/path") assert (result, self.fs.mock_calls) == \ (top_trash_dir_does_not_exist, [call.exists('/path')]) def test_parent_not_sticky(self): self.fs.exists.return_value = True self.fs.is_sticky_dir.return_value = False result = self.rules.valid_to_be_read("/path") assert (result, self.fs.mock_calls) == \ (top_trash_dir_invalid_because_not_sticky, [call.exists('/path'), call.is_sticky_dir('/')]) def test_parent_is_symlink(self): self.fs.exists.return_value = True self.fs.is_sticky_dir.return_value = True self.fs.is_symlink.return_value = True result = self.rules.valid_to_be_read("/path") assert (result, self.fs.mock_calls) == \ (top_trash_dir_invalid_because_parent_is_symlink, [call.exists('/path'), call.is_sticky_dir('/'), call.is_symlink('/')]) def test_parent_is_sym(self): self.fs.exists.return_value = True self.fs.is_sticky_dir.return_value = True self.fs.is_symlink.return_value = False result = self.rules.valid_to_be_read("/path") assert (result, self.fs.mock_calls) == \ (top_trash_dir_valid, [call.exists('/path'), call.is_sticky_dir('/'), call.is_symlink('/')])
2,033
Python
.py
47
33.404255
70
0.598174
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,639
test_user_info_provider.py
andreafrancia_trash-cli/tests/test_trashcli_lib/trash_dir_scanner/test_user_info_provider.py
import unittest from trashcli.lib.user_info import SingleUserInfoProvider class TestUserInfoProvider(unittest.TestCase): def setUp(self): self.provider = SingleUserInfoProvider() def test_getuid(self): info = self.provider.get_user_info({}, 123) assert [123] == [i.uid for i in info] def test_home(self): info = self.provider.get_user_info({'HOME':"~"}, 123) assert [['~/.local/share/Trash']] == \ [i.home_trash_dir_paths for i in info]
513
Python
.py
12
35.416667
61
0.650407
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,640
test_volumes_listing.py
andreafrancia_trash-cli/tests/test_trashcli_lib/test_fstab/test_volumes_listing.py
import unittest from trashcli.fstab.mount_points_listing import FakeMountPointsListing from trashcli.fstab.volume_listing import VolumesListingImpl class TestVolumesListingImpl(unittest.TestCase): def setUp(self): self.volumes_listing = VolumesListingImpl(FakeMountPointsListing(['/os-vol1', '/os-vol2'])) def test_os_mount_points(self): result = self.volumes_listing.list_volumes({}) assert list(result) == ['/os-vol1', '/os-vol2'] def test_one_vol_from_environ(self): result = self.volumes_listing.list_volumes({'TRASH_VOLUMES': '/fake-vol1'}) assert list(result) == ['/fake-vol1'] def test_multiple_vols_from_environ(self): result = self.volumes_listing.list_volumes({'TRASH_VOLUMES': '/fake-vol1:/fake-vol2:/fake-vol3'}) assert list(result) == ['/fake-vol1', '/fake-vol2', '/fake-vol3'] def test_empty_environ(self): result = self.volumes_listing.list_volumes({'TRASH_VOLUMES': ''}) assert list(result) == ['/os-vol1', '/os-vol2'] def test_skip_empty_vol(self): result = self.volumes_listing.list_volumes({'TRASH_VOLUMES': '/vol1::/vol2'}) assert list(result) == ['/vol1', '/vol2']
1,211
Python
.py
21
50.714286
105
0.675446
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,641
test_trash_rm.py
andreafrancia_trash-cli/tests/test_rm/cmd/test_trash_rm.py
import unittest from six import StringIO from tests.support.py2mock import Mock from tests.support.asserts import assert_starts_with from trashcli.rm.rm_cmd import RmCmd class TestTrashRmCmdRun(unittest.TestCase): def setUp(self): self.volumes_listing = Mock() self.stderr = StringIO() self.file_reader = Mock([]) self.file_reader.exists = Mock([], return_value=None) self.file_reader.entries_if_dir_exists = Mock([], return_value=[]) self.environ = {} self.getuid = lambda: '111' self.cmd = RmCmd(self.environ, self.getuid, self.volumes_listing, self.stderr, self.file_reader) def test_without_arguments(self): self.cmd.run([None], uid=None) assert_starts_with(self.stderr.getvalue(), 'Usage:\n trash-rm PATTERN\n\nPlease specify PATTERN.\n') def test_without_pattern_argument(self): self.volumes_listing.list_volumes.return_value = ['/vol1'] self.cmd.run([None, None], uid=None) assert '' == self.stderr.getvalue()
1,173
Python
.py
27
33.074074
87
0.610035
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,642
test_trash_rm_slow.py
andreafrancia_trash-cli/tests/test_rm/cmd/test_trash_rm_slow.py
import unittest import pytest from six import StringIO from tests.support.fakes.fake_trash_dir import FakeTrashDir from tests.support.dirs.my_path import MyPath from trashcli.fstab.volume_listing import NoVolumesListing from trashcli.rm.main import RealRmFileSystemReader from trashcli.rm.rm_cmd import RmCmd @pytest.mark.slow class TestTrashRm(unittest.TestCase): def setUp(self): self.xdg_data_home = MyPath.make_temp_dir() self.stderr = StringIO() self.trash_rm = RmCmd(environ={'XDG_DATA_HOME': self.xdg_data_home}, getuid=lambda: 123, volumes_listing=NoVolumesListing(), stderr=self.stderr, file_reader=RealRmFileSystemReader()) self.fake_trash_dir = FakeTrashDir(self.xdg_data_home / 'Trash') def test_issue69(self): self.fake_trash_dir.add_trashinfo_without_path('foo') self.trash_rm.run(['trash-rm', 'ignored'], uid=None) assert (self.stderr.getvalue() == "trash-rm: %s/Trash/info/foo.trashinfo: unable to parse 'Path'" '\n' % self.xdg_data_home) def test_integration(self): self.fake_trash_dir.add_trashinfo_basename_path("del", 'to/be/deleted') self.fake_trash_dir.add_trashinfo_basename_path("keep", 'to/be/kept') self.trash_rm.run(['trash-rm', 'delete*'], uid=None) assert self.fake_trash_dir.ls_info() == ['keep.trashinfo'] def tearDown(self): self.xdg_data_home.clean_up()
1,562
Python
.py
32
39.21875
79
0.647136
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,643
test_list_trash_info.py
andreafrancia_trash-cli/tests/test_rm/components/test_list_trash_info.py
import unittest import pytest from tests.support.fakes.fake_trash_dir import FakeTrashDir from tests.support.dirs.my_path import MyPath from trashcli.file_system_reader import FileSystemReader from trashcli.rm.list_trashinfo import ListTrashinfos @pytest.mark.slow class TestListTrashinfos(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() self.trash_dir = self.tmp_dir / 'Trash' self.fake_trash_dir = FakeTrashDir(self.trash_dir) self.listing = ListTrashinfos.make(FileSystemReader(), FileSystemReader()) def test_absolute_path(self): self.fake_trash_dir.add_trashinfo_basename_path('a', '/foo') result = list(self.listing.list_from_volume_trashdir(self.trash_dir, '/volume/')) assert result == [('trashed_file', ('/foo', '%s/info/a.trashinfo' % self.trash_dir))] def test_relative_path(self): self.fake_trash_dir.add_trashinfo_basename_path('a', 'foo') result = list(self.listing.list_from_volume_trashdir(self.trash_dir, '/volume/')) assert result == [('trashed_file', ('/volume/foo', '%s/info/a.trashinfo' % self.trash_dir))] def tearDown(self): self.tmp_dir.clean_up()
1,390
Python
.py
27
39.703704
84
0.615385
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,644
test_file_remover.py
andreafrancia_trash-cli/tests/test_rm/components/test_file_remover.py
import unittest from trashcli.rm.file_remover import FileRemover try: FileNotFoundError except NameError: FileNotFoundError = OSError # python 2 class TestFileRemover(unittest.TestCase): def test_remove_file_fails_when_file_does_not_exists(self): file_remover = FileRemover() self.assertRaises(FileNotFoundError, file_remover.remove_file2, '/non/existing/path')
422
Python
.py
11
32
71
0.731527
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,645
test_filter.py
andreafrancia_trash-cli/tests/test_rm/components/test_filter.py
import unittest from trashcli.rm.filter import Filter class TestFilter(unittest.TestCase): def test_a_star_matches_all(self): self.cmd = Filter('*') assert self.cmd.matches('foo') == True assert self.cmd.matches('bar') == True def test_basename_matches(self): self.cmd = Filter('foo') assert self.cmd.matches('foo') == True assert self.cmd.matches('bar') == False def test_example_with_star_dot_o(self): self.cmd = Filter('*.o') assert self.cmd.matches('/foo.h') == False assert self.cmd.matches('/foo.c') == False assert self.cmd.matches('/foo.o') == True assert self.cmd.matches('/bar.o') == True def test_absolute_pattern(self): self.cmd = Filter('/foo/bar.baz') assert self.cmd.matches('/foo/bar.baz') == True assert self.cmd.matches('/foo/bar') == False def test(self): self.cmd = Filter('/foo/*.baz') assert self.cmd.matches('/foo/bar.baz') == True assert self.cmd.matches('/foo/bar.bar') == False
1,073
Python
.py
25
35.16
56
0.61256
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,646
test_empty_cmd_fs.py
andreafrancia_trash-cli/tests/test_empty/cmd/test_empty_cmd_fs.py
# Copyright (C) 2011-2022 Andrea Francia Bereguardo(PV) Italy import unittest import pytest from tests.support.py2mock import Mock from six import StringIO from tests.support.fakes.stub_volume_of import StubVolumeOf from tests.support.files import make_unreadable_dir, make_readable from tests.support.dirs.my_path import MyPath from trashcli.empty.empty_cmd import EmptyCmd from trashcli.empty.existing_file_remover import ExistingFileRemover from trashcli.empty.file_system_dir_reader import FileSystemDirReader from trashcli.empty.main import FileSystemContentReader from trashcli.empty.top_trash_dir_rules_file_system_reader import \ RealTopTrashDirRulesReader from trashcli.fstab.volume_listing import VolumesListing @pytest.mark.slow class TestTrashEmptyCmdFs(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() self.unreadable_dir = self.tmp_dir / 'data/Trash/files/unreadable' self.volumes_listing = Mock(spec=VolumesListing) self.volumes_listing.list_volumes.return_value = [self.unreadable_dir] self.err = StringIO() self.environ = {'XDG_DATA_HOME': self.tmp_dir / 'data'} self.empty = EmptyCmd( argv0='trash-empty', out=StringIO(), err=self.err, volumes_listing=self.volumes_listing, now=None, file_reader=RealTopTrashDirRulesReader(), file_remover=ExistingFileRemover(), content_reader=FileSystemContentReader(), dir_reader=FileSystemDirReader(), version='unused', volumes=StubVolumeOf() ) def test_trash_empty_will_skip_unreadable_dir(self): make_unreadable_dir(self.unreadable_dir) self.empty.run_cmd([], self.environ, uid=123) assert ("trash-empty: cannot remove %s\n" % self.unreadable_dir == self.err.getvalue()) def tearDown(self): make_readable(self.unreadable_dir) self.tmp_dir.clean_up()
2,008
Python
.py
45
37.488889
78
0.71202
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,647
test_empty_cmd_with_multiple_volumes_fs.py
andreafrancia_trash-cli/tests/test_empty/cmd/test_empty_cmd_with_multiple_volumes_fs.py
# Copyright (C) 2011-2022 Andrea Francia Bereguardo(PV) Italy import os import unittest from tests.support.py2mock import Mock from six import StringIO from tests.support.fakes.stub_volume_of import StubVolumeOf from tests.support.files import make_empty_file, require_empty_dir, make_dirs, \ set_sticky_bit from tests.support.dirs.my_path import MyPath from trashcli.empty.empty_cmd import EmptyCmd from trashcli.empty.existing_file_remover import ExistingFileRemover from trashcli.empty.file_system_dir_reader import FileSystemDirReader from trashcli.empty.main import FileSystemContentReader from trashcli.empty.top_trash_dir_rules_file_system_reader import \ RealTopTrashDirRulesReader from trashcli.fstab.volume_listing import VolumesListing class TestEmptyCmdWithMultipleVolumesFs(unittest.TestCase): def setUp(self): self.temp_dir = MyPath.make_temp_dir() self.top_dir = self.temp_dir / 'topdir' self.volumes_listing = Mock(spec=VolumesListing) self.volumes_listing.list_volumes.return_value = [self.top_dir] require_empty_dir(self.top_dir) self.environ = {} self.empty_cmd = EmptyCmd( argv0='trash-empty', out=StringIO(), err=StringIO(), volumes_listing=self.volumes_listing, now=None, file_reader=RealTopTrashDirRulesReader(), file_remover=ExistingFileRemover(), content_reader=FileSystemContentReader(), dir_reader=FileSystemDirReader(), version='unused', volumes=StubVolumeOf(), ) def test_it_removes_trashinfos_from_method_1_dir(self): self.make_proper_top_trash_dir(self.top_dir / '.Trash') make_empty_file(self.top_dir / '.Trash/123/info/foo.trashinfo') self.empty_cmd.run_cmd([], self.environ, uid=123) assert not os.path.exists( self.top_dir / '.Trash/123/info/foo.trashinfo') def test_it_removes_trashinfos_from_method_2_dir(self): make_empty_file(self.top_dir / '.Trash-123/info/foo.trashinfo') self.empty_cmd.run_cmd([], self.environ, uid=123) assert not os.path.exists( self.top_dir / '.Trash-123/info/foo.trashinfo') def test_it_removes_trashinfo_from_specified_trash_dir(self): make_empty_file(self.temp_dir / 'specified/info/foo.trashinfo') self.empty_cmd.run_cmd(['--trash-dir', self.temp_dir / 'specified'], self.environ, uid=123) assert not os.path.exists( self.temp_dir / 'specified/info/foo.trashinfo') @staticmethod def make_proper_top_trash_dir(path): make_dirs(path) set_sticky_bit(path) def tearDown(self): self.temp_dir.clean_up()
2,782
Python
.py
60
38.4
80
0.685999
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,648
test_empty_cmd.py
andreafrancia_trash-cli/tests/test_empty/cmd/test_empty_cmd.py
# Copyright (C) 2011-2022 Andrea Francia Bereguardo(PV) Italy import unittest from typing import cast from tests.support.py2mock import Mock, call from six import StringIO from tests.support.fakes.stub_volume_of import StubVolumeOf from tests.support.fakes.mock_dir_reader import MockDirReader from trashcli.empty.delete_according_date import ContentsOf from trashcli.empty.empty_cmd import EmptyCmd from trashcli.empty.existing_file_remover import ExistingFileRemover from trashcli.fstab.volume_listing import FixedVolumesListing from trashcli.fstab.volume_listing import VolumesListing from trashcli.lib.dir_reader import DirReader from trashcli.trash_dirs_scanner import TopTrashDirRules class TestTrashEmptyCmdFs(unittest.TestCase): def setUp(self): self.volumes_listing = FixedVolumesListing([]) self.file_reader = Mock(spec=TopTrashDirRules.Reader) self.file_remover = Mock(spec=ExistingFileRemover) self.content_reader = Mock(spec=ContentsOf) self.dir_reader = MockDirReader() self.err = StringIO() self.out = StringIO() self.environ = {'XDG_DATA_HOME': '/xdg'} self.empty = EmptyCmd( argv0='trash-empty', out=self.out, err=self.err, volumes_listing=cast(VolumesListing, self.volumes_listing), now=None, file_reader=cast(TopTrashDirRules.Reader, self.file_reader), file_remover=cast(ExistingFileRemover, self.file_remover), content_reader=cast(ContentsOf, self.content_reader), dir_reader=cast(DirReader, self.dir_reader), version='unused', volumes=StubVolumeOf() ) def test(self): self.dir_reader.mkdir('/xdg') self.dir_reader.mkdir('/xdg/Trash') self.dir_reader.mkdir('/xdg/Trash/info') self.dir_reader.add_file('/xdg/Trash/info/pippo.trashinfo') self.dir_reader.mkdir('/xdg/Trash/files') self.empty.run_cmd([], self.environ, uid=123) assert self.file_remover.mock_calls == [ call.remove_file_if_exists('/xdg/Trash/files/pippo'), call.remove_file_if_exists('/xdg/Trash/info/pippo.trashinfo') ] def test_with_dry_run(self): self.dir_reader.mkdir('/xdg') self.dir_reader.mkdir('/xdg/Trash') self.dir_reader.mkdir('/xdg/Trash/info') self.dir_reader.add_file('/xdg/Trash/info/pippo.trashinfo') self.dir_reader.mkdir('/xdg/Trash/files') self.empty.run_cmd(['--dry-run'], self.environ, uid=123) assert self.file_remover.mock_calls == [] assert self.out.getvalue() == \ 'would remove /xdg/Trash/files/pippo\n' \ 'would remove /xdg/Trash/info/pippo.trashinfo\n'
2,778
Python
.py
59
39.050847
73
0.68155
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,649
test_user.py
andreafrancia_trash-cli/tests/test_empty/components/test_user.py
import unittest from tests.support.py2mock import Mock, call from trashcli.empty.user import User from trashcli.lib.my_input import HardCodedInput class TestUser(unittest.TestCase): def setUp(self): self.prepare_output_message = Mock(spec=[]) self.input = HardCodedInput() self.parse_reply = Mock(spec=[]) self.user = User(self.prepare_output_message, self.input, self.parse_reply) def test(self): self.prepare_output_message.return_value = 'output_msg' self.parse_reply.return_value = 'result' self.input.set_reply('reply') result = self.user.do_you_wanna_empty_trash_dirs(['trash_dirs']) assert [ result, self.input.used_prompt, self.prepare_output_message.mock_calls, self.parse_reply.mock_calls, ] == [ 'result', 'output_msg', [call(['trash_dirs'])], [call('reply')] ]
1,042
Python
.py
26
28.730769
83
0.574827
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,650
test_make_parser.py
andreafrancia_trash-cli/tests/test_empty/components/test_make_parser.py
import unittest from typing import Union from trashcli.empty.parser import Parser class TestMakeParser(unittest.TestCase): def setUp(self): self.parser = Parser() def test(self): parsed = self.parse(args=['--trash-dir=foo']) assert ['foo'] == parsed.user_specified_trash_dirs def test_non_interactive_default_is_non_interactive(self): parsed = self.parse(default_is_interactive=False, args=[]) assert parsed.interactive == False def test_interactive_default_is_interactive(self): parsed = self.parse(default_is_interactive=True, args=[]) assert parsed.interactive == True def test_interactive_made_non_interactive(self): parsed = self.parse(default_is_interactive=True, args=['-f']) assert parsed.interactive == False def test_dry_run(self): parsed = self.parse(args=['--dry-run']) assert parsed.dry_run == True def test_dry_run_default(self): parsed = self.parse(args=[]) assert parsed.dry_run == False def parse(self, args, default_is_interactive="ignored", # type: Union[bool, str] ): return self.parser.parse(default_is_interactive=default_is_interactive, args=args, environ={}, uid=0, argv0="ignored",)
1,513
Python
.py
35
30.685714
79
0.571819
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,651
test_empty_end_to_end_with_argument.py
andreafrancia_trash-cli/tests/test_empty/components/test_empty_end_to_end_with_argument.py
import datetime import unittest import pytest from tests.support.fakes.fake_trash_dir import FakeTrashDir from tests.support.trash_dirs.list_trash_dir import list_trash_dir from tests.support.dirs.my_path import MyPath from tests.support.run.run_command import run_command @pytest.mark.slow class TestEmptyEndToEndWithArgument(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() self.xdg_data_home = self.tmp_dir / 'XDG_DATA_HOME' self.environ = {'XDG_DATA_HOME': self.xdg_data_home} self.trash_dir = self.xdg_data_home / 'Trash' self.fake_trash_dir = FakeTrashDir(self.trash_dir) def user_run_trash_empty(self, args): return run_command(self.tmp_dir, "trash-empty", args, env=self.environ) def set_clock_at(self, yyyy_mm_dd): self.environ['TRASH_DATE'] = '%sT00:00:00' % yyyy_mm_dd def test_set_clock(self): self.set_clock_at('2000-01-01') result = self.user_run_trash_empty(['--print-time']) self.assertEqual(('2000-01-01T00:00:00\n', '', 0), result.all) def test_it_should_keep_files_newer_than_N_days(self): self.fake_trash_dir.add_trashinfo_with_date('foo', datetime.date(2000, 1, 1)) self.set_clock_at('2000-01-01') self.user_run_trash_empty(['2']) assert list_trash_dir(self.trash_dir) == ['info/foo.trashinfo'] def test_it_should_remove_files_older_than_N_days(self): self.fake_trash_dir.add_trashinfo_with_date('foo', datetime.date(1999, 1, 1)) self.set_clock_at('2000-01-01') self.user_run_trash_empty(['2']) assert list_trash_dir(self.trash_dir) == [] def test_it_should_kept_files_with_invalid_deletion_date(self): self.fake_trash_dir.add_trashinfo_with_invalid_date('foo', 'Invalid Date') self.set_clock_at('2000-01-01') self.user_run_trash_empty(['2']) assert list_trash_dir(self.trash_dir) == ['info/foo.trashinfo'] def tearDown(self): self.tmp_dir.clean_up()
2,033
Python
.py
40
43.95
85
0.674772
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,652
test_empty_end_to_end_with_trash_dir.py
andreafrancia_trash-cli/tests/test_empty/components/test_empty_end_to_end_with_trash_dir.py
import os import unittest from tests.support.run.run_command import run_command from tests.support.fakes.fake_trash_dir import FakeTrashDir from tests.support.files import make_file from tests.support.trash_dirs.list_trash_dir import list_trash_dir from tests.support.dirs.my_path import MyPath class TestEmptyEndToEndWithTrashDir(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() self.trash_dir = self.tmp_dir / 'trash-dir' self.fake_trash_dir = FakeTrashDir(self.trash_dir) def test_add_trashed_file(self): self.fake_trash_dir.add_trashed_file('foo', '/foo', 'FOO') assert list_trash_dir(self.trash_dir) == ['info/foo.trashinfo', 'files/foo'] def test_trash_dir(self): self.fake_trash_dir.add_trashed_file('foo', '/foo', 'FOO') result = run_command(self.tmp_dir, "trash-empty", ['--trash-dir', self.trash_dir]) assert [result.all, list_trash_dir(self.trash_dir)] == \ [('', '', 0), []] def test_xdg_data_home(self): xdg_data_home = self.tmp_dir / 'xdg' FakeTrashDir(xdg_data_home / 'Trash').add_trashed_file('foo', '/foo', 'FOO') result = run_command(self.tmp_dir, "trash-empty", [], env={'XDG_DATA_HOME': xdg_data_home}) trash_dir = xdg_data_home / 'Trash' assert [result.all, list_trash_dir(trash_dir)] == \ [('', '', 0), []] def test_non_trash_info_is_not_deleted(self): make_file(self.trash_dir / 'info' / 'non-trashinfo') result = run_command(self.tmp_dir, "trash-empty", ['--trash-dir', self.trash_dir]) assert [result.all, list_trash_dir(self.trash_dir)] == \ [('', '', 0), ['info/non-trashinfo']] def test_orphan_are_deleted(self): make_file(self.trash_dir / 'files' / 'orphan') os.makedirs(self.trash_dir / 'files' / 'orphan dir') result = run_command(self.tmp_dir, "trash-empty", ['--trash-dir', self.trash_dir]) assert [result.all, list_trash_dir(self.trash_dir)] == \ [('', '', 0), []] def tearDown(self): self.tmp_dir.clean_up()
2,431
Python
.py
48
37.9375
77
0.549683
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,653
test_empty_end_to_end_interactive.py
andreafrancia_trash-cli/tests/test_empty/components/test_empty_end_to_end_interactive.py
import datetime import unittest import pytest from tests.support.fakes.fake_trash_dir import FakeTrashDir from tests.support.dirs.my_path import MyPath from tests.support.run.run_command import run_command @pytest.mark.slow class TestEmptyEndToEndInteractive(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() self.xdg_data_home = self.tmp_dir / 'XDG_DATA_HOME' self.environ = { 'XDG_DATA_HOME': self.xdg_data_home, 'TRASH_VOLUMES': ':' } self.trash_dir = self.xdg_data_home / 'Trash' self.fake_trash_dir = FakeTrashDir(self.trash_dir) def user_run_trash_empty(self, args): return run_command(self.tmp_dir, "trash-empty", args, env=self.environ, input='y') def set_clock_at(self, yyyy_mm_dd): self.environ['TRASH_DATE'] = '%sT00:00:00' % yyyy_mm_dd def test_it_should_keep_files_newer_than_N_days(self): self.fake_trash_dir.add_trashinfo_with_date('foo', datetime.date(2000, 1, 1)) self.set_clock_at('2000-01-01') result = self.user_run_trash_empty(['-i']) assert result.all == ( 'Would empty the following trash directories:\n' ' - %s\n' 'Proceed? (y/N) ' % self.trash_dir, '', 0) def tearDown(self): self.tmp_dir.clean_up()
1,374
Python
.py
32
35.03125
85
0.631381
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,654
test_clock.py
andreafrancia_trash-cli/tests/test_empty/components/test_clock.py
import datetime import unittest from tests.support.py2mock import Mock, call from trashcli.empty.clock import Clock class TestClock(unittest.TestCase): def setUp(self): self.errors = Mock(spec=['print_error']) def test_return_real_time(self): clock = Clock(lambda: 'now', self.errors) result = clock.get_now_value({}) assert (result, []) == ('now', self.errors.mock_calls) def test_return_fake_time(self): clock = Clock(lambda: 'now', self.errors) result = clock.get_now_value({'TRASH_DATE': '2021-06-04T18:40:19'}) assert (result, []) == (datetime.datetime(2021, 6, 4, 18, 40, 19), self.errors.mock_calls) def test_return_true_now_whe_fake_time_is_invalid(self): clock = Clock(lambda: 'now', self.errors) result = clock.get_now_value({'TRASH_DATE': 'invalid'}) assert (result, [call.print_error('invalid TRASH_DATE: invalid')]) == \ ('now', self.errors.mock_calls)
1,037
Python
.py
22
38.363636
75
0.617149
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,655
test_prepare_output_message.py
andreafrancia_trash-cli/tests/test_empty/components/test_prepare_output_message.py
import unittest from trashcli.empty.prepare_output_message import prepare_output_message from trashcli.trash_dirs_scanner import trash_dir_found class TestPrepareOutputMessage(unittest.TestCase): def test_one_dir(self): trash_dirs = [ (trash_dir_found, ('/Trash', '/')), ] result = prepare_output_message(trash_dirs) assert """\ Would empty the following trash directories: - /Trash Proceed? (y/N) """ == result def test_multiple_dirs(self): trash_dirs = [ (trash_dir_found, ('/Trash1', '/')), (trash_dir_found, ('/Trash2', '/')), ] result = prepare_output_message(trash_dirs) assert """\ Would empty the following trash directories: - /Trash1 - /Trash2 Proceed? (y/N) """ == result def test_no_dirs(self): trash_dirs = [] result = prepare_output_message(trash_dirs) assert """\ No trash directories to empty. """ == result
981
Python
.py
30
26.466667
72
0.622081
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,656
test_guard.py
andreafrancia_trash-cli/tests/test_empty/components/test_guard.py
import unittest from tests.support.py2mock import Mock, call from trashcli.empty.guard import Guard, UserIntention class TestGuard(unittest.TestCase): def setUp(self): self.user = Mock(spec=['do_you_wanna_empty_trash_dirs']) self.guard = Guard(self.user) def test_user_says_yes(self): self.user.do_you_wanna_empty_trash_dirs.return_value = True result = self.guard.ask_the_user(True, ['trash_dirs']) assert UserIntention(ok_to_empty=True, trash_dirs=['trash_dirs']) == result def test_user_says_no(self): self.user.do_you_wanna_empty_trash_dirs.return_value = False result = self.guard.ask_the_user(True, ['trash_dirs']) assert UserIntention(ok_to_empty=False, trash_dirs=[]) == result def test_it_just_calls_the_emptier(self): result = self.guard.ask_the_user(False, ['trash_dirs']) assert UserIntention(ok_to_empty=True, trash_dirs=['trash_dirs']) == result
1,054
Python
.py
21
39.952381
68
0.632094
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,657
test_empty_end_to_end.py
andreafrancia_trash-cli/tests/test_empty/components/test_empty_end_to_end.py
import unittest from trashcli import trash from tests.support.help.help_reformatting import reformat_help_message from tests.support.dirs.my_path import MyPath from tests.support.run.run_command import run_command class TestEmptyEndToEnd(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() def test_help(self): result = run_command(self.tmp_dir, "trash-empty", ['--help']) self.assertEqual([reformat_help_message("""\ usage: trash-empty [-h] [--print-completion {bash,zsh,tcsh}] [--version] [-v] [--trash-dir TRASH_DIR] [--all-users] [-i] [-f] [--dry-run] [days] Purge trashed files. positional arguments: days options: -h, --help show this help message and exit --print-completion {bash,zsh,tcsh} print shell completion script --version show program's version number and exit -v, --verbose list files that will be deleted --trash-dir TRASH_DIR specify the trash directory to use --all-users empty all trashcan of all the users -i, --interactive ask before emptying trash directories -f don't ask before emptying trash directories --dry-run show which files would have been removed Report bugs to https://github.com/andreafrancia/trash-cli/issues """), '', 0], [result.reformatted_help(), result.stderr, result.exit_code]) def test_h(self): result = run_command(self.tmp_dir, "trash-empty", ['-h']) self.assertEqual(["usage:", '', 0], [result.stdout[0:6], result.stderr, result.exit_code]) def test_version(self): result = run_command(self.tmp_dir, "trash-empty", ['--version']) self.assertEqual(['trash-empty %s\n' % trash.version, '', 0], [result.stdout, result.stderr, result.exit_code]) def test_on_invalid_option(self): result = run_command(self.tmp_dir, "trash-empty", ['--wrong-option']) self.assertEqual(['', 'trash-empty: error: unrecognized arguments: --wrong-option', 2], [result.stdout, result.stderr.splitlines()[-1], result.exit_code]) def test_on_print_time(self): result = run_command(self.tmp_dir, "trash-empty", ['--print-time'], env={'TRASH_DATE': '1970-12-31T23:59:59'}) self.assertEqual(('1970-12-31T23:59:59\n', '', 0), result.all) def test_on_trash_date_not_parsable(self): result = run_command(self.tmp_dir, "trash-empty", ['--print-time'], env={'TRASH_DATE': 'not a valid date'}) self.assertEqual(['trash-empty: invalid TRASH_DATE: not a valid date\n', 0], [result.stderr, result.exit_code]) def tearDown(self): self.tmp_dir.clean_up()
3,165
Python
.py
66
36.272727
87
0.561221
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,658
test_existing_file_remover.py
andreafrancia_trash-cli/tests/test_empty/components/test_existing_file_remover.py
import unittest from trashcli.empty.existing_file_remover import ExistingFileRemover class TestExistingFileRemover(unittest.TestCase): def test_remove_file_if_exists_fails_when_file_does_not_exists(self): file_remover = ExistingFileRemover() file_remover.remove_file_if_exists('/non/existing/path')
323
Python
.py
6
48.833333
73
0.792332
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,659
test_parse_reply.py
andreafrancia_trash-cli/tests/test_empty/components/test_parse_reply.py
import unittest from trashcli.empty.parse_reply import parse_reply class TestParseReply(unittest.TestCase): def test_y(self): assert parse_reply('y') == True def test_Y(self): assert parse_reply('Y') == True def test_n(self): assert parse_reply('n') == False def test_N(self): assert parse_reply('N') == False def test_empty_string(self): assert parse_reply('') == False
438
Python
.py
13
27.538462
50
0.643541
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,660
capture_exit_code.py
andreafrancia_trash-cli/tests/support/capture_exit_code.py
def capture_exit_code(callable): try: callable() except SystemExit as e: return e.code return None
127
Python
.py
6
15.5
32
0.636364
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,661
project_root.py
andreafrancia_trash-cli/tests/support/project_root.py
import os def project_root(): this_file = os.path.realpath(__file__) support_dir = os.path.dirname(this_file) tests_dir = os.path.dirname(support_dir) return os.path.dirname(tests_dir)
203
Python
.py
6
29.833333
44
0.702564
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,662
make_scripts.py
andreafrancia_trash-cli/tests/support/make_scripts.py
import os from textwrap import dedent from tests.support.project_root import project_root from trashcli.fs import write_file, make_file_executable def make_scripts(): return Scripts(write_file, make_file_executable) class Scripts: def __init__(self, write_file, make_file_executable): self.write_file = write_file self.make_file_executable = make_file_executable self.created_scripts = [] def add_script(self, name, module, main_function): path = script_path_for(name) script_contents = dedent("""\ #!/usr/bin/env python from __future__ import absolute_import import sys from %(module)s import %(main_function)s as main sys.exit(main()) """) % locals() self.write_file(path, script_contents) self.make_file_executable(path) self.created_scripts.append(script_path_without_base_dir_for(name)) def script_path_for(name): return os.path.join(project_root(), script_path_without_base_dir_for(name)) def script_path_without_base_dir_for(name): return os.path.join(name)
1,131
Python
.py
27
34.740741
79
0.673675
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,663
py2mock.py
andreafrancia_trash-cli/tests/support/py2mock.py
import sys if sys.version_info > (3, 3): from unittest.mock import * else: from mock import *
103
Python
.py
5
17.8
31
0.690722
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,664
capture_error.py
andreafrancia_trash-cli/tests/support/capture_error.py
def capture_error(callable): try: callable() except Exception as e: return e return None
117
Python
.py
6
13.833333
28
0.621622
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,665
files.py
andreafrancia_trash-cli/tests/support/files.py
import os import shutil from trashcli.fs import has_sticky_bit from trashcli.fs import mkdirs from trashcli.fs import write_file def mkdir_p(path): if not os.path.isdir(path): os.makedirs(path) def make_empty_file(path): make_file(path, '') def make_file(filename, contents=''): make_parent_for(filename) write_file(filename, contents) def require_empty_dir(path): if os.path.exists(path): shutil.rmtree(path) make_dirs(path) check_empty_dir(path) def make_empty_dir(path): os.mkdir(path) check_empty_dir(path) def check_empty_dir(path): assert os.path.isdir(path) assert [] == list(os.listdir(path)) def make_dirs(path): if not os.path.isdir(path): os.makedirs(path) assert os.path.isdir(path) def make_parent_for(path): parent = os.path.dirname(os.path.realpath(path)) make_dirs(parent) def make_sticky_dir(path): os.mkdir(path) set_sticky_bit(path) def make_unsticky_dir(path): os.mkdir(path) unset_sticky_bit(path) def make_dir_unsticky(path): assert_is_dir(path) unset_sticky_bit(path) def assert_is_dir(path): assert os.path.isdir(path) def set_sticky_bit(path): import stat os.chmod(path, os.stat(path).st_mode | stat.S_ISVTX) def unset_sticky_bit(path): import stat os.chmod(path, os.stat(path).st_mode & ~ stat.S_ISVTX) def ensure_non_sticky_dir(path): import os assert os.path.isdir(path) assert not has_sticky_bit(path) def make_unreadable_file(path): make_file(path, '') import os os.chmod(path, 0) def make_unreadable_dir(path): mkdirs(path) os.chmod(path, 0o300) def make_readable(path): os.chmod(path, 0o700) def assert_dir_empty(path): assert len(os.listdir(path)) == 0 def assert_dir_contains(path, filename): assert os.path.exists(os.path.join(path, filename)) def does_not_exist(path): assert not os.path.exists(path) def is_a_symlink_to_a_dir(path): dest = "%s-dest" % path os.mkdir(dest) rel_dest = os.path.basename(dest) os.symlink(rel_dest, path)
2,099
Python
.py
71
25.338028
58
0.70348
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,666
dummy_clock.py
andreafrancia_trash-cli/tests/support/put/dummy_clock.py
import datetime from trashcli.put.clock import PutClock class FixedClock(PutClock): def __init__(self, now_value=None): self.now_value = now_value def set_clock(self, now_value): self.now_value = now_value def now(self): # type: () -> datetime.datetime return self.now_value @staticmethod def fixet_at_jan_1st_2024(): return FixedClock(now_value=jan_1st_2024()) def jan_1st_2024(): return datetime.datetime(2014, 1, 1, 0, 0, 0)
492
Python
.py
14
29.642857
51
0.66879
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,667
fake_random.py
andreafrancia_trash-cli/tests/support/put/fake_random.py
from typing import List from trashcli.put.core.int_generator import IntGenerator class FakeRandomInt(IntGenerator): def __init__(self, values, # type: List[int] ): self.values = values def new_int(self, _a, _b): return self.values.pop(0) def set_reply(self, value): self.values = [value]
364
Python
.py
11
25.272727
56
0.612069
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,668
my_file_not_found_error.py
andreafrancia_trash-cli/tests/support/put/my_file_not_found_error.py
try: FileNotFoundError except NameError: FileNotFoundError = OSError MyFileNotFoundError = FileNotFoundError
118
Python
.py
5
20.8
39
0.848214
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,669
inode.py
andreafrancia_trash-cli/tests/support/put/fake_fs/inode.py
from enum import Enum from tests.support.put.fake_fs.ent import Ent from trashcli.put.check_cast import check_cast class Stickiness(Enum): sticky = "sticky" not_sticky = "not_sticky" class INode: def __init__(self, entity, # type: Ent mode, # type: int stickiness, # type: Stickiness ): self.entity = entity self.mode = mode self.stickiness = stickiness def chmod(self, mode): self.mode = mode def __repr__(self): return "INode(%r, %r, %r)" % (self.entity, self.mode, self.stickiness) def directory(self): from tests.support.put.fake_fs.directory import Directory return check_cast(Directory, self.entity)
765
Python
.py
22
26.681818
78
0.609524
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,670
entry.py
andreafrancia_trash-cli/tests/support/put/fake_fs/entry.py
from typing import Union from tests.support.put.fake_fs.inode import INode from tests.support.put.fake_fs.symlink import SymLink Entry = Union[INode, SymLink]
161
Python
.py
4
38.75
53
0.832258
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,671
fake_fs.py
andreafrancia_trash-cli/tests/support/put/fake_fs/fake_fs.py
import errno import os from typing import cast from tests.support.fakes.fake_volume_of import FakeVolumeOf from tests.support.put.fake_fs.directory import Directory from tests.support.put.fake_fs.directory import make_inode_dir from tests.support.put.fake_fs.ent import Ent from tests.support.put.fake_fs.entry import Entry from tests.support.put.fake_fs.file import File from tests.support.put.fake_fs.inode import INode from tests.support.put.fake_fs.inode import Stickiness from tests.support.put.fake_fs.symlink import SymLink from tests.support.put.format_mode import format_mode from tests.support.put.my_file_not_found_error import MyFileNotFoundError from trashcli.fs import PathExists from trashcli.put.check_cast import check_cast from trashcli.put.fs.fs import Fs from trashcli.put.fs.fs import list_all def as_directory(ent): # type: (Ent) -> Directory return check_cast(Directory, ent) def as_inode(entry): # type: (Entry) -> INode return check_cast(INode, entry) class FakeFs(FakeVolumeOf, Fs, PathExists): def __init__(self, cwd='/'): super(FakeFs, self).__init__() self.root_inode = make_inode_dir('/', 0o755, None) self.root = self.root_inode.directory() self.cwd = cwd def touch(self, path): if not self.exists(path): self.make_file(path, '') def listdir(self, path): return self.ls_aa(path) def ls_existing(self, paths): return [p for p in paths if self.exists(p)] def ls_aa(self, path): all_entries = self.ls_a(path) all_entries.remove(".") all_entries.remove("..") return all_entries def ls_a(self, path): directory = self.get_entity_at(path) return list(directory.entries()) def mkdir(self, path): dirname, basename = os.path.split(path) directory = self.get_entity_at(dirname) directory.add_dir(basename, 0o755, path) def mkdir_p(self, path): self.makedirs(path, 0o755) def get_entity_at(self, path): # type: (str) -> Ent inode = check_cast(INode, self.get_entry_at(path)) return inode.entity def get_directory_at(self, path): return as_directory(self.get_entity_at(path)) def get_entry_at(self, path): # type: (str) -> Entry path = self._join_cwd(path) entry = self.root_inode for component in self.components_for(path): entry = as_inode(entry).directory().get_entry(component, path, self) return entry def makedirs(self, path, mode): path = self._join_cwd(path) inode = self.root_inode for component in self.components_for(path): try: inode = inode.directory().get_entry(component, path, self) except MyFileNotFoundError: directory = inode.directory() directory.add_dir(component, mode, path) inode = directory.get_entry(component, path, self) def _join_cwd(self, path): return os.path.join(os.path.join("/", self.cwd), path) def components_for(self, path): if path == '/': return [] return path.split('/')[1:] def atomic_write(self, path, content): if self.exists(path): raise OSError("already exists: %s" % path) self.make_file(path, content) def read(self, path): path = self._join_cwd(path) dirname, basename = os.path.split(os.path.normpath(path)) directory = as_directory(self.get_entity_at(dirname)) entry = directory.get_entry(basename, path, self) if isinstance(entry, SymLink): link_target = self.readlink(path) return self.read(os.path.join(dirname, link_target)) elif isinstance(as_inode(entry).entity, File): return cast(File, as_inode(entry).entity).content else: raise IOError("Unable to read: %s" % path) def readlink(self, path): path = self._join_cwd(path) maybe_link = self.get_entry_at(path) if isinstance(maybe_link, SymLink): return maybe_link.dest else: raise OSError(errno.EINVAL, "Invalid argument", path) def read_null(self, path): try: return self.get_entity_at(path).content except MyFileNotFoundError: return None def make_file_and_dirs(self, path, content=''): path = self._join_cwd(path) dirname, basename = os.path.split(path) self.makedirs(dirname, 0o755) self.make_file(path, content) def make_file(self, path, content=''): path = self._join_cwd(path) dirname, basename = os.path.split(path) directory = self.get_entity_at(dirname) directory.add_file(basename, content, path) def write_file(self, path, content): self.make_file(path, content) def get_mod(self, path): entry = self._find_entry(path) return entry.mode def _find_entry(self, path): path = self._join_cwd(path) dirname, basename = os.path.split(path) directory = self.get_entity_at(dirname) return directory.get_entry(basename, path, self) def chmod(self, path, mode): entry = self._find_entry(path) entry.chmod(mode) def isdir(self, path): try: entry = self.get_entry_at(path) except MyFileNotFoundError: return False else: if isinstance(entry, SymLink): return False file = entry.entity return isinstance(file, Directory) def exists(self, path): try: self.get_entity_at(path) return True except MyFileNotFoundError: return False def remove_file(self, path): dirname, basename = os.path.split(path) directory = self.get_entity_at(dirname) directory.remove(basename) def move(self, src, dest): basename, entry = self._pop_entry_from_dir(src) if self.exists(dest) and self.isdir(dest): dest_dir = self.get_directory_at(dest) dest_dir.add_entry(basename, entry) else: dest_dirname, dest_basename = os.path.split(dest) dest_dir = self.get_directory_at(dest_dirname) dest_dir.add_entry(dest_basename, entry) def _pop_entry_from_dir(self, path): dirname, basename = os.path.split(path) directory = self.get_directory_at(dirname) entry = directory.get_entry(basename, path, self) directory.remove(basename) return basename, entry def islink(self, path): try: entry = self._find_entry(path) except MyFileNotFoundError: return False else: return isinstance(entry, SymLink) def symlink(self, src, dest): dest = os.path.join(self.cwd, dest) dirname, basename = os.path.split(dest) if dirname == '': raise OSError("only absolute dests are supported, got %s" % dest) directory = as_directory(self.get_entity_at(dirname)) directory.add_link(basename, src) def has_sticky_bit(self, path): return self._find_entry(path).stickiness is Stickiness.sticky def set_sticky_bit(self, path): entry = self._find_entry(path) entry.stickiness = Stickiness.sticky def realpath(self, path): path = self._join_cwd(path) return os.path.join("/", path) def cd(self, path): self.cwd = path def isfile(self, path): try: file = self.get_entity_at(path) except MyFileNotFoundError: return False return isinstance(file, File) def getsize(self, path): file = self.get_entity_at(path) return file.getsize() def is_accessible(self, path): return self.exists(path) def get_mod_s(self, path): mode = self.get_mod(path) return format_mode(mode) def walk_no_follow(self, top): names = self.listdir(top) dirs, nondirs = [], [] for name in names: if self.isdir(os.path.join(top, name)): dirs.append(name) else: nondirs.append(name) yield top, dirs, nondirs for name in dirs: new_path = os.path.join(top, name) if not self.islink(new_path): for x in self.walk_no_follow(new_path): yield x def lexists(self, path): path = self._join_cwd(path) try: self.get_entry_at(path) except MyFileNotFoundError: return False else: return True def find_all(self): return list(list_all(self, "/")) def read_all_files(self): return [(f, self.read(f)) for f in list_all(self, "/") if self.isfile(f)]
8,944
Python
.py
228
30.416667
80
0.6178
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,672
file.py
andreafrancia_trash-cli/tests/support/put/fake_fs/file.py
from tests.support.put.fake_fs.ent import Ent class File(Ent): def __init__(self, content): self.content = content def getsize(self): return len(self.content)
186
Python
.py
6
25.5
45
0.672316
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,673
symlink.py
andreafrancia_trash-cli/tests/support/put/fake_fs/symlink.py
class SymLink: def __init__(self, dest): self.dest = dest def __repr__(self): return "SymLink(%r)" % self.dest
136
Python
.py
5
21.2
40
0.553846
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,674
failing_fake_fs.py
andreafrancia_trash-cli/tests/support/put/fake_fs/failing_fake_fs.py
import os.path from tests.support.put.fake_fs.fake_fs import FakeFs class FailingOnAtomicWriteFakeFs(FakeFs): def __init__(self): super(FailingOnAtomicWriteFakeFs, self).__init__() self._atomic_write_can_fail = False self._atomic_write_failure_stop = None def fail_atomic_create_unless(self, basename): self._atomic_write_can_fail = True self._atomic_write_failure_stop = basename def atomic_write(self, path, content): if self._atomic_write_is_supposed_to_fail(path): raise OSError("atomic_write failed") return super(FailingOnAtomicWriteFakeFs, self).atomic_write(path, content) def _atomic_write_is_supposed_to_fail(self, path, # type: str ): # type: (...) -> bool result = (self._atomic_write_can_fail and os.path.basename(path) != self._atomic_write_failure_stop) return result class FailOnMoveFakeFs(FakeFs): def __init__(self): super(FailOnMoveFakeFs, self).__init__() self._fail_move_on_path = None def move(self, src, dest): if src == self._fail_move_on_path: raise OSError("move failed") return super(FailOnMoveFakeFs, self).move(src, dest) def fail_move_on(self, path): self._fail_move_on_path = path class FailingFakeFs(FailingOnAtomicWriteFakeFs, FailOnMoveFakeFs): def __init__(self): super(FailingFakeFs, self).__init__() def assert_does_not_exist(self, path): if self.exists(path): raise AssertionError( "expected path to not exists but it does: %s" % path)
1,837
Python
.py
41
32.560976
76
0.577117
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,675
directory.py
andreafrancia_trash-cli/tests/support/put/fake_fs/directory.py
from collections import OrderedDict from typing import Optional from typing import Union from tests.support.put.fake_fs.ent import Ent from tests.support.put.fake_fs.inode import INode from tests.support.put.fake_fs.inode import Stickiness from tests.support.put.fake_fs.symlink import SymLink from tests.support.put.fake_fs.file import File from tests.support.put.my_file_not_found_error import MyFileNotFoundError from trashcli.lib.my_permission_error import MyPermissionError def make_inode_dir(directory_path, # type: str mode, # type: int parent_inode, # type: Optional[INode] ): # type: (...)->INode directory = Directory(directory_path) inode = INode(directory, mode, Stickiness.not_sticky) directory.set_dot_entries(inode, parent_inode or inode) return inode class Directory(Ent): def __init__(self, name): # type: (str) -> None self.name = name self._entries = OrderedDict() # type: dict[str, Union[INode, SymLink]] def __repr__(self): return "Directory(%r)" % self.name def set_dot_entries(self, inode, parent_inode): self._entries['.'] = inode self._entries['..'] = parent_inode def entries(self): return self._entries.keys() def add_dir(self, basename, mode, complete_path): if self._inode().mode & 0o200 == 0: raise MyPermissionError( "[Errno 13] Permission denied: '%s'" % complete_path) inode = make_inode_dir(basename, mode, self._inode()) self._entries[basename] = inode def add_file(self, basename, content, complete_path): mode = 0o644 if self._inode().mode & 0o200 == 0: raise MyPermissionError( "[Errno 13] Permission denied: '%s'" % complete_path) file = File(content) inode = INode(file, mode, Stickiness.not_sticky) self._entries[basename] = inode def _inode(self): # type: ()->Union[INode, SymLink] return self._entries["."] def get_file(self, basename): return self._entries[basename].entity def get_entry(self, basename, path, fs): try: return self._entries[basename] except KeyError: raise MyFileNotFoundError( "no such file or directory: %s\n%s" % ( path, "\n".join(fs.find_all()), )) def add_entry(self, basename, entry): self._entries[basename] = entry def add_link(self, basename, src): self._entries[basename] = SymLink(src) def remove(self, basename): self._entries.pop(basename) def getsize(self): raise NotImplementedError
2,736
Python
.py
64
34.40625
79
0.630508
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,676
help_reformatting.py
andreafrancia_trash-cli/tests/support/help/help_reformatting.py
def reformat_help_message(help_message): # type: (str) -> str return _collapse_usage_paragraph(_normalize_options(help_message)) def _normalize_options(help_message): # type: (str) -> str return help_message.replace('optional arguments', 'options') def _collapse_usage_paragraph(help_message): # type: (str) -> str paragraphs = split_paragraphs(help_message) return '\n'.join( [normalize_spaces(paragraphs[0]) + "\n"] + paragraphs[1:]) def normalize_spaces(text): # type: (str) -> str return " ".join(text.split()) def split_paragraphs(text): paragraphs = [] par = '' for line in text.splitlines(True): if _is_empty_line(line): paragraphs.append(par) par = '' else: par += line paragraphs.append(par) return paragraphs def _is_empty_line(line): return '' == line.strip()
898
Python
.py
24
31.291667
70
0.634994
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,677
restore_file_fixture.py
andreafrancia_trash-cli/tests/support/restore/restore_file_fixture.py
import os from tests.support.fakes.fake_trash_dir import trashinfo_content_default_date from tests.support.files import make_file class RestoreFileFixture: def __init__(self, XDG_DATA_HOME): self.XDG_DATA_HOME = XDG_DATA_HOME def having_a_trashed_file(self, path): self.make_file('%s/info/foo.trashinfo' % self._trash_dir(), trashinfo_content_default_date(path)) self.make_file('%s/files/foo' % self._trash_dir()) def make_file(self, filename, contents=''): return make_file(filename, contents) def make_empty_file(self, filename): return self.make_file(filename) def _trash_dir(self): return "%s/Trash" % self.XDG_DATA_HOME def file_should_have_been_restored(self, filename): assert os.path.exists(filename)
820
Python
.py
18
38.388889
77
0.677582
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,678
has_been_restored_matcher.py
andreafrancia_trash-cli/tests/support/restore/has_been_restored_matcher.py
from typing import NamedTuple, Union from trashcli.fs import PathExists def has_been_restored(fs): # type: (PathExists) -> HasBeenRestoredBaseMatcher return HasBeenRestoredBaseMatcher(fs, HasBeenRestoredExpectations()) def has_not_been_restored( fs): # type: (PathExists) -> HasBeenRestoredBaseMatcher return HasBeenRestoredBaseMatcher(fs, HasNotBeenYetRestoredExpectations()) class ShouldExists(NamedTuple('ShouldExists', [ ('name', str), ('path', str)])): def expectation_as_text(self): return "should exists" def should_exists(self): return True def actual(self, actually_exists): return {True: "and it does", False: "but it does not"}[actually_exists] class ShouldNotExists( NamedTuple('ShouldNotExists', [('name', str), ('path', str)])): def expectation_as_text(self): return "should not exists" def should_exists(self): return False def actual(self, actually_exists): return {False: "and it does not", True: "but it does"}[actually_exists] class Satisfaction: def __init__(self, expectation, actually_exists): self.expectation = expectation self.actually_exists = actually_exists def expectations_satisfied(self): return self.actually_exists == self.expectation.should_exists() def actual_description(self): return self.expectation.actual(self.actually_exists) def ok_or_fail_text(self): return {True: "OK", False: "FAIL"}[ self.expectations_satisfied()] def kind_of_file(self): return self.expectation.name def satisfaction_description(self): return "{0} {1} {2} {3}: '{4}'".format( self.ok_or_fail_text(), self.kind_of_file(), self.expectation.expectation_as_text(), self.actual_description(), self.expectation.path ) class HasBeenRestoredExpectations: def expectations_for_file(self, a_trashed_file): return [ ShouldExists("original_location", a_trashed_file.trashed_from), ShouldNotExists("info_file", a_trashed_file.info_file), ShouldNotExists("backup_copy", a_trashed_file.backup_copy), ] class HasNotBeenYetRestoredExpectations: def expectations_for_file(self, a_trashed_file): return [ ShouldNotExists("original_location", a_trashed_file.trashed_from), ShouldExists("info_file", a_trashed_file.info_file), ShouldExists("backup_copy", a_trashed_file.backup_copy), ] Expectations = Union[HasBeenRestoredExpectations,HasNotBeenYetRestoredExpectations] class HasBeenRestoredBaseMatcher: def __init__(self, fs, # type: PathExists expectations_maker, # type: Expectations ): self.fs = fs self.expectations_maker = expectations_maker def matches(self, a_trashed_file): return len(self._expectations_failed(a_trashed_file)) == 0 def describe_mismatch(self, a_trashed_file, focus_on=None): expectations_satisfactions = self._expectations_satisfactions( a_trashed_file, focus_on) return ("Expected file to be restore but it has not:\n" + "".join(" - %s\n" % satisfaction.satisfaction_description() for satisfaction in expectations_satisfactions)) def describe(self, description): return "The file has been restored" def _expectations_failed(self, a_trashed_file): return [ satisfaction for satisfaction in self._expectations_satisfactions(a_trashed_file, focus_on=None) if not satisfaction.expectations_satisfied()] def _expectations_satisfactions(self, a_trashed_file, focus_on=None): return [ Satisfaction(e, self.fs.exists(e.path)) for e in self._expectations_for(a_trashed_file, focus_on)] def _expectations_for(self, a_trashed_file, focus_on=None): all_expectations = self.expectations_maker.expectations_for_file( a_trashed_file) if focus_on is None: return all_expectations else: return [e for e in all_expectations if e.name == focus_on]
4,317
Python
.py
95
36.421053
83
0.656317
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,679
restore_user.py
andreafrancia_trash-cli/tests/support/restore/restore_user.py
import sys from io import StringIO from typing import Dict from tests.support.run.cmd_result import CmdResult from trashcli.fstab.volumes import Volumes from trashcli.lib.my_input import HardCodedInput from trashcli.restore.file_system import FakeReadCwd, FileReader, \ RestoreReadFileSystem, \ RestoreWriteFileSystem, ListingFileSystem from trashcli.restore.info_dir_searcher import InfoDirSearcher from trashcli.restore.info_files import InfoFiles from trashcli.restore.restore_cmd import RestoreCmd from trashcli.restore.trash_directories import TrashDirectoriesImpl from trashcli.restore.trashed_files import TrashedFiles class MemoLogger: def __init__(self): self.messages = [] def warning(self, msg): self.messages.append("warning: " + msg) class RestoreUser: def __init__(self, environ, # type: Dict[str, str] uid, # type: int file_reader, # type: FileReader read_fs, # type: RestoreReadFileSystem write_fs, # type: RestoreWriteFileSystem listing_file_system, # type: ListingFileSystem version, # type: str volumes, # type: Volumes ): self.environ = environ self.uid = uid self.file_reader = file_reader self.read_fs = read_fs self.write_fs = write_fs self.listing_file_system = listing_file_system self.version = version self.volumes = volumes no_args = object() def run_restore(self, args=no_args, reply='', from_dir=None): args = [] if args is self.no_args else args stdout = StringIO() stderr = StringIO() read_cwd = FakeReadCwd(from_dir) logger = MemoLogger() trash_directories = TrashDirectoriesImpl(self.volumes, self.uid, self.environ) searcher = InfoDirSearcher(trash_directories, InfoFiles(self.listing_file_system)) trashed_files = TrashedFiles(logger, self.file_reader, searcher) cmd = RestoreCmd.make(stdout=stdout, stderr=stderr, exit=sys.exit, input=HardCodedInput(reply), version=self.version, trashed_files=trashed_files, read_fs=self.read_fs, write_fs=self.write_fs, read_cwd=read_cwd) try: exit_code = cmd.run(args) except SystemExit as e: exit_code = e.code return CmdResult(stdout.getvalue(), stderr.getvalue(), exit_code)
2,922
Python
.py
68
29.279412
71
0.565752
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,680
fake_restore_fs.py
andreafrancia_trash-cli/tests/support/restore/fake_restore_fs.py
import os from tests.support.put.fake_fs.fake_fs import FakeFs from tests.support.restore.a_trashed_file import ATrashedFile from trashcli.fs import PathExists from trashcli.fstab.volumes import Volumes, FakeVolumes from trashcli.put.format_trash_info import format_trashinfo from trashcli.restore.file_system import ListingFileSystem, FileReader, \ RestoreWriteFileSystem, RestoreReadFileSystem class FakeRestoreFs(ListingFileSystem, Volumes, FileReader, RestoreWriteFileSystem, RestoreReadFileSystem, PathExists): def exists(self, path): return self.path_exists(path) def path_exists(self, path): return self.fake_fs.exists(path) def __init__(self): self.fake_fs = FakeFs() self.mount_points = [] def mkdirs(self, path): self.fake_fs.makedirs(path, 755) def move(self, path, dest): self.fake_fs.move(path, dest) def remove_file(self, path): self.fake_fs.remove_file(path) def add_volume(self, mount_point): self.mount_points.append(mount_point) def list_mount_points(self): return FakeVolumes(self.mount_points).list_mount_points() def volume_of(self, path): return FakeVolumes(self.mount_points).volume_of(path) def make_trashed_file(self, from_path, trash_dir, time, original_file_content): content = format_trashinfo(from_path, time) basename = os.path.basename(from_path) info_path = os.path.join(trash_dir, 'info', "%s.trashinfo" % basename) backup_copy_path = os.path.join(trash_dir, 'files', basename) trashed_file = ATrashedFile(trashed_from=from_path, info_file=info_path, backup_copy=backup_copy_path) self.add_file(info_path, content) self.add_file(backup_copy_path, original_file_content.encode('utf-8')) return trashed_file def add_trash_file(self, from_path, trash_dir, time, original_file_content): content = format_trashinfo(from_path, time) basename = os.path.basename(from_path) info_path = os.path.join(trash_dir, 'info', "%s.trashinfo" % basename) backup_copy_path = os.path.join(trash_dir, 'files', basename) self.add_file(info_path, content) self.add_file(backup_copy_path, original_file_content.encode('utf-8')) def add_file(self, path, content=b''): self.fake_fs.makedirs(os.path.dirname(path), 755) self.fake_fs.make_file(path, content) def list_files_in_dir(self, dir_path): for file_path in self.fake_fs.listdir(dir_path): yield os.path.join(dir_path, file_path) def contents_of(self, path): return self.fake_fs.read(path).decode('utf-8')
2,819
Python
.py
57
40.54386
80
0.664845
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,681
a_trashed_file.py
andreafrancia_trash-cli/tests/support/restore/a_trashed_file.py
from typing import NamedTuple def a_trashed_file(trashed_from, info_file, backup_copy): return ATrashedFile(trashed_from=str(trashed_from), info_file=str(info_file), backup_copy=str(backup_copy)) class ATrashedFile(NamedTuple('ATrashedFile', [ ('trashed_from', str), ('info_file', str), ('backup_copy', str), ])): pass
391
Python
.py
11
28
57
0.62766
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,682
set_dev_version.py
andreafrancia_trash-cli/tests/support/tools/set_dev_version.py
from __future__ import print_function import argparse import sys from six import text_type from tests.support.project_root import project_root from tests.support.tools.adapters.real_cal import RealCal from tests.support.tools.bump_cmd import trash_py_file from tests.support.tools.version_from_date import dev_version_from_date from tests.support.tools.version_saver import VersionSaver from trashcli.put.fs.real_fs import RealFs def main(): cmd = SetDevVersionCmd(RealFs(), sys.stdout, sys.stderr, RealCal()) cmd.run_set_dev_version(sys.argv, project_root()) class SetDevVersionCmd: def __init__(self, fs, stdout, stderr, cal): self.stdout = stdout self.stderr = stderr self.cal = cal self.version_saver = VersionSaver(fs) def run_set_dev_version(self, argv, root): parser = argparse.ArgumentParser(prog=argv[0]) parser.add_argument('ref') parser.add_argument('sha') args = parser.parse_args(argv[1:]) self.warn_about_using_underscore_as_ref(args) new_version = dev_version_from_date(args.ref, args.sha, self.cal.today()) self.version_saver.save_new_version(new_version, trash_py_file(root)) def warn_about_using_underscore_as_ref(self, args): if "-" in args.ref: print(text_type( "Ref cannot contain '-': %s\n" % args.ref + "The reason is because any '-' will be converted to '.' " "by setuptools during the egg_info phase that will result in " "an error in scripts/make-scripts because it will be not " "able to find the .tar.gz file"), file=self.stderr) sys.exit(1)
1,761
Python
.py
38
37.684211
78
0.651285
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,683
bump_main.py
andreafrancia_trash-cli/tests/support/tools/bump_main.py
import os import sys from tests.support.project_root import project_root from tests.support.tools.adapters.real_cal import RealCal from tests.support.tools.bump_cmd import BumpCmd from trashcli.put.fs.real_fs import RealFs def main(): print(project_root()) bump_cmd = BumpCmd(os.system, print, RealFs(), RealCal()) bump_cmd.run_bump(project_root(), sys.argv[1:])
378
Python
.py
10
35.3
61
0.772603
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,684
version_from_date.py
andreafrancia_trash-cli/tests/support/tools/version_from_date.py
from __future__ import print_function def version_from_date(today): return "0.%s.%s.%s" % (today.year % 100, today.month, today.day) def dev_version_from_date(ref, sha, today): new_version = '%s.dev0+git.%s.%s' % (version_from_date(today), ref, sha) return new_version
339
Python
.py
8
32.625
76
0.568807
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,685
bump_cmd.py
andreafrancia_trash-cli/tests/support/tools/bump_cmd.py
import os from tests.support.tools.version_from_date import version_from_date from tests.support.tools.version_saver import VersionSaver def trash_py_file(root): return os.path.join(root, 'trashcli', 'trash.py') class BumpCmd: def __init__(self, os_system, print_func, fs, cal): self.system = os_system self.print_func = print_func self.fs = fs self.cal = cal def run_bump(self, root, args): # https://unix.stackexchange.com/questions/155046/determine-if-git-working-directory-is-clean-from-a-script/394674#394674 if self.system("git diff-index --quiet HEAD") != 0: self.print_func("Dirty") exit(1) new_version = version_from_date(self.cal.today()) if not '--dry-run' in args: VersionSaver(self.fs).save_new_version(new_version, trash_py_file(root)) system = self.print_func if '--dry-run' in args else self.system system("git commit -m \"Bump version to '%s'\" -a" % new_version)
1,069
Python
.py
22
39.045455
129
0.626204
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,686
version_saver.py
andreafrancia_trash-cli/tests/support/tools/version_saver.py
import re class VersionSaver: def __init__(self, fs): self.fs = fs def save_new_version(self, new_version, path): content = self.fs.read(path) new_content = re.sub(r'^version(\s*)=.*', 'version = \'%s\'' % new_version, content, flags=re.MULTILINE) self.fs.write_file(path, new_content)
416
Python
.py
11
25
62
0.487562
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,687
real_cal.py
andreafrancia_trash-cli/tests/support/tools/adapters/real_cal.py
import datetime from tests.support.tools.core.cal import Cal class RealCal(Cal): def today(self): return datetime.datetime.today()
146
Python
.py
5
25.2
44
0.76087
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,688
cal.py
andreafrancia_trash-cli/tests/support/tools/core/cal.py
from abc import abstractmethod from trashcli.compat import Protocol class Cal(Protocol): @abstractmethod def today(self): raise NotImplementedError
167
Python
.py
6
23.666667
36
0.791139
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,689
my_path.py
andreafrancia_trash-cli/tests/support/dirs/my_path.py
import os import shutil import tempfile from tests.support.files import make_sticky_dir from trashcli.put.fs.real_fs import RealFs from trashcli.put.fs.fs import list_all class MyPath(str): def __truediv__(self, other_path): return self.path_join(other_path) def __div__(self, other_path): return self.path_join(other_path) def path_join(self, other_path): return MyPath(os.path.join(self, other_path)) def existence_of(self, *paths): return [self.existence_of_single(p) for p in paths] def existence_of_single(self, path): # type: (MyPath) -> str path = self / path existence = os.path.exists(path) existence_message = { True: "exists", False: "does not exist" }[existence] return "%s: %s" % (path.replace(self, ''), existence_message) def mkdir_rel(self, path): RealFs().mkdir(self / path) def symlink_rel(self, src, dest): RealFs().symlink(self / src, self / dest) def list_dir_rel(self): return RealFs().listdir(self) @property def parent(self): # type: (...) -> MyPath return MyPath(os.path.dirname(self)) def clean_up(self): shutil.rmtree(self) @classmethod def make_temp_dir(cls): return cls(os.path.realpath(tempfile.mkdtemp(suffix="_trash_cli_test"))) def list_all_files_sorted(self): return sorted([p.replace(self, '') for p in list_all(RealFs(), self)])
1,513
Python
.py
40
30.675
80
0.628944
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,690
list_file_in_dir.py
andreafrancia_trash-cli/tests/support/dirs/list_file_in_dir.py
import os def list_files_in_dir(path): if not os.path.isdir(path): return [] return os.listdir(path)
119
Python
.py
5
19.2
31
0.660714
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,691
temp_dir.py
andreafrancia_trash-cli/tests/support/dirs/temp_dir.py
import pytest from tests.support.dirs.my_path import MyPath @pytest.fixture def temp_dir(): temp_dir = MyPath.make_temp_dir() yield temp_dir temp_dir.clean_up()
176
Python
.py
7
22
45
0.740964
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,692
list_file_in_subdir.py
andreafrancia_trash-cli/tests/support/dirs/list_file_in_subdir.py
from tests.support.dirs.list_file_in_dir import list_files_in_dir def list_files_in_subdir(path, subdir): return ["%s/%s" % (subdir, f) for f in list_files_in_dir(path / subdir)]
185
Python
.py
3
58.666667
76
0.711111
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,693
parse_date.py
andreafrancia_trash-cli/tests/support/trashinfo/parse_date.py
from datetime import datetime def parse_date(date_string, # type: str ): # type: (...) -> datetime for format in ['%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S', ]: try: return datetime.strptime(date_string, format) except ValueError: continue raise ValueError("Can't parse date: %s" % date_string)
429
Python
.py
12
24.583333
58
0.477108
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,694
fake_file_system.py
andreafrancia_trash-cli/tests/support/fakes/fake_file_system.py
# Copyright (C) 2011-2021 Andrea Francia Bereguardo(PV) Italy class FakeFileSystem: def __init__(self): self.files = {} self.dirs = {} def contents_of(self, path): return self.files[path] def exists(self, path): return path in self.files def entries_if_dir_exists(self, path): return self.dirs.get(path, []) def create_fake_file(self, path, contents=''): import os self.files[path] = contents self.create_fake_dir(os.path.dirname(path), os.path.basename(path)) def create_fake_dir(self, dir_path, *dir_entries): self.dirs[dir_path] = dir_entries
647
Python
.py
17
31.117647
75
0.6384
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,695
mock_dir_reader.py
andreafrancia_trash-cli/tests/support/fakes/mock_dir_reader.py
import os from typing import List from trashcli.lib.dir_reader import DirReader class MockDirReader(DirReader): def __init__(self): self.root = {} def entries_if_dir_exists(self, path): # type: (str) -> List[str] return list(self.pick_dir(path).keys()) def exists(self, path): # type: (str) -> bool raise NotImplementedError() def add_file(self, path): dirname, basename = os.path.split(path) dir = self.pick_dir(dirname) dir[basename] = '' def mkdir(self, path): dirname, basename = os.path.split(path) cwd = self.pick_dir(dirname) cwd[basename] = {} def pick_dir(self, dir): cwd = self.root components = dir.split('/')[1:] if components != ['']: for p in components: if p not in cwd: raise FileNotFoundError("no such file or directory: %s" % dir) cwd = cwd[p] return cwd
976
Python
.py
27
27.703704
82
0.578723
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,696
fake_is_mount.py
andreafrancia_trash-cli/tests/support/fakes/fake_is_mount.py
import os from typing import List class FakeIsMount: def __init__(self, mount_points, # type: List[str] ): self.mount_points = mount_points def is_mount(self, path): if path == '/': return True path = os.path.normpath(path) if path in self.mount_points_list(): return True return False def mount_points_list(self): return set(['/'] + self.mount_points) def add_mount_point(self, path): self.mount_points.append(path)
553
Python
.py
18
22.222222
49
0.569811
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,697
stub_volume_of.py
andreafrancia_trash-cli/tests/support/fakes/stub_volume_of.py
from trashcli.fstab.volume_of import VolumeOf class StubVolumeOf(VolumeOf): def volume_of(self, path): return "volume_of %s" % path
146
Python
.py
4
32
45
0.728571
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,698
fake_volume_of.py
andreafrancia_trash-cli/tests/support/fakes/fake_volume_of.py
import os from typing import List from tests.support.fakes.fake_is_mount import FakeIsMount from trashcli.fstab.volume_of import VolumeOf from trashcli.fstab.volume_of_impl import VolumeOfImpl class FakeVolumeOf(VolumeOf): def __init__(self): # type: () -> None super(FakeVolumeOf, self).__init__() self.volumes = [] # type: List[str] def add_volume(self, volume): self.volumes.append(volume) def volume_of(self, path): impl = VolumeOfImpl(FakeIsMount(self.volumes), os.path.normpath) return impl.volume_of(path)
572
Python
.py
14
35.785714
72
0.708861
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,699
fake_trash_dir.py
andreafrancia_trash-cli/tests/support/fakes/fake_trash_dir.py
import datetime import os import uuid from tests.support.files import does_not_exist from tests.support.files import is_a_symlink_to_a_dir from tests.support.files import make_sticky_dir from tests.support.files import make_unsticky_dir from trashcli.put.format_trash_info import format_original_location from tests.support.files import make_file, make_parent_for, make_unreadable_file from tests.support.trashinfo.parse_date import parse_date def a_default_datetime(): return datetime.datetime(2000, 1, 1, 0, 0, 1) class FakeTrashDir: def __init__(self, path): self.path = path self.info_path = os.path.join(path, 'info') self.files_path = os.path.join(path, 'files') def add_unreadable_trashinfo(self, basename): path = self.a_trashinfo_path(basename) make_unreadable_file(path) def add_trashed_file(self, basename, path, content, date=a_default_datetime()): self.add_trashinfo3(basename, path, date) make_file(self.file_path(basename), content) def a_trashinfo_path(self, basename): return os.path.join(self.info_path, '%s.trashinfo' % basename) def file_path(self, basename): return os.path.join(self.files_path, basename) def add_trashinfo_basename_path(self, basename, path): self.add_trashinfo3(basename, path, a_default_datetime()) def add_trashinfo2(self, path, deletion_date): basename = str(uuid.uuid4()) self.add_trashinfo3(basename, path, deletion_date) def add_trashinfo3(self, basename, path, deletion_date): content = trashinfo_content(path, deletion_date) self.add_trashinfo_content(basename, content) def add_a_valid_trashinfo(self): self.add_trashinfo4('file1', "2000-01-01") def add_trashinfo4(self, path, deletion_date_as_string): if isinstance(deletion_date_as_string, datetime.datetime): raise ValueError("Use a string instead: %s" % repr(deletion_date_as_string.strftime('%Y-%m-%d %H:%M:%S'))) basename = str(uuid.uuid4()) deletion_date = parse_date(deletion_date_as_string) self.add_trashinfo3(basename, path, deletion_date) def add_trashinfo_with_date(self, basename, deletion_date): content = trashinfo_content2([ ("DeletionDate", deletion_date.strftime('%Y-%m-%dT%H:%M:%S')), ]) self.add_trashinfo_content(basename, content) def add_trashinfo_with_invalid_date(self, basename, invalid_date): content = trashinfo_content2([ ("DeletionDate", invalid_date), ]) self.add_trashinfo_content(basename, content) def add_trashinfo_without_path(self, basename): deletion_date = a_default_datetime() content = trashinfo_content2([ ("DeletionDate", deletion_date.strftime('%Y-%m-%dT%H:%M:%S')), ]) self.add_trashinfo_content(basename, content) def add_trashinfo_without_date(self, path): basename = str(uuid.uuid4()) content = trashinfo_content2([ ('Path', format_original_location(path)), ]) self.add_trashinfo_content(basename, content) def add_trashinfo_wrong_date(self, path, wrong_date): basename = str(uuid.uuid4()) content = trashinfo_content2([ ('Path', format_original_location(path)), ("DeletionDate", wrong_date), ]) self.add_trashinfo_content(basename, content) def add_trashinfo_content(self, basename, content): trashinfo_path = self.a_trashinfo_path(basename) make_parent_for(trashinfo_path) make_file(trashinfo_path, content) def ls_info(self): return os.listdir(self.info_path) def make_parent_sticky(self): make_sticky_dir(self.path.parent) def make_parent_unsticky(self): make_unsticky_dir(self.path.parent) def make_parent_symlink(self): is_a_symlink_to_a_dir(self.path.parent) def make_dir(self): os.mkdir(self.path) def does_not_exist(self): does_not_exist(self.path) def trashinfo_content_default_date(path): return trashinfo_content(path, a_default_datetime()) def trashinfo_content(path, deletion_date): return trashinfo_content2([ ('Path', format_original_location(path)), ("DeletionDate", deletion_date.strftime('%Y-%m-%dT%H:%M:%S')), ]) def trashinfo_content2(values): return ("[Trash Info]\n" + "".join("%s=%s\n" % (name, value) for name, value in values))
4,581
Python
.py
100
38.02
89
0.665392
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)