From 6bf8384c351924c4495c0cca52a220d214136cb0 Mon Sep 17 00:00:00 2001 From: Matthias Urlichs Date: Sun, 3 Feb 2019 14:25:41 +0100 Subject: [PATCH] Kill of u"" (visual clutter) --- docs/conf.py | 16 +-- src/octoprint/environment.py | 2 +- src/octoprint/filemanager/__init__.py | 2 +- src/octoprint/filemanager/analysis.py | 2 +- src/octoprint/filemanager/storage.py | 46 +++--- src/octoprint/plugin/core.py | 92 ++++++------ .../plugins/action_command_prompt/__init__.py | 2 +- .../plugins/announcements/__init__.py | 50 +++---- src/octoprint/plugins/appkeys/__init__.py | 10 +- src/octoprint/plugins/backup/__init__.py | 132 +++++++++--------- src/octoprint/plugins/cura/__init__.py | 70 +++++----- src/octoprint/plugins/discovery/__init__.py | 10 +- .../plugins/pluginmanager/__init__.py | 30 ++-- .../plugins/printer_safety_check/__init__.py | 4 +- .../plugins/softwareupdate/__init__.py | 6 +- .../scripts/update-octoprint.py | 6 +- .../plugins/softwareupdate/updaters/pip.py | 12 +- src/octoprint/printer/standard.py | 8 +- src/octoprint/server/__init__.py | 8 +- src/octoprint/server/util/flask.py | 10 +- src/octoprint/server/util/webassets.py | 6 +- src/octoprint/server/views.py | 6 +- src/octoprint/settings.py | 2 +- src/octoprint/util/__init__.py | 40 +++--- src/octoprint/util/comm.py | 30 ++-- src/octoprint/util/commandline.py | 16 +-- src/octoprint/util/pip.py | 2 +- tests/access/users/test_usermanager.py | 2 +- tests/filemanager/test_filemanager.py | 8 +- tests/filemanager/test_localstorage.py | 36 ++--- tests/server/util/test_flask.py | 8 +- tests/server/util/test_tornado.py | 18 +-- tests/util/test_file_helpers.py | 6 +- 33 files changed, 349 insertions(+), 349 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index e317c2d66..9de6f2608 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -51,8 +51,8 @@ source_suffix = '.rst' master_doc = 'index' # General information about the project. -project = u'OctoPrint' -copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%d, Gina Häußge' % year_since +project = 'OctoPrint' +copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -209,8 +209,8 @@ htmlhelp_basename = 'OctoPrintdoc' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). #latex_documents = [ -# ('index', 'OctoPrint.tex', u'OctoPrint Documentation', -# u'Gina Häußge', 'manual'), +# ('index', 'OctoPrint.tex', 'OctoPrint Documentation', +# 'Gina Häußge', 'manual'), #] # The name of an image file (relative to this directory) to place at the top of @@ -239,8 +239,8 @@ htmlhelp_basename = 'OctoPrintdoc' # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'octoprint', u'OctoPrint Documentation', - [u'Gina Häußge'], 1) + ('index', 'octoprint', 'OctoPrint Documentation', + ['Gina Häußge'], 1) ] # If true, show URL addresses after external links. @@ -253,8 +253,8 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'OctoPrint', u'OctoPrint Documentation', - u'Gina Häußge', 'OctoPrint', 'One line description of project.', + ('index', 'OctoPrint', 'OctoPrint Documentation', + 'Gina Häußge', 'OctoPrint', 'One line description of project.', 'Miscellaneous'), ] diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 1704273c2..b46a7eb1a 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -148,7 +148,7 @@ class EnvironmentDetector(object): indent=4, allow_unicode=True).strip() environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n"))) - return u"Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"], + return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"], environment["os"]["id"].title(), environment["os"]["platform"], environment_lines) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 0f4527de9..56b8474ec 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -338,7 +338,7 @@ class FileManager(object): links = [("model", dict(name=source_path))] _, stl_name = self.split_path(source_location, source_path) file_obj = StreamWrapper(os.path.basename(dest_path), - io.BytesIO(u";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")), + io.BytesIO(";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")), io.FileIO(tmp_path, 'rb')) printer_profile = self._printer_profile_manager.get(printer_profile_id) diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index bfeac3eb0..cec2e77c7 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -382,7 +382,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): if not p.commands[0].process: # the process might have been set to None in case of any exception - raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command))) + raise RuntimeError("Error while trying to run command {}".format(" ".join(command))) try: # let's wait for stuff to finish diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 503f538c2..3cbaa66ef 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -450,11 +450,11 @@ class LocalFileStorage(StorageInterface): This storage type implements :func:`path_on_disk`. """ - _UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]", re.U) + _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U) @classmethod def _no_unicode_variations(cls, text): - return cls._UNICODE_VARIATIONS.sub(u"", text) + return cls._UNICODE_VARIATIONS.sub("", text) _SLUGIFY = Slugify() _SLUGIFY.safe_chars = "-_.()[] " @@ -463,7 +463,7 @@ class LocalFileStorage(StorageInterface): def _slugify(cls, text): text = to_unicode(text) text = cls._no_unicode_variations(text) - text = demojize(text, delimiters=(u"", u"")) + text = demojize(text, delimiters=("", "")) return cls._SLUGIFY(text) def __init__(self, basefolder, create=False): @@ -597,10 +597,10 @@ class LocalFileStorage(StorageInterface): path = self.sanitize_path(to_unicode(path)) base = self.path_in_storage(path) if base: - base += u"/" + base += "/" else: path = self.basefolder - base = u"" + base = "" return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive) def add_folder(self, path, ignore_existing=True, display=None): @@ -912,14 +912,14 @@ class LocalFileStorage(StorageInterface): def split_path(self, path): path = to_unicode(path) - split = path.split(u"/") + split = path.split("/") if len(split) == 1: - return u"", split[0] + return "", split[0] else: return self.join_path(*split[:-1]), split[-1] def join_path(self, *path): - return u"/".join(map(to_unicode, path)) + return "/".join(map(to_unicode, path)) def sanitize(self, path): """ @@ -948,17 +948,17 @@ class LocalFileStorage(StorageInterface): path = to_unicode(path) if path.startswith(self.basefolder): path = path[len(self.basefolder):] - path = path.replace(os.path.sep, u"/") - path = path.split(u"/") + path = path.replace(os.path.sep, "/") + path = path.split("/") if isinstance(path, (list, tuple)): if len(path) == 1: name = to_unicode(path[0]) - path = u"" + path = "" else: name = to_unicode(path[-1]) path = self.join_path(*map(to_unicode, path[:-1])) if not path: - path = u"" + path = "" return path, name @@ -973,11 +973,11 @@ class LocalFileStorage(StorageInterface): if name is None: return None - if u"/" in name or u"\\" in name: + if "/" in name or "\\" in name: raise ValueError("name must not contain / or \\") - result = self._slugify(name).replace(u" ", u"_") - if result and result != u"." and result != u".." and result[0] == u".": + result = self._slugify(name).replace(" ", "_") + if result and result != "." and result != ".." and result[0] == ".": # hidden files under *nix result = result[1:] return result @@ -991,12 +991,12 @@ class LocalFileStorage(StorageInterface): path = to_unicode(path) if len(path): - if path[0] == u"/": + if path[0] == "/": path = path[1:] - elif path[0] == u"." and path[1] == u"/": + elif path[0] == "." and path[1] == "/": path = path[2:] - path_elements = path.split(u"/") + path_elements = path.split("/") joined_path = self.basefolder for path_element in path_elements: joined_path = os.path.join(joined_path, self.sanitize_name(path_element)) @@ -1016,16 +1016,16 @@ class LocalFileStorage(StorageInterface): counter = 1 while os.path.exists(sanitized_path): counter += 1 - sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext)) + sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext)) sanitized_path = os.path.join(path, sanitized) try: shutil.move(entry_path, sanitized_path) - self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path)) + self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path)) return sanitized, sanitized_path except Exception: - self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path)) + self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path)) raise return entry, entry_path @@ -1037,8 +1037,8 @@ class LocalFileStorage(StorageInterface): path = to_unicode(path) if path.startswith(self.basefolder): path = path[len(self.basefolder):] - path = path.replace(os.path.sep, u"/") - if path.startswith(u"/"): + path = path.replace(os.path.sep, "/") + if path.startswith("/"): path = path[1:] return path diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 0502c1ab4..676803c25 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -210,13 +210,13 @@ class PluginInfo(object): def __str__(self): if self.version: - return u"{name} ({version})".format(name=self.name, version=self.version) + return "{name} ({version})".format(name=self.name, version=self.version) else: return to_unicode(self.name) - def long_str(self, show_bundled=False, bundled_strs=(u" [B]", u""), - show_location=False, location_str=u" - {location}", - show_enabled=False, enabled_strs=(u"* ", u" ", u"X ")): + def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""), + show_location=False, location_str=" - {location}", + show_enabled=False, enabled_strs=("* ", " ", "X ")): """ Long string representation of the plugin's information. Will return a string of the format ````. @@ -249,7 +249,7 @@ class PluginInfo(object): else (to_unicode(enabled_strs[0]) if self.enabled else to_unicode(enabled_strs[1])) else: - ret = u"" + ret = "" ret += unicode(self) @@ -658,7 +658,7 @@ class PluginManager(object): result_added.update(added) result_found += found except Exception: - self.logger.exception(u"Error fetching plugins from folders") + self.logger.exception("Error fetching plugins from folders") if self.plugin_entry_points: existing.update(result_added) @@ -669,7 +669,7 @@ class PluginManager(object): result_added.update(added) result_found += found except Exception: - self.logger.exception(u"Error fetching plugins from entry points") + self.logger.exception("Error fetching plugins from entry points") return result_added, result_found @@ -688,7 +688,7 @@ class PluginManager(object): actual_readonly = not os.access(folder, os.W_OK) if not os.path.exists(folder): - self.logger.warning(u"Plugin folder {folder} could not be found, skipping it".format(folder=folder)) + self.logger.warning("Plugin folder {folder} could not be found, skipping it".format(folder=folder)) continue for entry in scandir(folder): @@ -727,9 +727,9 @@ class PluginManager(object): plugin.enabled = False added[key] = plugin except Exception: - self.logger.exception(u"Error processing folder entry {!r} from folder {}".format(entry, folder)) + self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder)) except Exception: - self.logger.exception(u"Error processing folder {}".format(folder)) + self.logger.exception("Error processing folder {}".format(folder)) return added, found @@ -759,8 +759,8 @@ class PluginManager(object): try: yield entry except Exception: - self.logger.exception(u"Something went wrong while processing the entry points of a package in the " - u"Python environment - broken entry_points.txt in some package?") + self.logger.exception("Something went wrong while processing the entry points of a package in the " + "Python environment - broken entry_points.txt in some package?") for group in groups: for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)): @@ -779,7 +779,7 @@ class PluginManager(object): try: entry_point_metadata = EntryPointMetadata(entry_point) except Exception: - self.logger.exception(u"Something went wrong while retrieving metadata for module {}".format(module_name)) + self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name)) else: kwargs.update(dict( name=entry_point_metadata.name, @@ -809,7 +809,7 @@ class PluginManager(object): added[key] = plugin except Exception: - self.logger.exception(u"Error processing entry point {!r} for group {}".format(entry_point, group)) + self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group)) return added, found @@ -824,7 +824,7 @@ class PluginManager(object): else: return None except Exception: - self.logger.warn(u"Could not locate plugin {key}".format(key=key)) + self.logger.warn("Could not locate plugin {key}".format(key=key)) return None # Create a simple dummy entry first ... @@ -833,11 +833,11 @@ class PluginManager(object): plugin.bundled = bundled if self._is_plugin_disabled(key): - self.logger.info(u"Plugin {} is disabled.".format(plugin)) + self.logger.info("Plugin {} is disabled.".format(plugin)) plugin.forced_disabled = True if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)): - self.logger.warning(u"Plugin {} is blacklisted.".format(plugin)) + self.logger.warning("Plugin {} is blacklisted.".format(plugin)) plugin.blacklisted = True if not plugin.validate("before_import", additional_validators=self.plugin_validators): @@ -864,13 +864,13 @@ class PluginManager(object): parsed_metadata=parsed_metadata) plugin.bundled = bundled except Exception: - self.logger.exception(u"Error loading plugin {key}".format(key=key)) + self.logger.exception("Error loading plugin {key}".format(key=key)) return None if plugin.check(): return plugin else: - self.logger.info(u"Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) + self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) return None def _is_plugin_disabled(self, key): @@ -890,7 +890,7 @@ class PluginManager(object): self.plugin_blacklist)) def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None): - self.logger.info(u"Loading plugins from {folders} and installed plugin packages...".format( + self.logger.info("Loading plugins from {folders} and installed plugin packages...".format( folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders)) )) @@ -934,7 +934,7 @@ class PluginManager(object): try: if plugin.loaded and not plugin.forced_disabled: if plugin.blacklisted: - self.logger.warning(u"Plugin {} is blacklisted. Not enabling it.".format(plugin)) + self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin)) continue self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup) except PluginNeedsRestart: @@ -947,9 +947,9 @@ class PluginManager(object): force_reload=force_reload) if len(self.enabled_plugins) <= 0: - self.logger.info(u"No plugins found") + self.logger.info("No plugins found") else: - self.logger.info(u"Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( + self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( count=len(self.enabled_plugins) + len(self.disabled_plugins), implementations=len(self.plugin_implementations), hooks=sum(map(lambda x: len(x), self.plugin_hooks.values())) @@ -957,7 +957,7 @@ class PluginManager(object): def mark_plugin(self, name, **kwargs): if not name in self.plugins: - self.logger.debug(u"Trying to mark an unknown plugin {name}".format(**locals())) + self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals())) for key, value in kwargs.items(): if value is None: @@ -976,7 +976,7 @@ class PluginManager(object): def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True): if not name in self.plugins: - self.logger.warning(u"Trying to load an unknown plugin {name}".format(**locals())) + self.logger.warning("Trying to load an unknown plugin {name}".format(**locals())) return if plugin is None: @@ -991,15 +991,15 @@ class PluginManager(object): self.on_plugin_loaded(name, plugin) plugin.loaded = True - self.logger.debug(u"Loaded plugin {name}: {plugin}".format(**locals())) + self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e except Exception: - self.logger.exception(u"There was an error loading plugin %s" % name) + self.logger.exception("There was an error loading plugin %s" % name) def unload_plugin(self, name): if not name in self.plugins: - self.logger.warning(u"Trying to unload unknown plugin {name}".format(**locals())) + self.logger.warning("Trying to unload unknown plugin {name}".format(**locals())) return plugin = self.plugins[name] @@ -1019,11 +1019,11 @@ class PluginManager(object): plugin.loaded = False - self.logger.debug(u"Unloaded plugin {name}: {plugin}".format(**locals())) + self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e except Exception: - self.logger.exception(u"There was an error unloading plugin {name}".format(**locals())) + self.logger.exception("There was an error unloading plugin {name}".format(**locals())) # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins if name in self.enabled_plugins: @@ -1033,7 +1033,7 @@ class PluginManager(object): def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False): if not name in self.disabled_plugins: - self.logger.warning(u"Tried to enable plugin {name}, however it is not disabled".format(**locals())) + self.logger.warning("Tried to enable plugin {name}, however it is not disabled".format(**locals())) return if plugin is None: @@ -1069,13 +1069,13 @@ class PluginManager(object): plugin.implementation.on_plugin_enabled() self.on_plugin_enabled(name, plugin) - self.logger.debug(u"Enabled plugin {name}: {plugin}".format(**locals())) + self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals())) return True def disable_plugin(self, name, plugin=None): if not name in self.enabled_plugins: - self.logger.warning(u"Tried to disable plugin {name}, however it is not enabled".format(**locals())) + self.logger.warning("Tried to disable plugin {name}, however it is not enabled".format(**locals())) return if plugin is None: @@ -1090,7 +1090,7 @@ class PluginManager(object): except PluginLifecycleException as e: raise e except Exception: - self.logger.exception(u"There was an error while disabling plugin {name}".format(**locals())) + self.logger.exception("There was an error while disabling plugin {name}".format(**locals())) return False else: if name in self.enabled_plugins: @@ -1102,7 +1102,7 @@ class PluginManager(object): plugin.implementation.on_plugin_disabled() self.on_plugin_disabled(name, plugin) - self.logger.debug(u"Disabled plugin {name}: {plugin}".format(**locals())) + self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals())) return True @@ -1114,7 +1114,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warning(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue self._plugin_hooks[hook].append((order, name, callback)) @@ -1133,7 +1133,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warning(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue try: @@ -1280,7 +1280,7 @@ class PluginManager(object): additional_pre_inits=additional_pre_inits, additional_post_inits=additional_post_inits) - self.logger.info(u"Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations))) + self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations))) def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): if plugin.implementation is None: @@ -1335,7 +1335,7 @@ class PluginManager(object): try: return_value = factory(name, implementation) except Exception: - self.logger.exception(u"Exception while executing injection factory %r" % factory) + self.logger.exception("Exception while executing injection factory %r" % factory) else: if return_value is not None: if isinstance(return_value, dict): @@ -1359,12 +1359,12 @@ class PluginManager(object): if isinstance(e, PluginLifecycleException): raise e else: - self.logger.exception(u"Exception while initializing plugin {name}, disabling it".format(**locals())) + self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals())) return False else: self.on_plugin_implementations_initialized(name, plugin) - self.logger.debug(u"Initialized plugin mixin implementation for plugin {name}".format(**locals())) + self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals())) return True @@ -1381,7 +1381,7 @@ class PluginManager(object): self.logger.log(level, message) if len(all_plugins) <= 0: - _log(u"No plugins available") + _log("No plugins available") else: formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled, bundled_strs=bundled_str, @@ -1390,7 +1390,7 @@ class PluginManager(object): show_enabled=show_enabled, enabled_strs=enabled_str), sorted(self.plugins.values(), key=lambda x: unicode(x).lower()))) - _log(u"{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), + _log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), plugins=formatted_plugins)) def get_plugin(self, identifier, require_enabled=True): @@ -1483,13 +1483,13 @@ class PluginManager(object): try: sorting_value = impl[1].get_sorting_key(sorting_context) except Exception: - self.logger.exception(u"Error while trying to retrieve sorting order for plugin {}".format(impl[0])) + self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0])) if sorting_value is not None: try: sorting_value = int(sorting_value) except ValueError: - self.logger.warning(u"The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) + self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) sorting_value = None plugin_info = self.get_plugin_info(impl[0], require_enabled=False) @@ -1576,7 +1576,7 @@ class PluginManager(object): try: client(plugin, data, permissions=permissions) except Exception: - self.logger.exception(u"Exception while sending plugin data to client") + self.logger.exception("Exception while sending plugin data to client") def _sort_hooks(self, hook): self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook], diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index d5356f631..bb9d6c0f6 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -185,7 +185,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, return # noinspection PyProtectedMember - return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode) + return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode) #~ capability reporting diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 1292eaf45..9eaf8d479 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -360,7 +360,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, now = time.time() if os.stat(channel_path).st_mtime + ttl > now: d = feedparser.parse(channel_path) - self._logger.debug(u"Loaded channel {} from cache at {}".format(key, channel_path)) + self._logger.debug("Loaded channel {} from cache at {}".format(key, channel_path)) return d return None @@ -375,10 +375,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, start = time.time() r = requests.get(url, timeout=30) r.raise_for_status() - self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start)) + self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start)) except Exception as e: self._logger.exception( - u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e))) + "Could not fetch channel {} from {}: {}".format(key, config["url"], str(e))) return None response = r.text @@ -434,22 +434,22 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, _image_tag_re = re.compile(r'') def _strip_images(text): """ - >>> _strip_images(u"I'm a link and this is an image: foo") - u"I'm a link and this is an image: " - >>> _strip_images(u"One and two and three and four \\"four\\"") - u'One and two and three and four ' - >>> _strip_images(u"No images here") - u'No images here' + >>> _strip_images("I'm a link and this is an image: foo") + "I'm a link and this is an image: " + >>> _strip_images("One and two and three and four \\"four\\"") + 'One and two and three and four ' + >>> _strip_images("No images here") + 'No images here' """ return _image_tag_re.sub('', text) def _replace_images(text, callback): """ >>> callback = lambda img: "foobar" - >>> _replace_images(u"I'm a link and this is an image: foo", callback) - u"I'm a link and this is an image: foobar" - >>> _replace_images(u"One and two and three and four \\"four\\"", callback) - u'One foobar and two foobar and three foobar and four foobar' + >>> _replace_images("I'm a link and this is an image: foo", callback) + "I'm a link and this is an image: foobar" + >>> _replace_images("One and two and three and four \\"four\\"", callback) + 'One foobar and two foobar and three foobar and four foobar' """ result = text for match in _image_tag_re.finditer(text): @@ -461,14 +461,14 @@ def _replace_images(text, callback): _image_src_re = re.compile(r'src=(?P[\'"]*)(?P.*?)(?P=quote)(?=\s+|>)') def _lazy_images(text, placeholder=None): """ - >>> _lazy_images(u"I'm a link and this is an image: foo") - u'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images(u"I'm a link and this is an image: foo", placeholder="ph.png") - u'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images(u"One and two and three and four \\"four\\"", placeholder="ph.png") - u'One and two and three and four four' - >>> _lazy_images(u"No images here") - u'No images here' + >>> _lazy_images("I'm a link and this is an image: foo") + 'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images("I'm a link and this is an image: foo", placeholder="ph.png") + 'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png") + 'One and two and three and four four' + >>> _lazy_images("No images here") + 'No images here' """ if placeholder is None: # 1px transparent gif @@ -487,10 +487,10 @@ def _lazy_images(text, placeholder=None): def _strip_tags(text): """ - >>> _strip_tags(u"Hello world<img src='foo.jpg'>") - u"Hello world<img src='foo.jpg'>" - >>> _strip_tags(u"> > Foo") - u'> > Foo' + >>> _strip_tags("Hello world<img src='foo.jpg'>") + "Hello world<img src='foo.jpg'>" + >>> _strip_tags("> > Foo") + '> > Foo' """ try: # noinspection PyCompatibility diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index af41e312d..6b1158c6a 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -410,11 +410,11 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, except Exception: self._logger.exception("Could not write application keys to {}".format(self._key_path)) -__plugin_name__ = u"Application Keys Plugin" -__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys" -__plugin_author__ = u"Gina Häußge, Aldo Hoeben" -__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to " - u"obtain an API key without you manually copy-pasting it.") +__plugin_name__ = "Application Keys Plugin" +__plugin_description__ = "Implements a workflow for third party clients to obtain API keys" +__plugin_author__ = "Gina Häußge, Aldo Hoeben" +__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to " + "obtain an API key without you manually copy-pasting it.") __plugin_implementation__ = AppKeysPlugin() __plugin_hooks__ = { "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 27775c212..98209857f 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -91,7 +91,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, ##~~ TemplatePlugin def get_template_configs(self): - return [dict(type="settings", name=gettext(u"Backup & Restore"))] + return [dict(type="settings", name=gettext("Backup & Restore"))] ##~~ BlueprintPlugin @@ -142,8 +142,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, exclude = data.get("exclude", []) def on_backup_start(name, temporary_path, exclude): - self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path, - u",".join(exclude) if len(exclude) else "-")) + self._logger.info("Creating backup zip at {} (excluded: {})...".format(temporary_path, + ",".join(exclude) if len(exclude) else "-")) with self._in_progress_lock: self._in_progress.append(name) @@ -154,7 +154,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, self._in_progress.remove(name) self._send_client_message("backup_done", payload=dict(name=name)) - self._logger.info(u"... done creating backup zip.") + self._logger.info("... done creating backup zip.") def on_backup_error(name, exc_info): with self._in_progress_lock: @@ -165,8 +165,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, pass self._send_client_message("backup_error", payload=dict(name=name, - error=u"{}".format(exc_info[1]))) - self._logger.error(u"Error while creating backup zip", exc_info=exc_info) + error="{}".format(exc_info[1]))) + self._logger.error("Error while creating backup zip", exc_info=exc_info) thread = threading.Thread(target=self._create_backup, args=(backup_file,), @@ -197,7 +197,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, try: os.remove(full_path) except Exception: - self._logger.exception(u"Could not delete {}".format(filename)) + self._logger.exception("Could not delete {}".format(filename)) raise return NO_CONTENT @@ -206,7 +206,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, @Permissions.PLUGIN_BACKUP_ACCESS.require(403) def perform_restore(self): if not is_os_compatible(["!windows"]): - return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400) + return flask.make_response("Invalid request, the restores are not supported on the underlying operating system", 400) input_name = "file" input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) @@ -225,7 +225,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, return flask.abort(404) else: - return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400) + return flask.make_response("Invalid request, neither a file nor a path of a file to restore provided", 400) def on_install_plugins(plugins): force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) @@ -241,20 +241,20 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, compatible = octoprint_compatible and os_compatible if not compatible: if not octoprint_compatible and not os_compatible: - self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version " - u"of OctoPrint and the underlying operating system".format(plugin["id"])) + self._logger.warn("Cannot install plugin {}, it is incompatible to this version " + "of OctoPrint and the underlying operating system".format(plugin["id"])) elif not octoprint_compatible: - self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version " - u"of OctoPrint".format(plugin["id"])) + self._logger.warn("Cannot install plugin {}, it is incompatible to this version " + "of OctoPrint".format(plugin["id"])) elif not os_compatible: - self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying " - u"operating system".format(plugin["id"])) + self._logger.warn("Cannot install plugin {}, it is incompatible to the underlying " + "operating system".format(plugin["id"])) self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"], octoprint_compatible=octoprint_compatible, os_compatible=os_compatible)) continue - self._logger.info(u"Installing plugin {}".format(plugin["id"])) + self._logger.info("Installing plugin {}".format(plugin["id"])) self._send_client_message("installing_plugin", dict(plugin=plugin["id"])) self.__class__._install_plugin(plugin, force_user=force_user, @@ -393,7 +393,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, path = os.path.join(datafolder, path) if not os.path.exists(path): - click.echo(u"Backup {} does not exist".format(path), err=True) + click.echo("Backup {} does not exist".format(path), err=True) sys.exit(-1) archive = tempfile.NamedTemporaryFile(delete=False) @@ -409,7 +409,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) def log(line): - click.echo(u"\t{}".format(line)) + click.echo("\t{}".format(line)) for plugin in plugins: octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"]) @@ -417,17 +417,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, compatible = octoprint_compatible and os_compatible if not compatible: if not octoprint_compatible and not os_compatible: - click.echo(u"Cannot install plugin {}, it is incompatible to this version of " - u"OctoPrint and the underlying operating system".format(plugin["id"])) + click.echo("Cannot install plugin {}, it is incompatible to this version of " + "OctoPrint and the underlying operating system".format(plugin["id"])) elif not octoprint_compatible: - click.echo(u"Cannot install plugin {}, it is incompatible to this version of " - u"OctoPrint".format(plugin["id"])) + click.echo("Cannot install plugin {}, it is incompatible to this version of " + "OctoPrint".format(plugin["id"])) elif not os_compatible: - click.echo(u"Cannot install plugin {}, it is incompatible to the underlying " - u"operating system".format(plugin["id"])) + click.echo("Cannot install plugin {}, it is incompatible to the underlying " + "operating system".format(plugin["id"])) continue - click.echo(u"Installing plugin {}".format(plugin["id"])) + click.echo("Installing plugin {}".format(plugin["id"])) self.__class__._install_plugin(plugin, force_user=force_user, pip_args=pip_args, @@ -437,9 +437,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if not plugins: return - click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.") + click.echo("The following plugins were not found in the plugin repository. You'll need to install them manually.") for plugin in plugins: - click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?")) + click.echo("\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?")) def on_log_progress(line): click.echo(line) @@ -462,9 +462,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, on_log_progress=on_log_progress, on_log_error=on_log_error, on_invalid_backup=on_log_error): - click.echo(u"Restored from {}".format(path)) + click.echo("Restored from {}".format(path)) else: - click.echo(u"Restoring from {} failed".format(path), err=True) + click.echo("Restoring from {} failed".format(path), err=True) return [backup_command, restore_command] @@ -503,15 +503,15 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, try: os.remove(data_file) except Exception: - self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file)) + self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file)) return unknown_plugins except Exception: - self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file)) + self._logger.exception("Error while reading list of unknown plugins from {}".format(data_file)) try: os.remove(data_file) except Exception: - self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file)) + self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file)) return [] @@ -523,10 +523,10 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if os.path.exists(basedir_backup): def remove_bck(): if callable(on_log_progress): - on_log_progress(u"Found config folder backup from prior restore, deleting it...") + on_log_progress("Found config folder backup from prior restore, deleting it...") shutil.rmtree(basedir_backup) if callable(on_log_progress): - on_log_progress(u"... deleted.") + on_log_progress("... deleted.") thread = threading.Thread(target=remove_bck) thread.daemon = True @@ -562,7 +562,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, r = requests.get(url, timeout=30) r.raise_for_status() except Exception: - logger.exception(u"Error while fetching the plugin repository data from {}".format(url)) + logger.exception("Error while fetching the plugin repository data from {}".format(url)) return dict() from octoprint.plugins.pluginmanager import map_repository_entry @@ -579,16 +579,16 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, # prepare pip caller def log(prefix, *lines): for line in lines: - on_log(u"{} {}".format(prefix, line.rstrip())) + on_log("{} {}".format(prefix, line.rstrip())) def log_call(*lines): - log(u">", *lines) + log(">", *lines) def log_stdout(*lines): - log(u"<", *lines) + log("<", *lines) def log_stderr(*lines): - log(u"!", *lines) + log("!", *lines) if cls._pip_caller is None: cls._pip_caller = LocalPipCaller(force_user=force_user) @@ -731,7 +731,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, on_restore_failed=None): if not is_os_compatible(["!windows"]): if callable(on_log_error): - on_log_error(u"Restore is not supported on this operating system") + on_log_error("Restore is not supported on this operating system") if callable(on_restore_failed): on_restore_failed(path) return False @@ -758,7 +758,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, metadata_zipinfo = zip.getinfo("metadata.json") except KeyError: if callable(on_invalid_backup): - on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json") + on_invalid_backup("Not an OctoPrint backup, lacks metadata.json") if callable(on_restore_failed): on_restore_failed(path) return False @@ -769,7 +769,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, backup_version = get_comparable_version(metadata["version"], base=True) if backup_version > get_octoprint_version(base=True): if callable(on_invalid_backup): - on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied") + on_invalid_backup("Backup is from a newer version of OctoPrint and cannot be applied") if callable(on_restore_failed): on_restore_failed(path) return False @@ -778,7 +778,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, temp = tempfile.mkdtemp() try: if callable(on_log_progress): - on_log_progress(u"Unpacking backup to {}...".format(temp)) + on_log_progress("Unpacking backup to {}...".format(temp)) abstemp = os.path.abspath(temp) for member in zip.infolist(): abspath = os.path.abspath(os.path.join(temp, member.filename)) @@ -789,7 +789,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, configfile = os.path.join(temp, "basedir", "config.yaml") if not os.path.exists(configfile): if callable(on_invalid_backup): - on_invalid_backup(u"Backup lacks config.yaml") + on_invalid_backup("Backup lacks config.yaml") if callable(on_restore_failed): on_restore_failed(path) return False @@ -803,13 +803,13 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, userfile = os.path.join(temp, "basedir", "users.yaml") if not os.path.exists(userfile): if callable(on_invalid_backup): - on_invalid_backup(u"Backup lacks users.yaml") + on_invalid_backup("Backup lacks users.yaml") if callable(on_restore_failed): on_restore_failed(path) return False if callable(on_log_progress): - on_log_progress(u"Unpacked") + on_log_progress("Unpacked") # install available plugins with codecs.open(os.path.join(temp, "plugin_list.json"), 'rt') as f: @@ -837,9 +837,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if callable(on_log_progress): if known_plugins: - on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins)))) + on_log_progress("Known and installable plugins: {}".format(", ".join(map(lambda x: x["id"], known_plugins)))) if unknown_plugins: - on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins)))) + on_log_progress("Unknown plugins: {}".format(", ".join(map(lambda x: x["key"], unknown_plugins)))) if callable(on_install_plugins): on_install_plugins(known_plugins) @@ -852,17 +852,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, basedir_extracted = os.path.join(temp, "basedir") if callable(on_log_progress): - on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup)) + on_log_progress("Renaming {} to {}...".format(basedir, basedir_backup)) shutil.move(basedir, basedir_backup) try: if callable(on_log_progress): - on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir)) + on_log_progress("Moving {} to {}...".format(basedir_extracted, basedir)) shutil.move(basedir_extracted, basedir) except Exception: if callable(on_log_error): - on_log_error(u"Error while restoring config data", exc_info=sys.exc_info()) - on_log_error(u"Rolling back old config data") + on_log_error("Error while restoring config data", exc_info=sys.exc_info()) + on_log_error("Rolling back old config data") shutil.move(basedir_backup, basedir) @@ -872,7 +872,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if unknown_plugins: if callable(on_log_progress): - on_log_progress(u"Writing info file about unknown plugins") + on_log_progress("Writing info file about unknown plugins") if not os.path.isdir(datafolder): os.makedirs(datafolder) @@ -883,19 +883,19 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, json.dump(unknown_plugins, f) except Exception: if callable(on_log_error): - on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path), + on_log_error("Could not persist list of unknown plugins to {}".format(unknown_plugins_path), exc_info = sys.exc_info()) finally: if callable(on_log_progress): - on_log_progress(u"Removing temporary unpacked folder") + on_log_progress("Removing temporary unpacked folder") shutil.rmtree(temp) except Exception: exc_info = sys.exc_info() try: if callable(on_log_error): - on_log_error(u"Error while running restore", exc_info=exc_info) + on_log_error("Error while running restore", exc_info=exc_info) if callable(on_restore_failed): on_restore_failed(path) finally: @@ -905,7 +905,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, finally: # remove zip if callable(on_log_progress): - on_log_progress(u"Removing temporary zip") + on_log_progress("Removing temporary zip") os.remove(path) # restart server @@ -913,7 +913,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, import sarge if callable(on_log_progress): - on_log_progress(u"Restarting...") + on_log_progress("Restarting...") if callable(on_restore_done): on_restore_done(path) @@ -921,9 +921,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, sarge.run(restart_command, async_=True) except Exception: if callable(on_log_error): - on_log_error(u"Error while restarting via command {}".format(restart_command), + on_log_error("Error while restarting via command {}".format(restart_command), exc_info=sys.exc_info()) - on_log_error(u"Please restart OctoPrint manually") + on_log_error("Please restart OctoPrint manually") return False else: @@ -944,12 +944,12 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, class InsufficientSpace(Exception): pass -__plugin_name__ = u"Backup & Restore" -__plugin_author__ = u"Gina Häußge" -__plugin_description__ = u"Backup & restore your OctoPrint settings and data" -__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup " - u"& restore your OctoPrint settings and data.") -__plugin_license__ = u"AGPLv3" +__plugin_name__ = "Backup & Restore" +__plugin_author__ = "Gina Häußge" +__plugin_description__ = "Backup & restore your OctoPrint settings and data" +__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to backup " + "& restore your OctoPrint settings and data.") +__plugin_license__ = "AGPLv3" __plugin_implementation__ = BackupPlugin() __plugin_hooks__ = { "octoprint.server.http.routes": __plugin_implementation__.route_hook, diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index bfb0b0e5c..cd171d7c4 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -84,8 +84,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, engine = self._settings.get(["cura_engine"]) if not self._is_engine_configured(cura_engine=engine): - self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), " - u"Cura will not be selectable for slicing" % engine) + self._logger.info("Path to CuraEngine has not been configured or does not exist (currently set to %r), " + "Cura will not be selectable for slicing" % engine) ##~~ BlueprintPlugin API @@ -102,23 +102,23 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, try: profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path]) except Exception as e: - self._logger.exception(u"Error while converting the imported profile") - return flask.make_response(u"Something went wrong while converting imported profile: {message}".format(message=str(e)), 500) + self._logger.exception("Error while converting the imported profile") + return flask.make_response("Something went wrong while converting imported profile: {message}".format(message=str(e)), 500) else: - self._logger.warning(u"No profile file included for importing, aborting") - return flask.make_response(u"No file included", 400) + self._logger.warning("No profile file included for importing, aborting") + return flask.make_response("No file included", 400) if profile_dict is None: - self._logger.warning(u"Could not convert profile, aborting") - return flask.make_response(u"Could not convert Cura profile", 400) + self._logger.warning("Could not convert profile, aborting") + return flask.make_response("Could not convert Cura profile", 400) name, _ = os.path.splitext(filename) # default values for name, display name and description profile_name = _sanitize_name(name) profile_display_name = name - profile_description = u"Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now())) + profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now())) profile_allow_overwrite = False profile_make_default = False @@ -143,15 +143,15 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, display_name=profile_display_name, description=profile_description) except octoprint.slicing.ProfileAlreadyExists: - self._logger.warning(u"Profile {profile_name} already exists, aborting".format(**locals())) - return flask.make_response(u"A profile named {profile_name} already exists for slicer cura".format(**locals()), 409) + self._logger.warning("Profile {profile_name} already exists, aborting".format(**locals())) + return flask.make_response("A profile named {profile_name} already exists for slicer cura".format(**locals()), 409) if profile_make_default: try: self._slicing_manager.set_default_profile("cura", profile_name) except octoprint.slicing.UnknownProfile: - self._logger.warning(u"Profile {profile_name} could not be set as default, aborting".format(**locals())) - return flask.make_response(u"The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500) + self._logger.warning("Profile {profile_name} could not be set as default, aborting".format(**locals())) + return flask.make_response("The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500) result = dict( resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True), @@ -184,8 +184,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, new_debug_logging = self._settings.get_boolean(["debug_logging"]) if old_engine != new_engine and not self._is_engine_configured(new_engine): - self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), " - u"Cura will not be selectable for slicing" % new_engine) + self._logger.info("Path to CuraEngine has not been configured or does not exist (currently set to %r), " + "Cura will not be selectable for slicing" % new_engine) if old_debug_logging != new_debug_logging: if new_debug_logging: @@ -270,14 +270,14 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, if not on_progress_kwargs: on_progress_kwargs = dict() - self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}" + self._cura_logger.info("### Slicing {} to {} using profile stored at {}" .format(to_unicode(model_path, errors="replace"), to_unicode(machinecode_path, errors="replace"), to_unicode(profile_path, errors="replace"))) executable = normalize_path(self._settings.get(["cura_engine"])) if not executable: - return False, u"Path to CuraEngine is not configured " + return False, "Path to CuraEngine is not configured " working_dir = os.path.dirname(executable) @@ -308,7 +308,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, args += ["-s", "%s=%s" % (k, str(v))] args += ["-o", machinecode_path, model_path] - self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"), + self._logger.info("Running {!r} in {}".format(" ".join(map(lambda x: to_unicode(x, errors="replace"), args)), working_dir)) @@ -360,14 +360,14 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, # # with being 0 for "inset", 1 for "skin" and 2 for "export". - if line.startswith(u"Layer count:") and layer_count is None: + if line.startswith("Layer count:") and layer_count is None: try: - layer_count = float(line[len(u"Layer count:"):].strip()) + layer_count = float(line[len("Layer count:"):].strip()) except Exception: pass - elif line.startswith(u"Progress:"): - split_line = line[len(u"Progress:"):].strip().split(":") + elif line.startswith("Progress:"): + split_line = line[len("Progress:"):].strip().split(":") if len(split_line) == 3: step, current_layer, _ = split_line try: @@ -380,9 +380,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3) on_progress(*on_progress_args, **on_progress_kwargs) - elif line.startswith(u"Print time:"): + elif line.startswith("Print time:"): try: - print_time = int(line[len(u"Print time:"):].strip()) + print_time = int(line[len("Print time:"):].strip()) if analysis is None: analysis = dict() analysis["estimatedPrintTime"] = print_time @@ -391,12 +391,12 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, # Get the filament usage - elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"): - if line.startswith(u"Filament:"): - filament_str = line[len(u"Filament:"):].strip() + elif line.startswith("Filament:") or line.startswith("Filament2:"): + if line.startswith("Filament:"): + filament_str = line[len("Filament:"):].strip() tool_key = "tool0" else: - filament_str = line[len(u"Filament2:"):].strip() + filament_str = line[len("Filament2:"):].strip() tool_key = "tool1" try: @@ -422,20 +422,20 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, with self._job_mutex: if machinecode_path in self._cancelled_jobs: - self._cura_logger.info(u"### Cancelled") + self._cura_logger.info("### Cancelled") raise octoprint.slicing.SlicingCancelled() - self._cura_logger.info(u"### Finished, returncode %d" % p.returncode) + self._cura_logger.info("### Finished, returncode %d" % p.returncode) if p.returncode == 0: return True, dict(analysis=analysis) else: - self._logger.warning(u"Could not slice via Cura, got return code %r" % p.returncode) + self._logger.warning("Could not slice via Cura, got return code %r" % p.returncode) return False, "Got returncode %r" % p.returncode except octoprint.slicing.SlicingCancelled as e: raise e except Exception: - self._logger.exception(u"Could not slice via Cura, got an unknown error") + self._logger.exception("Could not slice via Cura, got an unknown error") return False, "Unknown error, please consult the log file" finally: @@ -454,7 +454,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, command = self._slicing_commands[machinecode_path] if command is not None: command.terminate() - self._logger.info(u"Cancelled slicing of {}" + self._logger.info("Cancelled slicing of {}" .format(to_unicode(machinecode_path, errors="replace"))) def _load_profile(self, path): @@ -464,7 +464,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, try: profile_dict = yaml.safe_load(f) except Exception: - raise IOError(u"Couldn't read profile from {path}".format(path=path)) + raise IOError("Couldn't read profile from {path}".format(path=path)) if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)): profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"]) @@ -486,7 +486,7 @@ def _sanitize_name(name): return None if "/" in name or "\\" in name: - raise ValueError(u"name must not contain / or \\") + raise ValueError("name must not contain / or \\") import string valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits) diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index ba5237789..e1a45eb6b 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -199,13 +199,13 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, while True: try: self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) - self._logger.info(u"Registered '{name}' for {regtype}".format(**params)) + self._logger.info("Registered '{name}' for {regtype}".format(**params)) return True except pybonjour.BonjourError as be: if be.errorCode == pybonjour.kDNSServiceErr_NameConflict: # Name already registered by different service, let's try a counter postfix. See #2852 counter += 1 - params["name"] = u"{} ({})".format(name, counter) + params["name"] = "{} ({})".format(name, counter) else: raise @@ -653,7 +653,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0')) - self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name())) + self._logger.info("Registered {} for SSDP".format(self.get_instance_name())) self._ssdp_notify(alive=True) @@ -694,10 +694,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, def get_instance_name(self): name = self._settings.global_get(["appearance", "name"]) if name: - return u"OctoPrint instance \"{}\"".format(name) + return "OctoPrint instance \"{}\"".format(name) else: import socket - return u"OctoPrint instance on {}".format(socket.gethostname()) + return "OctoPrint instance on {}".format(socket.gethostname()) __plugin_name__ = "Discovery" diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 50481b42f..b348a0b58 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -538,7 +538,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return make_response("Bundled plugins cannot be uninstalled", 403) if plugin.origin is None: - self._logger.warning(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals())) + self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown".format(**locals())) return make_response("Could not uninstall plugin, its origin is unknown") if plugin.origin.type == "entry_point": @@ -551,7 +551,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, try: self._call_pip(pip_args) except Exception: - self._logger.exception(u"Could not uninstall plugin via pip") + self._logger.exception("Could not uninstall plugin via pip") return make_response("Could not uninstall plugin via pip, see the log for more details", 500) elif plugin.origin.type == "folder": @@ -561,10 +561,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if os.path.isdir(full_path): # plugin is installed via a plugin folder, need to use rmtree to get rid of it - self._log_stdout(u"Deleting plugin from {folder}".format(folder=plugin.location)) + self._log_stdout("Deleting plugin from {folder}".format(folder=plugin.location)) shutil.rmtree(full_path) elif os.path.isfile(full_path): - self._log_stdout(u"Deleting plugin from {file}".format(file=plugin.location)) + self._log_stdout("Deleting plugin from {file}".format(file=plugin.location)) os.remove(full_path) if full_path.endswith(".py"): @@ -573,7 +573,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, os.remove(pyc_file) else: - self._logger.warning(u"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals())) + self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals())) return make_response("Could not uninstall plugin, its origin is unknown") needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) @@ -590,7 +590,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if plugin.enabled: self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem disabling plugin {name}".format(name=plugin.key)) + self._logger.exception("Problem disabling plugin {name}".format(name=plugin.key)) result = dict(result=False, uninstalled=True, disabled=False, unloaded=False, reason=e.reason) self._send_result_notification("uninstall", result) return jsonify(result) @@ -599,7 +599,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if plugin.loaded: self._plugin_manager.unload_plugin(plugin.key) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem unloading plugin {name}".format(name=plugin.key)) + self._logger.exception("Problem unloading plugin {name}".format(name=plugin.key)) result = dict(result=False, uninstalled=True, disabled=True, unloaded=False, reason=e.reason) self._send_result_notification("uninstall", result) return jsonify(result) @@ -639,7 +639,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif command == "enable": self._mark_plugin_enabled(plugin, needs_restart=needs_restart) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason)) + self._logger.exception("Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason)) result = dict(result=False, reason=e.reason) except octoprint.plugin.core.PluginNeedsRestart: result = dict(result=True, @@ -694,10 +694,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _call_pip(self, args): if self._pip_caller is None or not self._pip_caller.available: - raise RuntimeError(u"No pip available, can't operate".format(**locals())) + raise RuntimeError("No pip available, can't operate".format(**locals())) if "--process-dependency-links" in args: - self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") + self._log_message("Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") additional_args = self._settings.get(["pip_args"]) @@ -713,16 +713,16 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return self._pip_caller.execute(*args) def _log_message(self, *lines): - self._log(lines, prefix=u"*", stream="message") + self._log(lines, prefix="*", stream="message") def _log_call(self, *lines): - self._log(lines, prefix=u" ", stream="call") + self._log(lines, prefix=" ", stream="call") def _log_stdout(self, *lines): - self._log(lines, prefix=u">", stream="stdout") + self._log(lines, prefix=">", stream="stdout") def _log_stderr(self, *lines): - self._log(lines, prefix=u"!", stream="stderr") + self._log(lines, prefix="!", stream="stderr") def _log(self, lines, prefix=None, stream=None, strip=True): if strip: @@ -731,7 +731,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: - self._console_logger.debug(u"{prefix} {line}".format(**locals())) + self._console_logger.debug("{prefix} {line}".format(**locals())) def _mark_plugin_enabled(self, plugin, needs_restart=False): disabled_list = list(self._settings.global_get(["plugins", "_disabled"], diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index b55b973ae..713a444b9 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -61,8 +61,8 @@ SAFETY_CHECKS = { REPETIER_BEFORE_092_M115_TEST), received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST, ENDER3_RECEIVED_TEST), cap=(THERMAL_PROTECTION_CAP_TEST,), - message=gettext(u"Your printer's firmware is known to lack mandatory safety features (e.g. " - u"thermal runaway protection). This is a fire risk.")) + message=gettext("Your printer's firmware is known to lack mandatory safety features (e.g. " + "thermal runaway protection). This is a fire risk.")) } def extract_repetier_version(name): diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 8c3ba870f..b7864e3ca 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1077,7 +1077,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, result["displayVersion"] = to_unicode(check.get("displayVersion"), errors="replace") if result["displayVersion"] is None: # displayVersion missing or set to None - result["displayVersion"] = u"{octoprint_version}" + result["displayVersion"] = "{octoprint_version}" stable_branch = "master" release_branches = [] @@ -1131,7 +1131,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, result["displayVersion"] = to_unicode(check.get("displayVersion", check.get("current")), errors="replace") if result["displayVersion"] is None: # displayVersion AND current missing or None - result["displayVersion"] = u"unknown" + result["displayVersion"] = "unknown" if check["type"] in self.COMMIT_TRACKING_TYPES: result["current"] = check.get("current", None) @@ -1150,7 +1150,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: - self._console_logger.debug(u"{} {}".format(prefix, line)) + self._console_logger.debug("{} {}".format(prefix, line)) def _send_client_message(self, message_type, data=None): self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data)) diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index e6c4e239c..303219c15 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -35,7 +35,7 @@ def _log(lines, prefix=None, stream=None): output_stream = sys.stderr for line in lines: - to_print = _to_str(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), + to_print = _to_str("{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), errors="replace") print(to_print, file=output_stream) @@ -178,7 +178,7 @@ def _to_error(*lines): lines = lines[0] elif not isinstance(lines[0], (str, unicode)): lines = [repr(lines[0]),] - return u"\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines)) + return "\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines)) def _rescue_changes(git_executable, folder): @@ -186,7 +186,7 @@ def _rescue_changes(git_executable, folder): returncode, stdout, stderr = _git(["diff", "--shortstat"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError("Could not update, \"git diff\" failed with returncode {}".format(returncode)) - if stdout and u"".join(stdout).strip(): + if stdout and "".join(stdout).strip(): # we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch import time import os diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py index 197f9451e..dff19ffb2 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -85,7 +85,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc install_arg = check["pip"].format(target_version=target_version, target=target_version) - logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg)) + logger.debug("Target: %s, executing pip install %s" % (target, install_arg)) pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"] pip_kwargs = dict() if pip_working_directory is not None: @@ -106,9 +106,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc return (_POTENTIAL_EGG_PROBLEM_POSIX in line or _POTENTIAL_EGG_PROBLEM_WINDOWS in line) and ".egg" in line if any(map(lambda x: is_egg_problem(x), stderr)) or any(map(lambda x: is_egg_problem(x), stdout)): - _log_message(u"This looks like an error caused by a specific issue in upgrading Python \"eggs\"", - u"via current versions of pip.", - u"Performing a second install attempt as a work around.") + _log_message("This looks like an error caused by a specific issue in upgrading Python \"eggs\"", + "via current versions of pip.", + "Performing a second install attempt as a work around.") returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs) if returncode != 0: raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr)) @@ -116,11 +116,11 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr)) if not force and any(map(lambda x: x.strip().startswith(_ALREADY_INSTALLED) and (install_arg in x or install_arg in x.lower()), stdout)): - _log_message(u"Looks like we were already installed in this version. Forcing a reinstall.") + _log_message("Looks like we were already installed in this version. Forcing a reinstall.") force = True if force: - logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg)) + logger.debug("Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg)) pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"] returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index f0b74e9e0..baf8cdddf 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -175,28 +175,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): try: callback.on_printer_add_temperature(data) except Exception: - self._logger.exception(u"Exception while adding temperature data point to callback {}".format(callback)) + self._logger.exception("Exception while adding temperature data point to callback {}".format(callback)) def _sendAddLogCallbacks(self, data): for callback in self._callbacks: try: callback.on_printer_add_log(data) except Exception: - self._logger.exception(u"Exception while adding communication log entry to callback {}".format(callback)) + self._logger.exception("Exception while adding communication log entry to callback {}".format(callback)) def _sendAddMessageCallbacks(self, data): for callback in self._callbacks: try: callback.on_printer_add_message(data) except Exception: - self._logger.exception(u"Exception while adding printer message to callback {}".format(callback)) + self._logger.exception("Exception while adding printer message to callback {}".format(callback)) def _sendCurrentDataCallbacks(self, data): for callback in self._callbacks: try: callback.on_printer_send_current_data(copy.deepcopy(data)) except Exception: - self._logger.exception(u"Exception while pushing current data to callback {}".format(callback)) + self._logger.exception("Exception while pushing current data to callback {}".format(callback)) #~~ callback from metadata analysis event diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index f5c63da46..4d3314f96 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1051,14 +1051,14 @@ class Server(object): def externalize_links(text): def repl(match): tag = match.group("tag") - if not u"href" in tag: + if not "href" in tag: return match.group(0) - if not u"target=" in tag and not u"rel=" in tag: - tag += u" target=\"_blank\" rel=\"noreferrer noopener\"" + if not "target=" in tag and not "rel=" in tag: + tag += " target=\"_blank\" rel=\"noreferrer noopener\"" content = match.group("content") - return u"<{tag}>{content}".format(tag=tag, content=content) + return "<{tag}>{content}".format(tag=tag, content=content) return html_link_regex.sub(repl, text) app.jinja_env.filters["regex_replace"] = regex_replace diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 8942183f3..755537963 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -241,7 +241,7 @@ def fix_webassets_filtertool(): return MemoryHunk(content) except Exception: error_logger.exception("Got an exception while trying to apply filter, ignoring file") - return MemoryHunk(u"") + return MemoryHunk("") FilterTool._wrap_cache = fixed_wrap_cache @@ -982,7 +982,7 @@ def preemptively_cached(cache, data, unless=None): try: cache.record(data, unless=unless) except Exception: - logging.getLogger(__name__).exception(u"Error while recording preemptive cache entry: {!r}".format(data)) + logging.getLogger(__name__).exception("Error while recording preemptive cache entry: {!r}".format(data)) return f(*args, **kwargs) return decorated_function return decorator @@ -1001,7 +1001,7 @@ def etagged(etag): if result: rv.set_etag(result) except Exception: - logging.getLogger(__name__).exception(u"Error while calculating the etag value for response {!r}".format(rv)) + logging.getLogger(__name__).exception("Error while calculating the etag value for response {!r}".format(rv)) return rv return decorated_function return decorator @@ -1025,7 +1025,7 @@ def lastmodified(date): if result: rv.headers["Last-Modified"] = result except Exception: - logging.getLogger(__name__).exception(u"Error while calculating the lastmodified value for response {!r}".format(rv)) + logging.getLogger(__name__).exception("Error while calculating the lastmodified value for response {!r}".format(rv)) return rv return decorated_function return decorator @@ -1043,7 +1043,7 @@ def conditional(condition, met): rv = met() return rv except Exception: - logging.getLogger(__name__).exception(u"Error while evaluating conditional {!r} or met {!r}".format(condition, met)) + logging.getLogger(__name__).exception("Error while evaluating conditional {!r} or met {!r}".format(condition, met)) # condition hasn't been met, call decorated function return f(*args, **kwargs) diff --git a/src/octoprint/server/util/webassets.py b/src/octoprint/server/util/webassets.py index 1b8e5399e..0c1497576 100644 --- a/src/octoprint/server/util/webassets.py +++ b/src/octoprint/server/util/webassets.py @@ -113,7 +113,7 @@ class ChainedHunk(BaseHunk): pass def data(self): - result = u"" + result = "" for hunk in self._hunks: if isinstance(hunk, tuple) and len(hunk) == 2: hunk, f = hunk @@ -124,12 +124,12 @@ class ChainedHunk(BaseHunk): _PLUGIN_BUNDLE_WRAPPER_PREFIX = \ -u"""// JS assets for plugin {plugin} +"""// JS assets for plugin {plugin} (function () {{ try {{ """ _PLUGIN_BUNDLE_WRAPPER_SUFFIX = \ -u""" +""" }} catch (error) {{ log.error("Error in JS assets for plugin {plugin}:", (error.stack || error)); }} diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 5d55d80ac..5f1429f04 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -485,13 +485,13 @@ def fetch_template_data(refresh=False): # Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and # that require to access APIs to function will run into errors since those APIs won't work before ACL # has been configured. See also #2140 - return u"0:{}".format(to_unicode(d[0])) + return "0:{}".format(to_unicode(d[0])) elif d[1].get("mandatory", False): # Other mandatory steps come before the optional ones - return u"1:{}".format(to_unicode(d[0])) + return "1:{}".format(to_unicode(d[0])) else: # Finally everything else - return u"2:{}".format(to_unicode(d[0])) + return "2:{}".format(to_unicode(d[0])) template_sorting = dict( navbar=dict(add="prepend", key=None), diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 88b2acc5c..a469200fb 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1834,7 +1834,7 @@ def _validate_folder(folder, create=True, check_writable=True, deep_check_writab testfile = os.path.join(folder, ".testballoon.txt") try: with io.open(testfile, 'wt', encoding='utf-8') as f: - f.write(u"test") + f.write("test") os.remove(testfile) except Exception: if log_error: diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index c627ec584..3d9e469c0 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -319,20 +319,20 @@ def get_dos_filename(input, existing_filenames=None, extension=None, whitelisted Examples: >>> get_dos_filename("test1234.gco") - u'test1234.gco' + 'test1234.gco' >>> get_dos_filename("test1234.gcode") - u'test1234.gco' + 'test1234.gco' >>> get_dos_filename("test12345.gco") - u'test12~1.gco' + 'test12~1.gco' >>> get_dos_filename("test1234.fnord", extension="gco") - u'test1234.gco' + 'test1234.gco' >>> get_dos_filename("auto0.g", extension="gco") - u'auto0.gco' + 'auto0.gco' >>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"]) - u'auto0.g' + 'auto0.g' >>> get_dos_filename(None) >>> get_dos_filename("foo") - u'foo' + 'foo' """ if input is None: @@ -404,37 +404,37 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= Examples: >>> find_collision_free_name("test1234", "gco", []) - u'test1234.gco' + 'test1234.gco' >>> find_collision_free_name("test1234", "gcode", []) - u'test1234.gco' + 'test1234.gco' >>> find_collision_free_name("test12345", "gco", []) - u'test12~1.gco' + 'test12~1.gco' >>> find_collision_free_name("test 123", "gco", []) - u'test_123.gco' + 'test_123.gco' >>> find_collision_free_name("test1234", "g o", []) - u'test1234.g_o' + 'test1234.g_o' >>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) - u'test12~2.gco' + 'test12~2.gco' >>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]] >>> find_collision_free_name("test12345", "gco", many_files) - u'test1~10.gco' + 'test1~10.gco' >>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)] >>> find_collision_free_name("test12345", "gco", many_more_files) - u'test1~99.gco' + 'test1~99.gco' >>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"] >>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) Traceback (most recent call last): ... ValueError: Can't create a collision free filename >>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3) - u'test~100.gco' + 'test~100.gco' """ filename = to_unicode(filename) extension = to_unicode(extension) - if filename.startswith(u"/"): + if filename.startswith("/"): filename = filename[1:] existing_filenames = [to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames] @@ -445,7 +445,7 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= extension = make_valid(extension) extension = extension[:3] if len(extension) > 3 else extension - full_name_format = u"{filename}.{extension}" if extension else u"{filename}" + full_name_format = "{filename}.{extension}" if extension else "{filename}" result = full_name_format.format(filename=filename, extension=extension) @@ -455,7 +455,7 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= counter = 1 power = 1 - prefix_format = u"{segment}~{counter}" + prefix_format = "{segment}~{counter}" while counter < (10 ** max_power): prefix = prefix_format.format(segment=filename[:(6 - power + 1)], counter=str(counter)) result = full_name_format.format(filename=prefix, @@ -1056,7 +1056,7 @@ def is_hidden_path(path): path = to_unicode(path) filename = os.path.basename(path) - if filename.startswith(u"."): + if filename.startswith("."): # filenames starting with a . are hidden return True diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 64f6779d7..9c2746b42 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -623,9 +623,9 @@ class MachineCom(object): self._serialLogger.debug(message) def _to_logfile_with_terminal(self, message=None, level=logging.INFO): - log = u"Last lines in terminal:\n" + u"\n".join(map(lambda x: u"| {}".format(x), list(self._terminal_log))) + log = "Last lines in terminal:\n" + "\n".join(map(lambda x: "| {}".format(x), list(self._terminal_log))) if message is not None: - log = message + u"\n| " + log + log = message + "\n| " + log self._logger.log(level, log) def _addToLastLines(self, cmd): @@ -2663,7 +2663,7 @@ class MachineCom(object): if ret: return line - self._to_logfile_with_terminal(u"Received an error from the printer's firmware: {}".format(stripped_error), + self._to_logfile_with_terminal("Received an error from the printer's firmware: {}".format(stripped_error), level=logging.WARN) if not self._ignore_errors: @@ -2865,8 +2865,8 @@ class MachineCom(object): self._log_resends_rate_start = now self._log_resends_rate_count = 0 - self._to_logfile_with_terminal(u"Got a resend request from the printer: requested line = {}, " - u"current line = {}".format(lineToResend, self._currentLine)) + self._to_logfile_with_terminal("Got a resend request from the printer: requested line = {}, " + "current line = {}".format(lineToResend, self._currentLine)) self._log_resends_rate_count += 1 self._send_queue.resend_active = True @@ -3149,17 +3149,17 @@ class MachineCom(object): def _log_command_phase(self, phase, command, *args, **kwargs): if self._phaseLogger.isEnabledFor(logging.DEBUG): - output_parts = [u"phase: {}".format(phase), - u"command: {}".format(command)] + output_parts = ["phase: {}".format(phase), + "command: {}".format(command)] if kwargs.get("command_type"): - output_parts.append(u"command_type: {}".format(kwargs["command_type"])) + output_parts.append("command_type: {}".format(kwargs["command_type"])) if kwargs.get("gcode"): - output_parts.append(u"gcode: {}".format(kwargs["gcode"])) + output_parts.append("gcode: {}".format(kwargs["gcode"])) if kwargs.get("subcode"): - output_parts.append(u"subcode: {}".format(kwargs["subcode"])) + output_parts.append("subcode: {}".format(kwargs["subcode"])) if kwargs.get("tags"): - output_parts.append(u"tags: [ {} ]".format(", ".join(sorted(kwargs["tags"])))) + output_parts.append("tags: [ {} ]".format(", ".join(sorted(kwargs["tags"])))) self._phaseLogger.debug(" | ".join(output_parts)) @@ -3564,7 +3564,7 @@ class MachineCom(object): self._resendDelta = None def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): - self._logger.info(u"Force-sending M112 to the printer") + self._logger.info("Force-sending M112 to the printer") # emergency stop, jump the queue with the M112, regardless of whether the EMERGENCY_PARSER capability is # available or not @@ -3598,10 +3598,10 @@ class MachineCom(object): return None, def _gcode_M108_queuing(self, cmd, gcode=None, *args, **kwargs): - return self._emergency_force_send(cmd, u"Force-sending M108 to the printer", gcode=gcode, *args, **kwargs) + return self._emergency_force_send(cmd, "Force-sending M108 to the printer", gcode=gcode, *args, **kwargs) def _gcode_M410_queuing(self, cmd, gcode=None, *args, **kwargs): - return self._emergency_force_send(cmd, u"Force-sending M410 to the printer", gcode=gcode, *args, **kwargs) + return self._emergency_force_send(cmd, "Force-sending M410 to the printer", gcode=gcode, *args, **kwargs) def _gcode_M114_queued(self, *args, **kwargs): self._reset_position_timers() @@ -3911,7 +3911,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): """ with self._handle_mutex: if self._handle is None: - self._logger.warning(u"File {} is not open for reading".format(self._filename)) + self._logger.warning("File {} is not open for reading".format(self._filename)) return None, None, None try: diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index e2bb0eff2..557204c3e 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -83,16 +83,16 @@ class CommandlineCaller(object): def log(prefix, *lines): for line in lines: - print(u"{} {}".format(prefix, line)) + print("{} {}".format(prefix, line)) def log_stdout(*lines): - log(u">>>", *lines) + log(">>>", *lines) def log_stderr(*lines): - log(u"!!!", *lines) + log("!!!", *lines) def log_call(*lines) - log(u"---", *lines) + log("---", *lines) caller = CommandLineCaller() caller.on_log_call = log_call @@ -102,9 +102,9 @@ class CommandlineCaller(object): try: caller.checked_call(["some", "command", "with", "parameters"]) except CommandLineError as err: - print(u"Command returned {}".format(err.returncode)) + print("Command returned {}".format(err.returncode)) else: - print(u"Command finished successfully") + print("Command finished successfully") """ def __init__(self): @@ -158,7 +158,7 @@ class CommandlineCaller(object): joined_command = " ".join(command) else: joined_command = command - self._logger.debug(u"Calling: {}".format(joined_command)) + self._logger.debug("Calling: {}".format(joined_command)) self.on_log_call(joined_command) kwargs.update(dict(async_=True, stdout=sarge.Capture(), stderr=sarge.Capture())) @@ -177,7 +177,7 @@ class CommandlineCaller(object): if not p.commands[0].process: # the process might have been set to None in case of any exception - self._logger.error(u"Error while trying to run command {}".format(joined_command)) + self._logger.error("Error while trying to run command {}".format(joined_command)) return None, [], [] all_stdout = [] diff --git a/src/octoprint/util/pip.py b/src/octoprint/util/pip.py index 42e51d6f9..43e4f5d55 100644 --- a/src/octoprint/util/pip.py +++ b/src/octoprint/util/pip.py @@ -428,7 +428,7 @@ class PipCaller(CommandlineCaller): >>> text = b'some text with some\x1b[?25h ANSI codes for \x1b[31mred words\x1b[39m and\x1b[?25l also some cursor control codes' >>> PipCaller._preprocess(text) - u'some text with some ANSI codes for red words and also some cursor control codes' + 'some text with some ANSI codes for red words and also some cursor control codes' """ return to_unicode(clean_ansi(text)) diff --git a/tests/access/users/test_usermanager.py b/tests/access/users/test_usermanager.py index 804001836..416422617 100644 --- a/tests/access/users/test_usermanager.py +++ b/tests/access/users/test_usermanager.py @@ -19,7 +19,7 @@ class UserManagerTest(unittest.TestCase): def test_createPasswordHash_nonascii(self): """Test for issue #1891""" - password = u"password with ümläutß" + password = "password with ümläutß" salt = "abc" # should not throw an exception diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index 82be9f795..02945fbb0 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -194,14 +194,14 @@ class FileManagerTest(unittest.TestCase): self.printer_profile_manager.get_current_or_default.return_value = test_profile file_path = self.file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, "test.gcode", wrapper, - display=u"täst.gcode") + display="täst.gcode") self.assertEqual(("", "test.gcode"), file_path) self.local_storage.add_file.assert_called_once_with("test.gcode", wrapper, printer_profile=test_profile, allow_overwrite=False, links=None, - display=u"täst.gcode") + display="täst.gcode") def test_remove_file(self): self.local_storage.path_on_disk.return_value = "prefix/test.gcode" @@ -248,11 +248,11 @@ class FileManagerTest(unittest.TestCase): with self.assertRaises(RuntimeError, msg="already there"): self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder", - display=u"täst_folder") + display="täst_folder") self.fail("Expected an exception to occur!") self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=True, - display=u"täst_folder") + display="täst_folder") def test_remove_folder(self): self.local_storage.split_path.return_value = ("", "test_folder") diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py index c8308edb4..59cbe4f81 100644 --- a/tests/filemanager/test_localstorage.py +++ b/tests/filemanager/test_localstorage.py @@ -81,12 +81,12 @@ class LocalStorageTest(unittest.TestCase): self._add_and_verify_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, overwrite=True) def test_add_file_with_display(self): - stl_name = self._add_and_verify_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, display=u"bp_cäse.stl") + stl_name = self._add_and_verify_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, display="bp_cäse.stl") stl_metadata = self.storage.get_metadata(stl_name) self.assertIsNotNone(stl_metadata) self.assertIn('display', stl_metadata) - self.assertEqual(u"bp_cäse.stl", stl_metadata['display']) + self.assertEqual("bp_cäse.stl", stl_metadata['display']) def test_add_file_with_web(self): import time @@ -195,7 +195,7 @@ class LocalStorageTest(unittest.TestCase): def test_copy_file_new_display(self): self._add_file("bp_case.stl", FILE_BP_CASE_STL) try: - self.storage.copy_file("bp_case.stl", u"bp_cäse.stl") + self.storage.copy_file("bp_case.stl", "bp_cäse.stl") self.fail("Expected an exception") except StorageError as e: self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION) @@ -204,7 +204,7 @@ class LocalStorageTest(unittest.TestCase): self._add_file("bp_case.stl", FILE_BP_CASE_STL) before_metadata = self.storage.get_metadata("bp_case.stl") - self.storage.move_file("bp_case.stl", u"bp_cäse.stl") + self.storage.move_file("bp_case.stl", "bp_cäse.stl") after_metadata = self.storage.get_metadata("bp_case.stl") self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "bp_case.stl"))) @@ -212,11 +212,11 @@ class LocalStorageTest(unittest.TestCase): self.assertIsNotNone(before_metadata) self.assertIsNotNone(after_metadata) self.assertIn('display', after_metadata) - self.assertEqual(u"bp_cäse.stl", after_metadata['display']) + self.assertEqual("bp_cäse.stl", after_metadata['display']) @data("copy_file", "move_file") def test_copy_move_file_different_display(self, operation): - self._add_file("bp_case.stl", FILE_BP_CASE_STL, display=u"bp_cäse.stl") + self._add_file("bp_case.stl", FILE_BP_CASE_STL, display="bp_cäse.stl") before_metadata = self.storage.get_metadata("bp_case.stl") getattr(self.storage, operation)("bp_case.stl", "test.stl") @@ -269,11 +269,11 @@ class LocalStorageTest(unittest.TestCase): self._add_and_verify_folder("test", "test") def test_add_folder_with_display(self): - self._add_and_verify_folder("test", "test", display=u"täst") + self._add_and_verify_folder("test", "test", display="täst") metadata = self.storage.get_metadata("test") self.assertIsNotNone(metadata) self.assertIn('display', metadata) - self.assertEqual(u"täst", metadata['display']) + self.assertEqual("täst", metadata['display']) def test_add_subfolder(self): folder_name = self._add_and_verify_folder("folder with some spaces", "folder_with_some_spaces") @@ -307,14 +307,14 @@ class LocalStorageTest(unittest.TestCase): self.assertFalse(os.path.isdir(os.path.join(self.basefolder, empty_folder))) def test_remove_folder_with_display(self): - self._add_folder("folder", display=u"földer") + self._add_folder("folder", display="földer") before_metadata = self.storage.get_metadata("folder") self.storage.remove_folder("folder") after_metadata = self.storage.get_metadata("folder") self.assertIsNotNone(before_metadata) - self.assertDictEqual(before_metadata, dict(display=u"földer")) + self.assertDictEqual(before_metadata, dict(display="földer")) self.assertIsNone(after_metadata) def test_copy_folder(self): @@ -362,7 +362,7 @@ class LocalStorageTest(unittest.TestCase): def test_copy_folder_new_display(self): self._add_folder("folder") try: - self.storage.copy_folder("folder", u"földer") + self.storage.copy_folder("folder", "földer") self.fail("Expected an exception") except StorageError as e: self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION) @@ -371,23 +371,23 @@ class LocalStorageTest(unittest.TestCase): self._add_folder("folder") before_metadata = self.storage.get_metadata("folder") - self.storage.move_folder("folder", u"földer") + self.storage.move_folder("folder", "földer") after_metadata = self.storage.get_metadata("folder") self.assertIsNone(before_metadata) self.assertIsNotNone(after_metadata) - self.assertDictEqual(after_metadata, dict(display=u"földer")) + self.assertDictEqual(after_metadata, dict(display="földer")) @data("copy_folder", "move_folder") def test_copy_move_folder_different_display(self, operation): - self._add_folder("folder", display=u"földer") + self._add_folder("folder", display="földer") before_metadata = self.storage.get_metadata("folder") getattr(self.storage, operation)("folder", "test") after_metadata = self.storage.get_metadata("test") self.assertIsNotNone(before_metadata) - self.assertDictEqual(before_metadata, dict(display=u"földer")) + self.assertDictEqual(before_metadata, dict(display="földer")) self.assertIsNone(after_metadata) @data("copy_folder", "move_folder") @@ -628,9 +628,9 @@ class LocalStorageTest(unittest.TestCase): self.assertEqual(expected_name, actual_name) @data( - (u"test", u"test"), - (u"\u2764", u"red_heart"), - (u"\u2764\ufe00", u"red_heart") + ("test", "test"), + ("\u2764", "red_heart"), + ("\u2764\ufe00", "red_heart") ) @unpack def test_slugify(self, input, expected): diff --git a/tests/server/util/test_flask.py b/tests/server/util/test_flask.py index 0937dac5a..33d1ebe84 100644 --- a/tests/server/util/test_flask.py +++ b/tests/server/util/test_flask.py @@ -549,10 +549,10 @@ class OctoPrintFlaskRequestTest(unittest.TestCase): request = OctoPrintFlaskRequest(environ) cookies = request.cookies - self.assertDictEqual({"postfixed": u"postfixed_value", - "postfixed_wrong_P5001": u"postfixed_wrong_value", - "unpostfixed": u"unpostfixed_value", - "both": u"both_postfixed_value"}, + self.assertDictEqual({"postfixed": "postfixed_value", + "postfixed_wrong_P5001": "postfixed_wrong_value", + "unpostfixed": "unpostfixed_value", + "both": "both_postfixed_value"}, cookies) ##~~ diff --git a/tests/server/util/test_tornado.py b/tests/server/util/test_tornado.py index ef1f04508..30bdcd89b 100644 --- a/tests/server/util/test_tornado.py +++ b/tests/server/util/test_tornado.py @@ -76,16 +76,16 @@ class StripValueQuotesTest(unittest.TestCase): class ExtendedHeaderValueTest(unittest.TestCase): @data( - (u"", u""), + ("", ""), (None, None), - (u'"quoted-string"', u"quoted-string"), - (u'"qüöted-string"', u"qüöted-string"), - (u"iso-8859-1'en'%A3%20rates", u"£ rates"), - (u"UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", u"£ and € rates"), - ('"quoted-string"', u"quoted-string"), - ('"qüöted-string"', u"qüöted-string"), - ("iso-8859-1'en'%A3%20rates", u"£ rates"), - ("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", u"£ and € rates") + ('"quoted-string"', "quoted-string"), + ('"qüöted-string"', "qüöted-string"), + ("iso-8859-1'en'%A3%20rates", "£ rates"), + ("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", "£ and € rates"), + ('"quoted-string"', "quoted-string"), + ('"qüöted-string"', "qüöted-string"), + ("iso-8859-1'en'%A3%20rates", "£ rates"), + ("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", "£ and € rates") ) @unpack def test_extended_header_value(self, value, expected): diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index 6cce1e640..fce9ecb85 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -53,8 +53,8 @@ class BomAwareOpenTest(unittest.TestCase): # assert self.assertEqual(len(contents), 3) - self.assertTrue(contents[0].startswith(u"\ufffd" * 3 + "#")) - self.assertTrue(contents[2].endswith(u"\ufffd\ufffd" * 6)) + self.assertTrue(contents[0].startswith("\ufffd" * 3 + "#")) + self.assertTrue(contents[2].endswith("\ufffd\ufffd" * 6)) def test_bom_aware_open_encoding_error(self): """Tests that an encoding error is thrown if not suppressed when opening a UTF8 file as ASCII.""" @@ -334,7 +334,7 @@ class IsHiddenPathTest(unittest.TestCase): self.path_always_hidden = os.path.join(self.basepath, ".always_hidden.txt") import sys - for attr in (u"path_always_visible", u"path_hidden_on_windows", u"path_always_hidden"): + for attr in ("path_always_visible", "path_hidden_on_windows", "path_always_hidden"): path = getattr(self, attr) with io.open(path, 'wt+', encoding='utf-8') as f: f.write(attr)