diff --git a/README.rst b/README.rst index c54e01f..6315eb9 100644 --- a/README.rst +++ b/README.rst @@ -43,4 +43,5 @@ Version Description ========= ========================================================================== 0.12.2 * For developers: move to pyprojet. add precomit * replace pkg_resources (deprecated) with importlib + * replace appdirs with more generic platformdirs ========= ========================================================================== diff --git a/doc/source/index.rst b/doc/source/index.rst index a4f6edb..9604850 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -73,4 +73,3 @@ easydev may now exist in standard modules of Python. installation quickstart references - diff --git a/doc/source/quickstart.rst b/doc/source/quickstart.rst index f4eb13d..0d36d5a 100644 --- a/doc/source/quickstart.rst +++ b/doc/source/quickstart.rst @@ -59,7 +59,7 @@ many more functionalities. ~easydev.tools.AttrDict ~easydev.tools.DevTools -For :class:`~easydev.tools.DevTools` and :class:`~easydev.tools.AttrDict`, +For :class:`~easydev.tools.DevTools` and :class:`~easydev.tools.AttrDict`, please see :ref:`devtools` and :ref:`attrdict` sections, respetively. Check validity of a values @@ -170,7 +170,7 @@ Timer populate a list variable with time spent in **with** statements with Timer(imes): time.sleep(0.2) sum(times) - + Profiling @@ -329,7 +329,3 @@ Each job must be a function with arguments and optional arguments but must retur The :meth:`add_job` takes as input a function name followed by a lost of arguments. You can then introspect individual results:: t.results - - - - diff --git a/doc/source/references.rst b/doc/source/references.rst index e065089..f99e317 100644 --- a/doc/source/references.rst +++ b/doc/source/references.rst @@ -12,7 +12,7 @@ browse .. automodule:: easydev.browser :members: :inherited-members: - :synopsis: + :synopsis: chunks ========== @@ -20,7 +20,7 @@ chunks .. automodule:: easydev.chunks :members: :inherited-members: - :synopsis: + :synopsis: codecs ========== @@ -28,14 +28,14 @@ codecs .. automodule:: easydev.codecs :members: :inherited-members: - :synopsis: + :synopsis: config ========== .. automodule:: easydev.config_tools :members: - :synopsis: + :synopsis: console =========== @@ -44,7 +44,7 @@ console :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: decorators =============== @@ -53,7 +53,7 @@ decorators :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: dependencies =============== @@ -62,7 +62,7 @@ dependencies :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: doc @@ -72,7 +72,7 @@ doc :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: easytest ========== @@ -81,7 +81,7 @@ easytest :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: @@ -92,7 +92,7 @@ logging_tools :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: Options =================================================================== @@ -101,7 +101,7 @@ Options :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: @@ -112,7 +112,7 @@ paths :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: progressbar ============== @@ -121,7 +121,7 @@ progressbar :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: sphinx themes =================================================================== @@ -130,7 +130,7 @@ sphinx themes :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: timer ================ @@ -145,25 +145,23 @@ tools .. automodule:: easydev.tools :members: :undoc-members: - :synopsis: + :synopsis: + - url ===== .. automodule:: easydev.url :members: :undoc-members: :inherited-members: - :synopsis: + :synopsis: + - multicore ================== .. automodule:: easydev.multicore :members: :undoc-members: :inherited-members: - :synopsis: - - + :synopsis: diff --git a/easydev/__init__.py b/easydev/__init__.py index 21336a6..36e4866 100644 --- a/easydev/__init__.py +++ b/easydev/__init__.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2014 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://packages.python.org/easydev @@ -66,8 +64,6 @@ def get_package_version(package_name): from .profiler import do_profile from .progressbar import Progress, TextProgressBar, progress_bar from .sphinx_themes import * - -# from . import timer from .timer import Timer from .tools import * from .url import * diff --git a/easydev/appdirs.py b/easydev/appdirs.py index 054ab3d..343fc7a 100644 --- a/easydev/appdirs.py +++ b/easydev/appdirs.py @@ -1,406 +1,20 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# Copyright (c) 2005-2010 ActiveState Software Inc. -# Copyright (c) 2013 Eddy Petrișor -"""Local version of appdirs 1.4.0 with their MIT License -This helps to have easydev under conda. - -# This is the MIT license - -Copyright (c) 2010 ActiveState Software Inc. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" - -"""Utilities for determining application-specific dirs. - -See for details and usage. -""" -# Dev Notes: -# - MSDN on where to store app data files: -# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 -# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html -# - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html - -# Note: Thomas Cokelaer Jan 2016 -# Added appdirs directly inside easydev to remove dependencies. This was -# to make a conda test but may not be required anymore ?? - -__version_info__ = (1, 4, 0) -__version__ = ".".join(map(str, __version_info__)) - - -import sys import os +import sys -PY3 = sys.version_info[0] == 3 - -if PY3: - unicode = str - -if sys.platform.startswith("java"): # pragma: no cover - import platform - - os_name = platform.java_ver()[3][0] - if os_name.startswith("Windows"): # "Windows XP", "Windows 7", etc. - system = "win32" - elif os_name.startswith("Mac"): # "Mac OS X", etc. - system = "darwin" - else: # "Linux", "SunOS", "FreeBSD", etc. - # Setting this to "linux2" is not ideal, but only Windows or Mac - # are actually checked for and the rest of the module expects - # *sys.platform* style strings. - system = "linux2" -else: - system = sys.platform - - -def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): - r"""Return full path to the user-specific data dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "roaming" (boolean, default False) can be set True to use the Windows - roaming appdata directory. That means that for users on a Windows - network setup for roaming profiles, this user data will be - sync'd on login. See - - for a discussion of issues. - - Typical user data directories are: - Mac OS X: ~/Library/Application Support/ - Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined - Win XP (not roaming): C:\Documents and Settings\\Application Data\\ - Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ - Win 7 (not roaming): C:\Users\\AppData\Local\\ - Win 7 (roaming): C:\Users\\AppData\Roaming\\ - - For Unix, we follow the XDG spec and support $XDG_DATA_HOME. - That means, by default "~/.local/share/". - """ - if system == "win32": # pragma: no cover - if appauthor is None: - appauthor = appname - const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" - path = os.path.normpath(_get_win_folder(const)) - if appname: - if appauthor is not False: - path = os.path.join(path, appauthor, appname) - else: - path = os.path.join(path, appname) - elif system == "darwin": - path = os.path.expanduser("~/Library/Application Support/") - if appname: - path = os.path.join(path, appname) - else: - path = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")) - if appname: - path = os.path.join(path, appname) - if appname and version: - path = os.path.join(path, version) - return path - - -def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): - """Return full path to the user-shared data dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "multipath" is an optional parameter only applicable to *nix - which indicates that the entire list of data dirs should be - returned. By default, the first item from XDG_DATA_DIRS is - returned, or '/usr/local/share/', - if XDG_DATA_DIRS is not set - - Typical user data directories are: - Mac OS X: /Library/Application Support/ - Unix: /usr/local/share/ or /usr/share/ - Win XP: C:\Documents and Settings\All Users\Application Data\\ - Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) - Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. - - For Unix, this is using the $XDG_DATA_DIRS[0] default. - - WARNING: Do not use this on Windows. See the Vista-Fail note above for why. - """ - if system == "win32": # pragma: no cover - if appauthor is None: - appauthor = appname - path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) - if appname: - if appauthor is not False: - path = os.path.join(path, appauthor, appname) - else: - path = os.path.join(path, appname) - elif system == "darwin": - path = os.path.expanduser("/Library/Application Support") - if appname: - path = os.path.join(path, appname) - else: # pragma: no cover - # XDG default for $XDG_DATA_DIRS - # only first, if multipath is False - path = os.getenv( - "XDG_DATA_DIRS", os.pathsep.join(["/usr/local/share", "/usr/share"]) - ) - pathlist = [ - os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) - ] - if appname: - if version: - appname = os.path.join(appname, version) - pathlist = [os.sep.join([x, appname]) for x in pathlist] - - if multipath: - path = os.pathsep.join(pathlist) - else: - path = pathlist[0] - return path - - if appname and version: - path = os.path.join(path, version) - return path - - -def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): - r"""Return full path to the user-specific config dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "roaming" (boolean, default False) can be set True to use the Windows - roaming appdata directory. That means that for users on a Windows - network setup for roaming profiles, this user data will be - sync'd on login. See - - for a discussion of issues. - - Typical user data directories are: - Mac OS X: same as user_data_dir - Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined - Win *: same as user_data_dir - - For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. - That means, by deafult "~/.config/". - """ - if system in ["win32", "darwin"]: - path = user_data_dir(appname, appauthor, None, roaming) - else: # pragma: no cover - path = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")) - if appname: - path = os.path.join(path, appname) - if appname and version: - path = os.path.join(path, version) - return path - - -def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): - """Return full path to the user-shared data dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "multipath" is an optional parameter only applicable to *nix - which indicates that the entire list of config dirs should be - returned. By default, the first item from XDG_CONFIG_DIRS is - returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set - - Typical user data directories are: - Mac OS X: same as site_data_dir - Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in - $XDG_CONFIG_DIRS - Win *: same as site_data_dir - Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) - - For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False - - WARNING: Do not use this on Windows. See the Vista-Fail note above for why. - """ - if system in ["win32", "darwin"]: - path = site_data_dir(appname, appauthor) - if appname and version: - path = os.path.join(path, version) - else: # pragma: no cover - # XDG default for $XDG_CONFIG_DIRS - # only first, if multipath is False - path = os.getenv("XDG_CONFIG_DIRS", "/etc/xdg") - pathlist = [ - os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) - ] - if appname: - if version: - appname = os.path.join(appname, version) - pathlist = [os.sep.join([x, appname]) for x in pathlist] - - if multipath: - path = os.pathsep.join(pathlist) - else: - path = pathlist[0] - return path - - -def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): - r"""Return full path to the user-specific cache dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "opinion" (boolean) can be False to disable the appending of - "Cache" to the base app data dir for Windows. See - discussion below. - - Typical user cache directories are: - Mac OS X: ~/Library/Caches/ - Unix: ~/.cache/ (XDG default) - Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache - Vista: C:\Users\\AppData\Local\\\Cache - - On Windows the only suggestion in the MSDN docs is that local settings go in - the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming - app data dir (the default returned by `user_data_dir` above). Apps typically - put cache data somewhere *under* the given dir here. Some examples: - ...\Mozilla\Firefox\Profiles\\Cache - ...\Acme\SuperApp\Cache\1.0 - OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. - This can be disabled with the `opinion=False` option. - """ - if system == "win32": # pragma: no cover - if appauthor is None: - appauthor = appname - path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) - if appname: - if appauthor is not False: - path = os.path.join(path, appauthor, appname) - else: - path = os.path.join(path, appname) - if opinion: - path = os.path.join(path, "Cache") - elif system == "darwin": - path = os.path.expanduser("~/Library/Caches") - if appname: - path = os.path.join(path, appname) - else: # pragma: no cover - path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")) - if appname: - path = os.path.join(path, appname) - if appname and version: - path = os.path.join(path, version) - return path - - -def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): - r"""Return full path to the user-specific log dir for this application. - - "appname" is the name of application. - If None, just the system directory is returned. - "appauthor" (only used on Windows) is the name of the - appauthor or distributing body for this application. Typically - it is the owning company name. This falls back to appname. You may - pass False to disable it. - "version" is an optional version path element to append to the - path. You might want to use this if you want multiple versions - of your app to be able to run independently. If used, this - would typically be ".". - Only applied when appname is present. - "opinion" (boolean) can be False to disable the appending of - "Logs" to the base app data dir for Windows, and "log" to the - base cache dir for Unix. See discussion below. - - Typical user cache directories are: - Mac OS X: ~/Library/Logs/ - Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined - Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs - Vista: C:\Users\\AppData\Local\\\Logs - - On Windows the only suggestion in the MSDN docs is that local settings - go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in - examples of what some windows apps use for a logs dir.) - - OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` - value for Windows and appends "log" to the user cache dir for Unix. - This can be disabled with the `opinion=False` option. - """ - if system == "darwin": - path = os.path.join(os.path.expanduser("~/Library/Logs"), appname) - elif system == "win32": # pragma: no cover - path = user_data_dir(appname, appauthor, version) - version = False - if opinion: - path = os.path.join(path, "Logs") - else: # pragma: no cover - path = user_cache_dir(appname, appauthor, version) - version = False - if opinion: - path = os.path.join(path, "log") - if appname and version: - path = os.path.join(path, version) - return path +from platformdirs import ( + site_config_dir, + site_data_dir, + user_cache_dir, + user_config_dir, + user_data_dir, + user_log_dir, +) class AppDirs(object): """Convenience wrapper for getting application dirs.""" - def __init__( - self, appname, appauthor=None, version=None, roaming=False, multipath=False - ): + def __init__(self, appname, appauthor=None, version=None, roaming=False, multipath=False): self.appname = appname self.appauthor = appauthor self.version = version @@ -409,27 +23,19 @@ def __init__( @property def user_data_dir(self): - return user_data_dir( - self.appname, self.appauthor, version=self.version, roaming=self.roaming - ) + return user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_data_dir(self): - return site_data_dir( - self.appname, self.appauthor, version=self.version, multipath=self.multipath - ) + return site_data_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_config_dir(self): - return user_config_dir( - self.appname, self.appauthor, version=self.version, roaming=self.roaming - ) + return user_config_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_config_dir(self): - return site_config_dir( - self.appname, self.appauthor, version=self.version, multipath=self.multipath - ) + return site_config_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_cache_dir(self): @@ -438,171 +44,3 @@ def user_cache_dir(self): @property def user_log_dir(self): return user_log_dir(self.appname, self.appauthor, version=self.version) - - -# ---- internal support stuff - - -def _get_win_folder_from_registry(csidl_name): # pragma: no cover - """This is a fallback technique at best. I'm not sure if using the - registry for this guarantees us the correct answer for all CSIDL_* - names. - """ - import _winreg - - shell_folder_name = { - "CSIDL_APPDATA": "AppData", - "CSIDL_COMMON_APPDATA": "Common AppData", - "CSIDL_LOCAL_APPDATA": "Local AppData", - }[csidl_name] - - key = _winreg.OpenKey( - _winreg.HKEY_CURRENT_USER, - r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", - ) - dir, type = _winreg.QueryValueEx(key, shell_folder_name) - return dir - - -def _get_win_folder_with_pywin32(csidl_name): # pragma: no cover - from win32com.shell import shellcon, shell - - dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) - # Try to make this a unicode path because SHGetFolderPath does - # not return unicode strings when there is unicode data in the - # path. - try: - dir = unicode(dir) - - # Downgrade to short path name if have highbit chars. See - # . - has_high_char = False - for c in dir: - if ord(c) > 255: - has_high_char = True - break - if has_high_char: - try: - import win32api - - dir = win32api.GetShortPathName(dir) - except ImportError: - pass - except UnicodeError: - pass - return dir - - -def _get_win_folder_with_ctypes(csidl_name): # pragma: no cover - import ctypes - - csidl_const = { - "CSIDL_APPDATA": 26, - "CSIDL_COMMON_APPDATA": 35, - "CSIDL_LOCAL_APPDATA": 28, - }[csidl_name] - - buf = ctypes.create_unicode_buffer(1024) - ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) - - # Downgrade to short path name if have highbit chars. See - # . - has_high_char = False - for c in buf: - if ord(c) > 255: - has_high_char = True - break - if has_high_char: - buf2 = ctypes.create_unicode_buffer(1024) - if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): - buf = buf2 - - return buf.value - - -def _get_win_folder_with_jna(csidl_name): # pragma: no cover - import array - from com.sun import jna - from com.sun.jna.platform import win32 - - buf_size = win32.WinDef.MAX_PATH * 2 - buf = array.zeros("c", buf_size) - shell = win32.Shell32.INSTANCE - shell.SHGetFolderPath( - None, - getattr(win32.ShlObj, csidl_name), - None, - win32.ShlObj.SHGFP_TYPE_CURRENT, - buf, - ) - dir = jna.Native.toString(buf.tostring()).rstrip("\0") - - # Downgrade to short path name if have highbit chars. See - # . - has_high_char = False - for c in dir: - if ord(c) > 255: - has_high_char = True - break - if has_high_char: - buf = array.zeros("c", buf_size) - kernel = win32.Kernel32.INSTANCE - if kernal.GetShortPathName(dir, buf, buf_size): - dir = jna.Native.toString(buf.tostring()).rstrip("\0") - - return dir - - -if system == "win32": # pragma: no cover - try: - import win32com.shell - - _get_win_folder = _get_win_folder_with_pywin32 - except ImportError: - try: - from ctypes import windll - - _get_win_folder = _get_win_folder_with_ctypes - except ImportError: - try: - import com.sun.jna - - _get_win_folder = _get_win_folder_with_jna - except ImportError: - _get_win_folder = _get_win_folder_from_registry - - -# ---- self test code - -if __name__ == "__main__": # pragma no cover - appname = "MyApp" - appauthor = "MyCompany" - - props = ( - "user_data_dir", - "site_data_dir", - "user_config_dir", - "site_config_dir", - "user_cache_dir", - "user_log_dir", - ) - - print("-- app dirs (with optional 'version')") - dirs = AppDirs(appname, appauthor, version="1.0") - for prop in props: - print("%s: %s" % (prop, getattr(dirs, prop))) - - print("\n-- app dirs (without optional 'version')") - dirs = AppDirs(appname, appauthor) - for prop in props: - print("%s: %s" % (prop, getattr(dirs, prop))) - - print("\n-- app dirs (without optional 'appauthor')") - dirs = AppDirs(appname) - for prop in props: - print("%s: %s" % (prop, getattr(dirs, prop))) - - print("\n-- app dirs (with disabled 'appauthor')") - dirs = AppDirs(appname, appauthor=False) - for prop in props: - print("%s: %s" % (prop, getattr(dirs, prop))) diff --git a/easydev/browser.py b/easydev/browser.py index 7c3e47c..cfca8c0 100644 --- a/easydev/browser.py +++ b/easydev/browser.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io @@ -36,7 +34,7 @@ browse image.png -Or a txt file (or any document provided there is a default executable +Or a txt file (or any document provided there is a default executable to open it). It works like a charm under Linux. Under MAC, it uses the **open** command so this should also work. @@ -48,7 +46,7 @@ browse ~/Pictures -See more examples below. +See more examples below. The interest of **browse** is that it can also be used programmatically:: @@ -63,10 +61,11 @@ from easydev import onweb """ +import argparse import os -import sys, webbrowser +import sys +import webbrowser from optparse import OptionParser -import argparse def browse(url, verbose=True): @@ -168,10 +167,7 @@ def main(args=None): # pragma: no cover browse(url, verbose) else: if verbose: - print( - "%s does not exists and does not starts with http, trying anyway." - % url - ) + print("%s does not exists and does not starts with http, trying anyway." % url) browse("http://" + url, verbose) diff --git a/easydev/chunks.py b/easydev/chunks.py index a4673dc..33ee073 100644 --- a/easydev/chunks.py +++ b/easydev/chunks.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io diff --git a/easydev/codecs.py b/easydev/codecs.py index 1914d70..083a568 100644 --- a/easydev/codecs.py +++ b/easydev/codecs.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 # # Website: https://www.assembla.com/spaces/pyeasydev/wiki # Documentation: http://packages.python.org/easydev diff --git a/easydev/config_tools.py b/easydev/config_tools.py index 214adcf..0fd8c58 100644 --- a/easydev/config_tools.py +++ b/easydev/config_tools.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2014 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under BSD3 license # # Website: https://github.com/cokelaer/easydev # Documentation: http://packages.python.org/easydev @@ -20,16 +18,12 @@ except ImportError: from configparser import ConfigParser - import os +__all__ = ["CustomConfig", "DynamicConfigParser"] -__all__ = ["CustomConfig", "DynamicConfigParser", "ConfigExample", "load_configfile"] - -# 53, 59, 64-65, 181, 260, 262, 267-270, 288-290, 329, 332-337, 340-341, 359-360, 386-388, 400-401, 406-426, 431-435 - -class _DictSection(object): +class _DictSection: """Dictionary section. Reference: https://gist.github.com/dangoakachan/3855920 @@ -76,49 +70,7 @@ def __contains__(self, attr): return config.has_section(section) and config.has_option(section, attr) -class ConfigExample(object): - """Create a simple example of ConfigParser instance to play with - - :: - - >>> from easydev.pipeline.config import ConfigExample - >>> c = ConfigExample().config # The ConfigParser instance - >>> assert 'General' in c.sections() - >>> assert 'GA' in c.sections() - - This example builds up a ConfigParser instance from scratch. - - This is equivalent to having the following input file:: - - [General] - verbose = True - tag = test - - [GA] - popsize = 1 - - - which can be read with ConfigParser as follows: - - .. doctest:: - - >>> # Python 3 code - >>> from configparser import ConfigParser - >>> config = ConfigParser() - >>> config.read("file.ini") - [] - - """ - - def __init__(self): - self.config = ConfigParser() - self.config.add_section("General") - self.config.set("General", "verbose", "true") - self.config.add_section("GA") - self.config.set("GA", "popsize", "50") - - -class DynamicConfigParser(ConfigParser, object): +class DynamicConfigParser(ConfigParser): """Enhanced version of Config Parser Provide some aliases to the original ConfigParser class and @@ -180,9 +132,7 @@ def __init__(self, config_or_filename=None, *args, **kargs): elif config_or_filename == None: pass else: - raise TypeError( - "config_or_filename must be a valid filename or valid ConfigParser instance" - ) + raise TypeError("config_or_filename must be a valid filename or valid ConfigParser instance") def read(self, filename): """Load a new config from a filename (remove all previous sections)""" @@ -334,16 +284,16 @@ def __getattr__(self, key): def __setattr__(self, attr, value): if attr.startswith("_") or attr: object.__setattr__(self, attr, value) - else: + else: # pragma: no cover self.__setitem__(attr, value) - def __setitem__(self, attr, value): - if isinstance(value, dict): - section = self[attr] - for k, v in value.items(): - section[k] = v - else: - raise TypeError("value must be a valid dictionary") + # def __setitem__(self, attr, value): + # if isinstance(value, dict): + # section = self[attr] + # for k, v in value.items(): + # section[k] = v + # else: + # raise TypeError("value must be a valid dictionary") def __delattr__(self, attr): if attr in self: @@ -362,9 +312,7 @@ def __eq__(self, data): for option in self.options(section): try: - if str(self.get(section, option, raw=True)) != str( - data.get(section, option, raw=True) - ): + if str(self.get(section, option, raw=True)) != str(data.get(section, option, raw=True)): print("option %s in section %s differ" % (option, section)) return False except: # pragma: no cover @@ -389,9 +337,7 @@ def _get_config_dir(self): sdir = self.appdirs.user_config_dir return self._get_and_create(sdir) - user_config_dir = property( - _get_config_dir, doc="return directory of this configuration file" - ) + user_config_dir = property(_get_config_dir, doc="return directory of this configuration file") def _get_and_create(self, sdir): if not os.path.exists(sdir): @@ -415,43 +361,3 @@ def remove(self): os.rmdir(sdir) except Exception as err: # pragma: no cover raise Exception(err) - - -def _load_configfile(configpath): # pragma: no cover - "Tries to load a JSON or YAML file into a dict." - try: - with open(configpath) as f: - try: - import json - - return json.load(f) - except ValueError: - f.seek(0) # try again - try: - import yaml - except ImportError: - raise IOError( - "Config file is not valid JSON and PyYAML " - "has not been installed. Please install " - "PyYAML to use YAML config files." - ) - try: - return yaml.load(f, Loader=yaml.FullLoader) - except yaml.YAMLError: - raise IOError( - "Config file is not valid JSON or YAML. " - "In case of YAML, make sure to not mix " - "whitespace and tab indentation." - ) - except Exception as err: - raise (err) - - -def load_configfile(configpath): - "Loads a JSON or YAML configfile as a dict." - config = _load_configfile(configpath) - if not isinstance(config, dict): - raise IOError( - "Config file must be given as JSON or YAML " "with keys at top level." - ) - return config diff --git a/easydev/console.py b/easydev/console.py index ec8a59f..4059e07 100644 --- a/easydev/console.py +++ b/easydev/console.py @@ -4,13 +4,11 @@ # This file is part of the easydev software # It is a modified version of console.py from the sphinx software # -# Copyright (c) 2011-2014 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://packages.python.org/easydev @@ -18,8 +16,8 @@ ############################################################################## """Format colored consoled output. Modified from sphinx.util.console""" import os -import sys import platform +import sys __all__ = ["color_terminal", "get_terminal_width", "term_width_line"] @@ -41,7 +39,9 @@ def get_terminal_width(): """Returns the current terminal width""" try: - import termios, fcntl, struct + import fcntl + import struct + import termios call = fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack("hhhh", 0, 0, 0, 0)) _, width = struct.unpack("hhhh", call)[:2] diff --git a/easydev/copybutton.py b/easydev/copybutton.py index cab51f0..1932705 100644 --- a/easydev/copybutton.py +++ b/easydev/copybutton.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2014 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://packages.python.org/easydev @@ -25,8 +23,8 @@ speaking required for the installation. """ import os -from os.path import join as pj import shutil +from os.path import join as pj try: from docutils import nodes diff --git a/easydev/decorators.py b/easydev/decorators.py index 880fdf0..db18f0b 100644 --- a/easydev/decorators.py +++ b/easydev/decorators.py @@ -3,21 +3,19 @@ # # This file is part of the easydev software # -# Copyright (c) 2012-2014 - +# Copyright (c) 2011-2024 - # # File author(s): Thomas Cokelaer (cokelaer, gmail.com) # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # website: http://github.com/cokelaer/easydev # ############################################################################## """Handy decorators""" -from functools import wraps import threading +from functools import wraps __all__ = ["ifpylab", "requires", "ifpandas"] @@ -51,9 +49,7 @@ def print(self): msg = args_deco[1] if len(attribute.split(".")) > 2: - raise AttributeError( - "This version of require decorator introspect only 2 levels" - ) + raise AttributeError("This version of require decorator introspect only 2 levels") def decorator(func): # func: function object of decorated method; has @@ -139,9 +135,7 @@ def actualDecorator(f): def wrapper(*args, **kwds): for require in requires: if hasattr(args[0], require) == False: - raise AttributeError( - "{} not found in {}. ".format(require, args[0]) + msg - ) + raise AttributeError("{} not found in {}. ".format(require, args[0]) + msg) return f(*args, **kwds) return wrapper diff --git a/easydev/dependencies.py b/easydev/dependencies.py index f41fd59..e17baea 100644 --- a/easydev/dependencies.py +++ b/easydev/dependencies.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io diff --git a/easydev/doc.py b/easydev/doc.py index c12ceb1..0ae0903 100644 --- a/easydev/doc.py +++ b/easydev/doc.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io diff --git a/easydev/easytest.py b/easydev/easytest.py index 5744fec..59c721f 100644 --- a/easydev/easytest.py +++ b/easydev/easytest.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2014 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://packages.python.org/easydev @@ -21,8 +19,6 @@ __all__ = ["assert_list_almost_equal", "trysetattr", "TempFile"] -# from easydev.decorators import ifpandas - def assert_list_almost_equal(first, second, places=None, deltas=None): """Combined version nose.tools.assert_almost_equal and assert_list_equal diff --git a/easydev/logging_tools.py b/easydev/logging_tools.py index 3bf63ba..0146e7b 100644 --- a/easydev/logging_tools.py +++ b/easydev/logging_tools.py @@ -2,13 +2,11 @@ # # This file is part of easydev software # -# Copyright (c) 2012-2014 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # @@ -44,9 +42,7 @@ class Logging(object): def __init__(self, name="root", level="WARNING", text_color="blue"): self._name = name self.formatter = colorlog.ColoredFormatter( - "%(log_color)s%(levelname)-8s[%(name)s:%(lineno)d]: %(reset)s %({})s%(message)s".format( - text_color - ), + "%(log_color)s%(levelname)-8s[%(name)s:%(lineno)d]: %(reset)s %({})s%(message)s".format(text_color), datefmt=None, reset=True, log_colors=colors, diff --git a/easydev/md5tools.py b/easydev/md5tools.py index 549abf3..dafef5a 100644 --- a/easydev/md5tools.py +++ b/easydev/md5tools.py @@ -1,13 +1,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2021 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io diff --git a/easydev/misc.py b/easydev/misc.py index 9a12919..3f2facd 100644 --- a/easydev/misc.py +++ b/easydev/misc.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io @@ -17,7 +15,6 @@ ############################################################################## import os - __all__ = ["get_home", "cmd_exists"] @@ -47,9 +44,7 @@ def cmd_exists(cmd): import subprocess # for unix/max only - result = subprocess.call( - "type " + cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) + result = subprocess.call("type " + cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result == 0: return True else: @@ -68,10 +63,7 @@ def in_ipynb(): """ try: # pragma: no cover cfg = get_ipython().config - if ( - "parent_appname" in cfg["IPKernelApp"].keys() - and cfg["IPKernelApp"]["parent_appname"] == "ipython-notebook" - ): + if "parent_appname" in cfg["IPKernelApp"].keys() and cfg["IPKernelApp"]["parent_appname"] == "ipython-notebook": return True elif "connection_file" in cfg["IPKernelApp"].keys(): if "jupyter" in cfg["IPKernelApp"]["connection_file"]: diff --git a/easydev/multicore.py b/easydev/multicore.py index dc0e839..c977525 100644 --- a/easydev/multicore.py +++ b/easydev/multicore.py @@ -3,20 +3,18 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io # ############################################################################## import time -from multiprocessing import cpu_count, Process, Queue, Pool +from multiprocessing import Pool, Process, Queue, cpu_count __all__ = ["MultiProcessing"] @@ -113,9 +111,7 @@ def init_worker(): self.pool = Pool(self.maxcpu, init_worker) for process in self.jobs: - self.pool.apply_async( - process._target, process._args, process._kwargs, callback=self._cb - ) + self.pool.apply_async(process._target, process._args, process._kwargs, callback=self._cb) # ensure the results have same order as jobs # maybe important if you expect the order of the results to diff --git a/easydev/options.py b/easydev/options.py index 251ebf0..a4ebf3a 100644 --- a/easydev/options.py +++ b/easydev/options.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io @@ -17,7 +15,6 @@ ############################################################################## import argparse - __all__ = ["SmartFormatter"] diff --git a/easydev/paths.py b/easydev/paths.py index 6658e62..e4f0387 100644 --- a/easydev/paths.py +++ b/easydev/paths.py @@ -4,19 +4,16 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io # ############################################################################## -# $:Id $ """Utilities to ease access to share data paths""" import importlib import os diff --git a/easydev/platform.py b/easydev/platform.py index d759088..98e1f6b 100644 --- a/easydev/platform.py +++ b/easydev/platform.py @@ -3,19 +3,18 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io # ############################################################################## from __future__ import absolute_import # avoids conflict with standard module + import os import sys diff --git a/easydev/profiler.py b/easydev/profiler.py index de6e079..1430126 100644 --- a/easydev/profiler.py +++ b/easydev/profiler.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io @@ -57,15 +55,11 @@ def profiled_func(*args, **kwargs): return inner - except ImportError: # pragma: no cover def do_profile(follow=[]): "Helpful if you accidentally leave in production!" - print( - "easydev warning:: line_profiler does not seem to be installed. " - + "Type 'pip install line_profiler'" - ) + print("easydev warning:: line_profiler does not seem to be installed. " + "Type 'pip install line_profiler'") def inner(func): def nothing(*args, **kwargs): diff --git a/easydev/progressbar.py b/easydev/progressbar.py index 8ebb0ba..e3f09ef 100644 --- a/easydev/progressbar.py +++ b/easydev/progressbar.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io @@ -22,10 +20,9 @@ import time import uuid - try: - from IPython.core.display import HTML, Javascript from IPython import display + from IPython.core.display import HTML, Javascript except ImportError: # pragma: no cover pass @@ -72,9 +69,7 @@ def __init__(self, iterations, printer, width=40, interval=None): def animate(self, i, dummy=None): # dummy=None is for back-compatibility if dummy is not None: # pragma: no cover - print( - "second argument in easydev.progress_bar.animate is deprecated. Update your code" - ) + print("second argument in easydev.progress_bar.animate is deprecated. Update your code") # +1 if i starts at 0 and finishes at N-1 if divmod(i, self.interval)[1] != 0 and i != self.iterations: pass @@ -141,9 +136,7 @@ def __init__(self, iterations, interval=None): def animate(self, i, dummy=None): if dummy is not None: - print( - "second argument in easydev.progress_bar.animate is deprecated. Update your code" - ) + print("second argument in easydev.progress_bar.animate is deprecated. Update your code") # +1 if i starts at 0 and finishes at N-1 if divmod(i, self.interval)[1] != 0 and i != self.iterations: @@ -153,10 +146,7 @@ def animate(self, i, dummy=None): fraction = percentage display(Javascript("$('div#%s').width('%i%%')" % (self.divid, percentage))) display( - Javascript( - "$('label#%s').text('%i%% in %.1f sec')" - % (self.sec_id, fraction, round(self.elapsed, 1)) - ) + Javascript("$('label#%s').text('%i%% in %.1f sec')" % (self.sec_id, fraction, round(self.elapsed, 1))) ) diff --git a/easydev/sphinx_themes.py b/easydev/sphinx_themes.py index 6ed86e1..e7befbe 100644 --- a/easydev/sphinx_themes.py +++ b/easydev/sphinx_themes.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io diff --git a/easydev/timer.py b/easydev/timer.py index 2213f1e..71594bd 100644 --- a/easydev/timer.py +++ b/easydev/timer.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io diff --git a/easydev/tools.py b/easydev/tools.py index b1b8d18..1463c05 100644 --- a/easydev/tools.py +++ b/easydev/tools.py @@ -1,25 +1,22 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2020 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io # ############################################################################## """toolkit to ease development""" -import subprocess import json import os +import subprocess import sys - __all__ = [ "shellcmd", "swapdict", @@ -98,9 +95,7 @@ def check_param_in_list(param, valid_values, name=None): if isinstance(valid_values, list) is False: raise TypeError( - "the valid_values second argument must be a list of valid values. {0} was provided.".format( - valid_values - ) + "the valid_values second argument must be a list of valid values. {0} was provided.".format(valid_values) ) if param not in valid_values: @@ -126,9 +121,7 @@ def shellcmd(cmd, show=False, verbose=False, ignore_errors=False): if show: print(cmd) try: - ret = subprocess.Popen( - [cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True - ) + ret = subprocess.Popen([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output = ret.stdout.read().strip() error = ret.stderr.read().strip() @@ -192,9 +185,7 @@ def swapdict(dic, check_ambiguity=True): """ # this version is more elegant but slightly slower : return {v:k for k,v in dic.items()} if check_ambiguity: - assert len(set(dic.keys())) == len( - set(dic.values()) - ), "values is not a set. ambiguities for keys." + assert len(set(dic.keys())) == len(set(dic.values())), "values is not a set. ambiguities for keys." return dict(zip(dic.values(), dic.keys())) diff --git a/easydev/url.py b/easydev/url.py index 094d4d4..baa2bf0 100644 --- a/easydev/url.py +++ b/easydev/url.py @@ -3,13 +3,11 @@ # # This file is part of the easydev software # -# Copyright (c) 2011-2017 +# Copyright (c) 2011-2024 # # File author(s): Thomas Cokelaer # -# Distributed under the GPLv3 License. -# See accompanying file LICENSE.txt or copy at -# http://www.gnu.org/licenses/gpl-3.0.html +# Distributed under the BSD3 License. # # Website: https://github.com/cokelaer/easydev # Documentation: http://easydev-python.readthedocs.io diff --git a/test/__init__.py b/test/__init__.py index e69de29..9d3b5c5 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -0,0 +1,3 @@ +import os + +test_dir = os.path.dirname(os.path.realpath(__file__)) diff --git a/test/data/config.ini b/test/data/config.ini new file mode 100644 index 0000000..05c382f --- /dev/null +++ b/test/data/config.ini @@ -0,0 +1,6 @@ +[General] +verbose = True +tag = test + +[GA] +popsize = 1 diff --git a/test/test_appdirs.py b/test/test_appdirs.py index d755880..d01d0bf 100644 --- a/test/test_appdirs.py +++ b/test/test_appdirs.py @@ -1,7 +1,7 @@ import mock -def test_app(): +def test_app(): def getter(app): app.user_data_dir app.site_data_dir @@ -12,15 +12,18 @@ def getter(app): with mock.patch("sys.platform", "darwin"): from easydev import appdirs + app = appdirs.AppDirs("test") getter(app) with mock.patch("sys.platform", "win32"): from easydev import appdirs + app = appdirs.AppDirs("test") getter(app) with mock.patch("sys.platform", "linux"): from easydev import appdirs + app = appdirs.AppDirs("test") getter(app) diff --git a/test/test_browse.py b/test/test_browse.py index 123d85a..109cb57 100644 --- a/test/test_browse.py +++ b/test/test_browse.py @@ -9,8 +9,9 @@ def test_browse(mocker): def func(*args, **kwargs): pass - with patch('webbrowser.open', func): - with patch('webbrowser.open_new', func): + + with patch("webbrowser.open", func): + with patch("webbrowser.open_new", func): browser.browse("http://pypi.python.org", verbose=True) browser.browse("pypi.python.org", verbose=True) browser.browse(".", verbose=True) @@ -18,12 +19,11 @@ def func(*args, **kwargs): def test_browse_module(mocker): from easydev.browser import main + def func(*args, **kwargs): pass - with patch('webbrowser.open', func): - main(["browse", "--help"]) - main(["browse", "." ]) - main(["browse", "http://www.uniprot.org" ]) - - + with patch("webbrowser.open", func): + main(["browse", "--help"]) + main(["browse", "."]) + main(["browse", "http://www.uniprot.org"]) diff --git a/test/test_chunks.py b/test/test_chunks.py index ba249dd..5cd5d20 100644 --- a/test/test_chunks.py +++ b/test/test_chunks.py @@ -1,15 +1,10 @@ from easydev import split_into_chunks - - - - - - def test_chunks(): - assert list(split_into_chunks([0,1,2,3,4,5,6], 2)) == [[0, 2, 4, 6], [1, 3, 5]] - assert list(split_into_chunks([0,1,2,3,4,5], 2)) == [[0, 2, 4], [1, 3, 5]] + assert list(split_into_chunks([0, 1, 2, 3, 4, 5, 6], 2)) == [[0, 2, 4, 6], [1, 3, 5]] + assert list(split_into_chunks([0, 1, 2, 3, 4, 5], 2)) == [[0, 2, 4], [1, 3, 5]] + test_chunks() diff --git a/test/test_cnolab_sphinx.py b/test/test_cnolab_sphinx.py index eaccb90..24cf6a1 100644 --- a/test/test_cnolab_sphinx.py +++ b/test/test_cnolab_sphinx.py @@ -1,12 +1,14 @@ import easydev + def test_path(): p = easydev.get_path_sphinx_themes() import os + dirs = os.listdir(p) - assert 'standard' in dirs + assert "standard" in dirs + def test_sphinx_themes(): p = easydev.get_sphinx_themes() - assert 'standard' in p - + assert "standard" in p diff --git a/test/test_codecs.py b/test/test_codecs.py index 99182d5..2fa4981 100644 --- a/test/test_codecs.py +++ b/test/test_codecs.py @@ -3,25 +3,26 @@ def test_tolist(): assert codecs.tolist(1) == [1] - assert codecs.tolist(1.) == [1.] - assert codecs.tolist('1') == ['1'] + assert codecs.tolist(1.0) == [1.0] + assert codecs.tolist("1") == ["1"] assert codecs.tolist([1]) == [1] assert codecs.tolist([1, 2]) == [1, 2] try: import numpy as np + x = np.array([1, 2]) assert codecs.tolist(x) == [1, 2] except: pass assert sorted(codecs.tolist((1, 2))) == [1, 2] - + codecs.tolist(set([1])) def test_tostring(): assert codecs.list2string([1, 2]) == "1, 2" assert codecs.list2string([1, 2], sep=";") == "1; 2" - assert codecs.list2string([1, 2], sep=';', space=False) == "1;2" + assert codecs.list2string([1, 2], sep=";", space=False) == "1;2" assert codecs.list2string(1) == "1" diff --git a/test/test_config.py b/test/test_config.py index f942a72..d28c4b8 100644 --- a/test/test_config.py +++ b/test/test_config.py @@ -1,52 +1,59 @@ -from easydev.config_tools import ConfigExample, DynamicConfigParser, load_configfile - -from easydev import CustomConfig import os +from easydev import CustomConfig +from easydev.config_tools import DynamicConfigParser +from . import test_dir def test_config_custom(): - c = CustomConfig('dummy') + c = CustomConfig("dummy") c.init() c.user_config_dir c.remove() def test_configExample(): - c = ConfigExample().config - assert 'General' in c.sections() - assert 'GA' in c.sections() + + c = DynamicConfigParser(f"{test_dir}/data/config.ini") + assert "General" in c.sections() + assert "GA" in c.sections() print(c) - c.remove_section('General') + c.remove_section("General") def test_ordered_dict_attribute(): # disabled because incompatible with python 3 c = DynamicConfigParser() c.add_section("GA") - c.GA.test = 2 # this is an attribute only, not yet a key + c.GA.test = 2 # this is an attribute only, not yet a key c.add_option("GA", "test", 1) c.GA.test = 2 - c['GA']['test'] = 4 - del c['GA']['test'] + c["GA"]["test"] = 4 + del c["GA"]["test"] + +def test_DynamicConfig(tmpdir): + + outname = tmpdir.join("test.ini") + + # constructor with filename + dc = DynamicConfigParser(f"{test_dir}/data/config.ini") + + # constructor with existing constructor + dc = DynamicConfigParser(dc) -def test_DynamicConfig(): - c = ConfigExample() - dc = DynamicConfigParser(c.config) - dc.save('test.ini') - dc = DynamicConfigParser('test.ini') - #dc = DynamicConfigParser(c.config) - dc._replace_config(c.config) dc.GA - dc.add_option("GA", "bool", 'True') + dc.add_option("GA", "bool", "True") dc.get_options("GA") - os.remove('test.ini') + # save file and read back + outname = tmpdir.join("test.ini") + dc.save(outname) + dc.save(outname) # called twice on purpose - dc.remove_section('GA') - assert 'GA' not in dc.sections() + dc.remove_section("GA") + assert "GA" not in dc.sections() print(dc) # try something stupid @@ -63,36 +70,34 @@ def test_DynamicConfig(): except: assert True + def test_DynamicConfigDelete(): - from easydev import ConfigExample - dcp = DynamicConfigParser(ConfigExample().config) + + cfg = DynamicConfigParser(f"{test_dir}/data/config.ini") + + dcp = DynamicConfigParser(cfg) try: - del(dcp["GA"]) - assert dcp.sections() == ['General'] + del dcp["GA"] + assert dcp.sections() == ["General"] except: pass - -def test_DynamicConfig_setter(): +def test_DynamicConfig_setter(tmpdir): + outname = tmpdir.join("test.ini") dc = DynamicConfigParser() dc.add_section("GA") - dc.add_option("GA", "test", 1) - dc.save("test.ini") + dc.add_option("GA", "popsize", 1) + dc.add_section("General") + dc.add_option("General", "verbose", True) + dc.add_option("General", "tag", "test") + dc.save(outname) - dc2 = DynamicConfigParser("test.ini") + dc2 = DynamicConfigParser(f"{test_dir}/data/config.ini") assert dc == dc2 - dc2.GA.test == 1 dc.GA.test = 10 - dc.save("test.ini") - dc2 = DynamicConfigParser("test.ini") - assert dc == dc2 - - assert dc2.GA.test == '10' - - os.remove('test.ini') def test_section2dict(): @@ -111,8 +116,7 @@ def test_compare(): dc2.add_section("GA2") dc2.add_option("GA2", "test", 1) - assert (dc==dc2) == False - + assert (dc == dc2) == False dc = DynamicConfigParser() dc.add_section("GA") @@ -122,7 +126,7 @@ def test_compare(): dc2.add_section("GA") dc2.add_option("GA", "test", 2) - assert (dc==dc2) == False + assert (dc == dc2) == False dc = DynamicConfigParser() dc.add_section("GA") @@ -132,7 +136,4 @@ def test_compare(): dc2.add_section("GA") dc2.add_option("GA", "test", 1) - assert (dc==dc2) == True - - - + assert (dc == dc2) == True diff --git a/test/test_console.py b/test/test_console.py index ecb88fc..1bd5895 100644 --- a/test/test_console.py +++ b/test/test_console.py @@ -1,5 +1,5 @@ -from easydev.console import * from easydev import console +from easydev.console import * def test_get_terminal_width(): @@ -7,7 +7,7 @@ def test_get_terminal_width(): def test_term_width_line(): - term_width_line('text') + term_width_line("text") def test_color_terminal(): @@ -15,6 +15,5 @@ def test_color_terminal(): def test_print_color(): - print(purple('\t%s' % "test")) - print(red('\t%s' % "test")) - + print(purple("\t%s" % "test")) + print(red("\t%s" % "test")) diff --git a/test/test_copybutton.py b/test/test_copybutton.py index 84bd0d3..71dea8b 100644 --- a/test/test_copybutton.py +++ b/test/test_copybutton.py @@ -2,13 +2,13 @@ def test_copybutton(): - copybutton.get_copybutton_path() + copybutton.get_copybutton_path() + def test_copy_javascript_into_static_path(): - copybutton.copy_javascript_into_static_path("_static", - copybutton.get_copybutton_path()) - copybutton.copy_javascript_into_static_path("_static", - copybutton.get_copybutton_path()) - import os + copybutton.copy_javascript_into_static_path("_static", copybutton.get_copybutton_path()) + copybutton.copy_javascript_into_static_path("_static", copybutton.get_copybutton_path()) + import os + os.remove("_static/copybutton.js") os.rmdir("_static") diff --git a/test/test_decorators.py b/test/test_decorators.py index dc16591..c978326 100644 --- a/test/test_decorators.py +++ b/test/test_decorators.py @@ -1,8 +1,7 @@ -from easydev.decorators import requires, ifpandas, ifpylab, _require +from easydev.decorators import _require, ifpandas, ifpylab, requires class A(object): - def __init__(self): pass @@ -14,10 +13,10 @@ def create(self): def print_str(self): print(self.a) - @requires(["a",'b'], "what to do") + @requires(["a", "b"], "what to do") def print_list(self): - print(self.a +self.b) - + print(self.a + self.b) + @_require("a", "what to do") def print_list(self): print(self.a) diff --git a/test/test_dependencies.py b/test/test_dependencies.py index e4d1cd6..c1ed8fe 100644 --- a/test/test_dependencies.py +++ b/test/test_dependencies.py @@ -1,7 +1,6 @@ from easydev.dependencies import get_dependencies - def test(): get_dependencies("easydev") get_dependencies("easydev_dummyi_dont_exists") diff --git a/test/test_doc.py b/test/test_doc.py index 51df3c6..7ad65ef 100644 --- a/test/test_doc.py +++ b/test/test_doc.py @@ -3,4 +3,3 @@ def test_underline(): a = doc.underline("test") - diff --git a/test/test_easytest.py b/test/test_easytest.py index 67e1ab4..acecb1a 100644 --- a/test/test_easytest.py +++ b/test/test_easytest.py @@ -1,5 +1,6 @@ from easydev.easytest import * + class A(object): pass @@ -23,20 +24,20 @@ def test_tempfile(): def test_list_almost_equal(): - assert_list_almost_equal([1,2], [1,2]) + assert_list_almost_equal([1, 2], [1, 2]) try: - assert_list_almost_equal([1,2], [1,3]) + assert_list_almost_equal([1, 2], [1, 3]) assert False except: assert True - - assert_list_almost_equal([1,1], [1, 0.9999], places=3) - assert_list_almost_equal([1,1], [1, 0.9999], deltas=1e-4) + assert_list_almost_equal([1, 1], [1, 0.9999], places=3) + assert_list_almost_equal([1, 1], [1, 0.9999], deltas=1e-4) try: - assert_list_almost_equal([1,1], [1, 0.9999], deltas=1e-5) + assert_list_almost_equal([1, 1], [1, 0.9999], deltas=1e-5) assert False except: assert True + test_list_almost_equal() diff --git a/test/test_logging_tools.py b/test/test_logging_tools.py index 66d531b..a73bc2b 100644 --- a/test/test_logging_tools.py +++ b/test/test_logging_tools.py @@ -11,12 +11,12 @@ def test_logging(): l.error("test") l.critical("test") - for level in ['DEBUG', 'INFO', 'ERROR', 'WARNING', 'CRITICAL']: + for level in ["DEBUG", "INFO", "ERROR", "WARNING", "CRITICAL"]: l.level = level assert l.level == level l.level = True l.level = False - for x in [10,20,30,40,50]: + for x in [10, 20, 30, 40, 50]: l.level = x try: @@ -27,5 +27,6 @@ def test_logging(): # FIXME is this working ??wierd syntax in loggibg_tools. import copy + copy.copy(l) copy.deepcopy(l) diff --git a/test/test_md5.py b/test/test_md5.py index 368b96d..f02943d 100644 --- a/test/test_md5.py +++ b/test/test_md5.py @@ -1,5 +1,5 @@ -from easydev.md5tools import md5 from easydev import TempFile +from easydev.md5tools import md5 def test_md5(): diff --git a/test/test_misc.py b/test/test_misc.py index 7d2a0a1..65c155e 100644 --- a/test/test_misc.py +++ b/test/test_misc.py @@ -1,23 +1,24 @@ -from easydev.misc import get_home, cmd_exists, in_ipynb -#from mock import patch -import subprocess import os.path +# from mock import patch +import subprocess + +from easydev.misc import cmd_exists, get_home, in_ipynb + def test_get_home(): get_home() - - #with patch.object(os.path, 'expanduser') as mymock: + # with patch.object(os.path, 'expanduser') as mymock: # mymock.side_effect = ImportError # get_home() def test_cmd_exists(): - assert cmd_exists('dummy_dummy') == False - assert cmd_exists('ls') == True + assert cmd_exists("dummy_dummy") == False + assert cmd_exists("ls") == True - #with patch.object(subprocess, 'call') as mymock: + # with patch.object(subprocess, 'call') as mymock: # mymock.side_effect = Exception # cmd_exists('ls') diff --git a/test/test_multicore.py b/test/test_multicore.py index 586cfa9..fa6ff1a 100644 --- a/test/test_multicore.py +++ b/test/test_multicore.py @@ -9,13 +9,15 @@ def func(n=400, *args, **kargs): """ print("inside func", args, kargs) import math - for i in range(0,n): - for j in range(0,n): - for k in range(0,n): + + for i in range(0, n): + for j in range(0, n): + for k in range(0, n): math.sqrt(float(i)) - d = {'id':n} + d = {"id": n} return d + def test_func(): t = MultiProcessing(verbose=True) t.add_job(func, 200) @@ -23,7 +25,3 @@ def test_func(): t.add_job(func, 50) t.run() print(t.results) - - - - diff --git a/test/test_options.py b/test/test_options.py index b808795..0260449 100644 --- a/test/test_options.py +++ b/test/test_options.py @@ -1,15 +1,16 @@ -from easydev import SmartFormatter import argparse +from easydev import SmartFormatter class Options(argparse.ArgumentParser): - def __init__(self, prog="test"): + def __init__(self, prog="test"): usage = """standalone test""" - description="""blabla""" - super(Options, self).__init__(usage=usage, prog=prog, - description=description, formatter_class=SmartFormatter) - self.add_argument("--config-params", dest="config_params", + description = """blabla""" + super(Options, self).__init__(usage=usage, prog=prog, description=description, formatter_class=SmartFormatter) + self.add_argument( + "--config-params", + dest="config_params", type=str, help="""FORMAT|Overwrite any field in the config file by using the following convention. A config file is in YAML format @@ -21,7 +22,8 @@ def __init__(self, prog="test"): bwa_mem_phix: mem: threads: 2 - """) + """, + ) def test(): diff --git a/test/test_paths.py b/test/test_paths.py index f0a8179..ef4b772 100644 --- a/test/test_paths.py +++ b/test/test_paths.py @@ -1,6 +1,7 @@ -from easydev.paths import * import os +from easydev.paths import * + def test_get_share_directory_path(): get_shared_directory_path("easydev") @@ -14,6 +15,7 @@ def test_get_share_directory_path(): def test_get_share_directories(): a = get_shared_directories("easydev", "themes") + def test_get_share_file(): f = get_share_file("easydev", os.sep.join(["themes", "standard"]), "theme.conf") diff --git a/test/test_platform.py b/test/test_platform.py index fc9d155..35ee9f4 100644 --- a/test/test_platform.py +++ b/test/test_platform.py @@ -1,12 +1,10 @@ import easydev -from easydev.platform import get_platform, is_windows -from easydev.platform import is_linux, is_mac +from easydev.platform import get_platform, is_linux, is_mac, is_windows def test_platform(mocker): - assert get_platform() in ['Linux', 'Windows', 'Mac'] - + assert get_platform() in ["Linux", "Windows", "Mac"] is_windows() is_linux() @@ -29,4 +27,3 @@ def test_platform(mocker): assert is_linux() is False assert is_windows() is False assert is_mac() is True - diff --git a/test/test_profiler.py b/test/test_profiler.py index 9d33963..0a5349e 100644 --- a/test/test_profiler.py +++ b/test/test_profiler.py @@ -1,8 +1,6 @@ from easydev import do_profile - - @do_profile() def test_profile(): @do_profile() diff --git a/test/test_progressbar.py b/test/test_progressbar.py index 93c59be..94d1bf8 100644 --- a/test/test_progressbar.py +++ b/test/test_progressbar.py @@ -1,21 +1,20 @@ - -from easydev import progressbar import time -from easydev import Progress + +from easydev import Progress, progressbar + def test_progressbar(): N = 2 p = progressbar.progress_bar(N) - for i in range(0,N): - time.sleep(.1) - p.animate(i+1, i) - + for i in range(0, N): + time.sleep(0.1) + p.animate(i + 1, i) p = progressbar.TextProgressBar(N, progressbar.consoleprint) - for i in range(0,N): - time.sleep(.1) - p.animate(i+1, i) + for i in range(0, N): + time.sleep(0.1) + p.animate(i + 1, i) p = Progress(100) p.animate(1) @@ -28,4 +27,3 @@ def test_progressbar(): # IPYthon test ? fails on travis # p = progressbar.IPythonNotebookPB(200) # p.animate(1) - diff --git a/test/test_timer.py b/test/test_timer.py index 0249032..fdeca7f 100644 --- a/test/test_timer.py +++ b/test/test_timer.py @@ -1,13 +1,14 @@ -from easydev.timer import Timer import time +from easydev.timer import Timer + def test_timer(): times = [] with Timer(times): - time.sleep(.1) + time.sleep(0.1) assert len(times) == 1 - assert sum(times) <1 + assert sum(times) < 1 tt = Timer(times) diff --git a/test/test_tools.py b/test/test_tools.py index 2869c73..7cfb37c 100644 --- a/test/test_tools.py +++ b/test/test_tools.py @@ -1,61 +1,59 @@ -import easydev -from easydev import tools as tools -from easydev import TempFile +from easydev import TempFile, tools def test_check_range(): - tools.check_range(1, 0,1) - tools.check_range(0, 0,1) - tools.check_range(0.5, 0,1) + tools.check_range(1, 0, 1) + tools.check_range(0, 0, 1) + tools.check_range(0.5, 0, 1) try: - tools.check_range(1, 0,1, strict=True) + tools.check_range(1, 0, 1, strict=True) assert False except: assert True try: - tools.check_range(0, 0,1, strict=True) + tools.check_range(0, 0, 1, strict=True) assert False except: assert True try: - tools.check_range(10, 0,1, strict=False) + tools.check_range(10, 0, 1, strict=False) assert False except: assert True try: - tools.check_range(-10, 0,1, strict=False) + tools.check_range(-10, 0, 1, strict=False) assert False except: assert True def test_swapdict(): - assert {1:'a'} == tools.swapdict({'a':1}) + assert {1: "a"} == tools.swapdict({"a": 1}) # if the are non-unique values, we can catch the error or no: try: - tools.swapdict({'a':1, 'b':1}) + tools.swapdict({"a": 1, "b": 1}) assert False except: assert True - tools.swapdict({'a':1, 'b':1}, check_ambiguity=False) + tools.swapdict({"a": 1, "b": 1}, check_ambiguity=False) def test_tools(): - tools.shellcmd('ls') - tools.shellcmd('ls', show=False) - tools.shellcmd('ls', show=True) - output = tools.shellcmd('ls', verbose=True) - tools.shellcmd('lssssssss', verbose=True, ignore_errors=True) + tools.shellcmd("ls") + tools.shellcmd("ls", show=False) + tools.shellcmd("ls", show=True) + output = tools.shellcmd("ls", verbose=True) + tools.shellcmd("lssssssss", verbose=True, ignore_errors=True) - tools.execute('ls') + tools.execute("ls") def test_tools2(): try: - tools.shellcmd('lsss', verbose=False) + tools.shellcmd("lsss", verbose=False) assert False except: assert True @@ -77,14 +75,14 @@ def test_checkParams(): def test_check_param_in_list(): - tools.check_param_in_list(1, [0,1,5], "test") + tools.check_param_in_list(1, [0, 1, 5], "test") try: - tools.check_param_in_list(10, [0,1,5]) + tools.check_param_in_list(10, [0, 1, 5]) assert False except: assert True try: - tools.check_param_in_list(10, [0,1,5], 'testt') + tools.check_param_in_list(10, [0, 1, 5], "testt") assert False except: assert True @@ -93,31 +91,30 @@ def test_check_param_in_list(): def test_precision(): assert tools.precision(2.123) == 2.12 assert tools.precision(2.123, 1) == 2.1 - assert tools.precision(2.123,3) == 2.123 - assert tools.precision(2123,-2) == 2100 + assert tools.precision(2.123, 3) == 2.123 + assert tools.precision(2123, -2) == 2100 def test_attrdict(): a = tools.AttrDict(value=1) assert a.value == 1 - assert 'value' in list(a.keys()) + assert "value" in list(a.keys()) assert 1 in (a.values()) - a.description = 'test' - assert a['description'] == 'test' + a.description = "test" + assert a["description"] == "test" - a['output'] = 'txt' - assert a.output == 'txt' + a["output"] = "txt" + assert a.output == "txt" - - d = {'a':{'b':1}, 'aa':2} + d = {"a": {"b": 1}, "aa": 2} ad = tools.AttrDict(**d) assert ad.a.b == 1 ad.a.b = 2 assert ad.a.b == 2 - ad['d'] = 4 + ad["d"] = 4 assert ad.d == 4 try: @@ -136,13 +133,15 @@ def test_attrdict(): def test_devtools(): d = tools.DevTools() - d.check_param_in_list(1, [1,2]) - d.check_range(1,0,2) - assert d.list2string(['a', 'b']) == 'a,b' - assert d.swapdict({'a':1}) == {1:'a'} - d.to_json({'a':1}) - assert d.to_list('a') == ['a'] - import tempfile, os + d.check_param_in_list(1, [1, 2]) + d.check_range(1, 0, 2) + assert d.list2string(["a", "b"]) == "a,b" + assert d.swapdict({"a": 1}) == {1: "a"} + d.to_json({"a": 1}) + assert d.to_list("a") == ["a"] + import os + import tempfile + d.mkdirs(tempfile.mkdtemp() + os.sep + "test") try: d.check_exists("ttttttttttt") @@ -153,7 +152,9 @@ def test_devtools(): def test_mkdirs(): - import tempfile, os + import os + import tempfile + tools.mkdirs(tempfile.mkdtemp() + os.sep + "test") try: tools.mkdirs(tempfile.mkdtemp() + os.sep + "test") @@ -169,9 +170,3 @@ def test_touch(): with TempFile() as fh: fh.name tools.touch(fh.name) - - - - - - diff --git a/test/test_url.py b/test/test_url.py index e04f8d6..3a719f2 100644 --- a/test/test_url.py +++ b/test/test_url.py @@ -1,11 +1,12 @@ from easydev import isurl_reachable -#from nose.plugins.attrib import attr + +# from nose.plugins.attrib import attr def test_isurl(): assert isurl_reachable("www.google.com") == True assert isurl_reachable("http://www.google.com") == True - #assert isurl_reachable("https://fr.yahoo.com") == False # moved + # assert isurl_reachable("https://fr.yahoo.com") == False # moved assert isurl_reachable("wrong.co.ujj") == False assert isurl_reachable("http://wrong.co.ujj") == False assert isurl_reachable("http://wrong.co") == False