diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3865694ba7..7c8ba587fb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,7 @@ Below are a list of things to keep in mind when developing and submitting contributions to this repository. 1. All python code must be compatible with versions 2.7/3.6. -2. The code should follow linting from pylint. +2. The code should follow linting from ruff. 3. All commits should have passed the pre-commit checks. 4. Don't change code that is not related to your issue/ticket, open a new issue/ticket if that's the case. diff --git a/convert2rhel/actions/__init__.py b/convert2rhel/actions/__init__.py index 6e66116267..cf30895599 100644 --- a/convert2rhel/actions/__init__.py +++ b/convert2rhel/actions/__init__.py @@ -159,7 +159,7 @@ class Action: # @property # @abc.abstractmethod # def id(self): - @abc.abstractproperty # pylint: disable=deprecated-decorator + @abc.abstractproperty def id(self): """ This should be replaced by a simple class attribute. @@ -203,7 +203,7 @@ def run(self): instead. """ if self._has_run: - raise ActionError("Action %s has already run" % self.id) + raise ActionError("Action {} has already run".format(self.id)) self._has_run = True @@ -324,7 +324,7 @@ def __hash__(self): return hash((self.level, self.id, self.title, self.description, self.diagnosis, self.remediations)) def __repr__(self): - return "%s(level=%s, id=%s, title=%s, description=%s, diagnosis=%s, remediations=%s, variables=%s)" % ( + return "{}(level={}, id={}, title={}, description={}, diagnosis={}, remediations={}, variables={})".format( self.__class__.__name__, _STATUS_NAME_FROM_CODE[self.level], self.id, @@ -364,7 +364,7 @@ def __init__(self, level="", id="", title="", description="", diagnosis="", reme # None of the result status codes are legal as a message. So we error if any # of them were given here. if not (STATUS_CODE["SUCCESS"] < STATUS_CODE[level] < STATUS_CODE["SKIP"]): - raise InvalidMessageError("Invalid level '%s', set for a non-result message" % level) + raise InvalidMessageError("Invalid level '{}', set for a non-result message".format(level)) super(ActionMessage, self).__init__(level, id, title, description, diagnosis, remediations, variables) @@ -392,7 +392,7 @@ def __init__( elif STATUS_CODE["SUCCESS"] < STATUS_CODE[level] < STATUS_CODE["SKIP"]: raise InvalidMessageError( - "Invalid level '%s', the level for result must be SKIP or more fatal or SUCCESS." % level + "Invalid level '{}', the level for result must be SKIP or more fatal or SUCCESS.".format(level) ) super(ActionResult, self).__init__(level, id, title, description, diagnosis, remediations, variables) @@ -520,10 +520,10 @@ def run(self, successes=None, failures=None, skips=None): running is WARNING or better (WARNING or SUCCESS) and failure as worse than WARNING (OVERRIDABLE, ERROR) """ - logger.task("Prepare: %s" % self.task_header) + logger.task("Prepare: {}".format(self.task_header)) if self._has_run: - raise ActionError("Stage %s has already run." % self.stage_name) + raise ActionError("Stage {} has already run.".format(self.stage_name)) self._has_run = True # Make a mutable copy of these parameters so we don't overwrite the caller's data. @@ -548,7 +548,7 @@ def run(self, successes=None, failures=None, skips=None): to_be = "was" if len(failed_deps) > 1: to_be = "were" - diagnosis = "Skipped because %s %s not successful" % ( + diagnosis = "Skipped because {} {} not successful".format( utils.format_sequence_as_message(failed_deps), to_be, ) @@ -559,12 +559,13 @@ def run(self, successes=None, failures=None, skips=None): title="Skipped action", description="This action was skipped due to another action failing.", diagnosis=diagnosis, - remediations="Please ensure that the %s check passes so that this Action can evaluate your system" - % utils.format_sequence_as_message(failed_deps), + remediations="Please ensure that the {} check passes so that this Action can evaluate your system".format( + utils.format_sequence_as_message(failed_deps) + ), ) skips.append(action) failed_action_ids.add(action.id) - logger.error("Skipped %s. %s" % (action.id, diagnosis)) + logger.error("Skipped {}. {}".format(action.id, diagnosis)) continue # Run the Action @@ -574,10 +575,10 @@ def run(self, successes=None, failures=None, skips=None): # Uncaught exceptions are handled by constructing a generic # failure message here that should be reported description = ( - "Unhandled exception was caught: %s\n" + "Unhandled exception was caught: {}\n" "Please file a bug at https://issues.redhat.com/ to have this" " fixed or a specific error message added.\n" - "Traceback: %s" % (e, traceback.format_exc()) + "Traceback: {}".format(e, traceback.format_exc()) ) action.set_result( level="ERROR", id="UNEXPECTED_ERROR", title="Unhandled exception caught", description=description @@ -585,7 +586,7 @@ def run(self, successes=None, failures=None, skips=None): # Categorize the results if action.result.level <= STATUS_CODE["WARNING"]: - logger.info("%s has succeeded" % action.id) + logger.info("{} has succeeded".format(action.id)) successes.append(action) if action.result.level > STATUS_CODE["WARNING"]: @@ -687,7 +688,9 @@ def resolve_action_order(potential_actions, previously_resolved_actions=None): # that there is a circular dependency that needs to be broken. if previous_number_of_unresolved_actions != 0: raise DependencyError( - "Unsatisfied dependencies in these actions: %s" % ", ".join(action.id for action in unresolved_actions) + "Unsatisfied dependencies in these actions: {}".format( + ", ".join(action.id for action in unresolved_actions) + ) ) @@ -749,7 +752,7 @@ def run_pre_actions(): except DependencyError as e: # We want to fail early if dependencies are not properly set. This # way we should fail in testing before release. - logger.critical("Some dependencies were set on Actions but not present in convert2rhel: %s" % e) + logger.critical("Some dependencies were set on Actions but not present in convert2rhel: {}".format(e)) # Run the Actions in system_checks and all subsequent Stages. results = system_checks.run() @@ -778,7 +781,7 @@ def run_post_actions(): except DependencyError as e: # We want to fail early if dependencies are not properly set. This # way we should fail in testing before release. - logger.critical("Some dependencies were set on Actions but not present in convert2rhel: %s" % e) + logger.critical("Some dependencies were set on Actions but not present in convert2rhel: {}".format(e)) # Run the Actions in conversion and all subsequent Stages. results = conversion.run() diff --git a/convert2rhel/actions/conversion/lock_releasever.py b/convert2rhel/actions/conversion/lock_releasever.py index 51e6dfe6d7..2c6a89cc5e 100644 --- a/convert2rhel/actions/conversion/lock_releasever.py +++ b/convert2rhel/actions/conversion/lock_releasever.py @@ -53,16 +53,17 @@ def run(self): ) return loggerinst.info( - "Updating /etc/yum.repos.d/rehat.repo to point to RHEL %s instead of the default latest minor version." - % system_info.releasever + "Updating /etc/yum.repos.d/rehat.repo to point to RHEL {} instead of the default latest minor version.".format( + system_info.releasever + ) ) cmd = [ "subscription-manager", "release", - "--set=%s" % system_info.releasever, + "--set={}".format(system_info.releasever), ] _, ret_code = utils.run_subprocess(cmd, print_output=False) if ret_code != 0: loggerinst.warning("Locking RHEL repositories failed.") return - loggerinst.info("RHEL repositories locked to the %s minor version." % system_info.releasever) + loggerinst.info("RHEL repositories locked to the {} minor version.".format(system_info.releasever)) diff --git a/convert2rhel/actions/conversion/preserve_only_rhel_kernel.py b/convert2rhel/actions/conversion/preserve_only_rhel_kernel.py index c34aa1658e..9768d33367 100644 --- a/convert2rhel/actions/conversion/preserve_only_rhel_kernel.py +++ b/convert2rhel/actions/conversion/preserve_only_rhel_kernel.py @@ -39,7 +39,7 @@ def run(self): # Solution for RHELC-1707 # Update is needed in the UpdateKernel action - global _kernel_update_needed # pylint: disable=global-statement + global _kernel_update_needed loggerinst.info("Installing RHEL kernel ...") output, ret_code = pkgmanager.call_yum_cmd(command="install", args=["kernel"]) @@ -85,7 +85,7 @@ def run(self): "We will try to install a lower version of the package,\n" "remove the conflicting kernel and then update to the latest security patched version." ) - loggerinst.info("\n%s" % info_message) + loggerinst.info("\n{}".format(info_message)) pkghandler.handle_no_newer_rhel_kernel_available() _kernel_update_needed = True @@ -102,10 +102,10 @@ def run(self): ("non-RHEL kernel", non_rhel_kernels) ) loggerinst.debug( - "Latest installed kernel version from the original vendor: %s" % latest_installed_non_rhel_kernel + "Latest installed kernel version from the original vendor: {}".format(latest_installed_non_rhel_kernel) ) latest_installed_rhel_kernel = pkghandler.get_highest_package_version(("RHEL kernel", rhel_kernels)) - loggerinst.debug("Latest installed RHEL kernel version: %s" % latest_installed_rhel_kernel) + loggerinst.debug("Latest installed RHEL kernel version: {}".format(latest_installed_rhel_kernel)) is_rhel_kernel_higher = pkghandler.compare_package_versions( latest_installed_rhel_kernel, latest_installed_non_rhel_kernel ) @@ -180,7 +180,7 @@ def run(self): for entry in boot_entries: # The boot loader entries in /boot/loader/entries/-.conf if machine_id not in os.path.basename(entry): - loggerinst.debug("Removing boot entry %s" % entry) + loggerinst.debug("Removing boot entry {}".format(entry)) os.remove(entry) # Removing a boot entry that used to be the default makes grubby to choose a different entry as default, @@ -189,7 +189,7 @@ def run(self): if ret_code: # Not setting the default entry shouldn't be a deal breaker and the reason to stop the conversions, # grub should pick one entry in any case. - description = "Couldn't get the default GRUB2 boot loader entry:\n%s" % output + description = "Couldn't get the default GRUB2 boot loader entry:\n{}".format(output) loggerinst.warning(description) self.add_message( level="WARNING", @@ -198,10 +198,10 @@ def run(self): description=description, ) return - loggerinst.debug("Setting RHEL kernel %s as the default boot loader entry." % output.strip()) + loggerinst.debug("Setting RHEL kernel {} as the default boot loader entry.".format(output.strip())) output, ret_code = utils.run_subprocess(["/usr/sbin/grubby", "--set-default", output.strip()]) if ret_code: - description = "Couldn't set the default GRUB2 boot loader entry:\n%s" % output + description = "Couldn't set the default GRUB2 boot loader entry:\n{}".format(output) loggerinst.warning(description) self.add_message( level="WARNING", @@ -246,7 +246,7 @@ def run(self): kernel_sys_cfg = kernel_sys_cfg.replace("DEFAULTKERNEL=" + kernel_to_change, new_kernel_str) utils.store_content_to_file("/etc/sysconfig/kernel", kernel_sys_cfg) - loggerinst.info("Boot kernel %s was changed to %s" % (kernel_to_change, new_kernel_str)) + loggerinst.info("Boot kernel {} was changed to {}".format(kernel_to_change, new_kernel_str)) else: loggerinst.debug("Boot kernel validated.") @@ -288,7 +288,7 @@ def install_additional_rhel_kernel_pkgs(self, additional_pkgs): pkg_names = [p.nevra.name.replace(ol_kernel_ext, "", 1) for p in additional_pkgs] for name in set(pkg_names): if name != "kernel": - loggerinst.info("Installing RHEL %s" % name) + loggerinst.info("Installing RHEL {}".format(name)) pkgmanager.call_yum_cmd("install", args=[name]) diff --git a/convert2rhel/actions/conversion/set_efi_config.py b/convert2rhel/actions/conversion/set_efi_config.py index 99a024b336..b43e3aa892 100644 --- a/convert2rhel/actions/conversion/set_efi_config.py +++ b/convert2rhel/actions/conversion/set_efi_config.py @@ -48,10 +48,10 @@ def run(self): for filename in grub.DEFAULT_INSTALLED_EFIBIN_FILENAMES: efi_path = os.path.join(RHEL_EFIDIR_CANONICAL_PATH, filename) if os.path.exists(efi_path): - logger.info("UEFI binary found: %s" % efi_path) + logger.info("UEFI binary found: {}".format(efi_path)) new_default_efibin = efi_path break - logger.debug("UEFI binary %s not found. Checking next possibility..." % efi_path) + logger.debug("UEFI binary {} not found. Checking next possibility...".format(efi_path)) missing_binaries.append(efi_path) if not new_default_efibin: self.set_result( @@ -65,9 +65,9 @@ def run(self): remediations=( "Verify the bootloader configuration as follows and reboot the system." " Ensure that `grubenv` and `grub.cfg` files" - " are present in the %s directory. Verify that `efibootmgr -v`" + " are present in the {} directory. Verify that `efibootmgr -v`" " shows a bootloader entry for Red Hat Enterprise Linux" - " that points to to '\\EFI\\redhat\\shimx64.efi'." % grub.RHEL_EFIDIR_CANONICAL_PATH + " that points to to '\\EFI\\redhat\\shimx64.efi'.".format(grub.RHEL_EFIDIR_CANONICAL_PATH) ), ) @@ -125,7 +125,7 @@ def run(self): # TODO(pstodulk): check behaviour for efibin from a different dir or with a different name for the possibility of # the different grub content... # E.g. if the efibin is located in a different directory, are these two files valid? - logger.info("Moving GRUB2 configuration files to the new UEFI directory %s." % RHEL_EFIDIR_CANONICAL_PATH) + logger.info("Moving GRUB2 configuration files to the new UEFI directory {}.".format(RHEL_EFIDIR_CANONICAL_PATH)) src_files = [ os.path.join(CENTOS_EFIDIR_CANONICAL_PATH, filename) for filename in ["grubenv", "grub.cfg", "user.cfg"] ] @@ -154,20 +154,22 @@ def run(self): # Skip non-existing file in destination directory if not os.path.exists(src_file): logger.debug( - "The %s file does not exist in %s folder. Moving skipped." - % (os.path.basename(src_file), CENTOS_EFIDIR_CANONICAL_PATH) + "The {} file does not exist in {} folder. Moving skipped.".format( + os.path.basename(src_file), CENTOS_EFIDIR_CANONICAL_PATH + ) ) continue # Skip already existing file in destination directory dst_file = os.path.join(RHEL_EFIDIR_CANONICAL_PATH, os.path.basename(src_file)) if os.path.exists(dst_file): logger.debug( - "The %s file already exists in %s folder. Moving skipped." - % (os.path.basename(src_file), RHEL_EFIDIR_CANONICAL_PATH) + "The {} file already exists in {} folder. Moving skipped.".format( + os.path.basename(src_file), RHEL_EFIDIR_CANONICAL_PATH + ) ) continue - logger.info("Moving '%s' to '%s'" % (src_file, dst_file)) + logger.info("Moving '{}' to '{}'".format(src_file, dst_file)) try: shutil.move(src_file, dst_file) @@ -178,8 +180,9 @@ def run(self): id="GRUB_FILES_NOT_MOVED_TO_BOOT_DIRECTORY", title="GRUB files have not been moved to boot directory", description=( - "I/O error(%s): '%s'. Some GRUB files have not been moved to /boot/efi/EFI/redhat." - % (err.errno, err.strerror) + "I/O error({}): '{}'. Some GRUB files have not been moved to /boot/efi/EFI/redhat.".format( + err.errno, err.strerror + ) ), ) diff --git a/convert2rhel/actions/post_conversion/hostmetering.py b/convert2rhel/actions/post_conversion/hostmetering.py index 03f7d8914f..26c20ab7de 100644 --- a/convert2rhel/actions/post_conversion/hostmetering.py +++ b/convert2rhel/actions/post_conversion/hostmetering.py @@ -155,7 +155,7 @@ def _check_env_var(self): return False if self.env_var not in ("force", "auto"): - logger.debug("Value for environment variable not recognized: %s" % self.env_var) + logger.debug("Value for environment variable not recognized: {}".format(self.env_var)) self.add_message( level="WARNING", id="UNRECOGNIZED_OPTION_CONFIGURE_HOST_METERING", @@ -221,7 +221,7 @@ def _enable_host_metering_service(self): command = ["systemctl", "enable", "host-metering.service"] output, ret_enable = run_subprocess(command) if output: - logger.debug("Output of systemctl call: %s" % output) + logger.debug("Output of systemctl call: {}".format(output)) if ret_enable: logger.warning("Failed to enable host-metering service.") return " ".join(command), output @@ -230,7 +230,7 @@ def _enable_host_metering_service(self): command = ["systemctl", "start", "host-metering.service"] output, ret_start = run_subprocess(command) if output: - logger.debug("Output of systemctl call: %s" % output) + logger.debug("Output of systemctl call: {}".format(output)) if ret_start: logger.warning("Failed to start host-metering service.") return " ".join(command), output diff --git a/convert2rhel/actions/post_conversion/modified_rpm_files_diff.py b/convert2rhel/actions/post_conversion/modified_rpm_files_diff.py index 7d7025a4e1..05e9ae20af 100644 --- a/convert2rhel/actions/post_conversion/modified_rpm_files_diff.py +++ b/convert2rhel/actions/post_conversion/modified_rpm_files_diff.py @@ -69,12 +69,15 @@ def run(self): if modified_rpm_files_diff: logger.info( - "Comparison of modified rpm files from before and after the conversion:\n%s" % modified_rpm_files_diff + "Comparison of modified rpm files from before and after the conversion:\n{}".format( + modified_rpm_files_diff + ) ) self.add_message( level="INFO", id="FOUND_MODIFIED_RPM_FILES", title="Modified rpm files from before and after the conversion were found.", - description="Comparison of modified rpm files from before and after " - "the conversion: \n%s" % modified_rpm_files_diff, + description="Comparison of modified rpm files from before and after " "the conversion: \n{}".format( + modified_rpm_files_diff + ), ) diff --git a/convert2rhel/actions/post_conversion/remove_tmp_dir.py b/convert2rhel/actions/post_conversion/remove_tmp_dir.py index 557f617db0..dea02ca7f8 100644 --- a/convert2rhel/actions/post_conversion/remove_tmp_dir.py +++ b/convert2rhel/actions/post_conversion/remove_tmp_dir.py @@ -41,11 +41,11 @@ def run(self): """ super(RemoveTmpDir, self).run() - loggerinst.task("Final: Remove temporary folder %s" % TMP_DIR) + loggerinst.task("Final: Remove temporary folder {}".format(TMP_DIR)) try: shutil.rmtree(self.tmp_dir) - loggerinst.info("Temporary folder %s removed" % self.tmp_dir) + loggerinst.info("Temporary folder {} removed".format(self.tmp_dir)) except OSError as exc: # We want run() to be idempotent, so do nothing silently if # the path doesn't exist. @@ -53,8 +53,8 @@ def run(self): if exc.errno == errno.ENOENT: return warning_message = ( - "The folder %s is left untouched. You may remove the folder manually" - " after you ensure there is no preserved data you would need." % self.tmp_dir + "The folder {} is left untouched. You may remove the folder manually" + " after you ensure there is no preserved data you would need.".format(self.tmp_dir) ) loggerinst.warning(warning_message) diff --git a/convert2rhel/actions/post_conversion/rhsm_custom_facts_config.py b/convert2rhel/actions/post_conversion/rhsm_custom_facts_config.py index 482dc6d0f7..6e7689a1d5 100644 --- a/convert2rhel/actions/post_conversion/rhsm_custom_facts_config.py +++ b/convert2rhel/actions/post_conversion/rhsm_custom_facts_config.py @@ -24,7 +24,6 @@ class RHSMCustomFactsConfig(actions.Action): - id = "RHSM_CUSTOM_FACTS_CONFIG" dependencies = () diff --git a/convert2rhel/actions/post_conversion/update_grub.py b/convert2rhel/actions/post_conversion/update_grub.py index 676e7d52ad..9d318af8c7 100644 --- a/convert2rhel/actions/post_conversion/update_grub.py +++ b/convert2rhel/actions/post_conversion/update_grub.py @@ -45,7 +45,7 @@ def run(self): output, ret_code = utils.run_subprocess( ["/usr/sbin/grub2-mkconfig", "-o", grub2_config_file], print_output=False ) - logger.debug("Output of the grub2-mkconfig call:\n%s" % output) + logger.debug("Output of the grub2-mkconfig call:\n{}".format(output)) if ret_code != 0: logger.warning("GRUB2 config file generation failed.") @@ -85,10 +85,10 @@ def run(self): ) return - logger.debug("Device to install the GRUB2 image to: '%s'" % blk_device) + logger.debug("Device to install the GRUB2 image to: '{}'".format(blk_device)) output, ret_code = utils.run_subprocess(["/usr/sbin/grub2-install", blk_device], print_output=False) - logger.debug("Output of the grub2-install call:\n%s" % output) + logger.debug("Output of the grub2-install call:\n{}".format(output)) if ret_code != 0: logger.warning("Couldn't install the new images with GRUB2.") diff --git a/convert2rhel/actions/pre_ponr_changes/backup_system.py b/convert2rhel/actions/pre_ponr_changes/backup_system.py index 16b8052735..da22e30da5 100644 --- a/convert2rhel/actions/pre_ponr_changes/backup_system.py +++ b/convert2rhel/actions/pre_ponr_changes/backup_system.py @@ -81,7 +81,7 @@ def run(self): super(BackupRepository, self).run() - logger.info("Backing up .repo files from %s." % DEFAULT_YUM_REPOFILE_DIR) + logger.info("Backing up .repo files from {}.".format(DEFAULT_YUM_REPOFILE_DIR)) if not os.listdir(DEFAULT_YUM_REPOFILE_DIR): logger.info("Repository folder %s seems to be empty.", DEFAULT_YUM_REPOFILE_DIR) @@ -90,7 +90,7 @@ def run(self): # backing up redhat.repo so repo files are properly backed up when doing satellite conversions if not repo.endswith(".repo"): - logger.info("Skipping backup as %s is not a repository file." % repo) + logger.info("Skipping backup as {} is not a repository file.".format(repo)) continue repo_path = os.path.join(DEFAULT_YUM_REPOFILE_DIR, repo) @@ -107,11 +107,11 @@ def run(self): super(BackupYumVariables, self).run() - logger.info("Backing up variables files from %s." % DEFAULT_YUM_VARS_DIR) + logger.info("Backing up variables files from {}.".format(DEFAULT_YUM_VARS_DIR)) self._backup_variables(path=DEFAULT_YUM_VARS_DIR) if system_info.version.major >= 8: - logger.info("Backing up variables files from %s." % DEFAULT_DNF_VARS_DIR) + logger.info("Backing up variables files from {}.".format(DEFAULT_DNF_VARS_DIR)) self._backup_variables(path=DEFAULT_DNF_VARS_DIR) def _backup_variables(self, path): @@ -195,7 +195,7 @@ def _get_changed_package_files(self): else: # The file should be there # If missing conversion is in unknown state - logger.warning("Error(%s): %s" % (err.errno, err.strerror)) + logger.warning("Error({}): {}".format(err.errno, err.strerror)) logger.critical("Missing file {rpm_va_output} in it's location".format(rpm_va_output=path)) lines = output.strip().split("\n") @@ -214,7 +214,7 @@ def _parse_line(self, line): if not match: # line not matching the regex if line.strip() != "": # Line is not empty string - logger.debug("Skipping invalid output %s" % line) + logger.debug("Skipping invalid output {}".format(line)) return {"status": None, "file_type": None, "path": None} line = line.split() diff --git a/convert2rhel/actions/pre_ponr_changes/handle_packages.py b/convert2rhel/actions/pre_ponr_changes/handle_packages.py index dd4a9bd3dd..6d667ccaf7 100644 --- a/convert2rhel/actions/pre_ponr_changes/handle_packages.py +++ b/convert2rhel/actions/pre_ponr_changes/handle_packages.py @@ -46,9 +46,9 @@ def run(self): sorted(third_party_pkgs, key=self.extract_packages), disable_repos=disable_repos ) warning_message = ( - "Only packages signed by %s are to be" + "Only packages signed by {} are to be" " replaced. Red Hat support won't be provided" - " for the following third party packages:\n" % system_info.name + " for the following third party packages:\n".format(system_info.name) ) logger.warning(warning_message) @@ -148,7 +148,7 @@ def run(self): # shows which packages were not removed, if false, all packages were removed pkgs_not_removed = sorted(frozenset(pkghandler.get_pkg_nevras(all_pkgs)).difference(pkgs_removed)) if pkgs_not_removed: - message = "The following packages were not removed: %s" % ", ".join(pkgs_not_removed) + message = "The following packages were not removed: {}".format(", ".join(pkgs_not_removed)) logger.warning(message) self.add_message( level="WARNING", @@ -159,7 +159,7 @@ def run(self): ) if pkgs_removed: - message = "The following packages will be removed during the conversion: %s" % ", ".join(pkgs_removed) + message = "The following packages will be removed during the conversion: {}".format(", ".join(pkgs_removed)) logger.info(message) self.add_message( level="INFO", @@ -186,10 +186,10 @@ def _remove_packages_unless_from_redhat(pkgs_list, disable_repos=None): return [] # this call can return None, which is not ideal to use with sorted. - logger.warning("Removing the following %s packages:\n" % len(pkgs_list)) + logger.warning("Removing the following {} packages:\n".format(len(pkgs_list))) pkghandler.print_pkg_info(pkgs_list, disable_repos) pkgs_removed = utils.remove_pkgs(pkghandler.get_pkg_nevras(pkgs_list)) - logger.debug("Successfully removed %s packages" % len(pkgs_list)) + logger.debug("Successfully removed {} packages".format(len(pkgs_list))) return pkgs_removed diff --git a/convert2rhel/actions/pre_ponr_changes/kernel_modules.py b/convert2rhel/actions/pre_ponr_changes/kernel_modules.py index da75c44b09..365f469207 100644 --- a/convert2rhel/actions/pre_ponr_changes/kernel_modules.py +++ b/convert2rhel/actions/pre_ponr_changes/kernel_modules.py @@ -68,13 +68,13 @@ def _get_rhel_supported_kmods(self): precache = [ "yum", "makecache", - "--releasever=%s" % system_info.releasever, + "--releasever={}".format(system_info.releasever), "--setopt=*.skip_if_unavailable=False", ] # Clearing the exclude field with setopt to prevent kernel being # excluded in the config. # https://issues.redhat.com/browse/RHELC-774 - basecmd = ["repoquery", "--releasever=%s" % system_info.releasever, "--setopt=exclude="] + basecmd = ["repoquery", "--releasever={}".format(system_info.releasever), "--setopt=exclude="] if system_info.version.major >= 8: basecmd.append("--setopt=module_platform_id=platform:el" + str(system_info.version.major)) @@ -94,11 +94,11 @@ def _get_rhel_supported_kmods(self): precache_out, precache_exit_code = run_subprocess(precache, print_output=False) if precache_exit_code != 0: raise PackageRepositoryError( - "We were unable to download the repository metadata for (%s) to" + "We were unable to download the repository metadata for ({}) to" " determine packages containing kernel modules. Can be caused by" " not enough disk space in /var/cache or too little memory. The" " yum output below may have a clue for what went wrong in this" - " case:\n\n%s" % (", ".join(system_info.get_enabled_rhel_repos()), precache_out) + " case:\n\n{}".format(", ".join(system_info.get_enabled_rhel_repos()), precache_out) ) cmd = basecmd[:] @@ -112,18 +112,20 @@ def _get_rhel_supported_kmods(self): if repoquery_exit_code != 0: raise PackageRepositoryError( - "We were unable to query the repositories (%s) to" + "We were unable to query the repositories ({}) to" " determine packages containing kernel modules." - " Output from the failed repoquery command:\n\n%s" - % (", ".join(system_info.get_enabled_rhel_repos()), kmod_pkgs_str) + " Output from the failed repoquery command:\n\n{}".format( + ", ".join(system_info.get_enabled_rhel_repos()), kmod_pkgs_str + ) ) # from these packages we select only the latest one kmod_pkgs = self._get_most_recent_unique_kernel_pkgs(kmod_pkgs_str.rstrip("\n").split()) if not kmod_pkgs: logger.debug("Output of the previous repoquery command:\n{0}".format(kmod_pkgs_str)) raise RHELKernelModuleNotFound( - "No packages containing kernel modules available in the enabled repositories (%s)." - % ", ".join(system_info.get_enabled_rhel_repos()) + "No packages containing kernel modules available in the enabled repositories ({}).".format( + ", ".join(system_info.get_enabled_rhel_repos()) + ) ) logger.info( @@ -306,5 +308,5 @@ def run(self): id="CANNOT_COMPARE_PACKAGE_VERSIONS", title="Error while comparing packages", description="There was an error while detecting the kernel package which corresponds to the kernel modules present on the system.", - diagnosis="Package comparison failed: %s" % str(e), + diagnosis="Package comparison failed: {}".format(str(e)), ) diff --git a/convert2rhel/actions/pre_ponr_changes/subscription.py b/convert2rhel/actions/pre_ponr_changes/subscription.py index 3f9fcb97e3..d57be2c39e 100644 --- a/convert2rhel/actions/pre_ponr_changes/subscription.py +++ b/convert2rhel/actions/pre_ponr_changes/subscription.py @@ -137,7 +137,7 @@ def run(self): id="UNABLE_TO_REGISTER", title="System unregistration failure", description="The system is already registered with subscription-manager even though it is running CentOS not RHEL. We have failed to remove that registration.", - diagnosis="Failed to unregister the system: %s" % e, + diagnosis="Failed to unregister the system: {}".format(e), remediations="You may want to unregister the system manually and re-run convert2rhel.", ) @@ -227,7 +227,7 @@ def run(self): id="MISSING_SUBSCRIPTION_MANAGER_BINARY", title="Missing subscription-manager binary", description="There is a missing subscription-manager binary", - diagnosis="Failed to execute command: %s" % e, + diagnosis="Failed to execute command: {}".format(e), ) except exceptions.CriticalError as e: self.set_result( @@ -255,5 +255,7 @@ def run(self): id="MISSING_REGISTRATION_COMBINATION", title="Missing registration combination", description="There are missing registration combinations", - diagnosis="One or more combinations were missing for subscription-manager parameters: %s" % str(e), + diagnosis="One or more combinations were missing for subscription-manager parameters: {}".format( + str(e) + ), ) diff --git a/convert2rhel/actions/report.py b/convert2rhel/actions/report.py index 68da500565..6fd9998189 100644 --- a/convert2rhel/actions/report.py +++ b/convert2rhel/actions/report.py @@ -280,7 +280,7 @@ def _summary(results, include_all_reports, disable_colors): if not combined_results_and_message: report.append("No problems detected!") - logger.info("%s\n" % "\n".join(report)) + logger.info("{}\n".format("\n".join(report))) def format_report_section_heading(status_code): diff --git a/convert2rhel/actions/system_checks/check_firewalld_availability.py b/convert2rhel/actions/system_checks/check_firewalld_availability.py index a80a419748..f3b72e7b12 100644 --- a/convert2rhel/actions/system_checks/check_firewalld_availability.py +++ b/convert2rhel/actions/system_checks/check_firewalld_availability.py @@ -43,7 +43,7 @@ def _is_modules_cleanup_enabled(): """ # Return True is the config file does not exist. if not os.path.exists(FIREWALLD_CONFIG_FILE): - logger.debug("%s does not exist." % FIREWALLD_CONFIG_FILE) + logger.debug("{} does not exist.".format(FIREWALLD_CONFIG_FILE)) return True contents = [] @@ -53,7 +53,7 @@ def _is_modules_cleanup_enabled(): # Contents list is empty for some reason, better to assume that there # is no content in the file that was read. if not contents: - logger.debug("%s is empty." % FIREWALLD_CONFIG_FILE) + logger.debug("{} is empty.".format(FIREWALLD_CONFIG_FILE)) return True # If the CleanupModulesOnExit is not present inside the contents list, we @@ -71,12 +71,12 @@ def _is_modules_cleanup_enabled(): # If the config file has this option set to true/yes, then we need to # return True to ask the user to change it to False. if list(filter(CLEANUP_MODULES_ON_EXIT_REGEX.match, contents)): - logger.debug("CleanupModulesOnExit option enabled in %s" % FIREWALLD_CONFIG_FILE) + logger.debug("CleanupModulesOnExit option enabled in {}".format(FIREWALLD_CONFIG_FILE)) return True # Default to return False as it is possible that the CleanupModulesOnExit # is set to no in the config already. - logger.debug("CleanupModulesOnExit option is disabled in %s" % FIREWALLD_CONFIG_FILE) + logger.debug("CleanupModulesOnExit option is disabled in {}".format(FIREWALLD_CONFIG_FILE)) return False diff --git a/convert2rhel/actions/system_checks/convert2rhel_latest.py b/convert2rhel/actions/system_checks/convert2rhel_latest.py index 5a552b61e4..8a8c505f7f 100644 --- a/convert2rhel/actions/system_checks/convert2rhel_latest.py +++ b/convert2rhel/actions/system_checks/convert2rhel_latest.py @@ -51,8 +51,8 @@ def run(self): cmd = [ "repoquery", - "--releasever=%s" % system_info.version.major, - "--setopt=reposdir=%s" % os.path.dirname(repofile_path), + "--releasever={}".format(system_info.version.major), + "--setopt=reposdir={}".format(os.path.dirname(repofile_path)), "--setopt=exclude=", "--qf", "C2R %{NAME}-%{EPOCH}:%{VERSION}-%{RELEASE}.%{ARCH}", @@ -64,7 +64,7 @@ def run(self): if return_code != 0: diagnosis = ( "Couldn't check if the current installed convert2rhel is the latest version.\n" - "repoquery failed with the following output:\n%s" % (raw_output_convert2rhel_versions) + "repoquery failed with the following output:\n{}".format(raw_output_convert2rhel_versions) ) logger.warning(diagnosis) self.add_message( @@ -91,12 +91,12 @@ def run(self): continue convert2rhel_versions.append(parsed_pkg) - logger.debug("Found %s convert2rhel package(s)" % len(convert2rhel_versions)) + logger.debug("Found {} convert2rhel package(s)".format(len(convert2rhel_versions))) # This loop will determine the latest available convert2rhel version in the yum repo. # It assigns the epoch, version, and release ex: ("0", "0.26", "1.el7") to the latest_available_version variable. for package_version in convert2rhel_versions: - logger.debug("...comparing version %s" % latest_available_version[1]) + logger.debug("...comparing version {}".format(latest_available_version[1])) # rpm.labelCompare(pkg1, pkg2) compare two package version strings and return # -1 if latest_version is greater than package_version, 0 if they are equal, 1 if package_version is greater than latest_version ver_compare = rpm.labelCompare( @@ -105,11 +105,11 @@ def run(self): if ver_compare > 0: logger.debug( - "...found %s to be newer than %s, updating" % (package_version[2], latest_available_version[1]) + "...found {} to be newer than {}, updating".format(package_version[2], latest_available_version[1]) ) latest_available_version = (package_version[1], package_version[2], package_version[3]) - logger.debug("Found %s to be latest available version" % (latest_available_version[1])) + logger.debug("Found {} to be latest available version".format(latest_available_version[1])) precise_available_version = ("0", latest_available_version[1], "0") precise_convert2rhel_version = ("0", running_convert2rhel_version, "0") # Get source files that we're running with import convert2rhel ; convert2rhel.__file__ @@ -132,8 +132,9 @@ def run(self): # If we couldn't get a NEVRA above, then print a warning that we could not determine the rpm release and use convert2rhel.__version__ to compare with the latest packaged version if return_code != 0 or len(running_convert2rhel_NEVRA) != 1: logger.warning( - "Couldn't determine the rpm release; We will check that the version of convert2rhel (%s) is the latest but ignore the rpm release." - % running_convert2rhel_version + "Couldn't determine the rpm release; We will check that the version of convert2rhel ({}) is the latest but ignore the rpm release.".format( + running_convert2rhel_version + ) ) else: @@ -148,8 +149,9 @@ def run(self): if return_code != 0: logger.warning( "Some files in the convert2rhel package have changed so the installed convert2rhel is not what was packaged." - " We will check that the version of convert2rhel (%s) is the latest but ignore the rpm release." - % running_convert2rhel_version + " We will check that the version of convert2rhel ({}) is the latest but ignore the rpm release.".format( + running_convert2rhel_version + ) ) # Otherwise use the NEVRA from above to compare with the latest packaged version @@ -172,9 +174,10 @@ def run(self): if ver_compare < 0: if "CONVERT2RHEL_ALLOW_OLDER_VERSION" in os.environ: diagnosis = ( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "'CONVERT2RHEL_ALLOW_OLDER_VERSION' environment variable detected, continuing conversion" - % (formatted_convert2rhel_version, formatted_available_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "'CONVERT2RHEL_ALLOW_OLDER_VERSION' environment variable detected, continuing conversion".format( + formatted_convert2rhel_version, formatted_available_version + ) ) logger.warning(diagnosis) self.add_message( @@ -187,9 +190,10 @@ def run(self): else: if int(system_info.version.major) <= 6: logger.warning( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "We encourage you to update to the latest version." - % (formatted_convert2rhel_version, formatted_available_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "We encourage you to update to the latest version.".format( + formatted_convert2rhel_version, formatted_available_version + ) ) self.add_message( level="WARNING", @@ -197,9 +201,10 @@ def run(self): title="Outdated convert2rhel version detected", description="An outdated convert2rhel version has been detected", diagnosis=( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "We encourage you to update to the latest version." - % (formatted_convert2rhel_version, formatted_available_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "We encourage you to update to the latest version.".format( + formatted_convert2rhel_version, formatted_available_version + ) ), ) @@ -210,9 +215,10 @@ def run(self): title="Outdated convert2rhel version detected", description="An outdated convert2rhel version has been detected", diagnosis=( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "Only the latest version is supported for conversion." - % (formatted_convert2rhel_version, formatted_available_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "Only the latest version is supported for conversion.".format( + formatted_convert2rhel_version, formatted_available_version + ) ), remediations="If you want to disregard this check, then set the environment variable 'CONVERT2RHEL_ALLOW_OLDER_VERSION=1' to continue.", ) @@ -233,8 +239,9 @@ def _download_convert2rhel_repofile(self): title="Did not perform convert2rhel latest version check", description="Checking whether the installed convert2rhel package is of the latest available version was" " skipped due to an unexpected system version.", - diagnosis="Expected system versions: %s. Detected major version: %s" - % (", ".join(str(x) for x in C2R_REPOFILE_URLS), system_info.version.major), + diagnosis="Expected system versions: {}. Detected major version: {}".format( + ", ".join(str(x) for x in C2R_REPOFILE_URLS), system_info.version.major + ), ) return None @@ -255,7 +262,7 @@ def _download_convert2rhel_repofile(self): def _format_EVR(epoch, version, release): - return "%s" % (version) + return "{}".format(version) def _extract_convert2rhel_versions(raw_versions): @@ -277,7 +284,7 @@ def _extract_convert2rhel_versions(raw_versions): # Mainly for debugging purposes to see what is happening if we got # anything else that does not have the C2R identifier at the start # of the line. - logger.debug("Got a line without the C2R identifier: %s" % raw_version) + logger.debug("Got a line without the C2R identifier: {}".format(raw_version)) precise_raw_version = parsed_versions return precise_raw_version diff --git a/convert2rhel/actions/system_checks/duplicate_packages.py b/convert2rhel/actions/system_checks/duplicate_packages.py index e05df11d08..53ba46a0a3 100644 --- a/convert2rhel/actions/system_checks/duplicate_packages.py +++ b/convert2rhel/actions/system_checks/duplicate_packages.py @@ -52,7 +52,7 @@ def run(self): id="DUPLICATE_PACKAGES_FOUND", title="Duplicate packages found on the system", description="The system contains one or more packages with multiple versions.", - diagnosis="The following packages have multiple versions: %s." % ", ".join(duplicate_packages), + diagnosis="The following packages have multiple versions: {}.".format(", ".join(duplicate_packages)), remediations="This error can be resolved by removing duplicate versions of the listed packages." " The command 'package-cleanup' can be used to automatically remove duplicate packages" " on the system.", diff --git a/convert2rhel/actions/system_checks/efi.py b/convert2rhel/actions/system_checks/efi.py index 20cef8f44d..469c332b93 100644 --- a/convert2rhel/actions/system_checks/efi.py +++ b/convert2rhel/actions/system_checks/efi.py @@ -87,8 +87,8 @@ def run(self): # NOTE(pstodulk): I am not sure what could be consequences after the conversion, as the # new UEFI bootloader entry is created referring to a RHEL UEFI binary. logger.warning( - "The current UEFI bootloader '%s' is not referring to any binary UEFI" - " file located on local EFI System Partition (ESP)." % efiboot_info.current_bootnum + "The current UEFI bootloader '{}' is not referring to any binary UEFI" + " file located on local EFI System Partition (ESP).".format(efiboot_info.current_bootnum) ) self.add_message( level="WARNING", @@ -96,8 +96,8 @@ def run(self): title="UEFI bootloader mismatch", description="There was a UEFI bootloader mismatch.", diagnosis=( - "The current UEFI bootloader '%s' is not referring to any binary UEFI" - " file located on local EFI System Partition (ESP)." % efiboot_info.current_bootnum + "The current UEFI bootloader '{}' is not referring to any binary UEFI" + " file located on local EFI System Partition (ESP).".format(efiboot_info.current_bootnum) ), ) # TODO(pstodulk): print warning when multiple orig. UEFI entries point diff --git a/convert2rhel/actions/system_checks/eus.py b/convert2rhel/actions/system_checks/eus.py index a047603942..e40e6635ff 100644 --- a/convert2rhel/actions/system_checks/eus.py +++ b/convert2rhel/actions/system_checks/eus.py @@ -33,7 +33,7 @@ def run(self): """Warn the user if their system is under EUS and past the EUS release date without using the --eus cli option.""" super(EusSystemCheck, self).run() - current_version = "%s.%s" % (system_info.version.major, system_info.version.minor) + current_version = "{}.{}".format(system_info.version.major, system_info.version.minor) eus_versions = list(EUS_MINOR_VERSIONS.keys()) if current_version in eus_versions: eus_release_date = EUS_MINOR_VERSIONS.get(current_version, False) diff --git a/convert2rhel/actions/system_checks/is_loaded_kernel_latest.py b/convert2rhel/actions/system_checks/is_loaded_kernel_latest.py index 0484abbf76..5be4b83961 100644 --- a/convert2rhel/actions/system_checks/is_loaded_kernel_latest.py +++ b/convert2rhel/actions/system_checks/is_loaded_kernel_latest.py @@ -33,7 +33,7 @@ class IsLoadedKernelLatest(actions.Action): # disabling here as some of the return statements would be raised as exceptions in normal code # but we don't do that in an Action class - def run(self): # pylint: disable= too-many-return-statements + def run(self): """Check if the loaded kernel is behind or of the same version as in yum repos.""" super(IsLoadedKernelLatest, self).run() logger.task("Prepare: Check if the loaded kernel version is the most recent") @@ -70,8 +70,8 @@ def run(self): # pylint: disable= too-many-return-statements if "CONVERT2RHEL_SKIP_KERNEL_CURRENCY_CHECK" in os.environ: logger.warning( "Detected 'CONVERT2RHEL_SKIP_KERNEL_CURRENCY_CHECK' environment variable, we will skip " - "the %s comparison.\n" - "Beware, this could leave your system in a broken state." % package_to_check + "the {} comparison.\n" + "Beware, this could leave your system in a broken state.".format(package_to_check) ) self.add_message( @@ -80,8 +80,8 @@ def run(self): # pylint: disable= too-many-return-statements title="Did not perform the kernel currency check", description=( "Detected 'CONVERT2RHEL_SKIP_KERNEL_CURRENCY_CHECK' environment variable, we will skip " - "the %s comparison.\n" - "Beware, this could leave your system in a broken state." % package_to_check + "the {} comparison.\n" + "Beware, this could leave your system in a broken state.".format(package_to_check) ), ) return @@ -126,7 +126,7 @@ def run(self): # pylint: disable= too-many-return-statements # Mainly for debugging purposes to see what is happening if we got # anything else that does not have the C2R identifier at the start # of the line. - logger.debug("Got a line without the C2R identifier: %s" % line) + logger.debug("Got a line without the C2R identifier: {}".format(line)) # If we don't have any packages, then something went wrong, bail out by default if not packages: @@ -136,7 +136,9 @@ def run(self): # pylint: disable= too-many-return-statements title="Kernel currency check failed", description="Please refer to the diagnosis for further information", diagnosis=( - "Could not find any %s from repositories to compare against the loaded kernel." % package_to_check + "Could not find any {} from repositories to compare against the loaded kernel.".format( + package_to_check + ) ), remediations=( "Please, check if you have any vendor repositories enabled to proceed with the conversion.\n" @@ -153,8 +155,8 @@ def run(self): # pylint: disable= too-many-return-statements loaded_kernel = uname_output.rsplit(".", 1)[0] # append the package name to loaded_kernel and latest_kernel so they can be properly processed by # compare_package_versions() - latest_kernel_pkg = "%s-%s" % (package_to_check, latest_kernel) - loaded_kernel_pkg = "%s-%s" % (package_to_check, loaded_kernel) + latest_kernel_pkg = "{}-{}".format(package_to_check, latest_kernel) + loaded_kernel_pkg = "{}-{}".format(package_to_check, loaded_kernel) try: match = compare_package_versions(latest_kernel_pkg, loaded_kernel_pkg) except ValueError as exc: @@ -175,15 +177,15 @@ def run(self): # pylint: disable= too-many-return-statements description="The loaded kernel version mismatch the latest one available in system repositories", diagnosis=( "The version of the loaded kernel is different from the latest version in system repositories. \n" - " Latest kernel version available in %s: %s\n" - " Loaded kernel version: %s" % (repoid, latest_kernel, loaded_kernel) + " Latest kernel version available in {}: {}\n" + " Loaded kernel version: {}".format(repoid, latest_kernel, loaded_kernel) ), remediations=( "To proceed with the conversion, update the kernel version by executing the following step:\n\n" - "1. yum install %s-%s -y\n" + "1. yum install {}-{} -y\n" "2. reboot\n" "If you wish to ignore this message, set the environment variable " - "'CONVERT2RHEL_SKIP_KERNEL_CURRENCY_CHECK' to 1." % (package_to_check, latest_kernel) + "'CONVERT2RHEL_SKIP_KERNEL_CURRENCY_CHECK' to 1.".format(package_to_check, latest_kernel) ), ) return diff --git a/convert2rhel/actions/system_checks/package_updates.py b/convert2rhel/actions/system_checks/package_updates.py index 8fb9542c45..842b6cc101 100644 --- a/convert2rhel/actions/system_checks/package_updates.py +++ b/convert2rhel/actions/system_checks/package_updates.py @@ -65,7 +65,7 @@ def run(self): package_up_to_date_error_message = ( "There was an error while checking whether the installed packages are up-to-date. Having an updated system is" " an important prerequisite for a successful conversion. Consider verifying the system is up to date manually" - " before proceeding with the conversion. %s" % str(e) + " before proceeding with the conversion. {}".format(str(e)) ) logger.warning(package_up_to_date_error_message) @@ -81,11 +81,12 @@ def run(self): if len(packages_to_update) > 0: package_not_up_to_date_skip = os.environ.get("CONVERT2RHEL_OUTDATED_PACKAGE_CHECK_SKIP", None) package_not_up_to_date_error_message = ( - "The system has %s package(s) not updated based on repositories defined in the system repositories.\n" - "List of packages to update: %s.\n\n" + "The system has {} package(s) not updated based on repositories defined in the system repositories.\n" + "List of packages to update: {}.\n\n" "Not updating the packages may cause the conversion to fail.\n" - "Consider updating the packages before proceeding with the conversion." - % (len(packages_to_update), " ".join(packages_to_update)) + "Consider updating the packages before proceeding with the conversion.".format( + len(packages_to_update), " ".join(packages_to_update) + ) ) if not package_not_up_to_date_skip: logger.warning(package_not_up_to_date_error_message) diff --git a/convert2rhel/actions/system_checks/readonly_mounts.py b/convert2rhel/actions/system_checks/readonly_mounts.py index 3eb59e3886..241d8c67ac 100644 --- a/convert2rhel/actions/system_checks/readonly_mounts.py +++ b/convert2rhel/actions/system_checks/readonly_mounts.py @@ -38,8 +38,8 @@ def readonly_mount_detection(mount_point): if file_mount_point == mount_point: if "ro" in flags: return True - logger.debug("%s mount point is not read-only." % file_mount_point) - logger.info("Read-only %s mount point not detected." % mount_point) + logger.debug("{} mount point is not read-only.".format(file_mount_point)) + logger.info("Read-only {} mount point not detected.".format(mount_point)) return False diff --git a/convert2rhel/actions/system_checks/rhel_compatible_kernel.py b/convert2rhel/actions/system_checks/rhel_compatible_kernel.py index 7b9e82e0f9..bbb819dac0 100644 --- a/convert2rhel/actions/system_checks/rhel_compatible_kernel.py +++ b/convert2rhel/actions/system_checks/rhel_compatible_kernel.py @@ -72,8 +72,9 @@ def run(self): title="Incompatible booted kernel version", description="Please refer to the diagnosis for further information", diagnosis=( - "The booted kernel version is incompatible with the standard RHEL kernel. %s" - % bad_kernel_message + "The booted kernel version is incompatible with the standard RHEL kernel. {}".format( + bad_kernel_message + ) ), remediations=( "To proceed with the conversion, boot into a kernel that is available in the {0} {1} base repository" @@ -87,7 +88,7 @@ def run(self): ), ) return - logger.info("The booted kernel %s is compatible with RHEL." % system_info.booted_kernel) + logger.info("The booted kernel {} is compatible with RHEL.".format(system_info.booted_kernel)) def _bad_kernel_version(kernel_release): @@ -123,7 +124,7 @@ def _bad_kernel_version(kernel_release): def _bad_kernel_package_signature(kernel_release): """Return True if the booted kernel is not signed by the original OS vendor, i.e. it's a custom kernel.""" - vmlinuz_path = "/boot/vmlinuz-%s" % kernel_release + vmlinuz_path = "/boot/vmlinuz-{}".format(kernel_release) kernel_pkg, return_code = run_subprocess(["rpm", "-qf", "--qf", "%{NEVRA}", vmlinuz_path], print_output=False) logger.debug("Booted kernel package name: %s", kernel_pkg) @@ -146,7 +147,7 @@ def _bad_kernel_package_signature(kernel_release): {"os_vendor": os_vendor}, ) - logger.debug("The booted kernel is signed by %s." % os_vendor) + logger.debug("The booted kernel is signed by {}.".format(os_vendor)) return False diff --git a/convert2rhel/applock.py b/convert2rhel/applock.py index 515c730550..cdead1cb09 100644 --- a/convert2rhel/applock.py +++ b/convert2rhel/applock.py @@ -99,7 +99,7 @@ def _try_create(self): if exc.errno == errno.EEXIST: return False raise exc - logger.debug("%s." % self) + logger.debug("{}.".format(self)) return True @property @@ -139,14 +139,14 @@ def try_to_lock(self, _recursive=False): self._locked = True return if _recursive: - raise ApplicationLockedError("Cannot lock %s" % self._name) + raise ApplicationLockedError("Cannot lock {}".format(self._name)) with open(self._pidfile, "r") as f: file_contents = f.read() try: pid = int(file_contents.rstrip()) except ValueError: - raise ApplicationLockedError("Lock file %s is corrupt" % self._pidfile) + raise ApplicationLockedError("Lock file {} is corrupt".format(self._pidfile)) if self._pid_exists(pid): raise ApplicationLockedError("%s locked by process %d" % (self._pidfile, pid)) @@ -167,7 +167,7 @@ def unlock(self): return os.unlink(self._pidfile) self._locked = False - logger.debug("%s." % self) + logger.debug("{}.".format(self)) def __enter__(self): self.try_to_lock() diff --git a/convert2rhel/backup/__init__.py b/convert2rhel/backup/__init__.py index e1b687148c..47776c38aa 100644 --- a/convert2rhel/backup/__init__.py +++ b/convert2rhel/backup/__init__.py @@ -68,7 +68,7 @@ def push(self, restorable): :arg restorable: RestorableChange object that can be restored later. """ if not isinstance(restorable, RestorableChange): - raise TypeError("`%s` is not a RestorableChange object" % restorable) + raise TypeError("`{}` is not a RestorableChange object".format(restorable)) # Check if the restorable is already backed up # if it is, we skip it @@ -129,7 +129,7 @@ def pop_all(self): # logger.critical in some places. except (Exception, SystemExit) as e: # Don't let a failure in one restore influence the others - message = "Error while rolling back a %s: %s" % (restorable.__class__.__name__, str(e)) + message = "Error while rolling back a {}: {}".format(restorable.__class__.__name__, str(e)) logger.warning(message) # Add the rollback failures to the list self._rollback_failures.append(message) diff --git a/convert2rhel/backup/certs.py b/convert2rhel/backup/certs.py index 0dbb894148..97a5551b46 100644 --- a/convert2rhel/backup/certs.py +++ b/convert2rhel/backup/certs.py @@ -54,7 +54,7 @@ def enable(self): if not self.installed: output, ret_code = utils.run_subprocess(["rpm", "--import", self.keyfile], print_output=False) if ret_code != 0: - raise utils.ImportGPGKeyError("Failed to import the GPG key %s: %s" % (self.keyfile, output)) + raise utils.ImportGPGKeyError("Failed to import the GPG key {}: {}".format(self.keyfile, output)) self.previously_installed = False @@ -66,22 +66,22 @@ def enable(self): @property def installed(self): """Whether the GPG key has been imported into the rpmdb.""" - output, status = utils.run_subprocess(["rpm", "-q", "gpg-pubkey-%s" % self.keyid], print_output=False) + output, status = utils.run_subprocess(["rpm", "-q", "gpg-pubkey-{}".format(self.keyid)], print_output=False) if status == 0: return True - if status == 1 and "package gpg-pubkey-%s is not installed" % self.keyid in output: + if status == 1 and "package gpg-pubkey-{} is not installed".format(self.keyid) in output: return False raise utils.ImportGPGKeyError( - "Searching the rpmdb for the gpg key %s failed: Code %s: %s" % (self.keyid, status, output) + "Searching the rpmdb for the gpg key {} failed: Code {}: {}".format(self.keyid, status, output) ) def restore(self): """Ensure the rpmdb has or does not have the GPG key according to the state before we ran.""" if self.enabled and self.previously_installed is False: - utils.run_subprocess(["rpm", "-e", "gpg-pubkey-%s" % self.keyid]) + utils.run_subprocess(["rpm", "-e", "gpg-pubkey-{}".format(self.keyid)]) super(RestorableRpmKey, self).restore() @@ -112,7 +112,7 @@ def enable(self): return if os.path.exists(self._target_cert_path): - logger.info("Certificate already present at %s. Skipping copy." % self._target_cert_path) + logger.info("Certificate already present at {}. Skipping copy.".format(self._target_cert_path)) self.previously_installed = True else: try: @@ -124,11 +124,12 @@ def enable(self): id_="FAILED_TO_INSTALL_CERTIFICATE", title="Failed to install certificate.", description="convert2rhel was unable to install a required certificate. This certificate allows the pre-conversion analysis to verify that packages are legitimate RHEL packages.", - diagnosis="Failed to install certificate %s to %s. Errno: %s, Error: %s" - % (self._get_source_cert_path, self._target_cert_dir, err.errno, err.strerror), + diagnosis="Failed to install certificate {} to {}. Errno: {}, Error: {}".format( + self._get_source_cert_path, self._target_cert_dir, err.errno, err.strerror + ), ) - logger.info("Certificate %s copied to %s." % (self._cert_filename, self._target_cert_dir)) + logger.info("Certificate {} copied to {}.".format(self._cert_filename, self._target_cert_dir)) super(RestorablePEMCert, self).enable() @@ -139,7 +140,7 @@ def restore(self): if self.enabled and not self.previously_installed: self._restore() else: - logger.info("Certificate %s was present before conversion. Skipping removal." % self._cert_filename) + logger.info("Certificate {} was present before conversion. Skipping removal.".format(self._cert_filename)) super(RestorablePEMCert, self).restore() @@ -170,14 +171,16 @@ def _restore(self): if "not owned by any package" in output: file_unowned = True elif "No such file or directory" in output: - logger.info("Certificate already removed from %s" % self._target_cert_path) + logger.info("Certificate already removed from {}".format(self._target_cert_path)) else: logger.warning( - "Unable to determine if a package owns certificate %s. Skipping removal." % self._target_cert_path + "Unable to determine if a package owns certificate {}. Skipping removal.".format( + self._target_cert_path + ) ) else: logger.info( - "A package was installed that owns the certificate %s. Skipping removal." % self._target_cert_path + "A package was installed that owns the certificate {}. Skipping removal.".format(self._target_cert_path) ) # Not safe to remove the certificate because the file might be owned by @@ -187,7 +190,7 @@ def _restore(self): try: os.remove(self._target_cert_path) - logger.info("Certificate %s removed" % self._target_cert_path) + logger.info("Certificate {} removed".format(self._target_cert_path)) except OSError as err: if err.errno == errno.ENOENT: # Resolves RHSM error when removing certs, as the system might not have installed any certs yet @@ -201,12 +204,12 @@ def _restore(self): def _get_cert(cert_dir): """Return the .pem certificate filename.""" if not os.access(cert_dir, os.R_OK | os.X_OK): - logger.critical("Error: Could not access %s." % cert_dir) + logger.critical("Error: Could not access {}.".format(cert_dir)) pem_filename = None for filename in os.listdir(cert_dir): if filename.endswith(".pem"): pem_filename = filename break if not pem_filename: - logger.critical("Error: No certificate (.pem) found in %s." % cert_dir) + logger.critical("Error: No certificate (.pem) found in {}.".format(cert_dir)) return pem_filename diff --git a/convert2rhel/backup/files.py b/convert2rhel/backup/files.py index ca3d6dc262..0b800460e6 100644 --- a/convert2rhel/backup/files.py +++ b/convert2rhel/backup/files.py @@ -53,16 +53,16 @@ def enable(self): if self.enabled: return - logger.info("Backing up %s." % self.filepath) + logger.info("Backing up {}.".format(self.filepath)) if os.path.isfile(self.filepath): try: backup_path = self._hash_backup_path() self.backup_path = backup_path shutil.copy2(self.filepath, backup_path) - logger.debug("Copied %s to %s." % (self.filepath, backup_path)) + logger.debug("Copied {} to {}.".format(self.filepath, backup_path)) except (OSError, IOError) as err: # IOError for py2 and OSError for py3 - logger.critical_no_exit("Error(%s): %s" % (err.errno, err.strerror)) + logger.critical_no_exit("Error({}): {}".format(err.errno, err.strerror)) raise exceptions.CriticalError( id_="FAILED_TO_SAVE_FILE_TO_BACKUP_DIR", title="Failed to copy file to the backup directory.", @@ -72,7 +72,9 @@ def enable(self): "In the current case, we encountered a failure while performing that backup so it is unsafe " "to continue. See the diagnosis section to identify which problem ocurred during the backup." ), - diagnosis="Failed to backup %s. Errno: %s, Error: %s" % (self.filepath, err.errno, err.strerror), + diagnosis="Failed to backup {}. Errno: {}, Error: {}".format( + self.filepath, err.errno, err.strerror + ), ) else: logger.info("Can't find %s.", self.filepath) @@ -120,12 +122,12 @@ def restore(self, rollback=True): :raises IOError: When the backed up file is missing. """ if rollback: - logger.task("Rollback: Restore %s from backup" % self.filepath) + logger.task("Rollback: Restore {} from backup".format(self.filepath)) else: - logger.info("Restoring %s from backup" % self.filepath) + logger.info("Restoring {} from backup".format(self.filepath)) if not self.enabled: - logger.info("%s hasn't been backed up." % self.filepath) + logger.info("{} hasn't been backed up.".format(self.filepath)) return # Possible exceptions will be handled in the BackupController @@ -135,10 +137,10 @@ def restore(self, rollback=True): os.remove(self.backup_path) if rollback: - logger.info("File %s restored." % self.filepath) + logger.info("File {} restored.".format(self.filepath)) super(RestorableFile, self).restore() else: - logger.debug("File %s restored." % self.filepath) + logger.debug("File {} restored.".format(self.filepath)) # not setting enabled to false since this is not being rollback # restoring the backed up file for conversion purposes @@ -146,9 +148,9 @@ def remove(self): """Remove restored file from original place, backup isn't removed""" try: os.remove(self.filepath) - logger.debug("File %s removed." % self.filepath) + logger.debug("File {} removed.".format(self.filepath)) except (OSError, IOError): - logger.debug("Couldn't remove restored file %s" % self.filepath) + logger.debug("Couldn't remove restored file {}".format(self.filepath)) def __eq__(self, value): if hash(self) == hash(value): diff --git a/convert2rhel/backup/packages.py b/convert2rhel/backup/packages.py index f2c96dee10..c683c26248 100644 --- a/convert2rhel/backup/packages.py +++ b/convert2rhel/backup/packages.py @@ -86,11 +86,11 @@ def enable(self): return if not os.path.isdir(BACKUP_DIR): - logger.warning("Can't access %s" % BACKUP_DIR) + logger.warning("Can't access {}".format(BACKUP_DIR)) return - logger.info("Backing up the packages: %s." % ",".join(self.pkgs)) - logger.debug("Using repository files stored in %s." % self.reposdir) + logger.info("Backing up the packages: {}.".format(",".join(self.pkgs))) + logger.debug("Using repository files stored in {}.".format(self.reposdir)) if self.reposdir: # Check if the reposdir exists and if the directory is empty @@ -127,7 +127,7 @@ def restore(self): logger.task("Rollback: Install removed packages") if not self._backedup_pkgs_paths: - logger.warning("Couldn't find a backup for %s package." % ",".join(self.pkgs)) + logger.warning("Couldn't find a backup for {} package.".format(",".join(self.pkgs))) raise exceptions.CriticalError( id_="FAILED_TO_INSTALL_PACKAGES", title="Couldn't find package backup", @@ -135,7 +135,7 @@ def restore(self): "While attempting to roll back changes, we encountered " "an unexpected failure while we cannot find a package backup." ), - diagnosis="Couldn't find a backup for %s package." % utils.format_sequence_as_message(self.pkgs), + diagnosis="Couldn't find a backup for {} package.".format(utils.format_sequence_as_message(self.pkgs)), ) self._install_local_rpms(replace=True, critical=True) @@ -153,7 +153,7 @@ def _install_local_rpms(self, replace=False, critical=True): if replace: cmd.append("--replacepkgs") - logger.info("Installing packages:\t%s" % ", ".join(self.pkgs)) + logger.info("Installing packages:\t{}".format(", ".join(self.pkgs))) for pkg in self._backedup_pkgs_paths: cmd.append(pkg) @@ -162,7 +162,7 @@ def _install_local_rpms(self, replace=False, critical=True): pkgs_as_str = utils.format_sequence_as_message(self.pkgs) logger.debug(output.strip()) if critical: - logger.critical_no_exit("Error: Couldn't install %s packages." % pkgs_as_str) + logger.critical_no_exit("Error: Couldn't install {} packages.".format(pkgs_as_str)) raise exceptions.CriticalError( id_="FAILED_TO_INSTALL_PACKAGES", title="Couldn't install packages.", @@ -176,7 +176,7 @@ def _install_local_rpms(self, replace=False, critical=True): % (pkgs_as_str, cmd, output, ret_code), ) - logger.warning("Couldn't install %s packages." % pkgs_as_str) + logger.warning("Couldn't install {} packages.".format(pkgs_as_str)) return False return True @@ -255,7 +255,7 @@ def _enable(self): formatted_pkgs_sequence = utils.format_sequence_as_message(self.pkgs_to_install) - logger.debug("RPMs scheduled for installation: %s" % formatted_pkgs_sequence) + logger.debug("RPMs scheduled for installation: {}".format(formatted_pkgs_sequence)) output, ret_code = call_yum_cmd( command="install", @@ -273,20 +273,21 @@ def _enable(self): if ret_code: logger.critical_no_exit( - "Failed to install scheduled packages. Check the yum output below for details:\n\n %s" % output + "Failed to install scheduled packages. Check the yum output below for details:\n\n {}".format(output) ) raise exceptions.CriticalError( id_="FAILED_TO_INSTALL_SCHEDULED_PACKAGES", title="Failed to install scheduled packages.", description="convert2rhel was unable to install scheduled packages.", - diagnosis="Failed to install packages %s. Output: %s, Status: %s" - % (formatted_pkgs_sequence, output, ret_code), + diagnosis="Failed to install packages {}. Output: {}, Status: {}".format( + formatted_pkgs_sequence, output, ret_code + ), ) # Need to do this here instead of in pkghandler.call_yum_cmd() to avoid # double printing the output if an error occurred. logger.info(output.rstrip("\n")) - logger.info("\nPackages we installed or updated:\n%s" % formatted_pkgs_sequence) + logger.info("\nPackages we installed or updated:\n{}".format(formatted_pkgs_sequence)) # We could rely on these always being installed/updated when # self.enabled is True but putting the values into separate attributes @@ -300,7 +301,7 @@ def restore(self): return logger.task("Rollback: Remove installed packages") - logger.info("Removing set of installed pkgs: %s" % utils.format_sequence_as_message(self.installed_pkgs)) + logger.info("Removing set of installed pkgs: {}".format(utils.format_sequence_as_message(self.installed_pkgs))) utils.remove_pkgs(self.installed_pkgs, critical=False) super(RestorablePackageSet, self).restore() diff --git a/convert2rhel/backup/subscription.py b/convert2rhel/backup/subscription.py index 92685eb463..945c79b945 100644 --- a/convert2rhel/backup/subscription.py +++ b/convert2rhel/backup/subscription.py @@ -34,7 +34,7 @@ class RestorableSystemSubscription(RestorableChange): """ # We need this __init__ because it is an abstractmethod in the base class - def __init__(self): # pylint: disable=useless-parent-delegation + def __init__(self): super(RestorableSystemSubscription, self).__init__() def enable(self): @@ -124,7 +124,9 @@ def enable(self): if repositories: self._repos_to_enable = repositories - logger.debug("Repositories enabled in the system prior to the conversion: %s" % ",".join(repositories)) + logger.debug( + "Repositories enabled in the system prior to the conversion: {}".format(",".join(repositories)) + ) subscription.disable_repos() super(RestorableDisableRepositories, self).enable() @@ -136,7 +138,7 @@ def restore(self): logger.task("Rollback: Restoring state of the repositories") if self._repos_to_enable: - logger.debug("Repositories to enable: %s" % ",".join(self._repos_to_enable)) + logger.debug("Repositories to enable: {}".format(",".join(self._repos_to_enable))) # This is not the ideal state. We should really have a generic # class for enabling/disabling the repositories we have touched for diff --git a/convert2rhel/breadcrumbs.py b/convert2rhel/breadcrumbs.py index 64e3862821..abcb552a1b 100644 --- a/convert2rhel/breadcrumbs.py +++ b/convert2rhel/breadcrumbs.py @@ -195,7 +195,7 @@ def _save_migration_results(self): def _save_rhsm_facts(self): """Write the results of the breadcrumbs to the rhsm custom facts file.""" if not os.path.exists(RHSM_CUSTOM_FACTS_FOLDER): - logger.debug("No RHSM facts folder found at '%s'. Creating a new one..." % RHSM_CUSTOM_FACTS_FOLDER) + logger.debug("No RHSM facts folder found at '{}'. Creating a new one...".format(RHSM_CUSTOM_FACTS_FOLDER)) # Using mkdir_p here as the `/etc/rhsm` might not exist at all. # Usually this can happen if we fail in the first run and we want to # save the custom facts gathered so far, or, if the `--no-rhsm` option @@ -268,4 +268,4 @@ def _write_obj_to_array_json(path, new_object, key): # Code to be executed upon module import -breadcrumbs = Breadcrumbs() # pylint: disable=C0103 +breadcrumbs = Breadcrumbs() diff --git a/convert2rhel/cli.py b/convert2rhel/cli.py index 8460181291..a4e83439ac 100644 --- a/convert2rhel/cli.py +++ b/convert2rhel/cli.py @@ -130,12 +130,13 @@ def _register_options(self): action="store_true", help="Skip gathering changed rpm files using" " 'rpm -Va'. By default it's performed before and after the conversion with the output" - " stored in log files %s and %s. At the end of the conversion, these logs are compared" + " stored in log files {} and {}. At the end of the conversion, these logs are compared" " to show you what rpm files have been affected by the conversion." " Cannot be used with analyze subcommand." " The environment variable CONVERT2RHEL_INCOMPLETE_ROLLBACK" - " needs to be set to 1 to use this argument." - % (utils.rpm.PRE_RPM_VA_LOG_FILENAME, utils.rpm.POST_RPM_VA_LOG_FILENAME), + " needs to be set to 1 to use this argument.".format( + utils.rpm.PRE_RPM_VA_LOG_FILENAME, utils.rpm.POST_RPM_VA_LOG_FILENAME + ), ) self._shared_options_parser.add_argument( "--eus", @@ -316,7 +317,7 @@ def _subcommand_used(args): if argument in ("convert", "analyze"): return argument - if not argument in PARENT_ARGS and args[index - 1] in ARGS_WITH_VALUES: + if argument not in PARENT_ARGS and args[index - 1] in ARGS_WITH_VALUES: return None return None diff --git a/convert2rhel/exceptions.py b/convert2rhel/exceptions.py index 09c2a29d04..426d224f57 100644 --- a/convert2rhel/exceptions.py +++ b/convert2rhel/exceptions.py @@ -50,7 +50,7 @@ def __init__(self, id_=None, title=None, description=None, diagnosis=None, remed self.variables = variables or {} def __repr__(self): - return "%s(%r, %r, description=%r, diagnosis=%r, remediations=%r, variables=%r)" % ( + return "{}({!r}, {!r}, description={!r}, diagnosis={!r}, remediations={!r}, variables={!r})".format( self.__class__.__name__, self.id, self.title, diff --git a/convert2rhel/grub.py b/convert2rhel/grub.py index 9d0cef4f31..11c3ed037c 100644 --- a/convert2rhel/grub.py +++ b/convert2rhel/grub.py @@ -105,8 +105,8 @@ def _get_partition(directory): """ stdout, ecode = utils.run_subprocess(["/usr/sbin/grub2-probe", "--target=device", directory], print_output=False) if ecode or not stdout: - logger.error("grub2-probe returned %s. Output:\n%s" % (ecode, stdout)) - raise BootloaderError("Unable to get device information for %s." % directory) + logger.error("grub2-probe returned {}. Output:\n{}".format(ecode, stdout)) + raise BootloaderError("Unable to get device information for {}.".format(directory)) return stdout.strip() @@ -146,8 +146,8 @@ def _get_blk_device(device): """ output, ecode = utils.run_subprocess(["lsblk", "-spnlo", "name", device], print_output=False) if ecode: - logger.debug("lsblk output:\n-----\n%s\n-----" % output) - raise BootloaderError("Unable to get a block device for '%s'." % device) + logger.debug("lsblk output:\n-----\n{}\n-----".format(output)) + raise BootloaderError("Unable to get a block device for '{}'.".format(device)) return output.strip().splitlines()[-1].strip() @@ -168,12 +168,12 @@ def get_device_number(device): ) output = output.strip() if ecode: - logger.debug("blkid output:\n-----\n%s\n-----" % output) - raise BootloaderError("Unable to get information about the '%s' device" % device) + logger.debug("blkid output:\n-----\n{}\n-----".format(output)) + raise BootloaderError("Unable to get information about the '{}' device".format(device)) # We are spliting the partition entry number, and we are just taking that # output as our desired partition number if not output: - raise BootloaderError("The '%s' device has no PART_ENTRY_NUMBER" % device) + raise BootloaderError("The '{}' device has no PART_ENTRY_NUMBER".format(device)) partition_number = output.split("PART_ENTRY_NUMBER=")[-1].replace('"', "") return int(partition_number) @@ -314,10 +314,10 @@ def _parse_boot_order(self, bootmgr_output): def _print_loaded_info(self): msg = "Bootloader setup:" - msg += "\nCurrent boot: %s" % self.current_bootnum - msg += "\nBoot order: %s\nBoot entries:" % ", ".join(self.boot_order) + msg += "\nCurrent boot: {}".format(self.current_bootnum) + msg += "\nBoot order: {}\nBoot entries:".format(", ".join(self.boot_order)) for bootnum, entry in self.entries.items(): - msg += "\n- %s: %s" % (bootnum, entry.label.rstrip()) + msg += "\n- {}: {}".format(bootnum, entry.label.rstrip()) logger.debug(msg) @@ -357,24 +357,24 @@ def _add_rhel_boot_entry(efibootinfo_orig): dev_number = get_device_number(get_efi_partition()) blk_dev = get_grub_device() - logger.debug("Block device: %s" % str(blk_dev)) - logger.debug("ESP device number: %s" % str(dev_number)) + logger.debug("Block device: {}".format(str(blk_dev))) + logger.debug("ESP device number: {}".format(str(dev_number))) efi_path = None for filename in DEFAULT_INSTALLED_EFIBIN_FILENAMES: tmp_efi_path = os.path.join(RHEL_EFIDIR_CANONICAL_PATH, filename) if os.path.exists(tmp_efi_path): efi_path = canonical_path_to_efi_format(tmp_efi_path) - logger.debug("The new UEFI binary: %s" % tmp_efi_path) + logger.debug("The new UEFI binary: {}".format(tmp_efi_path)) break if not efi_path: raise BootloaderError("Unable to detect any RHEL UEFI binary file.") - label = "Red Hat Enterprise Linux %s" % str(systeminfo.system_info.version.major) - logger.info("Adding '%s' UEFI bootloader entry." % label) + label = "Red Hat Enterprise Linux {}".format(str(systeminfo.system_info.version.major)) + logger.info("Adding '{}' UEFI bootloader entry.".format(label)) if _is_rhel_in_boot_entries(efibootinfo_orig, efi_path, label): - logger.info("The '%s' UEFI bootloader entry is already present." % label) + logger.info("The '{}' UEFI bootloader entry is already present.".format(label)) return efibootinfo_orig # The new boot entry is being set as first in the boot order @@ -393,7 +393,7 @@ def _add_rhel_boot_entry(efibootinfo_orig): stdout, ecode = utils.run_subprocess(cmd, print_output=False) if ecode: - logger.debug("efibootmgr output:\n-----\n%s\n-----" % stdout) + logger.debug("efibootmgr output:\n-----\n{}\n-----".format(stdout)) raise BootloaderError("Unable to add a new UEFI bootloader entry for RHEL.") # check that our new entry exists @@ -402,7 +402,7 @@ def _add_rhel_boot_entry(efibootinfo_orig): if not _is_rhel_in_boot_entries(efibootinfo_new, efi_path, label): raise BootloaderError("Unable to find the new UEFI bootloader entry.") - logger.info("The '%s' bootloader entry has been added." % label) + logger.info("The '{}' bootloader entry has been added.".format(label)) return efibootinfo_new @@ -423,23 +423,25 @@ def _remove_orig_boot_entry(efibootinfo_orig, efibootinfo_new): orig_boot_entry = efibootinfo_new.entries.get(efibootinfo_orig.current_bootnum, None) if not orig_boot_entry: logger.info( - "The original, currenly used bootloader entry '%s' (%s) has been removed already." - % (efibootinfo_orig.current_bootnum, efibootinfo_orig.entries[efibootinfo_orig.current_bootnum].label) + "The original, currenly used bootloader entry '{}' ({}) has been removed already.".format( + efibootinfo_orig.current_bootnum, efibootinfo_orig.entries[efibootinfo_orig.current_bootnum].label + ) ) return if orig_boot_entry != efibootinfo_orig.entries[orig_boot_entry.boot_number]: logger.warning( - "The original, currenly used bootloader entry '%s' (%s) has been modified. Skipping the removal." - % (orig_boot_entry.boot_number, orig_boot_entry.label) + "The original, currenly used bootloader entry '{}' ({}) has been modified. Skipping the removal.".format( + orig_boot_entry.boot_number, orig_boot_entry.label + ) ) return efibin_path_orig = orig_boot_entry.get_canonical_path() if not efibin_path_orig: logger.warning( - "Skipping the removal of the original, currenly used bootloader entry '%s' (%s):" - " Unable to get path of its UEFI binary file." % (orig_boot_entry.boot_number, orig_boot_entry.label) + "Skipping the removal of the original, currenly used bootloader entry '{}' ({}):" + " Unable to get path of its UEFI binary file.".format(orig_boot_entry.boot_number, orig_boot_entry.label) ) return @@ -447,9 +449,10 @@ def _remove_orig_boot_entry(efibootinfo_orig, efibootinfo_new): efibin_path_new = efibootinfo_new.entries[efibootinfo_new.boot_order[0]].get_canonical_path() if os.path.exists(efibin_path_orig) and efibin_path_orig != efibin_path_new: logger.warning( - "Skipping the removal of the original, currenly used bootloader entry '%s' (%s):" - " Its UEFI binary file still exists: %s" - % (orig_boot_entry.boot_number, orig_boot_entry.label, efibin_path_orig) + "Skipping the removal of the original, currenly used bootloader entry '{}' ({}):" + " Its UEFI binary file still exists: {}".format( + orig_boot_entry.boot_number, orig_boot_entry.label, efibin_path_orig + ) ) return _, ecode = utils.run_subprocess(["/usr/sbin/efibootmgr", "-Bb", orig_boot_entry.boot_number], print_output=False) @@ -459,8 +462,9 @@ def _remove_orig_boot_entry(efibootinfo_orig, efibootinfo_new): logger.warning("The removal of the original, currenly used UEFI bootloader entry has failed.") return logger.info( - "The removal of the original, currenly used UEFI bootloader entry '%s' (%s) has been successful." - % (orig_boot_entry.boot_number, orig_boot_entry.label) + "The removal of the original, currenly used UEFI bootloader entry '{}' ({}) has been successful.".format( + orig_boot_entry.boot_number, orig_boot_entry.label + ) ) @@ -506,12 +510,12 @@ def get_grub_config_file(): def _log_critical_error(title): logger.critical( - "%s\n" + "{}\n" "The migration of the bootloader setup was not successful.\n" "Do not reboot your machine before doing a manual check of the\n" "bootloader configuration. Ensure that grubenv and grub.cfg files\n" - "are present in the %s directory and that\n" + "are present in the {} directory and that\n" "a new bootloader entry for Red Hat Enterprise Linux exists\n" "(check `efibootmgr -v` output).\n" - "The entry should point to '\\EFI\\redhat\\shimx64.efi'." % (title, RHEL_EFIDIR_CANONICAL_PATH) + "The entry should point to '\\EFI\\redhat\\shimx64.efi'.".format(title, RHEL_EFIDIR_CANONICAL_PATH) ) diff --git a/convert2rhel/logger.py b/convert2rhel/logger.py index 2f3859ca2e..2ea1b6d01a 100644 --- a/convert2rhel/logger.py +++ b/convert2rhel/logger.py @@ -17,6 +17,16 @@ __metaclass__ = type + +import logging +import os +import shutil +import sys + +from logging.handlers import BufferingHandler +from time import gmtime, strftime + + """ Customized logging functionality @@ -30,14 +40,6 @@ FILE (10) CUSTOM LABEL - Outputs with the DEBUG label but only to a file """ -import logging -import os -import shutil -import sys - -from logging.handlers import BufferingHandler -from time import gmtime, strftime - LOG_DIR = "/var/log/convert2rhel" @@ -171,7 +173,7 @@ def should_disable_color_output(): """ if "NO_COLOR" in os.environ: NO_COLOR = os.environ["NO_COLOR"] - return NO_COLOR != None and NO_COLOR != "0" and NO_COLOR.lower() != "false" + return NO_COLOR is not None and NO_COLOR != "0" and NO_COLOR.lower() != "false" return False @@ -211,7 +213,7 @@ def archive_old_logger_files(log_name, log_dir): os.makedirs(archive_log_dir) file_name, suffix = tuple(log_name.rsplit(".", 1)) - archive_log_file = "%s/%s-%s.%s" % (archive_log_dir, file_name, formatted_time, suffix) + archive_log_file = "{}/{}-{}.{}".format(archive_log_dir, file_name, formatted_time, suffix) shutil.move(current_log_file, archive_log_file) diff --git a/convert2rhel/main.py b/convert2rhel/main.py index c62a266900..39f855b2cc 100644 --- a/convert2rhel/main.py +++ b/convert2rhel/main.py @@ -65,6 +65,7 @@ class ConversionPhase: ), } + # Track the exit codes for different scenarios during the conversion. class ConversionExitCodes: # No errors detected during the conversion @@ -96,7 +97,7 @@ def initialize_file_logging(log_name, log_dir): try: logger_module.archive_old_logger_files(log_name, log_dir) except (IOError, OSError) as e: - loggerinst.warning("Unable to archive previous log: %s" % e) + loggerinst.warning("Unable to archive previous log: {}".format(e)) logger_module.add_file_handler(log_name, log_dir) @@ -210,7 +211,7 @@ def main_locked(): loggerinst.critical_no_exit(err.diagnosis) results = _pick_conversion_results(process_phase, pre_conversion_results, post_conversion_results) return _handle_main_exceptions(process_phase, results) - except (Exception, SystemExit, KeyboardInterrupt) as err: + except (Exception, SystemExit, KeyboardInterrupt): results = _pick_conversion_results(process_phase, pre_conversion_results, post_conversion_results) return _handle_main_exceptions(process_phase, results) finally: @@ -394,7 +395,7 @@ def provide_status_after_rollback(pre_conversion_results, include_all_reports): "It is strongly recommended to store the Convert2RHEL logs for later investigation, and restore" " the system from a backup.\n" "Following errors were captured during rollback:\n" - "%s" % "\n".join(backup.backup_control.rollback_failures) + "{}".format("\n".join(backup.backup_control.rollback_failures)) ) return diff --git a/convert2rhel/pkghandler.py b/convert2rhel/pkghandler.py index 111ae6ca91..89f6785e02 100644 --- a/convert2rhel/pkghandler.py +++ b/convert2rhel/pkghandler.py @@ -114,7 +114,7 @@ def get_installed_pkgs_by_key_id(key_ids, name=""): # architecture to make sure both of them will be passed to dnf and, if # possible, converted. This issue does not happen on yum, so we can still # use only the package name for it. - return ["%s.%s" % (pkg.nevra.name, pkg.nevra.arch) for pkg in pkgs_w_key_ids if pkg.key_id in key_ids] + return ["{}.{}".format(pkg.nevra.name, pkg.nevra.arch) for pkg in pkgs_w_key_ids if pkg.key_id in key_ids] def _get_pkg_key_id(signature): @@ -196,7 +196,7 @@ def get_rpm_header(pkg_obj): return rpm_hdr # Package not found in the rpm db - logger.critical("Unable to find package '%s' in the rpm database." % pkg_obj.name) + logger.critical("Unable to find package '{}' in the rpm database.".format(pkg_obj.name)) def get_installed_pkg_objects(name=None, version=None, release=None, arch=None): @@ -217,13 +217,13 @@ def _get_installed_pkg_objects_yum(name=None, version=None, release=None, arch=N if name: pattern = name if version: - pattern += "-%s" % version + pattern += "-{}".format(version) if release: - pattern += "-%s" % release + pattern += "-{}".format(release) if arch: - pattern += ".%s" % arch + pattern += ".{}".format(arch) return yum_base.rpmdb.returnPackages(patterns=[pattern]) @@ -465,7 +465,7 @@ def get_pkg_nvra(pkg_obj): :rtype: str """ nevra = _get_nevra_from_pkg_obj(pkg_obj) - return "%s-%s-%s.%s" % ( + return "{}-{}-{}.{}".format( nevra.name, nevra.version, nevra.release, @@ -493,7 +493,7 @@ def get_pkg_nevra(pkg_obj, include_zero_epoch=False): nevra = _get_nevra_from_pkg_obj(pkg_obj) epoch = "" if str(nevra.epoch) == "0" and not include_zero_epoch else str(nevra.epoch) + ":" if pkgmanager.TYPE == "yum": - return "%s%s-%s-%s.%s" % ( + return "{}{}-{}-{}.{}".format( epoch, nevra.name, nevra.version, @@ -501,7 +501,7 @@ def get_pkg_nevra(pkg_obj, include_zero_epoch=False): nevra.arch, ) - return "%s-%s%s-%s.%s" % ( + return "{}-{}{}-{}.{}".format( nevra.name, epoch, nevra.version, @@ -559,7 +559,7 @@ def get_packages_to_remove(pkgs): temp = "." * (50 - len(pkg) - 2) pkg_objects = get_installed_pkgs_w_different_key_id(system_info.key_ids_rhel, pkg) pkgs_to_remove.extend(pkg_objects) - logger.info("%s %s %s" % (pkg, temp, str(len(pkg_objects)))) + logger.info("{} {} {}".format(pkg, temp, str(len(pkg_objects)))) return pkgs_to_remove @@ -576,7 +576,7 @@ def get_system_packages_for_replacement(): key_ids = system_info.key_ids_orig_os packages_with_key_ids = get_installed_pkg_information() - return ["%s.%s" % (pkg.nevra.name, pkg.nevra.arch) for pkg in packages_with_key_ids if pkg.key_id in key_ids] + return ["{}.{}".format(pkg.nevra.name, pkg.nevra.arch) for pkg in packages_with_key_ids if pkg.key_id in key_ids] def install_gpg_keys(): @@ -588,7 +588,7 @@ def install_gpg_keys(): restorable_key = RestorableRpmKey(gpg_key) backup.backup_control.push(restorable_key) except utils.ImportGPGKeyError as e: - logger.critical("Importing the GPG key into rpm failed:\n %s" % str(e)) + logger.critical("Importing the GPG key into rpm failed:\n {}".format(str(e))) logger.info("GPG key %s imported successfuly.", gpg_key) @@ -607,15 +607,15 @@ def handle_no_newer_rhel_kernel_available(): # of them - the one that has the same version as the available RHEL # kernel older = available[-1] - utils.remove_pkgs(pkgs_to_remove=["kernel-%s" % older]) - pkgmanager.call_yum_cmd(command="install", args=["kernel-%s" % older]) + utils.remove_pkgs(pkgs_to_remove=["kernel-{}".format(older)]) + pkgmanager.call_yum_cmd(command="install", args=["kernel-{}".format(older)]) else: replace_non_rhel_installed_kernel(installed[0]) return # Install the latest out of the available non-clashing RHEL kernels - pkgmanager.call_yum_cmd(command="install", args=["kernel-%s" % to_install[-1]]) + pkgmanager.call_yum_cmd(command="install", args=["kernel-{}".format(to_install[-1])]) def get_kernel_availability(): @@ -645,7 +645,7 @@ def replace_non_rhel_installed_kernel(version): ) utils.ask_to_continue() - pkg = "kernel-%s" % version + pkg = "kernel-{}".format(version) # For downloading the RHEL kernel we need to use the RHEL repositories. repos_to_enable = system_info.get_enabled_rhel_repos() @@ -658,7 +658,7 @@ def replace_non_rhel_installed_kernel(version): if not path: logger.critical("Unable to download the RHEL kernel package.") - logger.info("Replacing %s %s with RHEL kernel with the same NEVRA ... " % (system_info.name, pkg)) + logger.info("Replacing {} {} with RHEL kernel with the same NEVRA ... ".format(system_info.name, pkg)) output, ret_code = utils.run_subprocess( # The --nodeps is needed as some kernels depend on system-release (alias for redhat-release) and that package # is not installed at this stage. @@ -668,14 +668,14 @@ def replace_non_rhel_installed_kernel(version): "--force", "--nodeps", "--replacepkgs", - "%s*" % os.path.join(utils.TMP_DIR, pkg), + "{}*".format(os.path.join(utils.TMP_DIR, pkg)), ], print_output=False, ) if ret_code != 0: - logger.critical("Unable to replace the kernel package: %s" % output) + logger.critical("Unable to replace the kernel package: {}".format(output)) - logger.info("\nRHEL %s installed.\n" % pkg) + logger.info("\nRHEL {} installed.\n".format(pkg)) def update_rhel_kernel(): @@ -758,8 +758,8 @@ def _get_packages_to_update_yum(disable_repos=None): base = pkgmanager.YumBase() # Disable rhel repos during checks if system is up-to-date - for repo in disable_repos: - base.repos.disableRepo(repo) + for repo_to_disable in disable_repos: + base.repos.disableRepo(repo_to_disable) packages = base.doPackageLists(pkgnarrow="updates") for package in packages.updates: @@ -848,15 +848,17 @@ def compare_package_versions(version1, version2): # ensure package names match, error if not if version1_components[0] != version2_components[0]: raise ValueError( - "The package names ('%s' and '%s') do not match. Can only compare versions for the same packages." - % (version1_components[0], version2_components[0]) + "The package names ('{}' and '{}') do not match. Can only compare versions for the same packages.".format( + version1_components[0], version2_components[0] + ) ) # ensure package arches match, error if not if version1_components[4] != version2_components[4] and all(([version1_components[4]], version2_components[4])): raise ValueError( - "The arches ('%s' and '%s') do not match. Can only compare versions for the same arches. There is an architecture mismatch likely due to incorrectly defined repositories on the system." - % (version1_components[4], version2_components[4]) + "The arches ('{}' and '{}') do not match. Can only compare versions for the same arches. There is an architecture mismatch likely due to incorrectly defined repositories on the system.".format( + version1_components[4], version2_components[4] + ) ) # create list containing EVR for comparison @@ -911,18 +913,18 @@ def _validate_parsed_fields(package, name, epoch, version, release, arch): seperators = 4 if name is None or not PKG_NAME.match(name): - errors.append("name : %s" % name if name else "name : [None]") + errors.append("name : {}".format(name) if name else "name : [None]") if epoch is not None and not PKG_EPOCH.match(epoch): - errors.append("epoch : %s" % epoch) + errors.append("epoch : {}".format(epoch)) if version is None or not PKG_VERSION.match(version): - errors.append("version : %s" % version if version else "version : [None]") + errors.append("version : {}".format(version) if version else "version : [None]") if release is None or not PKG_RELEASE.match(release): - errors.append("release : %s" % release if release else "release : [None]") + errors.append("release : {}".format(release) if release else "release : [None]") if arch is not None and arch not in PKG_ARCH: - errors.append("arch : %s" % arch) + errors.append("arch : {}".format(arch)) if errors: - raise ValueError("The following field(s) are invalid - %s" % ", ".join(errors)) + raise ValueError("The following field(s) are invalid - {}".format(", ".join(errors))) pkg_fields = [name, epoch, version, release, arch] # this loop determines the number of separators required for each package type. The separators @@ -940,8 +942,8 @@ def _validate_parsed_fields(package, name, epoch, version, release, arch): parsed_pkg_length = len("".join(pkg_fields)) + seperators if pkg_length != parsed_pkg_length: raise ValueError( - "Invalid package - %s, packages need to be in one of the following formats: NEVRA, NEVR, NVRA, NVR, ENVRA, ENVR." - " Reason: The total length of the parsed package fields does not equal the package length," % package + "Invalid package - {}, packages need to be in one of the following formats: NEVRA, NEVR, NVRA, NVR, ENVRA, ENVR." + " Reason: The total length of the parsed package fields does not equal the package length,".format(package) ) @@ -975,7 +977,7 @@ def _parse_pkg_with_yum(pkg): if arch not in PKG_ARCH: temp_release = arch arch = None - release = "%s.%s" % (release, temp_release) + release = "{}.{}".format(release, temp_release) # convert any empty strings to None for consistency pkg_ver_components = tuple((i or None) for i in (name, epoch, version, release, arch)) @@ -1009,7 +1011,6 @@ def _parse_pkg_with_dnf(pkg): # loop through each possible set of nevra fields and select the valid one for nevra in possible_nevra: - # current arch is valid if str(nevra.arch) in PKG_ARCH: name = nevra.name @@ -1026,13 +1027,12 @@ def _parse_pkg_with_dnf(pkg): # arch is not valid, move on to next iteration else: # This else goes with the for loop - # if no_arch_data is still None by this point, the parser wasn't able to find valid fields # therefore the package entered is invalid and/or in the wrong format if no_arch_data is None: raise ValueError( - "Invalid package - %s, packages need to be in one of the following" - " formats: NEVRA, NEVR, NVRA, NVR, ENVRA, ENVR." % pkg + "Invalid package - {}, packages need to be in one of the following" + " formats: NEVRA, NEVR, NVRA, NVR, ENVRA, ENVR.".format(pkg) ) name = no_arch_data.name @@ -1062,7 +1062,7 @@ def get_highest_package_version(pkgs): name, nevra_list = pkgs if not nevra_list: - logger.debug("The list of %s packages is empty." % name) + logger.debug("The list of {} packages is empty.".format(name)) raise ValueError highest_version = nevra_list[0] diff --git a/convert2rhel/pkgmanager/__init__.py b/convert2rhel/pkgmanager/__init__.py index 0d9e93011b..2e492e2b0a 100644 --- a/convert2rhel/pkgmanager/__init__.py +++ b/convert2rhel/pkgmanager/__init__.py @@ -30,29 +30,28 @@ try: # this is used in pkghandler.py to parse version strings in the _parse_pkg_with_yum function - from rpmUtils.miscutils import splitFilename - from yum import * - from yum.callbacks import DownloadBaseCallback as DownloadProgress + from rpmUtils.miscutils import splitFilename # type: ignore # noqa: F401 + from yu import * # type: ignore # noqa: F403 + from yum.callbacks import DownloadBaseCallback as DownloadProgress # type: ignore # This is added here to prevent a generic try-except in the # `check_package_updates()` function. - from yum.Errors import RepoError - from yum.rpmtrans import SimpleCliCallBack as TransactionDisplay + from yum.Errors import RepoError # type: ignore + from yum.rpmtrans import SimpleCliCallBack as TransactionDisplay # type: ignore TYPE = "yum" # WARNING: if there is a bug in the yum import section, we might try to import dnf incorrectly -except ImportError as e: +except ImportError: + import hawkey # noqa: F401 - import hawkey - - from dnf import * # pylint: disable=import-error - from dnf.callback import Depsolve, DownloadProgress + from dnf import * # noqa: F403 + from dnf.callback import Depsolve, DownloadProgress # noqa: F401 # This is added here to prevent a generic try-except in the # `check_package_updates()` function. - from dnf.exceptions import RepoError - from dnf.yum.rpmtrans import TransactionDisplay + from dnf.exceptions import RepoError # noqa: F401 + from dnf.yum.rpmtrans import TransactionDisplay # noqa: F401 TYPE = "dnf" @@ -99,10 +98,10 @@ def clean_yum_metadata(): output, ret_code = utils.run_subprocess( ("yum", "clean", "metadata", "--enablerepo=*", "--quiet"), print_output=False ) - logger.debug("Output of yum clean metadata:\n%s" % output) + logger.debug("Output of yum clean metadata:\n{}".format(output)) if ret_code != 0: - logger.warning("Failed to clean yum metadata:\n%s" % output) + logger.warning("Failed to clean yum metadata:\n{}".format(output)) return logger.info("Cached repositories metadata cleaned successfully.") @@ -222,16 +221,16 @@ def call_yum_cmd( repos_to_disable = tool_opts.disablerepo for repo in repos_to_disable: - cmd.append("--disablerepo=%s" % repo) + cmd.append("--disablerepo={}".format(repo)) if set_releasever: if not custom_releasever and not system_info.releasever: raise AssertionError("custom_releasever or system_info.releasever must be set.") if custom_releasever: - cmd.append("--releasever=%s" % custom_releasever) + cmd.append("--releasever={}".format(custom_releasever)) else: - cmd.append("--releasever=%s" % system_info.releasever) + cmd.append("--releasever={}".format(system_info.releasever)) # Without the release package installed, dnf can't determine the modularity platform ID. if system_info.version.major >= 8: @@ -246,10 +245,10 @@ def call_yum_cmd( repos_to_enable = system_info.get_enabled_rhel_repos() for repo in repos_to_enable: - cmd.append("--enablerepo=%s" % repo) + cmd.append("--enablerepo={}".format(repo)) if setopts: - opts = ["--setopt=%s" % opt for opt in setopts] + opts = ["--setopt={}".format(opt) for opt in setopts] cmd.extend(opts) cmd.extend(args) diff --git a/convert2rhel/pkgmanager/handlers/dnf/__init__.py b/convert2rhel/pkgmanager/handlers/dnf/__init__.py index 6154a3100a..1651f3aa3a 100644 --- a/convert2rhel/pkgmanager/handlers/dnf/__init__.py +++ b/convert2rhel/pkgmanager/handlers/dnf/__init__.py @@ -96,7 +96,7 @@ def _enable_repos(self): self._base.read_all_repos() repos = self._base.repos.all() enabled_repos = system_info.get_enabled_rhel_repos() - logger.info("Enabling RHEL repositories:\n%s" % "\n".join(enabled_repos)) + logger.info("Enabling RHEL repositories:\n{}".format("\n".join(enabled_repos))) try: for repo in repos: # Disable the repositories that we don't want if the `repo.id` @@ -107,13 +107,13 @@ def _enable_repos(self): # Load metadata of the enabled repositories self._base.fill_sack() except pkgmanager.exceptions.RepoError as e: - logger.debug("Loading repository metadata failed: %s" % e) + logger.debug("Loading repository metadata failed: {}".format(e)) logger.critical_no_exit("Failed to populate repository metadata.") raise exceptions.CriticalError( id_="FAILED_TO_ENABLE_REPOS", title="Failed to enable repositories.", description="We've encountered a failure when accessing repository metadata.", - diagnosis="Loading repository metadata failed with error %s." % (str(e)), + diagnosis="Loading repository metadata failed with error {}.".format(str(e)), ) def _swap_base_os_specific_packages(self): @@ -127,10 +127,10 @@ def _swap_base_os_specific_packages(self): # Related issue: https://issues.redhat.com/browse/RHELC-1130, see comments # to get more proper description of solution for old_package, new_package in system_info.swap_pkgs.items(): - logger.debug("Checking if %s installed for later swap." % old_package) + logger.debug("Checking if {} installed for later swap.".format(old_package)) is_installed = system_info.is_rpm_installed(old_package) if is_installed: - logger.debug("Package %s will be swapped to %s during conversion." % (old_package, new_package)) + logger.debug("Package {} will be swapped to {} during conversion.".format(old_package, new_package)) # Order of commands based on DNF implementation of swap, different from YUM order: # https://github.com/rpm-software-management/dnf/blob/master/dnf/cli/commands/swap.py#L60 self._base.install(pkg_spec=new_package) @@ -187,26 +187,26 @@ def _resolve_dependencies(self): try: self._base.resolve(allow_erasing=True) except pkgmanager.exceptions.DepsolveError as e: - logger.debug("Got the following exception message: %s" % e) + logger.debug("Got the following exception message: {}".format(e)) logger.critical_no_exit("Failed to resolve dependencies in the transaction.") raise exceptions.CriticalError( id_="FAILED_TO_RESOLVE_DEPENDENCIES", title="Failed to resolve dependencies.", description="During package transaction dnf failed to resolve the necessary dependencies needed for a package replacement.", - diagnosis="Resolve dependencies failed with error %s." % (str(e)), + diagnosis="Resolve dependencies failed with error {}.".format(str(e)), ) logger.info("Downloading the packages that were added to the dnf transaction set.") try: self._base.download_packages(self._base.transaction.install_set, PackageDownloadCallback()) except pkgmanager.exceptions.DownloadError as e: - logger.debug("Got the following exception message: %s" % e) + logger.debug("Got the following exception message: {}".format(e)) logger.critical_no_exit("Failed to download the transaction packages.") raise exceptions.CriticalError( id_="FAILED_TO_DOWNLOAD_TRANSACTION_PACKAGES", title="Failed to download packages in the transaction.", description="During package transaction dnf failed to download the necessary packages needed for the transaction.", - diagnosis="Package download failed with error %s." % (str(e)), + diagnosis="Package download failed with error {}.".format(str(e)), ) def _process_transaction(self, validate_transaction): @@ -222,7 +222,7 @@ def _process_transaction(self, validate_transaction): logger.info("Validating the dnf transaction set, no modifications to the system will happen this time.") self._base.conf.tsflags.append("test") else: - logger.info("Replacing %s packages. This process may take some time to finish." % system_info.name) + logger.info("Replacing {} packages. This process may take some time to finish.".format(system_info.name)) try: self._base.do_transaction(display=TransactionDisplayCallback()) @@ -236,7 +236,7 @@ def _process_transaction(self, validate_transaction): id_="FAILED_TO_VALIDATE_TRANSACTION", title="Failed to validate dnf transaction.", description="During the dnf transaction execution an error occured and convert2rhel could no longer process the transaction.", - diagnosis="Transaction processing failed with error: %s" % str(e), + diagnosis="Transaction processing failed with error: {}".format(str(e)), ) if validate_transaction: diff --git a/convert2rhel/pkgmanager/handlers/dnf/callback.py b/convert2rhel/pkgmanager/handlers/dnf/callback.py index 6a648ee533..0155a409d1 100644 --- a/convert2rhel/pkgmanager/handlers/dnf/callback.py +++ b/convert2rhel/pkgmanager/handlers/dnf/callback.py @@ -101,7 +101,7 @@ def pkg_added(self, pkg, mode): message = self._DEPSOLVE_MODES[mode] except KeyError: message = None - logger.debug("Unknown operation (%s) for package '%s'." % (mode, pkg)) + logger.debug("Unknown operation ({}) for package '{}'.".format(mode, pkg)) if message: logger.info(message, pkg) @@ -204,7 +204,7 @@ def end(self, payload, status, err_msg): self.total_drpm, package, ) - message = "%s - %s" % (message, err_msg) + message = "{} - {}".format(message, err_msg) else: message = "(%d/%d) [%s]: %s" % ( self.done_files, @@ -259,7 +259,7 @@ def progress(self, package, action, ti_done, ti_total, ts_done, ts_total): # different. package = str(package) - message = "%s: %s [%s/%s]" % (pkgmanager.transaction.ACTIONS.get(action), package, ts_done, ts_total) + message = "{}: {} [{}/{}]".format(pkgmanager.transaction.ACTIONS.get(action), package, ts_done, ts_total) # The base API will call this callback class on every package update, # no matter if it is the same update or not, so, the below statement diff --git a/convert2rhel/pkgmanager/handlers/yum/__init__.py b/convert2rhel/pkgmanager/handlers/yum/__init__.py index 6ace2d710b..5449e7c139 100644 --- a/convert2rhel/pkgmanager/handlers/yum/__init__.py +++ b/convert2rhel/pkgmanager/handlers/yum/__init__.py @@ -56,7 +56,7 @@ def _resolve_yum_problematic_dependencies(output): """ packages_to_remove = [] if output: - logger.debug("Dependency resolution failed:\n- %s" % "\n- ".join(output)) + logger.debug("Dependency resolution failed:\n- {}".format("\n- ".join(output))) else: logger.debug("Dependency resolution failed with no detailed message reported by yum.") @@ -159,18 +159,18 @@ def _enable_repos(self): # Set the download progress display self._base.repos.setProgressBar(PackageDownloadCallback()) enabled_repos = system_info.get_enabled_rhel_repos() - logger.info("Enabling RHEL repositories:\n%s" % "\n".join(enabled_repos)) + logger.info("Enabling RHEL repositories:\n{}".format("\n".join(enabled_repos))) try: for repo in enabled_repos: self._base.repos.enableRepo(repo) except pkgmanager.Errors.RepoError as e: - logger.debug("Loading repository metadata failed: %s" % e) + logger.debug("Loading repository metadata failed: {}".format(e)) logger.critical_no_exit("Failed to populate repository metadata.") raise exceptions.CriticalError( id_="FAILED_TO_ENABLE_REPOS", title="Failed to enable repositories.", description="We've encountered a failure when accessing repository metadata.", - diagnosis="Loading repository metadata failed with error %s." % (str(e)), + diagnosis="Loading repository metadata failed with error {}.".format(str(e)), ) def _swap_base_os_specific_packages(self): @@ -184,10 +184,10 @@ def _swap_base_os_specific_packages(self): # Related issue: https://issues.redhat.com/browse/RHELC-1130, see comments # to get more proper description of solution for old_package, new_package in system_info.swap_pkgs.items(): - logger.debug("Checking if %s installed for later swap." % old_package) + logger.debug("Checking if {} installed for later swap.".format(old_package)) is_installed = system_info.is_rpm_installed(old_package) if is_installed: - logger.debug("Package %s will be swapped to %s during conversion." % (old_package, new_package)) + logger.debug("Package {} will be swapped to {} during conversion.".format(old_package, new_package)) # Order of operations based on YUM implementation of swap: # https://github.com/rpm-software-management/yum/blob/master/yumcommands.py#L3488 self._base.remove(pattern=old_package) @@ -238,7 +238,7 @@ def _perform_operations(self): id_="FAILED_TO_LOAD_REPOSITORIES", title="Failed to find suitable mirrors for the load repositories.", description="All available mirrors were tried and none were available.", - diagnosis="Repository mirrors failed with error %s." % (str(e)), + diagnosis="Repository mirrors failed with error {}.".format(str(e)), ) def _resolve_dependencies(self): @@ -323,7 +323,7 @@ def _process_transaction(self, validate_transaction): id_="FAILED_TO_VALIDATE_TRANSACTION", title="Failed to validate yum transaction.", description="During the yum transaction execution an error occurred and convert2rhel could no longer process the transaction.", - diagnosis="Transaction processing failed with error: %s" % " ".join(e.value), + diagnosis="Transaction processing failed with error: {}".format(" ".join(e.value)), ) if validate_transaction: diff --git a/convert2rhel/pkgmanager/handlers/yum/callback.py b/convert2rhel/pkgmanager/handlers/yum/callback.py index 2197f5d951..413ac0438c 100644 --- a/convert2rhel/pkgmanager/handlers/yum/callback.py +++ b/convert2rhel/pkgmanager/handlers/yum/callback.py @@ -66,9 +66,10 @@ logger = root_logger.getChild(__name__) """Instance of the logger used in this module.""" + # We need to double inherit here, both from the callback class and the base # object class, just to initialize properly with `super` -class PackageDownloadCallback(pkgmanager.DownloadProgress, object): # pylint: disable=useless-object-inheritance +class PackageDownloadCallback(pkgmanager.DownloadProgress, object): """Package download callback for YUM transaction.""" def __init__(self): @@ -113,7 +114,7 @@ def updateProgress(self, name, frac, fread, ftime): self.last_package_seen = name -class TransactionDisplayCallback(pkgmanager.TransactionDisplay, object): # pylint: disable=useless-object-inheritance +class TransactionDisplayCallback(pkgmanager.TransactionDisplay, object): """Transaction display callback for YUM transaction.""" def __init__(self): diff --git a/convert2rhel/redhatrelease.py b/convert2rhel/redhatrelease.py index 32fbf9f657..108be40fb0 100644 --- a/convert2rhel/redhatrelease.py +++ b/convert2rhel/redhatrelease.py @@ -47,7 +47,7 @@ def get_system_release_content(): try: return utils.get_file_content(filepath) except EnvironmentError as err: - logger.critical("%s\n%s file is essential for running this tool." % (err, filepath)) + logger.critical("{}\n{} file is essential for running this tool.".format(err, filepath)) class PkgManagerConf: @@ -79,7 +79,7 @@ def patch(self): # package is replaced but this config file is left unchanged and it keeps the original distroverpkg setting. self._comment_out_distroverpkg_tag() self._write_altered_pkg_manager_conf() - logger.info("%s patched." % self._pkg_manager_conf_path) + logger.info("{} patched.".format(self._pkg_manager_conf_path)) else: logger.info("Skipping patching, package manager configuration file has not been modified.") @@ -99,9 +99,11 @@ def is_modified(self): output, _ = utils.run_subprocess(["rpm", "-Vf", self._pkg_manager_conf_path], print_output=False) # rpm -Vf does not return information about the queried file but about all files owned by the rpm # that owns the queried file. Character '5' on position 3 means that the file was modified. - return True if re.search(r"^.{2}5.*? %s$" % self._pkg_manager_conf_path, output, re.MULTILINE) else False + return ( + True if re.search(r"^.{{2}}5.*? {}$".format(self._pkg_manager_conf_path), output, re.MULTILINE) else False + ) # Code to be executed upon module import -system_release_file = RestorableFile(get_system_release_filepath()) # pylint: disable=C0103 -os_release_file = RestorableFile(OS_RELEASE_FILEPATH) # pylint: disable=C0103 +system_release_file = RestorableFile(get_system_release_filepath()) +os_release_file = RestorableFile(OS_RELEASE_FILEPATH) diff --git a/convert2rhel/repo.py b/convert2rhel/repo.py index 8e6c68ebd0..1244d1a22f 100644 --- a/convert2rhel/repo.py +++ b/convert2rhel/repo.py @@ -53,7 +53,7 @@ def get_rhel_repoids(): else: repos_needed = system_info.default_rhsm_repoids - logger.info("RHEL repository IDs to enable: %s" % ", ".join(repos_needed)) + logger.info("RHEL repository IDs to enable: {}".format(", ".join(repos_needed))) return repos_needed @@ -113,9 +113,8 @@ def download_repofile(repofile_url): contents = response.read() if not contents: - description = ( - "The requested repository file seems to be empty. No content received when checking for url: %s" - % repofile_url + description = "The requested repository file seems to be empty. No content received when checking for url: {}".format( + repofile_url ) logger.critical_no_exit(description) raise exceptions.CriticalError( @@ -124,13 +123,13 @@ def download_repofile(repofile_url): description=description, ) - logger.info("Successfully downloaded a repository file from %s." % repofile_url) + logger.info("Successfully downloaded a repository file from {}.".format(repofile_url)) return contents.decode() except urllib.error.URLError as err: raise exceptions.CriticalError( id_="DOWNLOAD_REPOSITORY_FILE_FAILED", title="Failed to download a repository file", - description="Failed to download a repository file from %s.\n" "Reason: %s" % (repofile_url, err.reason), + description="Failed to download a repository file from {}.\n" "Reason: {}".format(repofile_url, err.reason), ) @@ -150,8 +149,8 @@ def write_temporary_repofile(contents): raise exceptions.CriticalError( id_="CREATE_TMP_DIR_FOR_REPOFILES_FAILED", title="Failed to create a temporary directory", - description="Failed to create a temporary directory for storing a repository file under %s.\n" - "Reason: %s" % (TMP_DIR, str(err)), + description="Failed to create a temporary directory for storing a repository file under {}.\n" + "Reason: {}".format(TMP_DIR, str(err)), ) with tempfile.NamedTemporaryFile(mode="w", suffix=".repo", delete=False, dir=repofile_dir) as f: try: @@ -161,5 +160,5 @@ def write_temporary_repofile(contents): raise exceptions.CriticalError( id_="STORE_REPOFILE_FAILED", title="Failed to store a repository file", - description="Failed to write a repository file contents to %s.\n" "Reason: %s" % (f.name, str(err)), + description="Failed to write a repository file contents to {}.\n" "Reason: {}".format(f.name, str(err)), ) diff --git a/convert2rhel/subscription.py b/convert2rhel/subscription.py index 41a4d44222..a235a6f397 100644 --- a/convert2rhel/subscription.py +++ b/convert2rhel/subscription.py @@ -103,7 +103,7 @@ def remove_subscription(): subscription_removal_cmd = ["subscription-manager", "remove", "--all"] output, ret_code = utils.run_subprocess(subscription_removal_cmd, print_output=False) if ret_code != 0: - raise SubscriptionRemovalError("Subscription removal result\n%s" % output) + raise SubscriptionRemovalError("Subscription removal result\n{}".format(output)) else: logger.info("Subscription removal successful.") @@ -141,7 +141,7 @@ def unregister_system(): unregistration_cmd = ["subscription-manager", "unregister"] output, ret_code = utils.run_subprocess(unregistration_cmd, print_output=False) if ret_code != 0: - raise UnregisterError("System unregistration result:\n%s" % output) + raise UnregisterError("System unregistration result:\n{}".format(output)) else: logger.info("System unregistered successfully.") @@ -211,13 +211,15 @@ def register_system(): os_release_file.restore(rollback=False) except (OSError, IOError) as e: logger.critical_no_exit( - "Failed to restore the /etc/os-release file needed for subscribing the system with message: %s" % str(e) + "Failed to restore the /etc/os-release file needed for subscribing the system with message: {}".format( + str(e) + ) ) raise exceptions.CriticalError( id_="FAILED_TO_SUBSCRIBE_SYSTEM", title="Failed to subscribe system.", description="Failed to restore the /etc/os-release file needed for subscribing the system.", - diagnosis="The restore failed with error %s." % (str(e)), + diagnosis="The restore failed with error {}.".format(str(e)), ) try: @@ -232,7 +234,7 @@ def register_system(): # When the user hits Control-C to exit, we shouldn't retry raise except Exception as e: - logger.info("System registration failed with error: %s" % str(e)) + logger.info("System registration failed with error: {}".format(str(e))) troublesome_exception = e sleep(REGISTRATION_ATTEMPT_DELAYS[attempt]) attempt += 1 @@ -247,7 +249,7 @@ def register_system(): id_="FAILED_TO_SUBSCRIBE_SYSTEM", title="Failed to subscribe system.", description="After several attempts, convert2rhel was unable to subscribe the system using subscription-manager. This issue might occur because of but not limited to DBus, file permission-related issues, bad credentials, or network issues.", - diagnosis="System registration failed with error %s." % (str(troublesome_exception)), + diagnosis="System registration failed with error {}.".format(str(troublesome_exception)), ) return None @@ -265,7 +267,7 @@ def refresh_subscription_info(): if ret_code != 0: raise RefreshSubscriptionManagerError( - "Asking subscription-manager to reexamine its configuration failed: %s; output: %s" % (ret_code, output) + "Asking subscription-manager to reexamine its configuration failed: {}; output: {}".format(ret_code, output) ) logger.info("subscription-manager has reloaded its configuration.") @@ -276,7 +278,7 @@ def _stop_rhsm(): cmd = ["/bin/systemctl", "stop", "rhsm"] output, ret_code = utils.run_subprocess(cmd, print_output=False) if ret_code != 0: - raise StopRhsmError("Stopping RHSM failed with code: %s; output: %s" % (ret_code, output)) + raise StopRhsmError("Stopping RHSM failed with code: {}; output: {}".format(ret_code, output)) logger.info("RHSM service stopped.") @@ -558,11 +560,11 @@ def _set_connection_opts_in_config(self): logger.info("Setting RHSM connection configuration.") sub_man_config_command = ["subscription-manager", "config"] for option, value in self.connection_opts.items(): - sub_man_config_command.append("--%s=%s" % (CONNECT_OPT_NAME_TO_CONFIG_KEY[option], value)) + sub_man_config_command.append("--{}={}".format(CONNECT_OPT_NAME_TO_CONFIG_KEY[option], value)) output, ret_code = utils.run_subprocess(sub_man_config_command, print_cmd=True) if ret_code != 0: - raise ValueError("Error setting the subscription-manager connection configuration: %s" % output) + raise ValueError("Error setting the subscription-manager connection configuration: {}".format(output)) logger.info("Successfully set RHSM connection configuration.") @@ -628,8 +630,8 @@ def install_rhel_subscription_manager(pkgs_to_install): client_tools_repofile_path = repo.write_temporary_repofile(contents) reposdir = [os.path.dirname(client_tools_repofile_path), backedup_reposdir] - setopts.append("reposdir=%s" % ",".join(reposdir)) - setopts.append("varsdir=%s" % backedup_varsdir) + setopts.append("reposdir={}".format(",".join(reposdir))) + setopts.append("varsdir={}".format(backedup_varsdir)) installed_pkg_set = RestorablePackageSet( pkgs_to_install, custom_releasever=system_info.version.major, @@ -722,7 +724,7 @@ def get_pool_id(sub_raw_attrs): if pool_id: return pool_id.group(1) - logger.critical("Cannot parse the subscription pool ID from string:\n%s" % sub_raw_attrs) + logger.critical("Cannot parse the subscription pool ID from string:\n{}".format(sub_raw_attrs)) def verify_rhsm_installed(): @@ -751,12 +753,12 @@ def disable_repos(): cmd.extend(disable_cmd) output, ret_code = utils.run_subprocess(cmd, print_output=False) if ret_code != 0: - logger.critical_no_exit("Could not disable subscription-manager repositories:\n%s" % output) + logger.critical_no_exit("Could not disable subscription-manager repositories:\n{}".format(output)) raise exceptions.CriticalError( id_="FAILED_TO_DISABLE_SUBSCRIPTION_MANAGER_REPOSITORIES", title="Could not disable repositories through subscription-manager.", description="As part of the conversion process, convert2rhel disables all current subscription-manager repositories and enables only repositories required for the conversion. convert2rhel was unable to disable these repositories, and the conversion is unable to proceed.", - diagnosis="Failed to disable repositories: %s." % (output), + diagnosis="Failed to disable repositories: {}.".format(output), ) logger.info("Repositories disabled.") @@ -782,7 +784,7 @@ def enable_repos(rhel_repoids): """ repos_to_enable = tool_opts.enablerepo if tool_opts.enablerepo else rhel_repoids - logger.info("Trying to enable the following RHEL repositories: %s" % ", ".join(repos_to_enable)) + logger.info("Trying to enable the following RHEL repositories: {}".format(", ".join(repos_to_enable))) submgr_enable_repos(repos_to_enable) system_info.submgr_enabled_repos = repos_to_enable @@ -791,12 +793,12 @@ def enable_repos(rhel_repoids): def submgr_enable_repos(repos_to_enable): """Go through subscription manager repos and try to enable them through subscription-manager.""" enable_cmd = ["subscription-manager", "repos"] - for repo in repos_to_enable: - enable_cmd.append("--enable=%s" % repo) + for repo_to_enable in repos_to_enable: + enable_cmd.append("--enable={}".format(repo_to_enable)) output, ret_code = utils.run_subprocess(enable_cmd, print_output=False) if ret_code != 0: - description = "Repositories were not possible to enable through subscription-manager:\n%s" % output + description = "Repositories were not possible to enable through subscription-manager:\n{}".format(output) logger.critical_no_exit(description) raise exceptions.CriticalError( id_="FAILED_TO_ENABLE_RHSM_REPOSITORIES", @@ -837,10 +839,10 @@ def needed_subscription_manager_pkgs(): # `get_installed_pkg_information()` again. installed_submgr_pkgs = [pkg.nevra.name for pkg in installed_submgr_pkgs] - logger.debug("Need the following packages: %s" % utils.format_sequence_as_message(subscription_manager_pkgs)) - logger.debug("Detected the following packages: %s" % utils.format_sequence_as_message(installed_submgr_pkgs)) + logger.debug("Need the following packages: {}".format(utils.format_sequence_as_message(subscription_manager_pkgs))) + logger.debug("Detected the following packages: {}".format(utils.format_sequence_as_message(installed_submgr_pkgs))) - logger.debug("Packages we will install: %s" % utils.format_sequence_as_message(to_install_pkgs)) + logger.debug("Packages we will install: {}".format(utils.format_sequence_as_message(to_install_pkgs))) return to_install_pkgs @@ -929,7 +931,7 @@ def get_rhsm_facts(): logger.info("RHSM facts loaded.") except (IOError, ValueError) as e: logger.critical_no_exit( - "Failed to get the RHSM facts : %s." % e, + "Failed to get the RHSM facts : {}.".format(e), ) return rhsm_facts diff --git a/convert2rhel/systeminfo.py b/convert2rhel/systeminfo.py index 606e75353d..e296c10d34 100644 --- a/convert2rhel/systeminfo.py +++ b/convert2rhel/systeminfo.py @@ -104,7 +104,7 @@ def __init__(self): # Operating system name (e.g. Oracle Linux) self.name = None # Single-word lowercase identificator of the system (e.g. oracle) - self.id = None # pylint: disable=C0103 + self.id = None # The optional last part of the distribution name in brackets: "... (Core)" or "... (Oopta)" self.distribution_id = None # Major and minor version of the operating system (e.g. version.major == 8, version.minor == 7) @@ -236,7 +236,7 @@ def parse_system_release_content(self, system_release_content=None): ) if not matched: - self.logger.critical_no_exit("Couldn't parse the system release content string: %s" % content) + self.logger.critical_no_exit("Couldn't parse the system release content string: {}".format(content)) return {} name = matched.group("name") @@ -328,7 +328,7 @@ def _get_cfg_opt(self, option_name): return self.cfg_content[option_name] else: self.logger.error( - "Internal error: %s option not found in %s config file." % (option_name, self.cfg_filename) + "Internal error: {} option not found in {} config file.".format(option_name, self.cfg_filename) ) def _get_gpg_key_ids(self): @@ -421,7 +421,7 @@ def generate_rpm_va(self, log_filename=PRE_RPM_VA_LOG_FILENAME): rpm_va, _ = utils.run_subprocess(["rpm", "-Va", "--nodeps"], print_output=False) output_file = os.path.join(logger.LOG_DIR, log_filename) utils.store_content_to_file(output_file, rpm_va) - self.logger.info("The 'rpm -Va' output has been stored in the %s file." % output_file) + self.logger.info("The 'rpm -Va' output has been stored in the {} file.".format(output_file)) @staticmethod def is_rpm_installed(name): @@ -491,7 +491,7 @@ def _is_dbus_running(self): # Wait for 1 second, 2 seconds, and then 4 seconds for dbus to be running # (In case it was started before convert2rhel but it is slow to start) - time.sleep(2 ** retries) + time.sleep(2**retries) retries += 1 else: # while-else @@ -549,4 +549,4 @@ def is_systemd_managed_service_running(service): # Code to be executed upon module import -system_info = SystemInfo() # pylint: disable=C0103 +system_info = SystemInfo() diff --git a/convert2rhel/toolopts/config.py b/convert2rhel/toolopts/config.py index 7b794fe8e6..9560786b6c 100644 --- a/convert2rhel/toolopts/config.py +++ b/convert2rhel/toolopts/config.py @@ -136,7 +136,7 @@ def options_from_config_files(self): paths = [os.path.expanduser(path) for path in self._config_files if os.path.exists(os.path.expanduser(path))] if not paths: - raise FileNotFoundError("No such file or directory: %s" % ", ".join(paths)) + raise FileNotFoundError("No such file or directory: {}".format(", ".join(paths))) found_opts = self._parse_options_from_config(paths) return found_opts @@ -156,19 +156,19 @@ def _parse_options_from_config(self, paths): found_opts = {} for path in reversed(paths): - loggerinst.debug("Checking configuration file at %s" % path) + loggerinst.debug("Checking configuration file at {}".format(path)) # Check for correct permissions on file if not oct(os.stat(path).st_mode)[-4:].endswith("00"): - loggerinst.critical("The %s file must only be accessible by the owner (0600)" % path) + loggerinst.critical("The {} file must only be accessible by the owner (0600)".format(path)) config_file.read(path) # Mapping of all supported options we can have in the config file for supported_header, supported_opts in CONFIG_FILE_MAPPING_OPTIONS.items(): - loggerinst.debug("Checking for header '%s'" % supported_header) + loggerinst.debug("Checking for header '{}'".format(supported_header)) if supported_header not in config_file.sections(): loggerinst.warning( - "Couldn't find header '%s' in the configuration file %s." % (supported_header, path) + "Couldn't find header '{}' in the configuration file {}.".format(supported_header, path) ) continue options = self._get_options_value(config_file, supported_header, supported_opts) @@ -192,12 +192,12 @@ def _get_options_value(self, config_file, header, supported_opts): conf_options = config_file.options(header) if len(conf_options) == 0: - loggerinst.debug("No options found for %s. It seems to be empty or commented." % header) + loggerinst.debug("No options found for {}. It seems to be empty or commented.".format(header)) return options for option in conf_options: if option.lower() not in supported_opts: - loggerinst.warning("Unsupported option '%s' in '%s'" % (option, header)) + loggerinst.warning("Unsupported option '{}' in '{}'".format(option, header)) continue # This is the only header that can contain boolean values for now. @@ -206,7 +206,7 @@ def _get_options_value(self, config_file, header, supported_opts): else: options[option] = config_file.get(header, option) - loggerinst.debug("Found %s in %s" % (option, header)) + loggerinst.debug("Found {} in {}".format(option, header)) return options @@ -240,7 +240,6 @@ def __init__(self, opts): self._opts = opts # type: arpgparse.Namepsace def run(self): - opts = vars(self._opts) opts = self._normalize_opts(opts) @@ -310,7 +309,7 @@ def _validate(self, opts): if duplicate_repos: message = "Duplicate repositories were found across disablerepo and enablerepo options:" for repo in duplicate_repos: - message += "\n%s" % repo + message += "\n{}".format(repo) message += "\nThis ambiguity may have unintended consequences." loggerinst.warning(message) diff --git a/convert2rhel/unit_tests/__init__.py b/convert2rhel/unit_tests/__init__.py index 517b87f573..ed47a34dfb 100644 --- a/convert2rhel/unit_tests/__init__.py +++ b/convert2rhel/unit_tests/__init__.py @@ -22,8 +22,6 @@ import os import sys -from typing import Any - import pytest import six @@ -39,7 +37,6 @@ pkgmanager, subscription, systeminfo, - toolopts, utils, ) from convert2rhel.actions import STATUS_CODE, report @@ -48,7 +45,7 @@ six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) -from six.moves import mock as six_mock +from six.moves import mock as six_mock # noqa: E402 TMP_DIR = "/tmp/convert2rhel_test/" @@ -163,7 +160,7 @@ def wrapped_fn(*args, **kwargs): # (e.g. to have the mocked function just as a wrapper for the # original function), save it as a temporary attribute # named "_orig" - orig_obj_attr = "%s_orig" % orig_obj + orig_obj_attr = "{}_orig".format(orig_obj) setattr(class_or_module, orig_obj_attr, orig_obj_saved) # Call the decorated test function return_value = None @@ -434,7 +431,11 @@ class GetInstalledPkgInformationMocked(MockFunctionObject): pkg1 = create_pkg_information(name="pkg1", key_id="199e2f91fd431d51") # RHEL pkg2 = create_pkg_information(name="pkg2", key_id="72f97b74ec551f03") # OL pkg3 = create_pkg_information( - name="gpg-pubkey", version="1.0.0", release="1", arch="x86_64", key_id="199e2f91fd431d51" # RHEL + name="gpg-pubkey", + version="1.0.0", + release="1", + arch="x86_64", + key_id="199e2f91fd431d51", # RHEL ) # Oracle Kernel Packages @@ -835,7 +836,7 @@ def __call__(self): """ if not self._exception: return self - raise self._exception # pylint: disable=raising-bad-type + raise self._exception def set_default_efi_entries(self): if not self.entries: diff --git a/convert2rhel/unit_tests/actions/actions_test.py b/convert2rhel/unit_tests/actions/actions_test.py index 948ef1a583..4737da09f8 100644 --- a/convert2rhel/unit_tests/actions/actions_test.py +++ b/convert2rhel/unit_tests/actions/actions_test.py @@ -127,7 +127,9 @@ def test_no_duplicate_ids(self): dupe_actions = [] for action_id, locations in action_id_locations.items(): if len(locations) > 1: - dupe_actions.append("%s is present in more than one location: %s" % (action_id, ", ".join(locations))) + dupe_actions.append( + "{} is present in more than one location: {}".format(action_id, ", ".join(locations)) + ) assert not dupe_actions, "\n".join(dupe_actions) @@ -228,12 +230,14 @@ def test_get_actions_smoketest(self): filesystem_detected_actions_count = 0 for rootdir, dirnames, filenames in os.walk(os.path.dirname(actions.__file__)): for directory in dirnames: - if "%s.%s." % (actions.__name__, directory) == "convert2rhel.actions.post_ponr": + if "{}.{}.".format(actions.__name__, directory) == "convert2rhel.actions.post_ponr": continue # Add to the actions that the production code finds here as it is non-recursive computed_actions.extend( - actions.get_actions([os.path.join(rootdir, directory)], "%s.%s." % (actions.__name__, directory)) + actions.get_actions( + [os.path.join(rootdir, directory)], "{}.{}.".format(actions.__name__, directory) + ) ) for filename in (os.path.join(rootdir, filename) for filename in filenames): @@ -253,10 +257,7 @@ def test_get_actions_no_dupes(self): def test_no_actions(self, tmpdir): """No Actions returns an empty list.""" # We need to make sure this returns an empty set, not just false-y - assert ( - actions.get_actions([str(tmpdir)], "tmp.") - == set() # pylint: disable=use-implicit-booleaness-not-comparison - ) + assert actions.get_actions([str(tmpdir)], "tmp.") == set() @pytest.mark.parametrize( ( @@ -280,7 +281,7 @@ def test_found_actions(self, sys_path, test_dir_name, expected_action_names): test_data = os.path.join(data_dir, test_dir_name) computed_action_names = sorted( m.__name__ - for m in actions.get_actions([test_data], "convert2rhel.unit_tests.actions.data.%s." % test_dir_name) + for m in actions.get_actions([test_data], "convert2rhel.unit_tests.actions.data.{}.".format(test_dir_name)) ) assert computed_action_names == sorted(expected_action_names) @@ -295,7 +296,6 @@ class TestStage: # Tests that the Stage is crated successfully # def test_init(self, stage_actions): - stage1 = actions.Stage("good_deps1", "Task Header") stage2 = actions.Stage("good_deps_failed_actions", "Task Header2", stage1) diff --git a/convert2rhel/unit_tests/actions/conversion/lock_releasever_test.py b/convert2rhel/unit_tests/actions/conversion/lock_releasever_test.py index 306867d772..6cf18136b3 100644 --- a/convert2rhel/unit_tests/actions/conversion/lock_releasever_test.py +++ b/convert2rhel/unit_tests/actions/conversion/lock_releasever_test.py @@ -52,7 +52,7 @@ def lock_releasever_in_rhel_repositories_instance(): def test_lock_releasever_in_rhel_repositories( lock_releasever_in_rhel_repositories_instance, subprocess, expected, monkeypatch, caplog, pretend_os ): - cmd = ["subscription-manager", "release", "--set=%s" % system_info.releasever] + cmd = ["subscription-manager", "release", "--set={}".format(system_info.releasever)] run_subprocess_mock = RunSubprocessMocked( side_effect=unit_tests.run_subprocess_side_effect( (cmd, subprocess), diff --git a/convert2rhel/unit_tests/actions/conversion/preserve_only_rhel_kernel_test.py b/convert2rhel/unit_tests/actions/conversion/preserve_only_rhel_kernel_test.py index 64684d8726..1d4b51d698 100644 --- a/convert2rhel/unit_tests/actions/conversion/preserve_only_rhel_kernel_test.py +++ b/convert2rhel/unit_tests/actions/conversion/preserve_only_rhel_kernel_test.py @@ -486,7 +486,6 @@ def test_fix_invalid_grub2_entries_messages( def test_fix_invalid_grub2_entries_execution( self, monkeypatch, fix_invalid_grub2_entries_instance, caplog, version, expected ): - monkeypatch.setattr(system_info, "version", version) run_subprocess_mocked = RunSubprocessMocked( side_effect=unit_tests.run_subprocess_side_effect( @@ -570,7 +569,7 @@ def test_fix_default_kernel_converting_success( monkeypatch.setattr( utils, "get_file_content", - lambda _: "UPDATEDEFAULT=yes\nDEFAULTKERNEL=%s\n" % old_kernel, + lambda _: "UPDATEDEFAULT=yes\nDEFAULTKERNEL={}\n".format(old_kernel), ) monkeypatch.setattr(utils, "store_content_to_file", StoreContentToFileMocked()) @@ -584,10 +583,10 @@ def test_fix_default_kernel_converting_success( kernel_file_lines = content.splitlines() assert "/etc/sysconfig/kernel" == filename - assert "DEFAULTKERNEL=%s" % new_kernel in kernel_file_lines + assert "DEFAULTKERNEL={}".format(new_kernel) in kernel_file_lines for kernel_name in not_default_kernels: - assert "DEFAULTKERNEL=%s" % kernel_name not in kernel_file_lines + assert "DEFAULTKERNEL={}".format(kernel_name) not in kernel_file_lines @centos7 def test_fix_default_kernel_with_no_incorrect_kernel( diff --git a/convert2rhel/unit_tests/actions/post_conversion/kernel_boot_files_test.py b/convert2rhel/unit_tests/actions/post_conversion/kernel_boot_files_test.py index 5cf055a4b3..5d2abceb49 100644 --- a/convert2rhel/unit_tests/actions/post_conversion/kernel_boot_files_test.py +++ b/convert2rhel/unit_tests/actions/post_conversion/kernel_boot_files_test.py @@ -132,11 +132,10 @@ def test_check_kernel_boot_files_missing( diagnosis=None, remediations=( "In order to fix this problem you might need to free/increase space in your boot partition and then run the following commands in your terminal:\n" - "1. yum reinstall kernel-core-%s -y\n" + "1. yum reinstall kernel-core-{} -y\n" "2. grub2-mkconfig -o /boot/grub2/grub.cfg\n" "3. reboot" - ) - % latest_installed_kernel, + ).format(latest_installed_kernel), ), ) ) diff --git a/convert2rhel/unit_tests/actions/post_conversion/modified_rpm_files_diff_test.py b/convert2rhel/unit_tests/actions/post_conversion/modified_rpm_files_diff_test.py index 69c36152dc..5a29e1919e 100644 --- a/convert2rhel/unit_tests/actions/post_conversion/modified_rpm_files_diff_test.py +++ b/convert2rhel/unit_tests/actions/post_conversion/modified_rpm_files_diff_test.py @@ -20,7 +20,7 @@ import pytest import six -from convert2rhel import actions, logger, systeminfo, toolopts, utils +from convert2rhel import actions, logger, systeminfo, utils from convert2rhel.actions.post_conversion import modified_rpm_files_diff from convert2rhel.systeminfo import system_info diff --git a/convert2rhel/unit_tests/actions/post_conversion/remove_tmp_dir_test.py b/convert2rhel/unit_tests/actions/post_conversion/remove_tmp_dir_test.py index 09da2b4b05..64377157f7 100644 --- a/convert2rhel/unit_tests/actions/post_conversion/remove_tmp_dir_test.py +++ b/convert2rhel/unit_tests/actions/post_conversion/remove_tmp_dir_test.py @@ -35,7 +35,7 @@ def test_remove_tmp_dir(remove_tmp_dir_instance, monkeypatch, tmpdir, caplog): monkeypatch.setattr(remove_tmp_dir_instance, "tmp_dir", path) assert os.path.isdir(path) remove_tmp_dir_instance.run() - assert "Temporary folder %s removed" % path in caplog.text + assert "Temporary folder {} removed".format(path) in caplog.text assert not os.path.isdir(path) @@ -45,7 +45,7 @@ def test_remove_tmp_dir_non_existent(remove_tmp_dir_instance, monkeypatch, caplo monkeypatch.setattr(remove_tmp_dir_instance, "tmp_dir", path) assert not os.path.isdir(path) remove_tmp_dir_instance.run() - assert "Temporary folder %s removed" % path not in caplog.text + assert "Temporary folder {} removed".format(path) not in caplog.text def test_remove_tmp_dir_failure(remove_tmp_dir_instance, monkeypatch, tmpdir, caplog): @@ -55,8 +55,8 @@ def test_remove_tmp_dir_failure(remove_tmp_dir_instance, monkeypatch, tmpdir, ca os.chmod(path, 0) remove_tmp_dir_instance.run() expected_message = ( - "The folder %s is left untouched. You may remove the folder manually" - " after you ensure there is no preserved data you would need." % path + "The folder {} is left untouched. You may remove the folder manually" + " after you ensure there is no preserved data you would need.".format(path) ) expected = set( ( diff --git a/convert2rhel/unit_tests/actions/post_conversion/update_grub_test.py b/convert2rhel/unit_tests/actions/post_conversion/update_grub_test.py index bc5ecd34f1..930ebf4bfa 100644 --- a/convert2rhel/unit_tests/actions/post_conversion/update_grub_test.py +++ b/convert2rhel/unit_tests/actions/post_conversion/update_grub_test.py @@ -65,7 +65,7 @@ def test_update_grub( ( "/usr/sbin/grub2-mkconfig", "-o", - "%s" % config_path, + "{}".format(config_path), ), ( "output", @@ -142,7 +142,7 @@ def test_update_grub_action_messages( ( "/usr/sbin/grub2-mkconfig", "-o", - "%s" % config_path, + "{}".format(config_path), ), ( "output", @@ -171,7 +171,6 @@ def test_update_grub_action_messages( ), ) def test_update_grub_error(update_grub_instance, monkeypatch, get_partition_error, get_blk_device_error, diagnosis): - monkeypatch.setattr(utils, "run_subprocess", RunSubprocessMocked(return_code=0)) monkeypatch.setattr(grub, "is_efi", mock.Mock(return_value=False)) if get_partition_error: diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/backup_system_test.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/backup_system_test.py index f9797bcd97..e9c337c66b 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/backup_system_test.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/backup_system_test.py @@ -337,7 +337,7 @@ def test_backup_package_file_complete( path = line.split()[-1] with open(path, mode="w") as f: # Append the original path to the content - f.write("Content for testing of file %s" % path) + f.write("Content for testing of file {}".format(path)) except (OSError, IOError): # case with invalid filepath pass @@ -365,7 +365,7 @@ def test_backup_package_file_complete( if backed_up[i]: # Check if the file exists and contains right content with open(backed_up_file_path, mode="r") as f: - assert f.read() == "Content for testing of file %s" % original_file_path + assert f.read() == "Content for testing of file {}".format(original_file_path) # Remove the original file try: os.remove(original_file_path) @@ -379,7 +379,7 @@ def test_backup_package_file_complete( elif status == "missing": with open(original_file_path, mode="w") as f: # Append the original path to the content - f.write("Content for testing of file %s" % original_file_path) + f.write("Content for testing of file {}".format(original_file_path)) else: assert not os.path.isfile(backed_up_file_path) @@ -395,7 +395,7 @@ def test_backup_package_file_complete( if backed_up[i]: assert os.path.isfile(original_file_path) with open(original_file_path, mode="r") as f: - assert f.read() == "Content for testing of file %s" % original_file_path + assert f.read() == "Content for testing of file {}".format(original_file_path) elif status == "missing": assert not os.path.isfile(original_file_path) @@ -470,7 +470,7 @@ def test_backup_repository_no_repofile_presence(self, tmpdir, monkeypatch, caplo backup_repository = backup_repository_action backup_repository.run() - assert ("Repository folder %s seems to be empty." % etc) in caplog.text + assert ("Repository folder {} seems to be empty.".format(etc)) in caplog.text class TestBackupVariables: diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/handle_packages_test.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/handle_packages_test.py index af285b53df..ef6e1b72af 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/handle_packages_test.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/handle_packages_test.py @@ -270,5 +270,5 @@ def test_remove_packages_unless_from_redhat(pkgs_to_remove, monkeypatch, caplog) monkeypatch.setattr(pkghandler, "format_pkg_info", FormatPkgInfoMocked()) handle_packages._remove_packages_unless_from_redhat(pkgs_list=pkgs_to_remove) - assert "Removing the following %s packages" % len(pkgs_to_remove) in caplog.records[-3].message - assert "Successfully removed %s packages" % len(pkgs_to_remove) in caplog.records[-1].message + assert "Removing the following {} packages".format(len(pkgs_to_remove)) in caplog.records[-3].message + assert "Successfully removed {} packages".format(len(pkgs_to_remove)) in caplog.records[-1].message diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/kernel_modules_test.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/kernel_modules_test.py index 665117cd19..9298d1bac8 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/kernel_modules_test.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/kernel_modules_test.py @@ -207,7 +207,6 @@ def test_ensure_compatibility_of_kmods_check_env_and_message( pretend_os, caplog, ): - monkeypatch.setattr(os, "environ", {"CONVERT2RHEL_ALLOW_UNAVAILABLE_KMODS": "1"}) monkeypatch.setattr( ensure_kernel_modules_compatibility_instance, "_get_loaded_kmods", mock.Mock(return_value=HOST_MODULES_STUB_BAD) diff --git a/convert2rhel/unit_tests/actions/system_checks/convert2rhel_latest_test.py b/convert2rhel/unit_tests/actions/system_checks/convert2rhel_latest_test.py index 6c4c95b2b3..149f9496dd 100644 --- a/convert2rhel/unit_tests/actions/system_checks/convert2rhel_latest_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/convert2rhel_latest_test.py @@ -158,8 +158,8 @@ def test_convert2rhel_latest_outdated_version_inhibitor( title="Outdated convert2rhel version detected", description="An outdated convert2rhel version has been detected", diagnosis=( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "Only the latest version is supported for conversion." % (running_version, latest_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "Only the latest version is supported for conversion.".format(running_version, latest_version) ), remediations="If you want to disregard this check, then set the environment variable 'CONVERT2RHEL_ALLOW_OLDER_VERSION=1' to continue.", ) @@ -245,8 +245,8 @@ def test_convert2rhel_latest_outdated_version_warning( title="Outdated convert2rhel version detected", description="An outdated convert2rhel version has been detected", diagnosis=( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "We encourage you to update to the latest version." % (running_version, latest_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "We encourage you to update to the latest version.".format(running_version, latest_version) ), remediations=None, ) @@ -334,9 +334,10 @@ def test_convert2rhel_latest_log_check_env( running_version, latest_version = prepare_convert2rhel_latest_action log_msg = ( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "'CONVERT2RHEL_ALLOW_OLDER_VERSION' environment variable detected, continuing conversion" - % (running_version, latest_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "'CONVERT2RHEL_ALLOW_OLDER_VERSION' environment variable detected, continuing conversion".format( + running_version, latest_version + ) ) assert log_msg in caplog.text @@ -577,8 +578,8 @@ def ttest_convert2rhel_latest_multiple_packages( title="Outdated convert2rhel version detected", description="An outdated convert2rhel version has been detected", diagnosis=( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "Only the latest version is supported for conversion." % (running_version, latest_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "Only the latest version is supported for conversion.".format(running_version, latest_version) ), remediations="If you want to disregard this check, then set the environment variable 'CONVERT2RHEL_ALLOW_OLDER_VERSION=1' to continue.", ) @@ -646,8 +647,9 @@ def mock_run_subprocess(cmd, print_output=False): log_msg = ( "Some files in the convert2rhel package have changed so the installed convert2rhel is not what was packaged." - " We will check that the version of convert2rhel (%s) is the latest but ignore the rpm release." - % running_version + " We will check that the version of convert2rhel ({}) is the latest but ignore the rpm release.".format( + running_version + ) ) assert log_msg in caplog.text @@ -713,9 +715,8 @@ def mock_run_subprocess(cmd, print_output=False): running_version, latest_version = prepare_convert2rhel_latest_action convert2rhel_latest_action_instance.run() - log_msg = ( - "Couldn't determine the rpm release; We will check that the version of convert2rhel (%s) is the latest but ignore the rpm release." - % running_version + log_msg = "Couldn't determine the rpm release; We will check that the version of convert2rhel ({}) is the latest but ignore the rpm release.".format( + running_version ) assert log_msg in caplog.text @@ -760,8 +761,8 @@ def test_convert2rhel_latest_bad_NEVRA_to_parse_pkg_string( title="Outdated convert2rhel version detected", description="An outdated convert2rhel version has been detected", diagnosis=( - "You are currently running %s and the latest version of convert2rhel is %s.\n" - "Only the latest version is supported for conversion." % (running_version, latest_version) + "You are currently running {} and the latest version of convert2rhel is {}.\n" + "Only the latest version is supported for conversion.".format(running_version, latest_version) ), remediations="If you want to disregard this check, then set the environment variable 'CONVERT2RHEL_ALLOW_OLDER_VERSION=1' to continue.", ) diff --git a/convert2rhel/unit_tests/actions/system_checks/duplicate_packages_test.py b/convert2rhel/unit_tests/actions/system_checks/duplicate_packages_test.py index 8c878b664a..7c2734a129 100644 --- a/convert2rhel/unit_tests/actions/system_checks/duplicate_packages_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/duplicate_packages_test.py @@ -24,7 +24,6 @@ from convert2rhel.actions.system_checks import duplicate_packages from convert2rhel.systeminfo import Version, system_info from convert2rhel.unit_tests import RunSubprocessMocked -from convert2rhel.unit_tests.conftest import all_systems @pytest.fixture @@ -70,7 +69,6 @@ def duplicate_packages_action(): def test_duplicate_packages_error( monkeypatch, version_string, output, expected, global_tool_opts, duplicate_packages_action ): - monkeypatch.setattr(utils, "run_subprocess", RunSubprocessMocked(return_value=(output, 0))) monkeypatch.setattr(system_info, "version", version_string) monkeypatch.setattr(systeminfo, "tool_opts", global_tool_opts) @@ -82,7 +80,7 @@ def test_duplicate_packages_error( id="DUPLICATE_PACKAGES_FOUND", title="Duplicate packages found on the system", description="The system contains one or more packages with multiple versions.", - diagnosis="The following packages have multiple versions: %s." % ", ".join(expected), + diagnosis="The following packages have multiple versions: {}.".format(", ".join(expected)), remediations="This error can be resolved by removing duplicate versions of the listed packages." " The command 'package-cleanup' can be used to automatically remove duplicate packages" " on the system.", @@ -126,7 +124,6 @@ def test_duplicate_packages_unsuccessful( ((""),), ) def test_duplicate_packages_success(monkeypatch, duplicate_packages_action, output): - monkeypatch.setattr(utils, "run_subprocess", RunSubprocessMocked(return_value=(output, 0))) duplicate_packages_action.run() unit_tests.assert_actions_result( diff --git a/convert2rhel/unit_tests/actions/system_checks/els_test.py b/convert2rhel/unit_tests/actions/system_checks/els_test.py index 064bb0e54d..1ee0f2e48d 100644 --- a/convert2rhel/unit_tests/actions/system_checks/els_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/els_test.py @@ -50,7 +50,6 @@ class TestEus: ), ) def test_els_warning_message(self, els_action, monkeypatch, global_tool_opts, version_string, message_reported): - global_tool_opts.els = False monkeypatch.setattr(system_info, "version", version_string) monkeypatch.setattr(systeminfo, "tool_opts", global_tool_opts) diff --git a/convert2rhel/unit_tests/actions/system_checks/eus_test.py b/convert2rhel/unit_tests/actions/system_checks/eus_test.py index e103ebd13d..0f13be28d4 100644 --- a/convert2rhel/unit_tests/actions/system_checks/eus_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/eus_test.py @@ -50,7 +50,6 @@ class TestEus: ) @pytest.mark.skipif(pkgmanager.TYPE != "dnf", reason="el7 systems are not under eus") def test_eus_warning_message(self, eus_action, monkeypatch, global_tool_opts, version_string, message_reported): - global_tool_opts.eus = False monkeypatch.setattr(system_info, "version", version_string) monkeypatch.setattr(systeminfo, "tool_opts", global_tool_opts) diff --git a/convert2rhel/unit_tests/actions/system_checks/is_loaded_kernel_latest_test.py b/convert2rhel/unit_tests/actions/system_checks/is_loaded_kernel_latest_test.py index b334a4f8ff..d5221b35a7 100644 --- a/convert2rhel/unit_tests/actions/system_checks/is_loaded_kernel_latest_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/is_loaded_kernel_latest_test.py @@ -267,7 +267,6 @@ def test_is_loaded_kernel_latest_invalid_kernel_package_yum( monkeypatch, is_loaded_kernel_latest_action, ): - run_subprocess_mocked = mock.Mock( spec=run_subprocess, side_effect=run_subprocess_side_effect( diff --git a/convert2rhel/unit_tests/actions/system_checks/rhel_compatible_kernel_test.py b/convert2rhel/unit_tests/actions/system_checks/rhel_compatible_kernel_test.py index e170cc6eb0..dc1a5b4ece 100644 --- a/convert2rhel/unit_tests/actions/system_checks/rhel_compatible_kernel_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/rhel_compatible_kernel_test.py @@ -257,7 +257,7 @@ def test_bad_kernel_package_signature_success( monkeypatch.setattr(rhel_compatible_kernel, "get_installed_pkg_information", get_installed_pkg_information_mocked) assert rhel_compatible_kernel._bad_kernel_package_signature(kernel_release) == exp_return run_subprocess_mocked.assert_called_with( - ["rpm", "-qf", "--qf", "%{NEVRA}", "/boot/vmlinuz-%s" % kernel_release], + ["rpm", "-qf", "--qf", "%{NEVRA}", "/boot/vmlinuz-{}".format(kernel_release)], print_output=False, ) @@ -311,7 +311,7 @@ def test_bad_kernel_package_signature_invalid_signature( assert excinfo.value.template == template assert excinfo.value.variables == variables run_subprocess_mocked.assert_called_with( - ["rpm", "-qf", "--qf", "%{NEVRA}", "/boot/vmlinuz-%s" % kernel_release], + ["rpm", "-qf", "--qf", "%{NEVRA}", "/boot/vmlinuz-{}".format(kernel_release)], print_output=False, ) diff --git a/convert2rhel/unit_tests/actions/system_checks/tainted_kmods_test.py b/convert2rhel/unit_tests/actions/system_checks/tainted_kmods_test.py index ca6c5e5185..1ae9cb30db 100644 --- a/convert2rhel/unit_tests/actions/system_checks/tainted_kmods_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/tainted_kmods_test.py @@ -73,7 +73,7 @@ def test_check_tainted_kmods(monkeypatch, command_return, is_error, tainted_kmod diagnosis=( "Tainted kernel modules detected:\n system76_io\n system76_acpi\nThird-party " "components are not supported per our software support" - " policy:\n%s\n" % LINK_KMODS_RH_POLICY + " policy:\n{}\n".format(LINK_KMODS_RH_POLICY) ), remediations=( "Prevent the modules from loading by following {0}" @@ -129,7 +129,7 @@ def test_check_tainted_kmods_skip(monkeypatch, command_return, is_error, tainted diagnosis=( "Tainted kernel modules detected:\n system76_io\n system76_acpi\nThird-party " "components are not supported per our software support" - " policy:\n%s\n" % LINK_KMODS_RH_POLICY + " policy:\n{}\n".format(LINK_KMODS_RH_POLICY) ), remediations=( "Prevent the modules from loading by following {0}" diff --git a/convert2rhel/unit_tests/backup/backup_test.py b/convert2rhel/unit_tests/backup/backup_test.py index d50c929189..b9f34b4ea3 100644 --- a/convert2rhel/unit_tests/backup/backup_test.py +++ b/convert2rhel/unit_tests/backup/backup_test.py @@ -67,7 +67,7 @@ def test_pop_multiple(self, backup_controller): assert restorable2.called["restore"] == 1 assert restorable3.called["restore"] == 1 - assert backup_controller.rollback_failed == False + assert backup_controller.rollback_failed is False assert backup_controller.rollback_failures == [] def test_pop_when_empty(self, backup_controller): @@ -94,7 +94,7 @@ def test_pop_all(self, backup_controller): assert restorable2.called["restore"] == 1 assert restorable3.called["restore"] == 1 - assert backup_controller.rollback_failed == False + assert backup_controller.rollback_failed is False assert backup_controller.rollback_failures == [] def test_ready_to_push_after_pop_all(self, backup_controller): @@ -109,13 +109,13 @@ def test_ready_to_push_after_pop_all(self, backup_controller): assert popped_restorables[0] == restorable1 assert len(backup_controller._restorables) == 1 assert backup_controller._restorables[0] is restorable2 - assert backup_controller.rollback_failed == False + assert backup_controller.rollback_failed is False def test_pop_all_when_empty(self, backup_controller): with pytest.raises(IndexError, match="No backups to restore"): backup_controller.pop_all() - assert backup_controller.rollback_failed == False + assert backup_controller.rollback_failed is False assert backup_controller.rollback_failures == [] def test_pop_all_error_in_restore(self, backup_controller, caplog): @@ -132,7 +132,7 @@ def test_pop_all_error_in_restore(self, backup_controller, caplog): assert len(popped_restorables) == 3 assert popped_restorables == [restorable3, restorable2, restorable1] assert caplog.records[-1].message == "Error while rolling back a ErrorOnRestoreRestorable: Restorable2 failed" - assert backup_controller.rollback_failed == True + assert backup_controller.rollback_failed is True assert backup_controller.rollback_failures == [ "Error while rolling back a ErrorOnRestoreRestorable: Restorable2 failed" ] diff --git a/convert2rhel/unit_tests/backup/certs_test.py b/convert2rhel/unit_tests/backup/certs_test.py index a03d74cf5c..1e1d45f0ad 100644 --- a/convert2rhel/unit_tests/backup/certs_test.py +++ b/convert2rhel/unit_tests/backup/certs_test.py @@ -135,7 +135,7 @@ def test_init_cert_paths(self, arch, rhel_version, pem): assert system_cert._cert_filename == pem assert system_cert._source_cert_path == os.path.join(source_cert_dir, pem) assert system_cert._target_cert_path == os.path.join(fake_target_dir, pem) - assert system_cert.previously_installed == False + assert not system_cert.previously_installed def test_enable_cert(self, system_cert_with_target_path): system_cert_with_target_path.enable() @@ -199,7 +199,7 @@ def test_enable_certificate_already_present(self, caplog, system_cert_with_targe assert system_cert_with_target_path.enabled assert system_cert_with_target_path.previously_installed assert ( - "Certificate already present at %s. Skipping copy." % system_cert_with_target_path._target_cert_path + "Certificate already present at {}. Skipping copy.".format(system_cert_with_target_path._target_cert_path) == caplog.messages[-1] ) @@ -222,7 +222,7 @@ def test_restore_cert(self, caplog, monkeypatch, system_cert_with_target_path): system_cert_with_target_path.restore() - assert "Certificate %s removed" % system_cert_with_target_path._target_cert_path in caplog.messages[-1] + assert "Certificate {} removed".format(system_cert_with_target_path._target_cert_path) in caplog.messages[-1] def test_restore_cert_previously_installed(self, caplog, monkeypatch, system_cert_with_target_path): monkeypatch.setattr(os.path, "exists", lambda x: True) @@ -231,8 +231,9 @@ def test_restore_cert_previously_installed(self, caplog, monkeypatch, system_cer system_cert_with_target_path.restore() assert ( - "Certificate %s was present before conversion. Skipping removal." - % system_cert_with_target_path._cert_filename + "Certificate {} was present before conversion. Skipping removal.".format( + system_cert_with_target_path._cert_filename + ) in caplog.messages[-1] ) diff --git a/convert2rhel/unit_tests/backup/files_test.py b/convert2rhel/unit_tests/backup/files_test.py index 618af0991b..832f9f4440 100644 --- a/convert2rhel/unit_tests/backup/files_test.py +++ b/convert2rhel/unit_tests/backup/files_test.py @@ -4,7 +4,6 @@ import os import pytest -import six from convert2rhel import exceptions from convert2rhel.backup import files @@ -12,10 +11,6 @@ from convert2rhel.unit_tests.conftest import centos7, centos8 -six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) -from six.moves import mock - - class TestRestorableFile: @pytest.fixture def get_backup_file_dir(self, tmpdir, filename="filename", content="content", backup_dir_name="backup"): @@ -220,7 +215,7 @@ def test_restorable_file_restore(self, tmpdir, caplog, messages, enabled, rollba assert not os.path.isfile(orig_file_path) @centos7 - def test_restorable_file_missing_backup(self, tmpdir, pretend_os): + def test_restorable_file_missing_backup_centos7(self, tmpdir, pretend_os): """Test when the backed up file is missing in the backup folder.""" # Get the path of the original file, not creating it orig_file_path = str(tmpdir.join("filename")) @@ -239,7 +234,7 @@ def test_restorable_file_missing_backup(self, tmpdir, pretend_os): file_backup.restore() @centos8 - def test_restorable_file_missing_backup(self, tmpdir, pretend_os): + def test_restorable_file_missing_backup_centos8(self, tmpdir, pretend_os): """Test when the backed up file is missing in the backup folder.""" # Get the path of the original file, not creating it orig_file_path = str(tmpdir.join("filename")) @@ -299,7 +294,7 @@ def test_hash_backup_path(self, filepath, tmpdir, monkeypatch): backup_dir = str(tmpdir) monkeypatch.setattr(files, "BACKUP_DIR", backup_dir) path, name = os.path.split(filepath) - expected = "%s/%s/%s" % (backup_dir, hashlib.md5(path.encode()).hexdigest(), name) + expected = "{}/{}/{}".format(backup_dir, hashlib.md5(path.encode()).hexdigest(), name) file = RestorableFile(filepath) result = file._hash_backup_path() diff --git a/convert2rhel/unit_tests/backup/packages_test.py b/convert2rhel/unit_tests/backup/packages_test.py index 2408412d0d..90515e2b7f 100644 --- a/convert2rhel/unit_tests/backup/packages_test.py +++ b/convert2rhel/unit_tests/backup/packages_test.py @@ -173,7 +173,7 @@ def test_restorable_package_backup_without_dir(self, monkeypatch, tmpdir, caplog rp = RestorablePackage(pkgs=["pkg-1"]) rp.enable() - assert "Can't access %s" % backup_dir in caplog.records[-1].message + assert "Can't access {}".format(backup_dir) in caplog.records[-1].message def test_install_local_rpms_package_install_warning(self, monkeypatch, caplog): pkg_name = "pkg-1" @@ -188,9 +188,9 @@ def test_install_local_rpms_package_install_warning(self, monkeypatch, caplog): rp._backedup_pkgs_paths = pkgs result = rp._install_local_rpms(replace=False, critical=False) - assert result == False + assert not result assert run_subprocess_mock.call_count == 1 - assert "Couldn't install %s packages." % pkg_name in caplog.records[-1].message + assert "Couldn't install {} packages.".format(pkg_name) in caplog.records[-1].message def test_test_install_local_rpms_system_exit(self, monkeypatch, caplog): pkg_name = ["pkg-1"] @@ -211,7 +211,7 @@ def test_test_install_local_rpms_system_exit(self, monkeypatch, caplog): rp._install_local_rpms(replace=False, critical=True) assert run_subprocess_mock.call_count == 1 - assert "Error: Couldn't install %s packages." % "".join(pkg_name) in caplog.records[-1].message + assert "Error: Couldn't install {} packages.".format("".join(pkg_name)) in caplog.records[-1].message class TestRestorablePackageSet: @@ -259,7 +259,7 @@ def test_smoketest_init(self, pkgs_to_install, setopts): assert package_set.enabled is False # We actually care that this is an empty list and not just False-y - assert package_set.installed_pkgs == [] # pylint: disable=use-implicit-booleaness-not-comparison + assert package_set.installed_pkgs == [] @pytest.mark.parametrize( ("major", "minor"), diff --git a/convert2rhel/unit_tests/breadcrumbs_test.py b/convert2rhel/unit_tests/breadcrumbs_test.py index 5e99b47b11..c0bc7d46a6 100644 --- a/convert2rhel/unit_tests/breadcrumbs_test.py +++ b/convert2rhel/unit_tests/breadcrumbs_test.py @@ -240,18 +240,18 @@ def test_save_rhsm_facts(pretend_os, monkeypatch, tmpdir, caplog): ) breadcrumbs.breadcrumbs._save_rhsm_facts() - assert "Writing RHSM custom facts to '%s'" % rhsm_file in caplog.records[-1].message + assert "Writing RHSM custom facts to '{}'".format(rhsm_file) in caplog.records[-1].message def test_save_rhsm_facts_no_rhsm_folder(monkeypatch, tmpdir, caplog): rhsm_folder = str(tmpdir.join("rhsm").join("facts")) - rhsm_file = "%s/convert2rhel.facts" % rhsm_folder + rhsm_file = "{}/convert2rhel.facts".format(rhsm_folder) monkeypatch.setattr(breadcrumbs, "RHSM_CUSTOM_FACTS_FOLDER", rhsm_folder) monkeypatch.setattr(breadcrumbs, "RHSM_CUSTOM_FACTS_FILE", rhsm_file) breadcrumbs.breadcrumbs._save_rhsm_facts() - assert "No RHSM facts folder found at '%s'." % rhsm_folder in caplog.records[-2].message - assert "Writing RHSM custom facts to '%s'" % rhsm_file in caplog.records[-1].message + assert "No RHSM facts folder found at '{}'.".format(rhsm_folder) in caplog.records[-2].message + assert "Writing RHSM custom facts to '{}'".format(rhsm_file) in caplog.records[-1].message def test_save_migration_results(tmpdir, monkeypatch, caplog): @@ -262,7 +262,7 @@ def test_save_migration_results(tmpdir, monkeypatch, caplog): breadcrumbs.breadcrumbs._save_migration_results() - assert "Writing breadcrumbs to '%s'." % migration_results in caplog.records[-1].message + assert "Writing breadcrumbs to '{}'.".format(migration_results) in caplog.records[-1].message assert write_obj_to_array_json_mock.call_count == 1 @@ -294,14 +294,6 @@ def test_set_nevra_yum(monkeypatch, _mock_pkg_obj): assert breadcrumbs.breadcrumbs.nevra == "1:convert2rhel-2-3.x86_64" -def test_set_nevra_dnf(monkeypatch, _mock_pkg_obj): - monkeypatch.setattr(pkgmanager, "TYPE", "dnf") - monkeypatch.setattr(breadcrumbs.breadcrumbs, "_pkg_object", _mock_pkg_obj) - breadcrumbs.breadcrumbs._set_nevra() - - assert breadcrumbs.breadcrumbs.nevra == "convert2rhel-1:2-3.x86_64" - - def test_set_signature(monkeypatch, _mock_pkg_obj, _mock_pkg_information): monkeypatch.setattr(pkgmanager, "TYPE", "yum") monkeypatch.setattr(breadcrumbs.breadcrumbs, "_pkg_object", _mock_pkg_obj) diff --git a/convert2rhel/unit_tests/checks_test.py b/convert2rhel/unit_tests/checks_test.py index 271dd265d3..a0397c5acf 100644 --- a/convert2rhel/unit_tests/checks_test.py +++ b/convert2rhel/unit_tests/checks_test.py @@ -43,4 +43,4 @@ def testis_initramfs_file_valid(latest_installed_kernel, subprocess_output, expe if not expected: assert "Couldn't verify initramfs file. It may be corrupted." in caplog.records[-2].message - assert "Output of lsinitrd: %s" % subprocess_output[0] in caplog.records[-1].message + assert "Output of lsinitrd: {}".format(subprocess_output[0]) in caplog.records[-1].message diff --git a/convert2rhel/unit_tests/cli_test.py b/convert2rhel/unit_tests/cli_test.py index 2525ee2cd6..e290ba0416 100644 --- a/convert2rhel/unit_tests/cli_test.py +++ b/convert2rhel/unit_tests/cli_test.py @@ -122,7 +122,7 @@ def test_bad_serverurl(self, caplog, monkeypatch, serverurl): message = ( "Failed to parse a valid subscription-manager server from the --serverurl option.\n" "Please check for typos and run convert2rhel again with a corrected --serverurl.\n" - "Supplied serverurl: %s\nError: " % serverurl + "Supplied serverurl: {}\nError: ".format(serverurl) ) assert message in caplog.records[-1].message assert caplog.records[-1].levelname == "CRITICAL" diff --git a/convert2rhel/unit_tests/conftest.py b/convert2rhel/unit_tests/conftest.py index a461eb1e71..f1315e0090 100644 --- a/convert2rhel/unit_tests/conftest.py +++ b/convert2rhel/unit_tests/conftest.py @@ -225,7 +225,7 @@ def pretend_os(request, pkg_root, monkeypatch, global_tool_opts): monkeypatch.setattr( utils, "DATA_DIR", - value=str(pkg_root / ("convert2rhel/data/%s/x86_64/" % system_version_major)), + value=str(pkg_root / ("convert2rhel/data/{}/x86_64/".format(system_version_major))), ) monkeypatch.setattr( redhatrelease, @@ -235,7 +235,7 @@ def pretend_os(request, pkg_root, monkeypatch, global_tool_opts): monkeypatch.setattr( utils, "get_file_content", - value=lambda _: "%s release %s" % (system_name, system_version), + value=lambda _: "{} release {}".format(system_name, system_version), ) monkeypatch.setattr( system_info, diff --git a/convert2rhel/unit_tests/grub_test.py b/convert2rhel/unit_tests/grub_test.py index b2aac73d53..03c2064dfd 100644 --- a/convert2rhel/unit_tests/grub_test.py +++ b/convert2rhel/unit_tests/grub_test.py @@ -98,7 +98,7 @@ def test__get_partition(monkeypatch, caplog, expected_res, directory, exception, if exception: with pytest.raises(exception): grub._get_partition(directory) - assert "grub2-probe returned %s. Output:\n%s" % (subproc[1], subproc[0]) in caplog.records[-1].message + assert "grub2-probe returned {}. Output:\n{}".format(subproc[1], subproc[0]) in caplog.records[-1].message else: assert grub._get_partition(directory) == expected_res assert len(caplog.records) == 0 diff --git a/convert2rhel/unit_tests/main_test.py b/convert2rhel/unit_tests/main_test.py index 1715b1a481..610781675d 100644 --- a/convert2rhel/unit_tests/main_test.py +++ b/convert2rhel/unit_tests/main_test.py @@ -63,7 +63,7 @@ def test_rollback_changes(self, monkeypatch, global_backup_control): main.rollback_changes() assert global_backup_control.pop_all.call_args_list == mock.call() - assert backup.backup_control.rollback_failed == False + assert backup.backup_control.rollback_failed is False def test_backup_control_unknown_exception(self, monkeypatch, global_backup_control): monkeypatch.setattr( diff --git a/convert2rhel/unit_tests/pkghandler_test.py b/convert2rhel/unit_tests/pkghandler_test.py index c4ce17d9c0..36744e71c7 100644 --- a/convert2rhel/unit_tests/pkghandler_test.py +++ b/convert2rhel/unit_tests/pkghandler_test.py @@ -94,7 +94,7 @@ def _setup_pkg(self): self.pkg_obj = TestPkgObj() self.pkg_obj.name = "installed_pkg" - def __iter__(self): # pylint: disable=non-iterator-returned + def __iter__(self): return self def __next__(self): @@ -338,7 +338,7 @@ def test_replace_non_rhel_installed_kernel_rhsm_repos(self, monkeypatch): "--force", "--nodeps", "--replacepkgs", - "%skernel-4.7.4-200.fc24*" % utils.TMP_DIR, + "{}kernel-4.7.4-200.fc24*".format(utils.TMP_DIR), ] def test_replace_non_rhel_installed_kernel_custom_repos(self, monkeypatch, global_tool_opts): @@ -746,13 +746,13 @@ def test_get_total_packages_to_update( if package_manager_type == "dnf": monkeypatch.setattr( pkghandler, - "_get_packages_to_update_%s" % package_manager_type, + "_get_packages_to_update_{}".format(package_manager_type), value=lambda disable_repos: packages, ) else: monkeypatch.setattr( pkghandler, - "_get_packages_to_update_%s" % package_manager_type, + "_get_packages_to_update_{}".format(package_manager_type), value=lambda disable_repos: packages, ) assert get_total_packages_to_update() == expected @@ -1806,9 +1806,9 @@ def test_get_package_repositories_repoquery_failure(pretend_os, monkeypatch, cap result = pkghandler._get_package_repositories(packages) assert "Repoquery exited with return code 1 and with output: failed" in caplog.records[-1].message - for package, repo in result.items(): + for package, package_repo in result.items(): assert package in packages - assert repo == "N/A" + assert package_repo == "N/A" @pytest.mark.parametrize( diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/dnf/dnf_test.py b/convert2rhel/unit_tests/pkgmanager/handlers/dnf/dnf_test.py index 219975191c..ceae3ac05d 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/dnf/dnf_test.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/dnf/dnf_test.py @@ -178,7 +178,7 @@ def test_enable_repos( monkeypatch.setattr(system_info, "get_enabled_rhel_repos", lambda: enabled_rhel_repos) instance._enable_repos() - assert "Enabling RHEL repositories:\n%s" % "\n".join(enabled_rhel_repos) in caplog.records[-1].message + assert "Enabling RHEL repositories:\n{}".format("\n".join(enabled_rhel_repos)) in caplog.records[-1].message for repo in enabled_repos: assert repo.enabled == is_enabled diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/yum/callback_test.py b/convert2rhel/unit_tests/pkgmanager/handlers/yum/callback_test.py index 1c6def1c8e..f56fa046e8 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/yum/callback_test.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/yum/callback_test.py @@ -77,7 +77,7 @@ def test_event_multiple_packages(self, caplog): for package in packages: instance.event(package=package, action=20, te_current=1, te_total=1, ts_current=1, ts_total=1) - assert "Installing: %s [1/1]" % package in caplog.records[-1].message + assert "Installing: {} [1/1]".format(package) in caplog.records[-1].message assert len(caplog.records) == 2 diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/yum/yum_test.py b/convert2rhel/unit_tests/pkgmanager/handlers/yum/yum_test.py index c4365a3776..f7575976f5 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/yum/yum_test.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/yum/yum_test.py @@ -116,7 +116,7 @@ def test_enable_repos(self, pretend_os, enabled_rhel_repos, caplog, monkeypatch) monkeypatch.setattr(system_info, "get_enabled_rhel_repos", lambda: enabled_rhel_repos) instance._enable_repos() - assert "Enabling RHEL repositories:\n%s" % "".join(enabled_rhel_repos) in caplog.records[-1].message + assert "Enabling RHEL repositories:\n{}".format("".join(enabled_rhel_repos)) in caplog.records[-1].message assert pkgmanager.RepoStorage.disableRepo.called_once() assert pkgmanager.RepoStorage.enableRepo.call_count == len(enabled_rhel_repos) diff --git a/convert2rhel/unit_tests/pkgmanager/pkgmanager_test.py b/convert2rhel/unit_tests/pkgmanager/pkgmanager_test.py index d7fd21788b..73694dd52d 100644 --- a/convert2rhel/unit_tests/pkgmanager/pkgmanager_test.py +++ b/convert2rhel/unit_tests/pkgmanager/pkgmanager_test.py @@ -22,7 +22,6 @@ from convert2rhel import pkgmanager, systeminfo, utils from convert2rhel.systeminfo import Version, system_info -from convert2rhel.toolopts import tool_opts from convert2rhel.unit_tests import RunSubprocessMocked, run_subprocess_side_effect from convert2rhel.unit_tests.conftest import centos7, centos8 @@ -266,7 +265,7 @@ def test_call_yum_cmd_setopts_override(self, setopts, pretend_os, monkeypatch, c ] for setopt in setopts: - expected_cmd.append("--setopt=%s" % setopt) + expected_cmd.append("--setopt={}".format(setopt)) expected_cmd.append("pkg") assert utils.run_subprocess.cmd == expected_cmd diff --git a/convert2rhel/unit_tests/pyproject.toml b/convert2rhel/unit_tests/pyproject.toml index e0048323eb..7d057d0654 100644 --- a/convert2rhel/unit_tests/pyproject.toml +++ b/convert2rhel/unit_tests/pyproject.toml @@ -2,4 +2,5 @@ # Extend the `pyproject.toml` file in the parent directory... extend = "../../pyproject.toml" +[tool.ruff.lint] ignore = ["E402"] diff --git a/convert2rhel/unit_tests/redhatrelease_test.py b/convert2rhel/unit_tests/redhatrelease_test.py index a3e9e980ac..f47ede87e3 100644 --- a/convert2rhel/unit_tests/redhatrelease_test.py +++ b/convert2rhel/unit_tests/redhatrelease_test.py @@ -60,7 +60,6 @@ def test_get_pkg_manager_conf_content(monkeypatch): @pytest.mark.parametrize("version", SUPPORTED_RHEL_VERSIONS) def test_patch_pkg_manager_conf_missing_distroverpkg(version, monkeypatch, pkg_manager_conf_instance): - monkeypatch.setattr(system_info, "version", version) pkg_manager_conf = pkg_manager_conf_instance pkg_manager_conf._pkg_manager_conf_content = PKG_MANAGER_CONF_WITHOUT_DISTROVERPKG @@ -74,7 +73,6 @@ def test_patch_pkg_manager_conf_missing_distroverpkg(version, monkeypatch, pkg_m @pytest.mark.parametrize("version", SUPPORTED_RHEL_VERSIONS) def test_patch_pkg_manager_conf_existing_distroverpkg(version, monkeypatch, pkg_manager_conf_instance): - monkeypatch.setattr(system_info, "version", systeminfo.Version(version, 0)) pkg_manager_conf = pkg_manager_conf_instance pkg_manager_conf._pkg_manager_conf_content = PKG_MANAGER_CONF_WITH_DISTROVERPKG diff --git a/convert2rhel/unit_tests/repo_test.py b/convert2rhel/unit_tests/repo_test.py index 88cadae6d2..be04b0a848 100644 --- a/convert2rhel/unit_tests/repo_test.py +++ b/convert2rhel/unit_tests/repo_test.py @@ -20,13 +20,10 @@ import os import pytest -import six from convert2rhel import exceptions, repo from convert2rhel.unit_tests.conftest import centos7, centos8 - -six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock, urllib diff --git a/convert2rhel/unit_tests/subscription_test.py b/convert2rhel/unit_tests/subscription_test.py index 9edc643057..b20bc5a0e8 100644 --- a/convert2rhel/unit_tests/subscription_test.py +++ b/convert2rhel/unit_tests/subscription_test.py @@ -892,7 +892,7 @@ def test_unregister_system_failure(self, output, ret_code, expected, monkeypatch with pytest.raises( subscription.UnregisterError, - match="System unregistration result:\n%s" % output, + match="System unregistration result:\n{}".format(output), ): subscription.unregister_system() @@ -999,8 +999,8 @@ def test_enable_repos_rhel_repoids( ): monkeypatch.setattr(subscription, "system_info", global_system_info) cmd_mock = ["subscription-manager", "repos"] - for repo in rhel_repoids: - cmd_mock.append("--enable=%s" % repo) + for repo_to_enable in rhel_repoids: + cmd_mock.append("--enable={}".format(repo_to_enable)) run_subprocess_mock = RunSubprocessMocked( side_effect=unit_tests.run_subprocess_side_effect( @@ -1063,8 +1063,8 @@ def test_enable_repos_toolopts_enablerepo( ): monkeypatch.setattr(subscription, "system_info", global_system_info) cmd_mock = ["subscription-manager", "repos"] - for repo in toolopts_enablerepo: - cmd_mock.append("--enable=%s" % repo) + for repo_to_enable in toolopts_enablerepo: + cmd_mock.append("--enable={}".format(repo_to_enable)) run_subprocess_mock = RunSubprocessMocked( side_effect=unit_tests.run_subprocess_side_effect( diff --git a/convert2rhel/unit_tests/systeminfo_test.py b/convert2rhel/unit_tests/systeminfo_test.py index 802c0646a7..c9699e17fb 100644 --- a/convert2rhel/unit_tests/systeminfo_test.py +++ b/convert2rhel/unit_tests/systeminfo_test.py @@ -160,7 +160,7 @@ def test_get_dbus_status_in_progress(monkeypatch, states, expected): side_effects = [] for state in states: - side_effects.append(("ActiveState=%s\n" % state, 0)) + side_effects.append(("ActiveState={}\n".format(state), 0)) run_subprocess_mocked = RunSubprocessMocked(side_effect=side_effects) monkeypatch.setattr(utils, "run_subprocess", run_subprocess_mocked) diff --git a/convert2rhel/unit_tests/utils/utils_test.py b/convert2rhel/unit_tests/utils/utils_test.py index 2a61212a86..3e1fa73f8b 100644 --- a/convert2rhel/unit_tests/utils/utils_test.py +++ b/convert2rhel/unit_tests/utils/utils_test.py @@ -44,8 +44,8 @@ DOWNLOADED_RPM_NVRA = "kernel-4.18.0-193.28.1.el8_2.x86_64" -DOWNLOADED_RPM_NEVRA = "7:%s" % DOWNLOADED_RPM_NVRA -DOWNLOADED_RPM_FILENAME = "%s.rpm" % DOWNLOADED_RPM_NVRA +DOWNLOADED_RPM_NEVRA = "7:{}".format(DOWNLOADED_RPM_NVRA) +DOWNLOADED_RPM_FILENAME = "{}.rpm".format(DOWNLOADED_RPM_NVRA) YUMDOWNLOADER_OUTPUTS = ( "{0} 97% [================================================- ] 6.8 MB/s | 21 MB 00:00:00 ETA\n" @@ -53,11 +53,11 @@ "{0} | 21 MB 00:00:01\n" "== Rebuilding _local repo. with 1 new packages ==".format(DOWNLOADED_RPM_FILENAME), "Last metadata expiration check: 2:47:36 ago on Thu 22 Oct 2020 06:07:08 PM CEST.\n" - "%s 2.7 MB/s | 2.8 MB 00:01" % DOWNLOADED_RPM_FILENAME, - "/var/lib/convert2rhel/%s already exists and appears to be complete" % DOWNLOADED_RPM_FILENAME, - "rpmdb time: 0.000\nusing local copy of %s" % DOWNLOADED_RPM_NEVRA, - "rpmdb time: 0.000\nusing local copy of %s\r\n" % DOWNLOADED_RPM_NEVRA, - "[SKIPPED] %s: Already downloaded" % DOWNLOADED_RPM_FILENAME, + "{} 2.7 MB/s | 2.8 MB 00:01".format(DOWNLOADED_RPM_FILENAME), + "/var/lib/convert2rhel/{} already exists and appears to be complete".format(DOWNLOADED_RPM_FILENAME), + "rpmdb time: 0.000\nusing local copy of {}".format(DOWNLOADED_RPM_NEVRA), + "rpmdb time: 0.000\nusing local copy of {}\r\n".format(DOWNLOADED_RPM_NEVRA), + "[SKIPPED] {}: Already downloaded".format(DOWNLOADED_RPM_FILENAME), ) @@ -145,7 +145,7 @@ def test_run_cmd_in_pty_expect_script(capfd): prompt_cmd = "input" with capfd.disabled(): output, code = utils.run_cmd_in_pty( - [sys.executable, "-c", 'print(%s("Ask for password: "))' % prompt_cmd], + [sys.executable, "-c", 'print({}("Ask for password: "))'.format(prompt_cmd)], expect_script=(("password: *", "Foo bar\n"),), ) @@ -389,7 +389,8 @@ def test_find_keyid_no_gpg_output(self, monkeypatch): monkeypatch.setattr(utils, "run_subprocess", FakeSecondCallToRunSubprocessMocked(second_call_return_code=0)) with pytest.raises( - utils.ImportGPGKeyError, match="Unable to determine the gpg keyid for the rpm key file: %s" % self.gpg_key + utils.ImportGPGKeyError, + match="Unable to determine the gpg keyid for the rpm key file: {}".format(self.gpg_key), ): utils.find_keyid(self.gpg_key) @@ -447,7 +448,14 @@ def test_download_pkgs(self, monkeypatch): monkeypatch.setattr( utils, "download_pkg", - lambda pkg, dest, reposdir, enable_repos, disable_repos, set_releasever, custom_releasever, varsdir: "/filepath/", + lambda pkg, + dest, + reposdir, + enable_repos, + disable_repos, + set_releasever, + custom_releasever, + varsdir: "/filepath/", ) paths = utils.download_pkgs( @@ -493,8 +501,8 @@ def test_download_pkg_success_with_all_params(self, monkeypatch): "yumdownloader", "-v", "--setopt=exclude=", - "--destdir=%s" % dest, - "--setopt=reposdir=%s" % reposdir, + "--destdir={}".format(dest), + "--setopt=reposdir={}".format(reposdir), "--disablerepo=*", "--enablerepo=repo1", "--enablerepo=repo2", @@ -900,12 +908,12 @@ def test_run_subprocess(self, command, expected): assert (output, code) == expected - @pytest.mark.popen_output([u"test of nonascii output: café".encode("utf-8")]) + @pytest.mark.popen_output(["test of nonascii output: café".encode("utf-8")]) def test_run_subprocess_env(self, dummy_popen, monkeypatch): monkeypatch.setattr(utils.subprocess, "Popen", dummy_popen) output, rc = utils.run_subprocess(["echo", "foobar"]) - assert u"test of nonascii output: café" == output + assert "test of nonascii output: café" == output assert 0 == rc @@ -946,7 +954,7 @@ def return_with_parameter(something): @staticmethod def return_with_both_args_and_kwargs(args, kwargs): - return "%s, %s" % (args, kwargs) + return "{}, {}".format(args, kwargs) @staticmethod def raise_bare_system_exit_exception(): diff --git a/convert2rhel/utils/__init__.py b/convert2rhel/utils/__init__.py index 8d5bd35040..713d428b9f 100644 --- a/convert2rhel/utils/__init__.py +++ b/convert2rhel/utils/__init__.py @@ -127,7 +127,7 @@ def run(self): try: self._cconn.send(e) except pickle.PicklingError: - self._cconn.send(UnableToSerialize("Child process raised %s: %s" % (type(e), str(e)))) + self._cconn.send(UnableToSerialize("Child process raised {}: {}".format(type(e), str(e)))) @property def exception(self): @@ -342,9 +342,9 @@ def run_subprocess(cmd, print_cmd=True, print_output=True): raise TypeError("cmd should be a list, not a str") if print_cmd: - logger.debug("Calling command '%s'" % " ".join(cmd)) + logger.debug("Calling command '{}'".format(" ".join(cmd))) - process = subprocess.Popen( # pylint: disable=consider-using-with + process = subprocess.Popen( # Popen is only a context manager in Python-3.2+ cmd, stdout=subprocess.PIPE, @@ -401,7 +401,7 @@ def run_cmd_in_pty(cmd, expect_script=(), print_cmd=True, print_output=True, col raise TypeError("cmd should be a list, not a str") if print_cmd: - logger.debug("Calling command '%s'" % " ".join(cmd)) + logger.debug("Calling command '{}'".format(" ".join(cmd))) process = PexpectSpawnWithDimensions( cmd[0], @@ -490,7 +490,7 @@ def _setwinsize(rows, cols): super(PexpectSpawnWithDimensions, self).setwinsize(dimensions[0], dimensions[1]) # Save the real setwinsize and monkeypatch our kludge in - real_setwinsize = self.setwinsize # pylint: disable=access-member-before-definition + real_setwinsize = self.setwinsize self.setwinsize = _setwinsize # Call pexpect.spawn.__init__() which will use the monkeypatched setwinsize() @@ -556,11 +556,11 @@ def remove_tmp_dir(): """Remove temporary folder (TMP_DIR), not needed post-conversion.""" try: shutil.rmtree(TMP_DIR) - logger.info("Temporary folder %s removed" % TMP_DIR) + logger.info("Temporary folder {} removed".format(TMP_DIR)) except OSError as err: - logger.warning("Failed removing temporary folder %s\nError (%s): %s" % (TMP_DIR, err.errno, err.strerror)) + logger.warning("Failed removing temporary folder {}\nError ({}): {}".format(TMP_DIR, err.errno, err.strerror)) except TypeError: - logger.warning("TypeError error while removing temporary folder %s" % TMP_DIR) + logger.warning("TypeError error while removing temporary folder {}".format(TMP_DIR)) class DictWListValues(dict): @@ -636,32 +636,32 @@ def download_pkg( """ from convert2rhel.systeminfo import system_info - logger.debug("Downloading the %s package." % pkg) + logger.debug("Downloading the {} package.".format(pkg)) # On RHEL 7, it's necessary to invoke yumdownloader with -v, otherwise there's no output to stdout. - cmd = ["yumdownloader", "-v", "--setopt=exclude=", "--destdir=%s" % dest] + cmd = ["yumdownloader", "-v", "--setopt=exclude=", "--destdir={}".format(dest)] if reposdir: - cmd.append("--setopt=reposdir=%s" % reposdir) + cmd.append("--setopt=reposdir={}".format(reposdir)) if isinstance(disable_repos, list): for repo in disable_repos: - cmd.append("--disablerepo=%s" % repo) + cmd.append("--disablerepo={}".format(repo)) if isinstance(enable_repos, list): for repo in enable_repos: - cmd.append("--enablerepo=%s" % repo) + cmd.append("--enablerepo={}".format(repo)) if set_releasever: if not custom_releasever and not system_info.releasever: raise AssertionError("custom_releasever or system_info.releasever must be set.") if custom_releasever: - cmd.append("--releasever=%s" % custom_releasever) + cmd.append("--releasever={}".format(custom_releasever)) else: - cmd.append("--releasever=%s" % system_info.releasever) + cmd.append("--releasever={}".format(system_info.releasever)) if varsdir: - cmd.append("--setopt=varsdir=%s" % varsdir) + cmd.append("--setopt=varsdir={}".format(varsdir)) if system_info.version.major >= 8: cmd.append("--setopt=module_platform_id=platform:el" + str(system_info.version.major)) @@ -678,8 +678,8 @@ def download_pkg( report_on_a_download_error(output, pkg) return None - logger.info("Successfully downloaded the %s package." % pkg) - logger.debug("Path of the downloaded package: %s" % path) + logger.info("Successfully downloaded the {} package.".format(pkg)) + logger.debug("Path of the downloaded package: {}".format(path)) return path @@ -709,7 +709,7 @@ def remove_pkgs(pkgs_to_remove, critical=True): # handle the epoch well and considers the package we want to remove as not installed. On the other hand, the # epoch in NEVRA returned by dnf is handled by rpm just fine. nvra = _remove_epoch_from_yum_nevra_notation(nevra) - logger.info("Removing package: %s" % nvra) + logger.info("Removing package: {}".format(nvra)) _, ret_code = run_subprocess(["rpm", "-e", "--nodeps", nvra]) if ret_code != 0: pkgs_failed_to_remove.append(nevra) @@ -719,15 +719,15 @@ def remove_pkgs(pkgs_to_remove, critical=True): if pkgs_failed_to_remove: pkgs_as_str = format_sequence_as_message(pkgs_failed_to_remove) if critical: - logger.critical_no_exit("Error: Couldn't remove %s." % pkgs_as_str) + logger.critical_no_exit("Error: Couldn't remove {}.".format(pkgs_as_str)) raise exceptions.CriticalError( id_="FAILED_TO_REMOVE_PACKAGES", title="Couldn't remove packages.", description="While attempting to roll back changes, we encountered an unexpected failure while attempting to remove one or more of the packages we installed earlier.", - diagnosis="Couldn't remove %s." % pkgs_as_str, + diagnosis="Couldn't remove {}.".format(pkgs_as_str), ) else: - logger.warning("Couldn't remove %s." % pkgs_as_str) + logger.warning("Couldn't remove {}.".format(pkgs_as_str)) return pkgs_removed @@ -757,7 +757,7 @@ def report_on_a_download_error(output, pkg): :param output: Output of the yumdownloader call :param pkg: Name of a package to be downloaded """ - logger.warning("Output from the yumdownloader call:\n%s" % output) + logger.warning("Output from the yumdownloader call:\n{}".format(output)) # Note: Using toolopts here is a temporary solution. We need to # restructure this to raise an exception on error and have the caller @@ -789,28 +789,28 @@ def report_on_a_download_error(output, pkg): if toolopts.tool_opts.activity == "conversion": if "CONVERT2RHEL_INCOMPLETE_ROLLBACK" not in os.environ: logger.critical( - "Couldn't download the %s package. This means we will not be able to do a" + "Couldn't download the {} package. This means we will not be able to do a" " complete rollback and may put the system in a broken state.\n" - "Check to make sure that the %s repositories are enabled" + "Check to make sure that the {} repositories are enabled" " and the package is updated to its latest version.\n" "If you would rather disregard this check set the environment variable" - " 'CONVERT2RHEL_INCOMPLETE_ROLLBACK=1'." % (pkg, system_info.name) + " 'CONVERT2RHEL_INCOMPLETE_ROLLBACK=1'.".format(pkg, system_info.name) ) else: logger.warning( - "Couldn't download the %s package. This means we will not be able to do a" + "Couldn't download the {} package. This means we will not be able to do a" " complete rollback and may put the system in a broken state.\n" "'CONVERT2RHEL_INCOMPLETE_ROLLBACK' environment variable detected, continuing" - " conversion." % pkg + " conversion.".format(pkg) ) else: logger.critical( - "Couldn't download the %s package which is needed to do a rollback of this action." - " Check to make sure that the %s repositories are enabled and the package is" + "Couldn't download the {} package which is needed to do a rollback of this action." + " Check to make sure that the {} repositories are enabled and the package is" " updated to its latest version.\n" "Note that you can choose to disregard this check when running a conversion by" " setting the environment variable 'CONVERT2RHEL_INCOMPLETE_ROLLBACK=1'" - " but not during a pre-conversion analysis." % (pkg, system_info.name) + " but not during a pre-conversion analysis.".format(pkg, system_info.name) ) @@ -823,7 +823,7 @@ def get_rpm_path_from_yumdownloader_output(cmd, output, dest): RHEL 8: "[SKIPPED] oraclelinux-release-8.2-1.0.8.el8.x86_64.rpm: Already downloaded" """ if not output: - logger.warning("The output of running yumdownloader is unexpectedly empty. Command:\n%s" % cmd) + logger.warning("The output of running yumdownloader is unexpectedly empty. Command:\n{}".format(cmd)) return None rpm_name_match = re.search(r"\S+\.rpm", output) @@ -836,7 +836,7 @@ def get_rpm_path_from_yumdownloader_output(cmd, output, dest): else: logger.warning( "Couldn't find the name of the downloaded rpm in the output of yumdownloader.\n" - "Command:\n%s\nOutput:\n%s" % (cmd, output) + "Command:\n{}\nOutput:\n{}".format(cmd, output) ) return None @@ -895,7 +895,7 @@ def find_keyid(keyfile): print_output=False, ) if ret_code != 0: - raise ImportGPGKeyError("Failed to import the rpm gpg key into a temporary keyring: %s" % output) + raise ImportGPGKeyError("Failed to import the rpm gpg key into a temporary keyring: {}".format(output)) # Step 2: Print the information about the keys in the temporary keyfile. # --with-colons give us guaranteed machine parsable, stable output. @@ -913,7 +913,7 @@ def find_keyid(keyfile): print_output=False, ) if ret_code != 0: - raise ImportGPGKeyError("Failed to read the temporary keyring with the rpm gpg key: %s" % output) + raise ImportGPGKeyError("Failed to read the temporary keyring with the rpm gpg key: {}".format(output)) finally: # Try five times to work around a race condition: # @@ -939,7 +939,9 @@ def find_keyid(keyfile): # If we get here, we tried and failed to rmtree five times # Don't make this fatal but do let the user know so they can clean # it up themselves. - logger.info("Failed to remove temporary directory %s that held Red Hat gpg public keys." % temporary_dir) + logger.info( + "Failed to remove temporary directory {} that held Red Hat gpg public keys.".format(temporary_dir) + ) keyid = None for line in output.splitlines(): @@ -952,7 +954,7 @@ def find_keyid(keyfile): break if not keyid: - raise ImportGPGKeyError("Unable to determine the gpg keyid for the rpm key file: %s" % keyfile) + raise ImportGPGKeyError("Unable to determine the gpg keyid for the rpm key file: {}".format(keyfile)) return keyid.lower() diff --git a/convert2rhel/utils/subscription.py b/convert2rhel/utils/subscription.py index d23563f0f6..d255b21021 100644 --- a/convert2rhel/utils/subscription.py +++ b/convert2rhel/utils/subscription.py @@ -60,7 +60,7 @@ def setup_rhsm_parts(opts): loggerinst.critical( "Failed to parse a valid subscription-manager server from the --serverurl option.\n" "Please check for typos and run convert2rhel again with a corrected --serverurl.\n" - "Supplied serverurl: %s\nError: %s" % (opts.serverurl, e) + "Supplied serverurl: {}\nError: {}".format(opts.serverurl, e) ) rhsm_parts["rhsm_hostname"] = url_parts.hostname @@ -88,7 +88,7 @@ def _parse_subscription_manager_serverurl(serverurl): raise ValueError("Unable to parse --serverurl. Make sure it starts with http://HOST or https://HOST") # If there isn't a scheme, add one now - serverurl = "https://%s" % serverurl + serverurl = "https://{}".format(serverurl) url_parts = urllib.parse.urlsplit(serverurl, allow_fragments=False) @@ -105,7 +105,7 @@ def _validate_serverurl_parsing(url_parts): """ if url_parts.scheme not in ("https", "http"): raise ValueError( - "Subscription manager must be accessed over http or https. %s is not valid" % url_parts.scheme + "Subscription manager must be accessed over http or https. {} is not valid".format(url_parts.scheme) ) if not url_parts.hostname: diff --git a/scripts/whitelist.py b/scripts/whitelist.py index a20785dfa5..02b46affc5 100644 --- a/scripts/whitelist.py +++ b/scripts/whitelist.py @@ -3,7 +3,6 @@ of things to be ignored by vulture. """ -# pylint: skip-file ti_done # unused variable (convert2rhel/pkgmanager/handlers/dnf/callback.py:231) ti_total # unused variable (convert2rhel/pkgmanager/handlers/dnf/callback.py:231) te_current # unused variable (convert2rhel/pkgmanager/handlers/yum/callback.py:126) diff --git a/setup.py b/setup.py index e27696df4e..fc507ed6cf 100755 --- a/setup.py +++ b/setup.py @@ -41,11 +41,10 @@ def get_version(): except IndexError: raise ValueError( ( - "Unable to extract the version from %s file. Make sure the " + "Unable to extract the version from {} file. Make sure the " "first line has the following form: `__version__ = " '"some.version.here"`' - ) - % version_source + ).format(version_source) ) diff --git a/tests/integration/common/checks-after-conversion/test_release_version.py b/tests/integration/common/checks-after-conversion/test_release_version.py index a928c701be..64c346f8b8 100644 --- a/tests/integration/common/checks-after-conversion/test_release_version.py +++ b/tests/integration/common/checks-after-conversion/test_release_version.py @@ -52,4 +52,4 @@ def test_correct_distro(): break else: # We did not find a known destination_distro - assert False, "Unknown destination distro '%s'" % destination_distro + assert False, "Unknown destination distro '{}'".format(destination_distro) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index eafa408ff6..9d848861d2 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -1,5 +1,4 @@ import configparser -import dataclasses import json import logging import os @@ -70,7 +69,7 @@ def factory(command, silent=False, hide_command=False): "\nExecuting a command:\n{}\n\n".format(command), color="green", ) - # pylint: disable=consider-using-with + # Popen is a context-manager in python-3.2+ process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = "" @@ -337,7 +336,7 @@ def factory( message.extend( ( "== Action caught SystemExit and returned an UNKNOWN_ERROR:", - "%s: %s" % (action.id, action["result"]), + "{}: {}".format(action.id, action["result"]), ) ) @@ -345,7 +344,7 @@ def factory( message.extend( ( "== Action Framework caught an unhandled exception from an Action and returned an UNEXPECTED_ERROR:", - "%s: %s" % (action.id, action["result"]), + "{}: {}".format(action.id, action["result"]), ) ) @@ -359,7 +358,7 @@ def factory( message.extend( ( "== Action caught SystemExit while removing packages:", - "%s: %s" % (action.id, action["result"]), + "{}: {}".format(action.id, action["result"]), ) ) @@ -371,7 +370,7 @@ def factory( message.extend( ( "== Action caught SystemExit while removing packages:", - "%s: %s" % (action.id, action["result"]), + "{}: {}".format(action.id, action["result"]), ) ) @@ -493,7 +492,7 @@ def pre_registered(shell, request, fixture_subman): hide_command=True, ).returncode == 0 - ), f"Failed to pre-register the system. The subscription manager call has failed." + ), "Failed to pre-register the system. The subscription manager call has failed." rhsm_uuid_command = "subscription-manager identity | grep identity" @@ -784,7 +783,7 @@ def _curl_the_satellite_script(self, curl_command): # Should be around November 2024 if "oracle-7.9" in SystemInformationRelease.system_release: self.shell( - fr"sed -i 's/$PKG_MANAGER_UPGRADE subscription-manager/& --setopt=exclude=rhn-client-tools/' {self._sat_script_location}" + rf"sed -i 's/$PKG_MANAGER_UPGRADE subscription-manager/& --setopt=exclude=rhn-client-tools/' {self._sat_script_location}" ) def _run_satellite_reg_script(self): diff --git a/tests/integration/tier0/destructive/single-yum-transaction/test_single_yum_transaction.py b/tests/integration/tier0/destructive/single-yum-transaction/test_single_yum_transaction.py index 5cbdb32a5c..52961fde28 100644 --- a/tests/integration/tier0/destructive/single-yum-transaction/test_single_yum_transaction.py +++ b/tests/integration/tier0/destructive/single-yum-transaction/test_single_yum_transaction.py @@ -22,7 +22,7 @@ def test_single_yum_transaction(convert2rhel, shell): ) ) as c2r: c2r.expect("no modifications to the system will happen this time.", timeout=1200) - c2r.expect("Successfully validated the %s transaction set." % pkgmanager, timeout=600) + c2r.expect("Successfully validated the {} transaction set.".format(pkgmanager), timeout=600) c2r.expect("This process may take some time to finish.", timeout=300) c2r.expect("System packages replaced successfully.", timeout=900) c2r.expect("Conversion successful!") diff --git a/tests/integration/tier0/non-destructive/config-file/test_config_file.py b/tests/integration/tier0/non-destructive/config-file/test_config_file.py index cdc9ee9b1b..af0022a322 100644 --- a/tests/integration/tier0/non-destructive/config-file/test_config_file.py +++ b/tests/integration/tier0/non-destructive/config-file/test_config_file.py @@ -39,20 +39,19 @@ def c2r_config_setup(request, backup_directory): shutil.move(bkp_original_config, c2r_original_config) +# We disable formatting because it changes the configuration +# files in parametrize, which makes them hard to read. +# https://docs.astral.sh/ruff/formatter/#format-suppression +# fmt: off @pytest.mark.parametrize( "c2r_config_setup", [ Config( "~/.convert2rhel.ini", - # We disable the Black pre-commit hook because it changes formatting - # of the following configuration files, which makes them hard to read. - # https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#ignoring-sections - # fmt: off ( "[subscription_manager]\n" "password = config_password\n" ), - # fmt: on ) ], indirect=True, @@ -75,12 +74,10 @@ def test_std_path_std_filename(convert2rhel, c2r_config_setup): [ Config( "~/.convert2rhel_custom.ini", - # fmt: off ( "[subscription_manager]\n" "activation_key = config_activationkey\n" ), - # fmt: on ) ], indirect=True, @@ -103,7 +100,6 @@ def test_user_path_custom_filename(convert2rhel, c2r_config_setup): [ Config( "~/.convert2rhel.ini", - # fmt: off ( "[subscription_manager]\n" "username = config_username\n" @@ -111,7 +107,6 @@ def test_user_path_custom_filename(convert2rhel, c2r_config_setup): "activation_key = config_key\n" "org = config_org\n" ), - # fmt: on ) ], indirect=True, @@ -145,23 +140,19 @@ def test_config_cli_priority(convert2rhel, c2r_config_setup): [ Config( "~/.convert2rhel.ini", - # fmt: off ( "[subscription_manager]\n" "password = config_password\n" "username = config_username\n" ), - # fmt: on ), Config( "/etc/convert2rhel.ini", - # fmt: off ( "[subscription_manager]\n" f"activation_key = {TEST_VARS['RHSM_SCA_KEY']}\n" f"org = {TEST_VARS['RHSM_SCA_ORG']}\n" ), - # fmt: on ), ] ], @@ -194,23 +185,19 @@ def test_config_standard_paths_priority_diff_methods(convert2rhel, c2r_config_se [ Config( "~/.convert2rhel.ini", - # fmt: off ( "[subscription_manager]\n" f"username = {TEST_VARS['RHSM_SCA_USERNAME']}\n" f"password = {TEST_VARS['RHSM_SCA_PASSWORD']}\n" ), - # fmt: on ), Config( "/etc/convert2rhel.ini", - # fmt: off ( "[subscription_manager]\n" "username = config_username\n" "password = config_password\n" ), - # fmt: on ), ] ], diff --git a/tests/integration/tier0/non-destructive/kernel/test_custom_kernel.py b/tests/integration/tier0/non-destructive/kernel/test_custom_kernel.py index 9484ae5625..aeb97fbfb1 100644 --- a/tests/integration/tier0/non-destructive/kernel/test_custom_kernel.py +++ b/tests/integration/tier0/non-destructive/kernel/test_custom_kernel.py @@ -65,7 +65,7 @@ def custom_kernel(shell, hybrid_rocky_image, backup_directory): kernel_info_storage = os.path.join(backup_directory, "original-kernel") if os.environ["TMT_REBOOT_COUNT"] == "0": # Store the current running kernel NVRA in a file - shell("echo $(uname -r) > %s" % kernel_info_storage) + shell("echo $(uname -r) > {}".format(kernel_info_storage)) # The version of yum on el7 like systems does not allow the --repofrompath option. # Therefore, we need to install the rpm directly diff --git a/tests/integration/tier0/non-destructive/single-yum-transaction-validation/test_single_yum_transaction_validation.py b/tests/integration/tier0/non-destructive/single-yum-transaction-validation/test_single_yum_transaction_validation.py index 6957ee23ac..16c8134cdb 100644 --- a/tests/integration/tier0/non-destructive/single-yum-transaction-validation/test_single_yum_transaction_validation.py +++ b/tests/integration/tier0/non-destructive/single-yum-transaction-validation/test_single_yum_transaction_validation.py @@ -54,7 +54,7 @@ def remove_entitlement_certs(): try: os.unlink(cert_path) except Exception as e: - print("Failed to delete %s. Reason: %s" % (cert_path, e)) + print("Failed to delete {}. Reason: {}".format(cert_path, e)) def test_package_download_error(convert2rhel, shell, yum_cache): diff --git a/tests/integration/tier1/destructive/detect-bootloader-partition/test_detect_correct_boot_partition.py b/tests/integration/tier1/destructive/detect-bootloader-partition/test_detect_correct_boot_partition.py index 6ab25d9c97..a1e67fce88 100644 --- a/tests/integration/tier1/destructive/detect-bootloader-partition/test_detect_correct_boot_partition.py +++ b/tests/integration/tier1/destructive/detect-bootloader-partition/test_detect_correct_boot_partition.py @@ -57,20 +57,21 @@ def test_detect_correct_boot_partition(convert2rhel): TEST_VARS["RHSM_SCA_PASSWORD"], ) ) as c2r: - assert c2r.expect("Calling command '/usr/sbin/blkid -p -s PART_ENTRY_NUMBER %s'" % boot_device) == 0 + assert c2r.expect("Calling command '/usr/sbin/blkid -p -s PART_ENTRY_NUMBER {}'".format(boot_device)) == 0 # This assertion should always match what comes from boot_partition. - assert c2r.expect("Block device: %s" % boot_device_name) == 0 - assert c2r.expect("ESP device number: %s" % boot_partition) == 0 + assert c2r.expect("Block device: {}".format(boot_device_name)) == 0 + assert c2r.expect("ESP device number: {}".format(boot_partition)) == 0 - assert c2r.expect("Adding 'Red Hat Enterprise Linux %s' UEFI bootloader entry." % rhel_version) == 0 + assert c2r.expect("Adding 'Red Hat Enterprise Linux {}' UEFI bootloader entry.".format(rhel_version)) == 0 # Only asserting half of the command as we care mostly about the # `--disk` and `--part`. assert ( c2r.expect( - "Calling command '/usr/sbin/efibootmgr --create --disk %s --part %s" - % (boot_device_name, boot_partition) + "Calling command '/usr/sbin/efibootmgr --create --disk {} --part {}".format( + boot_device_name, boot_partition + ) ) == 0 ) diff --git a/tests/integration/tier1/destructive/kernel-boot-files/test_handle_corrupted_files.py b/tests/integration/tier1/destructive/kernel-boot-files/test_handle_corrupted_files.py index 6da87acd90..2af539f705 100644 --- a/tests/integration/tier1/destructive/kernel-boot-files/test_handle_corrupted_files.py +++ b/tests/integration/tier1/destructive/kernel-boot-files/test_handle_corrupted_files.py @@ -13,7 +13,7 @@ def get_latest_installed_kernel_version(kernel_name): output = subprocess.check_output(["rpm", "-q", "--last", kernel_name]).decode() latest_installed_kernel = output.split("\n", maxsplit=1)[0].split(" ")[0] - latest_installed_kernel = latest_installed_kernel.split("%s-" % kernel_name)[-1] + latest_installed_kernel = latest_installed_kernel.split("{}-".format(kernel_name))[-1] return latest_installed_kernel.strip() @@ -26,10 +26,10 @@ def corrupt_initramfs_file(shell, kernel_version): assert os.path.exists(initramfs_file) # Copy the original file as a backup, so we can restore it later - assert shell("cp %s %s" % (initramfs_file, initramfs_backup)).returncode == 0 + assert shell("cp {} {}".format(initramfs_file, initramfs_backup)).returncode == 0 # Corrupt the file - cmd = ["dd", "if=/dev/urandom", "bs=1024", "count=1", "of=%s" % initramfs_file] + cmd = ["dd", "if=/dev/urandom", "bs=1024", "count=1", "of={}".format(initramfs_file)] subprocess.run(cmd, check=False) @@ -42,10 +42,10 @@ def restore_original_initramfs(shell, kernel_version): assert os.path.exists(initramfs_file) # Delete it as we will restore from the backup - assert shell("rm -rf %s" % initramfs_file).returncode == 0 + assert shell("rm -rf {}".format(initramfs_file)).returncode == 0 # Move the backup to be the original one again - assert shell("mv %s %s" % (initramfs_backup, initramfs_file)).returncode == 0 + assert shell("mv {} {}".format(initramfs_backup, initramfs_file)).returncode == 0 # Assert that the file exists assert os.path.exists(initramfs_file) diff --git a/tests/integration/tier1/destructive/kernel-boot-files/test_handle_missing_boot_files.py b/tests/integration/tier1/destructive/kernel-boot-files/test_handle_missing_boot_files.py index 1abe6d6184..9d33660630 100644 --- a/tests/integration/tier1/destructive/kernel-boot-files/test_handle_missing_boot_files.py +++ b/tests/integration/tier1/destructive/kernel-boot-files/test_handle_missing_boot_files.py @@ -13,7 +13,7 @@ def get_latest_installed_kernel_version(kernel_name): output = subprocess.check_output(["rpm", "-q", "--last", kernel_name]).decode() latest_installed_kernel = output.split("\n", maxsplit=1)[0].split(" ")[0] - latest_installed_kernel = latest_installed_kernel.split("%s-" % kernel_name)[-1] + latest_installed_kernel = latest_installed_kernel.split("{}-".format(kernel_name))[-1] return latest_installed_kernel.strip() @@ -28,8 +28,8 @@ def remove_kernel_boot_files(shell, kernel_version): assert os.path.exists(vmlinuz_file) # Remove the installed RHEL kernel boot files, simulating that they failed to be generated during the conversion - assert shell("rm -f %s" % initramfs_file).returncode == 0 - assert shell("rm -f %s" % vmlinuz_file).returncode == 0 + assert shell("rm -f {}".format(initramfs_file)).returncode == 0 + assert shell("rm -f {}".format(vmlinuz_file)).returncode == 0 def test_handling_missing_kernel_boot_files(convert2rhel, shell): diff --git a/tests/integration/tier1/destructive/kernel-check-skip/test_latest_kernel_check_skip.py b/tests/integration/tier1/destructive/kernel-check-skip/test_latest_kernel_check_skip.py index d04eaad745..e5feba1112 100644 --- a/tests/integration/tier1/destructive/kernel-check-skip/test_latest_kernel_check_skip.py +++ b/tests/integration/tier1/destructive/kernel-check-skip/test_latest_kernel_check_skip.py @@ -1,5 +1,4 @@ import os -import re from conftest import SYSTEM_RELEASE_ENV, TEST_VARS, SystemInformationRelease diff --git a/tests/integration/tier1/destructive/one-kernel-scenario/test_one_kernel_scenario.py b/tests/integration/tier1/destructive/one-kernel-scenario/test_one_kernel_scenario.py index 421be4f1aa..7e71ceb328 100644 --- a/tests/integration/tier1/destructive/one-kernel-scenario/test_one_kernel_scenario.py +++ b/tests/integration/tier1/destructive/one-kernel-scenario/test_one_kernel_scenario.py @@ -47,7 +47,6 @@ def test_one_kernel_scenario(shell, convert2rhel, one_kernel): """TODO(r0x0d) better description and function name""" if os.environ["TMT_REBOOT_COUNT"] == "2": - # The nfnetlink kmod is causing issues on OracleLinux 7 if "oracle-7" in SYSTEM_RELEASE_ENV: shell("rmmod nfnetlink")