diff --git a/docs/plugins/python3_migration.rst b/docs/plugins/python3_migration.rst index 1a85d2dc0..170e039e7 100644 --- a/docs/plugins/python3_migration.rst +++ b/docs/plugins/python3_migration.rst @@ -211,7 +211,7 @@ NOT need to convert to bytes when implementing API endpoints that return JSON, a anyhow. OctoPrint includes two utility methods you should use to ensure your strings enter/exit your code in the right format, -under both Python versions: :py:func:`octoprint.util.to_bytes` and :py:func:`octoprint.util.to_str`. Use them to ensure the correct data +under both Python versions: :py:func:`octoprint.util.to_bytes` and :py:func:`octoprint.util.to_unicode`. Use them to ensure the correct data types and to avoid weird conversion and encoding issues during runtime. You can read more about this specific issue in the corresponding section of the diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 9594824b9..eb78e770e 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -12,7 +12,14 @@ from os import scandir, walk import pylru import octoprint.filemanager -from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_str, yaml +from octoprint.util import ( + atomic_write, + is_hidden_path, + time_this, + to_bytes, + to_unicode, + yaml, +) from octoprint.util.files import sanitize_filename @@ -468,7 +475,7 @@ class LocalFileStorage(StorageInterface): """ self._logger = logging.getLogger(__name__) - self.basefolder = os.path.realpath(os.path.abspath(to_str(basefolder))) + self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder))) if not os.path.exists(self.basefolder) and create: os.makedirs(self.basefolder) if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder): @@ -604,7 +611,7 @@ class LocalFileStorage(StorageInterface): self, path=None, filter=None, recursive=True, level=0, force_refresh=False ): if path: - path = self.sanitize_path(to_str(path)) + path = self.sanitize_path(to_unicode(path)) base = self.path_in_storage(path) if base: base += "/" @@ -1097,7 +1104,7 @@ class LocalFileStorage(StorageInterface): self._save_metadata(path, metadata) def split_path(self, path): - path = to_str(path) + path = to_unicode(path) split = path.split("/") if len(split) == 1: return "", split[0] @@ -1105,7 +1112,7 @@ class LocalFileStorage(StorageInterface): return self.join_path(*split[:-1]), split[-1] def join_path(self, *path): - return "/".join(map(to_str, path)) + return "/".join(map(to_unicode, path)) def sanitize(self, path): """ @@ -1131,18 +1138,18 @@ class LocalFileStorage(StorageInterface): def canonicalize(self, path): name = None if isinstance(path, str): - path = to_str(path) + path = to_unicode(path) if path.startswith(self.basefolder): path = path[len(self.basefolder) :] path = path.replace(os.path.sep, "/") path = path.split("/") if isinstance(path, (list, tuple)): if len(path) == 1: - name = to_str(path[0]) + name = to_unicode(path[0]) path = "" else: - name = to_str(path[-1]) - path = self.join_path(*map(to_str, path[:-1])) + name = to_unicode(path[-1]) + path = self.join_path(*map(to_unicode, path[:-1])) if not path: path = "" @@ -1162,7 +1169,7 @@ class LocalFileStorage(StorageInterface): relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the absolute path including leading ``basefolder`` path. """ - path = to_str(path) + path = to_unicode(path) if len(path): if path[0] == "/": @@ -1185,7 +1192,7 @@ class LocalFileStorage(StorageInterface): return path def _sanitize_entry(self, entry, path, entry_path): - entry = to_str(entry) + entry = to_unicode(entry) sanitized = self.sanitize_name(entry) if sanitized != entry: # entry is not sanitized yet, let's take care of that @@ -1219,7 +1226,7 @@ class LocalFileStorage(StorageInterface): if isinstance(path, (tuple, list)): path = self.join_path(*path) if isinstance(path, str): - path = to_str(path) + path = to_unicode(path) if path.startswith(self.basefolder): path = path[len(self.basefolder) :] path = path.replace(os.path.sep, "/") @@ -1542,7 +1549,7 @@ class LocalFileStorage(StorageInterface): entry_name, path, entry_path ) if entry_name != new_entry_name or entry_path != new_entry_path: - entry_display = to_str(entry_name) + entry_display = to_unicode(entry_name) entry_name = new_entry_name entry_path = new_entry_path entry_stat = os.stat(entry_path) diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index b56ae3444..047d63e9a 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -143,17 +143,17 @@ def get_divider_line(c, message=None, length=78, indent=3): def prefix_multilines(text: str, prefix: str = ": ") -> str: - from octoprint.util import to_str + from octoprint.util import to_unicode lines = text.splitlines() if not lines: return "" if len(lines) == 1: - return to_str(lines[0]) + return to_unicode(lines[0]) return ( - to_str(lines[0]) + to_unicode(lines[0]) + "\n" - + "\n".join(map(lambda line: prefix + to_str(line), lines[1:])) + + "\n".join(map(lambda line: prefix + to_unicode(line), lines[1:])) ) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index ea728f4bb..7bc89dc7e 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -23,7 +23,7 @@ from octoprint.plugin.core import Plugin, PluginInfo, PluginManager # noqa: F40 from octoprint.plugin.types import * # noqa: F401,F403 ## used by multiple other modules from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin from octoprint.settings import settings as s -from octoprint.util import deprecated, to_str +from octoprint.util import deprecated, to_unicode # singleton _instance = None @@ -618,7 +618,7 @@ class PluginSettings: def _func(*args, **kwargs): return orig_func(*args_mapper(args), **kwargs_mapper(kwargs)) - _func.__name__ = to_str(item) + _func.__name__ = to_unicode(item) _func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None return _func diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 603d859c4..7c075eafb 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -33,7 +33,7 @@ import pkg_resources import pkginfo import octoprint.vendor.imp as imp -from octoprint.util import sv, time_this, to_str +from octoprint.util import sv, time_this, to_unicode from octoprint.util.version import get_python_version_string, is_python_compatible @@ -418,7 +418,7 @@ class PluginInfo: if self.version: return f"{self.name} ({self.version})" else: - return to_str(self.name) + return to_unicode(self.name) def long_str( self, @@ -459,23 +459,27 @@ class PluginInfo: """ if show_enabled: if self.incompatible: - ret = to_str(enabled_strs[3]) + ret = to_unicode(enabled_strs[3]) elif self.blacklisted: - ret = to_str(enabled_strs[2]) + ret = to_unicode(enabled_strs[2]) elif not self.enabled: - ret = to_str(enabled_strs[1]) + ret = to_unicode(enabled_strs[1]) else: - ret = to_str(enabled_strs[0]) + ret = to_unicode(enabled_strs[0]) else: ret = "" ret += str(self) if show_bundled: - ret += to_str(bundled_strs[0]) if self.bundled else to_str(bundled_strs[1]) + ret += ( + to_unicode(bundled_strs[0]) + if self.bundled + else to_unicode(bundled_strs[1]) + ) if show_location and self.location: - ret += to_str(location_str).format(location=self.location) + ret += to_unicode(location_str).format(location=self.location) return ret diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 63074d2f5..86af5b3b8 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -30,7 +30,7 @@ from octoprint.server.util.flask import ( no_firstrun_access, with_revalidation_checking, ) -from octoprint.util import dict_merge, get_formatted_size, to_str, yaml +from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml from octoprint.util.pip import create_pip_caller from octoprint.util.version import ( get_comparable_version, @@ -2195,13 +2195,13 @@ class SoftwareUpdatePlugin( if displayName is None: # displayName missing or set to None displayName = gettext("OctoPrint") - result["displayName"] = to_str(displayName, errors="replace") + result["displayName"] = to_unicode(displayName, errors="replace") displayVersion = check.get("displayVersion") if displayVersion is None: # displayVersion missing or set to None displayVersion = "{octoprint_version}" - result["displayVersion"] = to_str(displayVersion, errors="replace") + result["displayVersion"] = to_unicode(displayVersion, errors="replace") result["released_version"] = is_released_octoprint_version() @@ -2217,7 +2217,7 @@ class SoftwareUpdatePlugin( if displayName is None: # displayName missing or set to None displayName = gettext("pip") - result["displayName"] = to_str(displayName, errors="replace") + result["displayName"] = to_unicode(displayName, errors="replace") displayVersion = check.get("displayVersion") if displayVersion is None: @@ -2225,7 +2225,7 @@ class SoftwareUpdatePlugin( distribution = pkg_resources.get_distribution("pip") if distribution: displayVersion = distribution.version - result["displayVersion"] = to_str(displayVersion, errors="replace") + result["displayVersion"] = to_unicode(displayVersion, errors="replace") result["pip_command"] = check.get( "pip_command", @@ -2233,12 +2233,12 @@ class SoftwareUpdatePlugin( ) else: - result["displayName"] = to_str(check.get("displayName"), errors="replace") + result["displayName"] = to_unicode(check.get("displayName"), errors="replace") if result["displayName"] is None: # displayName missing or None - result["displayName"] = to_str(target, errors="replace") + result["displayName"] = to_unicode(target, errors="replace") - result["displayVersion"] = to_str( + result["displayVersion"] = to_unicode( check.get("displayVersion", check.get("current")), errors="replace" ) if result["displayVersion"] is None: diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 6a9362de1..0c2d415e2 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -14,7 +14,7 @@ import time from serial import SerialTimeoutException from octoprint.plugin import plugin_manager -from octoprint.util import RepeatedTimer, get_dos_filename, to_bytes, to_str +from octoprint.util import RepeatedTimer, get_dos_filename, to_bytes, to_unicode # noinspection PyBroadException @@ -457,7 +457,7 @@ class VirtualPrinter: data += b"\n" - data = to_str(data, encoding="ascii", errors="replace").strip() + data = to_unicode(data, encoding="ascii", errors="replace").strip() if data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG": debug_command = "" @@ -1998,7 +1998,7 @@ class VirtualPrinter: def write(self, data: bytes) -> int: data = to_bytes(data, errors="replace") - u_data = to_str(data, errors="replace") + u_data = to_unicode(data, errors="replace") if self._debug_awol: return len(data) @@ -2059,7 +2059,7 @@ class VirtualPrinter: try: # fetch a line from the queue, wait no longer than timeout - line = to_str(self.outgoing.get(timeout=timeout), errors="replace") + line = to_unicode(self.outgoing.get(timeout=timeout), errors="replace") self._seriallog.info(f">>> {line.strip()}") self.outgoing.task_done() return to_bytes(line) @@ -2120,7 +2120,7 @@ class VirtualEEPROM: # no eeprom file, make new one with defaults data = self.get_default_settings() with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: - eeprom_file.write(to_str(json.dumps(data))) + eeprom_file.write(to_unicode(json.dumps(data))) return data @staticmethod @@ -2231,7 +2231,7 @@ class VirtualEEPROM: def save_settings(self): # M500 behind-the-scenes with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: - eeprom_file.write(to_str(json.dumps(self._eeprom))) + eeprom_file.write(to_unicode(json.dumps(self._eeprom))) def read_settings(self): # M501 - if the file has disappeared, then recreate it diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 0a564935c..e276d485d 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -31,7 +31,7 @@ from octoprint.settings import settings from octoprint.util import InvariantContainer from octoprint.util import comm as comm from octoprint.util import get_fully_qualified_classname as fqcn -from octoprint.util import to_str +from octoprint.util import to_unicode class Printer(PrinterInterface, comm.MachineComPrintCallback): @@ -1426,7 +1426,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): """ Callback method for the comm object, called upon log output. """ - self._addLog(to_str(message, "utf-8", errors="replace")) + self._addLog(to_unicode(message, "utf-8", errors="replace")) def on_comm_temperature_update(self, tools, bed, chamber, custom=None): if custom is None: @@ -1521,7 +1521,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): Callback method for the comm object, called upon message exchanges via serial. Stores the message in the message buffer, truncates buffer to the last 300 lines. """ - self._addMessage(to_str(message, "utf-8", errors="replace")) + self._addMessage(to_unicode(message, "utf-8", errors="replace")) def on_comm_progress(self): """ diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index b2134caea..e52036a49 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -16,7 +16,7 @@ import octoprint.timelapse import octoprint.vendor.flask_principal as flask_principal from octoprint.plugin import plugin_manager from octoprint.settings import settings -from octoprint.util import deprecated, to_str +from octoprint.util import deprecated, to_unicode from . import flask, sockjs, tornado, watchdog # noqa: F401 @@ -257,7 +257,7 @@ def get_user_for_authorization_header(header): header = header.replace("Basic ", "", 1) try: - header = to_str(base64.b64decode(header)) + header = to_unicode(base64.b64decode(header)) except TypeError: return None diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 67e65db87..16e35f251 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -643,7 +643,7 @@ def _extended_header_value(value): return unquote(value, encoding=encoding) else: # no encoding provided, strip potentially present quotes and call it a day - return octoprint.util.to_str(_strip_value_quotes(value), encoding="utf-8") + return octoprint.util.to_unicode(_strip_value_quotes(value), encoding="utf-8") class WsgiInputContainer: @@ -1504,7 +1504,7 @@ class DynamicZipBundleHandler(StaticZipBundleHandler): self._access_validator(self.request) files = list( - map(octoprint.util.to_str, self.request.query_arguments.get("files", [])) + map(octoprint.util.to_unicode, self.request.query_arguments.get("files", [])) ) return self._get_files_zip(files) @@ -1524,7 +1524,7 @@ class DynamicZipBundleHandler(StaticZipBundleHandler): raise tornado.web.HTTPError(400) return self._get_files_zip( - list(map(octoprint.util.to_str, data.get("files", []))) + list(map(octoprint.util.to_unicode, data.get("files", []))) ) def _get_files_zip(self, files): diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 4220d19c7..2c110318a 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -40,7 +40,7 @@ from octoprint.server import ( # noqa: F401 ) from octoprint.server.util import has_permissions, require_login_with from octoprint.settings import settings -from octoprint.util import sv, to_bytes, to_str +from octoprint.util import sv, to_bytes, to_unicode from octoprint.util.version import get_python_version_string from . import util @@ -375,7 +375,9 @@ def index(): wizard_active(_templates.get(locale)), ] + sorted( [ - "{}:{}".format(to_str(k, errors="replace"), to_str(v, errors="replace")) + "{}:{}".format( + to_unicode(k, errors="replace"), to_unicode(v, errors="replace") + ) for k, v in _plugin_vars.items() ] ) @@ -792,13 +794,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 "0:{}".format(to_str(d[0])) + return "0:{}".format(to_unicode(d[0])) elif d[1].get("mandatory", False): # Other mandatory steps come before the optional ones - return "1:{}".format(to_str(d[0])) + return "1:{}".format(to_unicode(d[0])) else: # Finally everything else - return "2:{}".format(to_str(d[0])) + return "2:{}".format(to_unicode(d[0])) template_sorting = { "navbar": {"add": "prepend", "key": None}, diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 3ba55877f..ea224a905 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -74,11 +74,11 @@ def to_bytes( return s_or_u -def to_str( +def to_unicode( s_or_u: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict" ) -> str: """ - Make sure ``s_or_u`` is a str. + Make sure ``s_or_u`` is a unicode string (str). Arguments: s_or_u (str or bytes): The value to convert @@ -99,10 +99,6 @@ def to_str( return s_or_u -to_unicode = to_str # left for backwards compatibility -to_native_str = to_str # left for backwards compatibility - - def sortable_value(value, default_value=""): if value is None: return default_value @@ -319,6 +315,20 @@ Returns: value: The value of the variable with the deprecation warnings in place. """ +# TODO rename to_unicode to to_str and deprecate to_unicode in 2.0.0 +to_str = deprecated( + "to_str has been renamed to to_bytes and in a future version will become the new to_unicode", + includedoc="to_str has been renamed to to_bytes and in a future version will become the new to_unicode", + since="1.3.11", +)(to_bytes) + + +to_native_str = deprecated( + "to_native_str is no longer needed, use to_unicode instead", + includedoc="to_native_str is no longer needed, use to_unicode instead", + since="1.8.0", +)(to_unicode) + def get_formatted_size(num): """ @@ -464,7 +474,7 @@ def sanitize_ascii(line): line.__class__.__name__ if line is not None else None ) ) - return to_str(line, encoding="ascii", errors="replace").rstrip() + return to_unicode(line, encoding="ascii", errors="replace").rstrip() def filter_non_ascii(line): @@ -479,7 +489,7 @@ def filter_non_ascii(line): """ try: - to_bytes(to_str(line, encoding="ascii"), encoding="ascii") + to_bytes(to_unicode(line, encoding="ascii"), encoding="ascii") return False except ValueError: return True @@ -487,7 +497,7 @@ def filter_non_ascii(line): def filter_non_utf8(line): try: - to_bytes(to_str(line, encoding="utf-8"), encoding="utf-8") + to_bytes(to_unicode(line, encoding="utf-8"), encoding="utf-8") return False except ValueError: return True @@ -1095,7 +1105,7 @@ def is_hidden_path(path): # we define a None path as not hidden here return False - path = to_str(path) + path = to_unicode(path) filename = os.path.basename(path) if filename.startswith("."): diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 38ebe9b0c..6cd8caa47 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -40,7 +40,7 @@ from octoprint.util import ( get_bom, get_exception_string, sanitize_ascii, - to_str, + to_unicode, ) from octoprint.util.platform import get_os, set_close_exec @@ -880,7 +880,7 @@ class MachineCom: self._log(prefix + message) def _log(self, message): - message = to_str(message) + message = to_unicode(message) self._terminal_log.append(message) self._callback.on_comm_log(message) @@ -1238,7 +1238,7 @@ class MachineCom: tags=None, ): if not isinstance(cmd, QueueMarker): - cmd = to_str(cmd, errors="replace") + cmd = to_unicode(cmd, errors="replace") if not processed: cmd = process_gcode_line(cmd) if not cmd: @@ -4554,7 +4554,7 @@ class MachineCom: if self._phaseLogger.isEnabledFor(logging.DEBUG): output_parts = [ f"phase: {phase}", - "command: {}".format(to_str(command, errors="replace")), + "command: {}".format(to_unicode(command, errors="replace")), ] if kwargs.get("command_type"): @@ -4633,7 +4633,7 @@ class MachineCom: "command as-is.".format( name=name, phase=phase, - command=to_str(command, errors="replace"), + command=to_unicode(command, errors="replace"), ), extra={"plugin": name}, ) @@ -4729,7 +4729,7 @@ class MachineCom: self._logger.exception( "Error while processing hook {} for " "phase {} and command {}:".format( - name, phase, to_str(atcommand, errors="replace") + name, phase, to_unicode(atcommand, errors="replace") ), extra={"plugin": name}, ) @@ -4742,7 +4742,7 @@ class MachineCom: except Exception: self._logger.exception( "Error in handler for phase {} and command {}".format( - phase, to_str(atcommand, errors="replace") + phase, to_unicode(atcommand, errors="replace") ) ) diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index e72968a44..42efcc2ad 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -12,7 +12,7 @@ from typing import Dict, List, Tuple, Union import sarge -from octoprint.util import to_bytes, to_str +from octoprint.util import to_bytes, to_unicode from octoprint.util.platform import CLOSE_FDS # These regexes are based on the colorama package @@ -54,7 +54,7 @@ def clean_ansi(line: Union[str, bytes]) -> Union[str, bytes]: "Calling clean_ansi with bytes is deprecated, call with str instead", DeprecationWarning, ) - return to_bytes(_ANSI_REGEX.sub("", to_str(line))) + return to_bytes(_ANSI_REGEX.sub("", to_unicode(line))) return _ANSI_REGEX.sub("", line) @@ -223,7 +223,7 @@ class CommandlineCaller: if not lines: return [] processed = self._preprocess_lines( - *map(lambda x: to_str(x, errors="replace"), lines) + *map(lambda x: to_unicode(x, errors="replace"), lines) ) logger(*processed) return list(processed) diff --git a/src/octoprint/util/files.py b/src/octoprint/util/files.py index 567165500..47c8df636 100644 --- a/src/octoprint/util/files.py +++ b/src/octoprint/util/files.py @@ -47,9 +47,9 @@ def sanitize_filename(name, really_universal=False): Returns: the sanitized file name """ - from octoprint.util import to_str + from octoprint.util import to_unicode - name = to_str(name) + name = to_unicode(name) if name is None: return None @@ -214,15 +214,15 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= 'test~100.gco' """ - from octoprint.util import to_str + from octoprint.util import to_unicode - filename = to_str(filename) - extension = to_str(extension) + filename = to_unicode(filename) + extension = to_unicode(extension) if filename.startswith("/"): filename = filename[1:] existing_filenames = [ - to_str(x[1:] if x.startswith("/") else x) for x in existing_filenames + to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames ] def make_valid(text): diff --git a/src/octoprint/util/json/__init__.py b/src/octoprint/util/json/__init__.py index 244adb6c1..0f1976392 100644 --- a/src/octoprint/util/json/__init__.py +++ b/src/octoprint/util/json/__init__.py @@ -7,7 +7,7 @@ import json from frozendict import frozendict -from octoprint.util import to_str +from octoprint.util import to_unicode def dump(obj): @@ -43,4 +43,4 @@ class JsonEncoding: JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj)) -JsonEncoding.add_encoder(bytes, lambda obj: to_str(obj)) +JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj)) diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py index 6c04451b8..0e266103c 100644 --- a/src/octoprint/util/net.py +++ b/src/octoprint/util/net.py @@ -249,10 +249,10 @@ def server_reachable(host, port, timeout=3.05, proto="tcp", source=None): def resolve_host(host): import socket - from octoprint.util import to_str + from octoprint.util import to_unicode try: - return [to_str(x[4][0]) for x in socket.getaddrinfo(host, 80)] + return [to_unicode(x[4][0]) for x in socket.getaddrinfo(host, 80)] except Exception: return [] diff --git a/src/octoprint/util/text.py b/src/octoprint/util/text.py index d82f47b41..81d0f580d 100644 --- a/src/octoprint/util/text.py +++ b/src/octoprint/util/text.py @@ -5,7 +5,7 @@ import re from emoji import demojize -from octoprint.util import to_str +from octoprint.util import to_unicode from octoprint.vendor.awesome_slugify import Slugify _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U) @@ -13,7 +13,7 @@ _SLUGIFIES = {} def demojify(text): - text = to_str(text) + text = to_unicode(text) text = remove_unicode_variations(text) return demojize(text, delimiters=("", "")) @@ -48,7 +48,7 @@ def sanitize(text, safe_chars="-_.", demoji=True): slugify.safe_chars = safe_chars _SLUGIFIES[safe_chars] = slugify - text = to_str(text) + text = to_unicode(text) if demoji: text = demojify(text) return slugify(text) diff --git a/tests/util/test_string_helpers.py b/tests/util/test_string_helpers.py index 84343a9ed..44eed395b 100644 --- a/tests/util/test_string_helpers.py +++ b/tests/util/test_string_helpers.py @@ -3,37 +3,39 @@ __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms import unittest +import pytest + import octoprint.util class StringHelperTest(unittest.TestCase): - def test_to_str_unicode(self): - result = octoprint.util.to_str("test") + def test_to_unicode_unicode(self): + result = octoprint.util.to_unicode("test") self.assertEqual(result, "test") self.assertIsInstance(result, str) - def test_to_str_bytes(self): - result = octoprint.util.to_str(b"test") + def test_to_unicode_bytes(self): + result = octoprint.util.to_unicode(b"test") self.assertEqual(result, "test") self.assertIsInstance(result, str) - def test_to_str_bytes_utf8(self): + def test_to_unicode_bytes_utf8(self): data = "äöüß" - result = octoprint.util.to_str(data.encode("utf-8"), encoding="utf-8") + result = octoprint.util.to_unicode(data.encode("utf-8"), encoding="utf-8") self.assertEqual(result, data) self.assertIsInstance(result, str) - def test_to_str_bytes_utf8_vs_ascii(self): + def test_to_unicode_bytes_utf8_vs_ascii(self): self.assertRaises( UnicodeDecodeError, - octoprint.util.to_str, + octoprint.util.to_unicode, "äöüß".encode(), encoding="ascii", ) - def test_to_str_bytes_utf8_vs_ascii_replace(self): + def test_to_unicode_bytes_utf8_vs_ascii_replace(self): data = "äöüß" - result = octoprint.util.to_str( + result = octoprint.util.to_unicode( data.encode("utf-8"), encoding="ascii", errors="replace" ) self.assertEqual(result, data.encode("utf-8").decode("ascii", errors="replace")) @@ -66,12 +68,14 @@ class StringHelperTest(unittest.TestCase): self.assertEqual(result, data.encode("ascii", errors="replace")) self.assertIsInstance(result, bytes) - def test_to_unicode(self): - result = octoprint.util.to_unicode(b"test") - self.assertEqual(result, "test") - self.assertIsInstance(result, str) + def test_to_str(self): + with pytest.deprecated_call(): + result = octoprint.util.to_str("test") + self.assertEqual(result, b"test") + self.assertIsInstance(result, bytes) def test_to_native_str(self): - result = octoprint.util.to_native_str(b"test") - self.assertEqual(result, "test") - self.assertIsInstance(result, str) + with pytest.deprecated_call(): + result = octoprint.util.to_native_str(b"test") + self.assertEqual(result, "test") + self.assertIsInstance(result, str)