diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 289e304734..caee64cb01 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ minimum_pre_commit_version: "2.9.0" repos: - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.7.3 + rev: v0.16.6 hooks: # Run the linter. - id: ruff @@ -11,7 +11,7 @@ repos: - id: ruff-format - repo: "https://github.com/pre-commit/pre-commit-hooks" - rev: "v5.0.0" + rev: "v6.0.0" hooks: - id: "end-of-file-fixer" - id: "trailing-whitespace" @@ -19,29 +19,29 @@ repos: - id: "check-yaml" - id: "check-merge-conflict" - repo: "https://gitlab.com/bmares/check-json5" - rev: "v1.0.0" + rev: "v1.0.1" hooks: - id: "check-json5" - repo: "https://github.com/teemtee/tmt.git" - rev: "1.70.0" + rev: "1.78.0" hooks: - id: "tmt-tests-lint" verbose: false files: ^(tests/|plans/) - repo: https://github.com/packit/pre-commit-hooks - rev: v1.2.0 + rev: v1.3.0 hooks: - id: check-rebase args: - https://github.com/oamg/convert2rhel.git stages: [manual, pre-push] - repo: https://github.com/gitleaks/gitleaks - rev: v8.21.2 + rev: v8.30.0 hooks: - id: gitleaks stages: [manual, pre-push] - repo: https://github.com/jendrikseipp/vulture - rev: v2.13 + rev: v2.16 hooks: - id: vulture diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7c8ba587fb..597785bddc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -313,13 +313,13 @@ from rpmUtils.miscutils import checkSignals yb = YumBase() try: - #yb.doConfigSetup(init_plugins=False) + # yb.doConfigSetup(init_plugins=False) yb.runTransaction(False) except (BaseException, SystemExit, Exception) as e: - print('We were able to catch an exception from runTransaction!') + print("We were able to catch an exception from runTransaction!") print(type(e)) print(e) -print('Sleeping') +print("Sleeping") time.sleep(3) # Hit Ctrl-C # If KeyboardInterrupt is raised, chances are that this did not cause the @@ -327,11 +327,11 @@ time.sleep(3) try: checkSignals() except (BaseException, SystemExit, Exception) as e: - print('We were able to catch an exception from checkSignals!') + print("We were able to catch an exception from checkSignals!") print(type(e)) print(e) finally: - print('In the finally block') + print("In the finally block") # If the previous try: except exits immediately without message, then the # issue occurred. # If it raises a KeyboardInterrupt traceback then we're okay. diff --git a/convert2rhel/__init__.py b/convert2rhel/__init__.py index 0900dd16a3..3a5935a2d0 100644 --- a/convert2rhel/__init__.py +++ b/convert2rhel/__init__.py @@ -1,2 +1 @@ -__metaclass__ = type __version__ = "2.3.1" diff --git a/convert2rhel/actions/__init__.py b/convert2rhel/actions/__init__.py index 880624a88a..4bbae1d3ea 100644 --- a/convert2rhel/actions/__init__.py +++ b/convert2rhel/actions/__init__.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import abc import collections @@ -22,7 +20,6 @@ import itertools import pkgutil import traceback - from functools import wraps import six @@ -30,7 +27,6 @@ from convert2rhel import utils from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) @@ -135,7 +131,7 @@ class DependencyError(ActionError): """ def __init__(self, *args, **kwargs): - super(DependencyError, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.unresolved_actions = kwargs.pop("unresolved_actions", []) self.resolved_actions = kwargs.pop("resolved_actions", []) @@ -203,7 +199,7 @@ def run(self): instead. """ if self._has_run: - raise ActionError("Action {} has already run".format(self.id)) + raise ActionError(f"Action {self.id} has already run") self._has_run = True @@ -324,16 +320,7 @@ def __hash__(self): return hash((self.level, self.id, self.title, self.description, self.diagnosis, self.remediations)) def __repr__(self): - return "{}(level={}, id={}, title={}, description={}, diagnosis={}, remediations={}, variables={})".format( - self.__class__.__name__, - _STATUS_NAME_FROM_CODE[self.level], - self.id, - self.title, - self.description, - self.diagnosis, - self.remediations, - self.variables, - ) + return f"{self.__class__.__name__}(level={_STATUS_NAME_FROM_CODE[self.level]}, id={self.id}, title={self.title}, description={self.description}, diagnosis={self.diagnosis}, remediations={self.remediations}, variables={self.variables})" def to_dict(self): """ @@ -364,9 +351,9 @@ 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 '{}', set for a non-result message".format(level)) + raise InvalidMessageError(f"Invalid level '{level}', set for a non-result message") - super(ActionMessage, self).__init__(level, id, title, description, diagnosis, remediations, variables) + super().__init__(level, id, title, description, diagnosis, remediations, variables) class ActionResult(ActionMessageBase): @@ -392,10 +379,10 @@ def __init__( elif STATUS_CODE["SUCCESS"] < STATUS_CODE[level] < STATUS_CODE["SKIP"]: raise InvalidMessageError( - "Invalid level '{}', the level for result must be SKIP or more fatal or SUCCESS.".format(level) + f"Invalid level '{level}', the level for result must be SKIP or more fatal or SUCCESS." ) - super(ActionResult, self).__init__(level, id, title, description, diagnosis, remediations, variables) + super().__init__(level, id, title, description, diagnosis, remediations, variables) def get_actions(actions_path, prefix): @@ -520,10 +507,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("{}".format(self.task_header)) + logger.task(f"{self.task_header}") if self._has_run: - raise ActionError("Stage {} has already run.".format(self.stage_name)) + raise ActionError(f"Stage {self.stage_name} has already run.") self._has_run = True # Make a mutable copy of these parameters so we don't overwrite the caller's data. @@ -548,10 +535,7 @@ def run(self, successes=None, failures=None, skips=None): to_be = "was" if len(failed_deps) > 1: to_be = "were" - diagnosis = "Skipped because {} {} not successful".format( - utils.format_sequence_as_message(failed_deps), - to_be, - ) + diagnosis = f"Skipped because {utils.format_sequence_as_message(failed_deps)} {to_be} not successful" action.set_result( level="SKIP", @@ -559,13 +543,11 @@ 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 {} check passes so that this Action can evaluate your system".format( - utils.format_sequence_as_message(failed_deps) - ), + remediations=f"Please ensure that the {utils.format_sequence_as_message(failed_deps)} check passes so that this Action can evaluate your system", ) skips.append(action) failed_action_ids.add(action.id) - logger.error("Skipped {}. {}".format(action.id, diagnosis)) + logger.error(f"Skipped {action.id}. {diagnosis}") continue # Run the Action @@ -575,10 +557,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: {}\n" + f"Unhandled exception was caught: {e}\n" "Please file a bug at https://issues.redhat.com/ to have this" " fixed or a specific error message added.\n" - "Traceback: {}".format(e, traceback.format_exc()) + f"Traceback: {traceback.format_exc()}" ) action.set_result( level="ERROR", id="UNEXPECTED_ERROR", title="Unhandled exception caught", description=description @@ -586,7 +568,7 @@ def run(self, successes=None, failures=None, skips=None): # Categorize the results if action.result.level <= STATUS_CODE["WARNING"]: - logger.info("{} has succeeded".format(action.id)) + logger.info(f"{action.id} has succeeded") successes.append(action) if action.result.level > STATUS_CODE["WARNING"]: @@ -752,7 +734,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: {}".format(e)) + logger.critical(f"Some dependencies were set on Actions but not present in convert2rhel: {e}") # Run the Actions in system_checks and all subsequent Stages. results = system_checks.run() @@ -781,7 +763,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: {}".format(e)) + logger.critical(f"Some dependencies were set on Actions but not present in convert2rhel: {e}") # Run the Actions in conversion and all subsequent Stages. results = conversion.run() diff --git a/convert2rhel/actions/conversion/list_non_red_hat_pkgs_left.py b/convert2rhel/actions/conversion/list_non_red_hat_pkgs_left.py index 5c4d4a934a..ca75fdd96e 100644 --- a/convert2rhel/actions/conversion/list_non_red_hat_pkgs_left.py +++ b/convert2rhel/actions/conversion/list_non_red_hat_pkgs_left.py @@ -13,13 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from convert2rhel import actions, logger from convert2rhel.pkghandler import get_installed_pkgs_w_different_key_id, print_pkg_info from convert2rhel.systeminfo import system_info - loggerinst = logger.root_logger.getChild(__name__) @@ -31,7 +29,7 @@ def run(self): """List all the packages that have not been replaced by the Red Hat-signed ones during the conversion. """ - super(ListNonRedHatPkgsLeft, self).run() + super().run() loggerinst.task("List remaining non-Red Hat packages") loggerinst.info("Listing packages not signed by Red Hat") diff --git a/convert2rhel/actions/conversion/lock_releasever.py b/convert2rhel/actions/conversion/lock_releasever.py index e3b708d069..8ed13638df 100644 --- a/convert2rhel/actions/conversion/lock_releasever.py +++ b/convert2rhel/actions/conversion/lock_releasever.py @@ -13,13 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from convert2rhel import actions, logger, utils from convert2rhel.systeminfo import system_info from convert2rhel.toolopts import tool_opts - loggerinst = logger.root_logger.getChild(__name__) @@ -38,7 +36,7 @@ def run(self): keeps receiving updates for the specific EUS minor version instead of the latest minor version which is the default. """ - super(LockReleaseverInRHELRepositories, self).run() + super().run() loggerinst.task("Lock releasever in RHEL repositories") # We only lock the releasever on rhel repos if we detect that the running system is an EUS correspondent and if @@ -51,17 +49,15 @@ def run(self): ) return loggerinst.info( - "Updating /etc/yum.repos.d/rehat.repo to point to RHEL {} instead of the default latest minor version.".format( - system_info.releasever - ) + f"Updating /etc/yum.repos.d/rehat.repo to point to RHEL {system_info.releasever} instead of the default latest minor version." ) cmd = [ "subscription-manager", "release", - "--set={}".format(system_info.releasever), + f"--set={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 {} minor version.".format(system_info.releasever)) + loggerinst.info(f"RHEL repositories locked to the {system_info.releasever} minor version.") diff --git a/convert2rhel/actions/conversion/pkg_manager_config.py b/convert2rhel/actions/conversion/pkg_manager_config.py index c2bf754f8c..a44854aa52 100644 --- a/convert2rhel/actions/conversion/pkg_manager_config.py +++ b/convert2rhel/actions/conversion/pkg_manager_config.py @@ -13,12 +13,10 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from convert2rhel import actions, redhatrelease from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) @@ -31,7 +29,7 @@ def run(self): Check if the distroverpkg tag inside the package manager config has been modified before the conversion and if so comment it out and write to the file. """ - super(ConfigurePkgManager, self).run() + super().run() logger.task("Patch package manager configuration file") diff --git a/convert2rhel/actions/conversion/preserve_only_rhel_kernel.py b/convert2rhel/actions/conversion/preserve_only_rhel_kernel.py index c430bfd022..bf3f77041c 100644 --- a/convert2rhel/actions/conversion/preserve_only_rhel_kernel.py +++ b/convert2rhel/actions/conversion/preserve_only_rhel_kernel.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import glob import os @@ -21,7 +20,6 @@ from convert2rhel import actions, logger, pkghandler, pkgmanager, utils from convert2rhel.systeminfo import system_info - loggerinst = logger.root_logger.getChild(__name__) @@ -35,7 +33,7 @@ def run(self): The RHEL kernel might have not been installed during the main conversion transaction in case the installed non-RHEL kernel(s) conflicted with the available RHEL kernels. """ - super(InstallRhelKernel, self).run() + super().run() loggerinst.info("Verifying that RHEL kernel has been installed") rhel_kernels = pkghandler.get_installed_pkgs_by_key_id(system_info.key_ids_rhel, name="kernel") @@ -77,7 +75,7 @@ def run(self): The solution handled by this function is to remove the non-functioning boot entries upon the removal of the original OS kernels, and set the RHEL kernel as default. """ - super(FixInvalidGrub2Entries, self).run() + super().run() if system_info.version.major < 8: # Applicable only on systems derived from RHEL 8 and later, and systems using GRUB2 (s390x uses zipl) @@ -90,7 +88,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 {}".format(entry)) + loggerinst.debug(f"Removing boot entry {entry}") os.remove(entry) # Removing a boot entry that used to be the default makes grubby to choose a different entry as default, @@ -99,7 +97,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{}".format(output) + description = f"Couldn't get the default GRUB2 boot loader entry:\n{output}" loggerinst.warning(description) self.add_message( level="WARNING", @@ -108,10 +106,10 @@ def run(self): description=description, ) return - loggerinst.debug("Setting RHEL kernel {} as the default boot loader entry.".format(output.strip())) + loggerinst.debug(f"Setting RHEL kernel {output.strip()} as the default boot loader entry.") 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{}".format(output) + description = f"Couldn't set the default GRUB2 boot loader entry:\n{output}" loggerinst.warning(description) self.add_message( level="WARNING", @@ -136,31 +134,29 @@ def run(self): Systems converted from Oracle Linux or CentOS Linux may have leftover kernel-uek or kernel-plus as DEFAULTKERNEL. This function creates the file if missing or fixes leftover values. """ - super(FixDefaultKernel, self).run() + super().run() default_kernel = "kernel" if system_info.version.major <= 7 else "kernel-core" if not os.path.exists(self.KERNEL_SYSCONFIG_PATH): loggerinst.warning( - "{} does not exist. Creating it with DEFAULTKERNEL={}.".format( - self.KERNEL_SYSCONFIG_PATH, default_kernel - ) + f"{self.KERNEL_SYSCONFIG_PATH} does not exist. Creating it with DEFAULTKERNEL={default_kernel}." ) self.add_message( level="WARNING", id="MISSING_KERNEL_SYSCONFIG_CREATED", - title="{} missing".format(self.KERNEL_SYSCONFIG_PATH), + title=f"{self.KERNEL_SYSCONFIG_PATH} missing", description=( - "The {} file was missing on the system, likely because the original OS" + f"The {self.KERNEL_SYSCONFIG_PATH} file was missing on the system, likely because the original OS" " does not ship it. The file has been created with" - " DEFAULTKERNEL={} to ensure RHEL compatibility.".format(self.KERNEL_SYSCONFIG_PATH, default_kernel) + f" DEFAULTKERNEL={default_kernel} to ensure RHEL compatibility." ), ) content = ( "# UPDATEDEFAULT specifies if new-kernel-pkg should make\n" "# new kernels the default\n" "UPDATEDEFAULT=yes\n" - "DEFAULTKERNEL={}\n".format(default_kernel) + f"DEFAULTKERNEL={default_kernel}\n" ) utils.store_content_to_file(self.KERNEL_SYSCONFIG_PATH, content) return @@ -186,7 +182,7 @@ def run(self): kernel_sys_cfg = kernel_sys_cfg.replace("DEFAULTKERNEL=" + kernel_to_change, new_kernel_str) utils.store_content_to_file(self.KERNEL_SYSCONFIG_PATH, kernel_sys_cfg) - loggerinst.info("Boot kernel {} was changed to {}".format(kernel_to_change, new_kernel_str)) + loggerinst.info(f"Boot kernel {kernel_to_change} was changed to {new_kernel_str}") else: loggerinst.debug("Boot kernel validated.") @@ -197,7 +193,7 @@ class KernelPkgsInstall(actions.Action): def run(self): """Remove non-RHEL kernels.""" - super(KernelPkgsInstall, self).run() + super().run() kernel_pkgs_to_install = self.remove_non_rhel_kernels() if kernel_pkgs_to_install: @@ -228,7 +224,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 {}".format(name)) + loggerinst.info(f"Installing RHEL {name}") pkgmanager.call_yum_cmd("install", args=[name]) @@ -245,6 +241,6 @@ def run(self): At this point though all non-RHEL kernels are already removed so the latest RHEL kernel won't conflict with them anymore. """ - super(UpdateKernel, self).run() + super().run() pkghandler.update_rhel_kernel() diff --git a/convert2rhel/actions/conversion/set_efi_config.py b/convert2rhel/actions/conversion/set_efi_config.py index 280644be53..89a6386129 100644 --- a/convert2rhel/actions/conversion/set_efi_config.py +++ b/convert2rhel/actions/conversion/set_efi_config.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import shutil @@ -22,7 +21,6 @@ from convert2rhel.grub import CENTOS_EFIDIR_CANONICAL_PATH, RHEL_EFIDIR_CANONICAL_PATH from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) @@ -32,7 +30,7 @@ class NewDefaultEfiBin(actions.Action): def run(self): """Check that the expected RHEL UEFI binaries exist.""" - super(NewDefaultEfiBin, self).run() + super().run() logger.task("Configure the bootloader") @@ -48,10 +46,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: {}".format(efi_path)) + logger.info(f"UEFI binary found: {efi_path}") new_default_efibin = efi_path break - logger.debug("UEFI binary {} not found. Checking next possibility...".format(efi_path)) + logger.debug(f"UEFI binary {efi_path} not found. Checking next possibility...") missing_binaries.append(efi_path) if not new_default_efibin: self.set_result( @@ -65,9 +63,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 {} directory. Verify that `efibootmgr -v`" + f" are present in the {grub.RHEL_EFIDIR_CANONICAL_PATH} directory. Verify that `efibootmgr -v`" " shows a bootloader entry for Red Hat Enterprise Linux" - " that points to to '\\EFI\\redhat\\shimx64.efi'.".format(grub.RHEL_EFIDIR_CANONICAL_PATH) + " that points to to '\\EFI\\redhat\\shimx64.efi'." ), ) @@ -78,7 +76,7 @@ class EfibootmgrUtilityInstalled(actions.Action): def run(self): """Check if the Efibootmgr utility is installed""" - super(EfibootmgrUtilityInstalled, self).run() + super().run() if not grub.is_efi(): logger.info( @@ -112,7 +110,7 @@ def run(self): The move of the centos/ directory should be ok. In case of the conversion from Oracle Linux, the redhat/ directory is already used. """ - super(MoveGrubFiles, self).run() + super().run() if not grub.is_efi(): logger.info("Unable to collect data about UEFI on a BIOS system, did not perform moving of Grub2 files.") @@ -125,7 +123,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 {}.".format(RHEL_EFIDIR_CANONICAL_PATH)) + logger.info(f"Moving GRUB2 configuration files to the new UEFI directory {RHEL_EFIDIR_CANONICAL_PATH}.") src_files = [ os.path.join(CENTOS_EFIDIR_CANONICAL_PATH, filename) for filename in ["grubenv", "grub.cfg", "user.cfg"] ] @@ -154,35 +152,29 @@ def run(self): # Skip non-existing file in destination directory if not os.path.exists(src_file): logger.debug( - "The {} file does not exist in {} folder. Moving skipped.".format( - os.path.basename(src_file), CENTOS_EFIDIR_CANONICAL_PATH - ) + f"The {os.path.basename(src_file)} file does not exist in {CENTOS_EFIDIR_CANONICAL_PATH} folder. Moving skipped." ) 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 {} file already exists in {} folder. Moving skipped.".format( - os.path.basename(src_file), RHEL_EFIDIR_CANONICAL_PATH - ) + f"The {os.path.basename(src_file)} file already exists in {RHEL_EFIDIR_CANONICAL_PATH} folder. Moving skipped." ) continue - logger.info("Moving '{}' to '{}'".format(src_file, dst_file)) + logger.info(f"Moving '{src_file}' to '{dst_file}'") try: shutil.move(src_file, dst_file) - except (OSError, IOError) as err: + except OSError as err: # IOError for py2 and OSError for py3 self.set_result( level="ERROR", id="GRUB_FILES_NOT_MOVED_TO_BOOT_DIRECTORY", title="GRUB files have not been moved to boot directory", description=( - "I/O error({}): '{}'. Some GRUB files have not been moved to /boot/efi/EFI/redhat.".format( - err.errno, err.strerror - ) + f"I/O error({err.errno}): '{err.strerror}'. Some GRUB files have not been moved to /boot/efi/EFI/redhat." ), ) @@ -200,7 +192,7 @@ def run(self): UEFI files are present, we should keep the directory for now, until we deal with it. """ - super(RemoveEfiCentos, self).run() + super().run() if not grub.is_efi(): logger.info( @@ -214,14 +206,14 @@ def run(self): return try: os.rmdir(CENTOS_EFIDIR_CANONICAL_PATH) - except (OSError, IOError) as err: + except OSError as err: warning_message = ( - "Failed to remove the {dir} directory as files still exist." + f"Failed to remove the {CENTOS_EFIDIR_CANONICAL_PATH} directory as files still exist." " During conversion we make sure to move over files needed to their RHEL counterpart." " However, some files we didn't expect likely exist in the directory that needs human oversight." " Make sure that the files within the directory is taken care of and proceed with deleting the directory" - " manually after conversion. We received error: '{err}'." - ).format(dir=CENTOS_EFIDIR_CANONICAL_PATH, err=err) + f" manually after conversion. We received error: '{err}'." + ) logger.warning(warning_message) self.add_message( @@ -248,12 +240,11 @@ def run(self): The current (original) UEFI bootloader entry is removed under some conditions (see `py:grub._remove_orig_boot_entry()` for more info). """ - super(ReplaceEfiBootEntry, self).run() + super().run() if not grub.is_efi(): logger.info( - "Unable to collect data about UEFI on a BIOS system, did not perform UEFI bootloader " - "entry replacement." + "Unable to collect data about UEFI on a BIOS system, did not perform UEFI bootloader entry replacement." ) return @@ -267,6 +258,6 @@ def run(self): description=( "As the current UEFI bootloader entry could be invalid or missing we need to ensure that a " "RHEL UEFI entry exists. The UEFI boot entry could not be replaced due to the following" - " error: '{err}'".format(err=e.message) + f" error: '{e.message}'" ), ) diff --git a/convert2rhel/actions/conversion/transaction.py b/convert2rhel/actions/conversion/transaction.py index 0797207d79..5b0be64014 100644 --- a/convert2rhel/actions/conversion/transaction.py +++ b/convert2rhel/actions/conversion/transaction.py @@ -13,13 +13,10 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions, exceptions, pkgmanager from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) @@ -28,7 +25,7 @@ class ConvertSystemPackages(actions.Action): def run(self): """Convert the system packages using either yum/dnf.""" - super(ConvertSystemPackages, self).run() + super().run() try: logger.task("Replace system packages") diff --git a/convert2rhel/actions/post_conversion/breadcrumbs_finish_collection.py b/convert2rhel/actions/post_conversion/breadcrumbs_finish_collection.py index 222714c14c..c756d02117 100644 --- a/convert2rhel/actions/post_conversion/breadcrumbs_finish_collection.py +++ b/convert2rhel/actions/post_conversion/breadcrumbs_finish_collection.py @@ -13,13 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging from convert2rhel import actions, breadcrumbs - logger = logging.getLogger(__name__) @@ -31,7 +29,7 @@ class BreadcumbsFinishCollection(actions.Action): ) def run(self): - super(BreadcumbsFinishCollection, self).run() + super().run() logger.task("Update breadcrumbs") breadcrumbs.breadcrumbs.finish_collection(success=True) diff --git a/convert2rhel/actions/post_conversion/hostmetering.py b/convert2rhel/actions/post_conversion/hostmetering.py index 0e6dc34cb5..9529e106a6 100644 --- a/convert2rhel/actions/post_conversion/hostmetering.py +++ b/convert2rhel/actions/post_conversion/hostmetering.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from convert2rhel import actions, systeminfo from convert2rhel.logger import root_logger @@ -23,7 +22,6 @@ from convert2rhel.toolopts import tool_opts from convert2rhel.utils import run_subprocess, warn_deprecated_env - logger = root_logger.getChild(__name__) @@ -46,7 +44,7 @@ def run(self): """ logger.task("Configure host-metering") - super(ConfigureHostMetering, self).run() + super().run() warn_deprecated_env("CONVERT2RHEL_CONFIGURE_HOST_METERING") if not self._check_host_metering_configuration(): @@ -77,9 +75,7 @@ def run(self): title="Failed to install host metering package.", description="When installing host metering package an error occurred meaning we can't" " enable host metering on the system.", - diagnosis="`yum install host-metering` command returned {ret_install} with message {output}".format( - ret_install=ret_install, output=output - ), + diagnosis=f"`yum install host-metering` command returned {ret_install} with message {output}", remediations="You can try install and set up the host metering" " manually using following commands:\n" " - `yum install host-metering`\n" @@ -95,11 +91,8 @@ def run(self): level="WARNING", id="CONFIGURE_HOST_METERING_FAILURE", title="Failed to enable and start host metering service.", - description="The host metering service failed to start" - " successfully and won't be able to keep track.", - diagnosis="Command {command} failed with {error_message}".format( - command=command, error_message=error_message - ), + description="The host metering service failed to start successfully and won't be able to keep track.", + diagnosis=f"Command {command} failed with {error_message}", remediations="You can try set up the host metering" " service manually using following commands:\n" " - `systemctl enable host-metering.service`\n" @@ -137,18 +130,14 @@ def _check_host_metering_configuration(self): if tool_opts.configure_host_metering not in ("force", "auto"): logger.debug( "Unexpected value of 'configure_host_metering' in convert2rhel.ini or the" - " CONVERT2RHEL_CONFIGURE_HOST_METERING environment variable: {}".format( - tool_opts.configure_host_metering - ) + f" CONVERT2RHEL_CONFIGURE_HOST_METERING environment variable: {tool_opts.configure_host_metering}" ) self.add_message( level="WARNING", id="UNRECOGNIZED_OPTION_CONFIGURE_HOST_METERING", title="Unexpected value of the host metering setting", diagnosis="Unexpected value of 'configure_host_metering' in convert2rhel.ini or the" - " CONVERT2RHEL_CONFIGURE_HOST_METERING environment variable: {}".format( - tool_opts.configure_host_metering - ), + f" CONVERT2RHEL_CONFIGURE_HOST_METERING environment variable: {tool_opts.configure_host_metering}", description="Host metering will not be configured.", remediations="Set the option to 'auto' or 'force' if you want to configure host metering.", ) @@ -210,7 +199,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: {}".format(output)) + logger.debug(f"Output of systemctl call: {output}") if ret_enable: logger.warning("Failed to enable host-metering service.") return " ".join(command), output @@ -219,7 +208,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: {}".format(output)) + logger.debug(f"Output of systemctl call: {output}") if ret_start: logger.warning("Failed to start host-metering service.") return " ".join(command), output diff --git a/convert2rhel/actions/post_conversion/kernel_boot_files.py b/convert2rhel/actions/post_conversion/kernel_boot_files.py index 3cb398196f..476269dea6 100644 --- a/convert2rhel/actions/post_conversion/kernel_boot_files.py +++ b/convert2rhel/actions/post_conversion/kernel_boot_files.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os @@ -22,7 +21,6 @@ from convert2rhel.systeminfo import system_info from convert2rhel.utils import run_subprocess - logger = root_logger.getChild(__name__) VMLINUZ_FILEPATH = "/boot/vmlinuz-%s" @@ -37,7 +35,7 @@ class KernelBootFiles(actions.Action): def run(self): """Check if the required kernel files exist and are valid under the boot partition.""" - super(KernelBootFiles, self).run() + super().run() logger.task("Check kernel boot files") @@ -74,18 +72,14 @@ def run(self): 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_name}-{latest_installed_kernel} -y\n" - "2. grub2-mkconfig -o {grub2_config_file}\n" - "3. reboot".format( - kernel_name=kernel_name, - latest_installed_kernel=latest_installed_kernel, - grub2_config_file=grub2_config_file, - ) + f"1. yum reinstall {kernel_name}-{latest_installed_kernel} -y\n" + f"2. grub2-mkconfig -o {grub2_config_file}\n" + "3. reboot" ) logger.warning( "Couldn't verify the kernel boot files in the boot partition. This" " might cause problems during the next boot of your system.\n" - "{0}".format(remediations), + f"{remediations}", ) self.add_message( level="WARNING", diff --git a/convert2rhel/actions/post_conversion/modified_rpm_files_diff.py b/convert2rhel/actions/post_conversion/modified_rpm_files_diff.py index a458817f57..c6fba73b80 100644 --- a/convert2rhel/actions/post_conversion/modified_rpm_files_diff.py +++ b/convert2rhel/actions/post_conversion/modified_rpm_files_diff.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import difflib import os @@ -22,7 +21,6 @@ from convert2rhel.logger import LOG_DIR, root_logger from convert2rhel.systeminfo import system_info - logger = root_logger.getChild(__name__) @@ -34,7 +32,7 @@ def run(self): Get a list of modified rpm files after the conversion and compare it to the one from before the conversion. """ - super(ModifiedRPMFilesDiff, self).run() + super().run() logger.task("Show RPM files modified by the conversion") @@ -69,15 +67,12 @@ def run(self): if modified_rpm_files_diff: logger.info( - "Comparison of modified rpm files from before and after the conversion:\n{}".format( - modified_rpm_files_diff - ) + f"Comparison of modified rpm files from before and after the conversion:\n{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{}".format( - modified_rpm_files_diff - ), + description="Comparison of modified rpm files from before and after " + f"the conversion: \n{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 d89088572b..383c346c15 100644 --- a/convert2rhel/actions/post_conversion/remove_tmp_dir.py +++ b/convert2rhel/actions/post_conversion/remove_tmp_dir.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import errno import shutil @@ -22,7 +21,6 @@ from convert2rhel.logger import root_logger from convert2rhel.utils import TMP_DIR - loggerinst = root_logger.getChild(__name__) @@ -39,13 +37,13 @@ def run(self): This function is idempotent and will do nothing if the temporary directory does not exist. """ - super(RemoveTmpDir, self).run() + super().run() - loggerinst.task("Remove temporary folder {}".format(TMP_DIR)) + loggerinst.task(f"Remove temporary folder {TMP_DIR}") try: shutil.rmtree(self.tmp_dir) - loggerinst.info("Temporary folder {} removed".format(self.tmp_dir)) + loggerinst.info(f"Temporary folder {self.tmp_dir} removed") except OSError as exc: # We want run() to be idempotent, so do nothing silently if # the path doesn't exist. @@ -53,14 +51,14 @@ def run(self): if exc.errno == errno.ENOENT: return warning_message = ( - "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) + f"The folder {self.tmp_dir} is left untouched. You may remove the folder manually" + " after you ensure there is no preserved data you would need." ) loggerinst.warning(warning_message) self.add_message( level="WARNING", id="UNSUCCESSFUL_REMOVE_TMP_DIR", - title="Temporary folder {tmp_dir} wasn't removed.".format(tmp_dir=self.tmp_dir), + title=f"Temporary folder {self.tmp_dir} wasn't removed.", description=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 bf6e9c2cec..0e25631584 100644 --- a/convert2rhel/actions/post_conversion/rhsm_custom_facts_config.py +++ b/convert2rhel/actions/post_conversion/rhsm_custom_facts_config.py @@ -13,13 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging from convert2rhel import actions, subscription - loggerinst = logging.getLogger(__name__) @@ -29,19 +27,17 @@ class RHSMCustomFactsConfig(actions.Action): dependencies = () def run(self): - super(RHSMCustomFactsConfig, self).run() + super().run() loggerinst.task("Update RHSM custom facts") ret_code, output = subscription.update_rhsm_custom_facts() if not output: - return None + return if ret_code != 0: self.add_message( level="WARNING", id="FAILED_TO_UPDATE_RHSM_CUSTOM_FACTS", title="Failed to update RHSM custom facts", - description="Failed to update the RHSM custom facts with return code: {0} and output: {1}.".format( - ret_code, output - ), + description=f"Failed to update the RHSM custom facts with return code: {ret_code} and output: {output}.", ) diff --git a/convert2rhel/actions/post_conversion/update_grub.py b/convert2rhel/actions/post_conversion/update_grub.py index a4d9aa2c9b..6a470134ac 100644 --- a/convert2rhel/actions/post_conversion/update_grub.py +++ b/convert2rhel/actions/post_conversion/update_grub.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions, backup, grub, utils from convert2rhel.backup.files import RestorableFile @@ -33,7 +31,7 @@ def run(self): Additionally the GRUB_DISTRIBUTOR and GRAB_DISABLE_SUBMENU are missing causing the GRUB menu to be in an unsatisfactory format. Ensure the options to yield correct values. """ - super(FixGrubSettingsOnAL2, self).run() + super().run() logger.task("Fix GRUB2 settings on Amazon Linux 2") if system_info.version.major != 2: @@ -55,26 +53,26 @@ def run(self): if old_value in content: content = content.replace(old_value, new_value) - logger.debug("Replaced {} with {} in {}.".format(old_value, new_value, file_path)) + logger.debug(f"Replaced {old_value} with {new_value} in {file_path}.") content_modified = True else: - logger.info("{} not found in {}. Nothing to do.".format(old_value, file_path)) + logger.info(f"{old_value} not found in {file_path}. Nothing to do.") for opt in missing_grub_opts: key = opt.split("=", 1)[0] lines = content.splitlines() if any(line.startswith(key + "=") for line in lines): content = "\n".join(opt if line.startswith(key + "=") else line for line in lines) + "\n" - logger.debug("Replaced existing {} entry in {}.".format(key, file_path)) + logger.debug(f"Replaced existing {key} entry in {file_path}.") else: content = content.rstrip("\n") + "\n" + opt + "\n" - logger.debug("Added {} to {}.".format(opt, file_path)) + logger.debug(f"Added {opt} to {file_path}.") content_modified = True if content_modified: with open(file_path, "w") as file: file.write(content) - logger.info("Successfully updated {}.".format(file_path)) + logger.info(f"Successfully updated {file_path}.") class UpdateGrub(actions.Action): @@ -88,7 +86,7 @@ def run(self): generates images that expect different format of a config file. To be on the safe side we rather re-generate the GRUB2 config file and install the GRUB2 image. """ - super(UpdateGrub, self).run() + super().run() logger.task("Update GRUB2 configuration") @@ -100,7 +98,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{}".format(output)) + logger.debug(f"Output of the grub2-mkconfig call:\n{output}") if ret_code != 0: logger.warning("GRUB2 config file generation failed.") @@ -111,8 +109,8 @@ def run(self): description="There may be issues with the bootloader configuration." " Follow the recommended remediation before rebooting the system.", diagnosis="The grub2-mkconfig call failed with output:\n'{0}'".format(output.rstrip("\n")), - remediations="Resolve the problem reported in the diagnosis and then run 'grub2-mkconfig -o {0}' and" - " 'grub2-install [block device, e.g. /dev/sda]'.".format(grub2_config_file), + remediations=f"Resolve the problem reported in the diagnosis and then run 'grub2-mkconfig -o {grub2_config_file}' and" + " 'grub2-install [block device, e.g. /dev/sda]'.", ) return @@ -138,10 +136,10 @@ def run(self): ) return - logger.debug("Device to install the GRUB2 image to: '{}'".format(blk_device)) + logger.debug(f"Device to install the GRUB2 image to: '{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{}".format(output)) + logger.debug(f"Output of the grub2-install call:\n{output}") if ret_code != 0: logger.warning("Couldn't install the new images with GRUB2.") @@ -150,8 +148,8 @@ def run(self): id="GRUB2_INSTALL_FAILED", title="The grub2-install call failed to complete", description=( - "The grub2-install call failed with output: '{0}'. The conversion will continue but" - " there may be issues with the current grub2 image formats.".format(output) + f"The grub2-install call failed with output: '{output}'. The conversion will continue but" + " there may be issues with the current grub2 image formats." ), remediations="If there are issues with the current grub2 image we recommend manually" " re-generating it with 'grub2-install [block device, e.g. /dev/sda]'.", diff --git a/convert2rhel/actions/pre_ponr_changes/__init__.py b/convert2rhel/actions/pre_ponr_changes/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/actions/pre_ponr_changes/__init__.py +++ b/convert2rhel/actions/pre_ponr_changes/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/actions/pre_ponr_changes/backup_system.py b/convert2rhel/actions/pre_ponr_changes/backup_system.py index 6280ea7575..92d2dd4ba7 100644 --- a/convert2rhel/actions/pre_ponr_changes/backup_system.py +++ b/convert2rhel/actions/pre_ponr_changes/backup_system.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os import re @@ -29,7 +27,6 @@ from convert2rhel.utils import warn_deprecated_env from convert2rhel.utils.rpm import PRE_RPM_VA_LOG_FILENAME - # Regex explanation: # Match missing or SM5DLUGTP (letters can be replaced by dots or ?) - output of rpm -Va: # (missing|([S\.\?][M\.\?][5\.\?][D\.\?][L\.\?][U\.\?][G\.\?][T\.\?][P\.\?])) @@ -53,7 +50,7 @@ def run(self): """Backup redhat release file before starting conversion process""" logger.task("Backup Redhat Release Files") - super(BackupRedhatRelease, self).run() + super().run() try: # TODO(r0x0d): We need to keep calling those global objects from @@ -80,9 +77,9 @@ def run(self): """Backup .repo files in /etc/yum.repos.d/ so the repositories can be restored on rollback.""" logger.task("Backup Repository Files") - super(BackupRepository, self).run() + super().run() - logger.info("Backing up .repo files from {}.".format(DEFAULT_YUM_REPOFILE_DIR)) + logger.info(f"Backing up .repo files from {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) @@ -91,7 +88,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 {} is not a repository file.".format(repo)) + logger.info(f"Skipping backup as {repo} is not a repository file.") continue repo_path = os.path.join(DEFAULT_YUM_REPOFILE_DIR, repo) @@ -109,7 +106,7 @@ class BackupPackageFiles(actions.Action): def run(self): """Backup changed package files""" - super(BackupPackageFiles, self).run() + super().run() logger.task("Backup package files") @@ -154,7 +151,7 @@ def _get_changed_package_files(self): with open(path, "r") as f: output = f.read() # Catch the IOError due Python 2 compatibility - except IOError as err: + except OSError as err: warn_deprecated_env("CONVERT2RHEL_INCOMPLETE_ROLLBACK") if tool_opts.incomplete_rollback: logger.debug( @@ -166,8 +163,8 @@ def _get_changed_package_files(self): else: # The file should be there # If missing conversion is in unknown state - logger.warning("Error({}): {}".format(err.errno, err.strerror)) - logger.critical("Missing file {rpm_va_output} in it's location".format(rpm_va_output=path)) + logger.warning(f"Error({err.errno}): {err.strerror}") + logger.critical(f"Missing file {path} in it's location") lines = output.strip().split("\n") for line in lines: @@ -185,7 +182,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 {}".format(line)) + logger.debug(f"Skipping invalid output {line}") return {"status": None, "file_type": None, "path": None} line = line.split() diff --git a/convert2rhel/actions/pre_ponr_changes/custom_repos_are_valid.py b/convert2rhel/actions/pre_ponr_changes/custom_repos_are_valid.py index ef68bbea8d..8b21b86097 100644 --- a/convert2rhel/actions/pre_ponr_changes/custom_repos_are_valid.py +++ b/convert2rhel/actions/pre_ponr_changes/custom_repos_are_valid.py @@ -13,15 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions from convert2rhel.logger import root_logger from convert2rhel.pkgmanager import call_yum_cmd from convert2rhel.toolopts import tool_opts - logger = root_logger.getChild(__name__) @@ -35,7 +32,7 @@ def run(self): - YUM/DNF is able to find the repoids (to rule out a typo) - the repository "baseurl" is accessible and contains repository metadata """ - super(CustomReposAreValid, self).run() + super().run() logger.task("Check if --enablerepo repositories are accessible") if not tool_opts.enablerepo: @@ -54,9 +51,9 @@ def run(self): title="Unable to access repositories", description="Access could not be made to the custom repositories.", diagnosis="Unable to access the repositories passed through the --enablerepo option.", - remediations="For more details, see YUM/DNF output:\n{0}".format(output), + remediations=f"For more details, see YUM/DNF output:\n{output}", ) return - logger.debug("Output of the previous yum command:\n{0}".format(output)) + logger.debug(f"Output of the previous yum command:\n{output}") logger.info("The repositories passed through the --enablerepo option are all accessible.") diff --git a/convert2rhel/actions/pre_ponr_changes/handle_packages.py b/convert2rhel/actions/pre_ponr_changes/handle_packages.py index 61db62ae9f..7ac6a47fb1 100644 --- a/convert2rhel/actions/pre_ponr_changes/handle_packages.py +++ b/convert2rhel/actions/pre_ponr_changes/handle_packages.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os @@ -24,7 +23,6 @@ from convert2rhel.repo import DEFAULT_YUM_REPOFILE_DIR from convert2rhel.systeminfo import system_info - logger = root_logger.getChild(__name__) AMZN2_EXTRAS_REPOFILE_PATH = "/etc/yum.repos.d/amzn2-extras.repo" @@ -37,7 +35,7 @@ def run(self): List packages not packaged by the original OS vendor or Red Hat and warn that these are not going to be converted. """ - super(ListThirdPartyPackages, self).run() + super().run() logger.task("List third-party packages") third_party_pkgs = pkghandler.get_third_party_pkgs() @@ -49,9 +47,9 @@ def run(self): sorted(third_party_pkgs, key=self.extract_packages), disable_repos=repos_to_disable ) warning_message = ( - "Only packages signed by {} are to be" + f"Only packages signed by {system_info.name} are to be" " replaced. Red Hat support won't be provided" - " for the following third party packages:\n".format(system_info.name) + " for the following third party packages:\n" ) logger.warning(warning_message) @@ -97,7 +95,7 @@ def run(self): got merged together into this one, making possible to remove and back up all the packages in a single transaction. """ - super(RemoveSpecialPackages, self).run() + super().run() all_pkgs = [] pkgs_removed = [] @@ -170,7 +168,7 @@ def run(self): " conversion. This list includes packages that are known to cause a conversion failure." ), remediations=( - "Remove the packages manually before running convert2rhel again:\n" "yum remove -y {}".format( + "Remove the packages manually before running convert2rhel again:\nyum remove -y {}".format( " ".join(pkgs_not_removed) ) ), @@ -205,11 +203,11 @@ 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 {} packages:\n".format(len(pkgs_list))) + logger.warning(f"Removing the following {len(pkgs_list)} packages:\n") pkghandler.print_pkg_info(pkgs_list, disable_repos) pkgs_removed = utils.remove_pkgs(pkghandler.get_pkg_nevras(pkgs_list)) - logger.debug("Successfully removed {} packages".format(len(pkgs_list))) + logger.debug(f"Successfully removed {len(pkgs_list)} packages") return pkgs_removed @@ -219,7 +217,7 @@ def _fix_repos_directory(): repo_dir = DEFAULT_YUM_REPOFILE_DIR if not os.path.exists(repo_dir): os.mkdir(repo_dir) - logger.debug("Recreated repository directory {} as it was removed with some special package.".format(repo_dir)) + logger.debug(f"Recreated repository directory {repo_dir} as it was removed with some special package.") def _cleanup_amzn2_extras_repofile(): diff --git a/convert2rhel/actions/pre_ponr_changes/kernel_modules.py b/convert2rhel/actions/pre_ponr_changes/kernel_modules.py index 7651bb696d..07e9d13bb2 100644 --- a/convert2rhel/actions/pre_ponr_changes/kernel_modules.py +++ b/convert2rhel/actions/pre_ponr_changes/kernel_modules.py @@ -13,11 +13,9 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import itertools import re - from functools import cmp_to_key from convert2rhel import actions, pkghandler @@ -26,7 +24,6 @@ from convert2rhel.toolopts import tool_opts from convert2rhel.utils import run_subprocess, warn_deprecated_env - logger = root_logger.getChild(__name__) LINK_PREVENT_KMODS_FROM_LOADING = "https://access.redhat.com/solutions/41278" @@ -68,7 +65,7 @@ def _get_rhel_supported_kmods(self): precache = [ "yum", "makecache", - "--releasever={}".format(system_info.releasever), + f"--releasever={system_info.releasever}", "--setopt=*.skip_if_unavailable=False", ] # Clearing the exclude field with setopt to prevent kernel being @@ -76,9 +73,9 @@ def _get_rhel_supported_kmods(self): # https://issues.redhat.com/browse/RHELC-774 basecmd = [ "repoquery", - "--releasever={}".format(system_info.releasever), + f"--releasever={system_info.releasever}", "--setopt=exclude=", - "--archlist={}".format(system_info.arch), + f"--archlist={system_info.arch}", ] if system_info.version.major >= 8: @@ -135,7 +132,7 @@ def _get_rhel_supported_kmods(self): # 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)) + logger.debug(f"Output of the previous repoquery command:\n{kmod_pkgs_str}") raise RHELKernelModuleNotFound( "No packages containing kernel modules available in the enabled repositories ({}).".format( ", ".join(system_info.get_enabled_rhel_repos()) @@ -245,14 +242,13 @@ def _get_unsupported_kmods(self, host_kmods, rhel_supported_kmods): """ unsupported_kmods_subpaths = host_kmods - rhel_supported_kmods - set(system_info.kmods_to_ignore) unsupported_kmods_full_paths = [ - "/lib/modules/{kver}/{kmod}".format(kver=system_info.booted_kernel, kmod=kmod) - for kmod in unsupported_kmods_subpaths + f"/lib/modules/{system_info.booted_kernel}/{kmod}" for kmod in unsupported_kmods_subpaths ] return unsupported_kmods_full_paths def run(self): """Ensure that the host kernel modules are compatible with RHEL.""" - super(EnsureKernelModulesCompatibility, self).run() + super().run() logger.task("Ensure kernel modules compatibility with RHEL") @@ -291,11 +287,11 @@ def run(self): "\n".join(unsupported_kmods) ), remediations="Ensure you have updated the kernel to the latest available version and rebooted the system.\nIf this " - "message persists, you can prevent the modules from loading by following {0} and rerun convert2rhel.\n" + f"message persists, you can prevent the modules from loading by following {LINK_PREVENT_KMODS_FROM_LOADING} and rerun convert2rhel.\n" "Keeping them loaded could cause the system to malfunction after the conversion as they might not work " "properly with the RHEL kernel.\n" "To circumvent this check and accept the risk, set the allow_unavailable_kmods inhibitor override in the" - "/etc/convert2rhel.ini config file to true.".format(LINK_PREVENT_KMODS_FROM_LOADING), + "/etc/convert2rhel.ini config file to true.", ) return @@ -323,5 +319,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: {}".format(str(e)), + diagnosis=f"Package comparison failed: {e!s}", ) diff --git a/convert2rhel/actions/pre_ponr_changes/special_cases.py b/convert2rhel/actions/pre_ponr_changes/special_cases.py index 20c7305c44..b6aae4ed6a 100644 --- a/convert2rhel/actions/pre_ponr_changes/special_cases.py +++ b/convert2rhel/actions/pre_ponr_changes/special_cases.py @@ -13,15 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions from convert2rhel.logger import root_logger from convert2rhel.systeminfo import system_info from convert2rhel.utils import run_subprocess - logger = root_logger.getChild(__name__) @@ -45,7 +42,7 @@ def run(self): Related: https://bugzilla.redhat.com/show_bug.cgi?id=2078916 """ - super(RemoveIwlax2xxFirmware, self).run() + super().run() logger.task("Resolve possible edge case") iwl7260_firmware = system_info.is_rpm_installed(name="iwl7260-firmware") diff --git a/convert2rhel/actions/pre_ponr_changes/subscription.py b/convert2rhel/actions/pre_ponr_changes/subscription.py index 8646469209..908e51b75c 100644 --- a/convert2rhel/actions/pre_ponr_changes/subscription.py +++ b/convert2rhel/actions/pre_ponr_changes/subscription.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os.path @@ -27,7 +25,6 @@ ) from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) # Source and target directories for the cdn.redhat.com domain ssl ca cert that: @@ -46,7 +43,7 @@ class InstallRedHatCertForYumRepositories(actions.Action): id = "INSTALL_RED_HAT_CERT_FOR_YUM" def run(self): - super(InstallRedHatCertForYumRepositories, self).run() + super().run() # We need to make sure the redhat-uep.pem file exists since RHEL yum repositories use it. # The subscription-manager-rhsm-certificates package contains this cert but for @@ -61,7 +58,7 @@ class InstallRedHatGpgKeyForRpm(actions.Action): id = "INSTALL_RED_HAT_GPG_KEY" def run(self): - super(InstallRedHatGpgKeyForRpm, self).run() + super().run() # Import the Red Hat GPG Keys for installing Subscription-manager # and for later. @@ -78,7 +75,7 @@ class PreSubscription(actions.Action): ) def run(self): - super(PreSubscription, self).run() + super().run() if toolopts.tool_opts.no_rhsm: # Note: we don't use subscription.should_subscribe here because we @@ -137,7 +134,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: {}".format(e), + diagnosis=f"Failed to unregister the system: {e}", remediations="You may want to unregister the system manually and re-run convert2rhel.", ) @@ -152,7 +149,7 @@ class SubscribeSystem(actions.Action): ) def run(self): - super(SubscribeSystem, self).run() + super().run() if not subscription.should_subscribe(): if toolopts.tool_opts.no_rhsm: @@ -227,7 +224,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: {}".format(e), + diagnosis=f"Failed to execute command: {e}", ) except exceptions.CriticalError as e: self.set_result( @@ -255,7 +252,5 @@ 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: {}".format( - str(e) - ), + diagnosis=f"One or more combinations were missing for subscription-manager parameters: {e!s}", ) diff --git a/convert2rhel/actions/pre_ponr_changes/transaction.py b/convert2rhel/actions/pre_ponr_changes/transaction.py index 7e68f18ada..8ea5685f74 100644 --- a/convert2rhel/actions/pre_ponr_changes/transaction.py +++ b/convert2rhel/actions/pre_ponr_changes/transaction.py @@ -13,13 +13,10 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions, exceptions, pkgmanager from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) @@ -39,7 +36,7 @@ class ValidatePackageManagerTransaction(actions.Action): def run(self): """Validate the package manager transaction is passing the tests.""" - super(ValidatePackageManagerTransaction, self).run() + super().run() try: logger.task("Validate the %s transaction", pkgmanager.TYPE) diff --git a/convert2rhel/actions/pre_ponr_changes/yum_variables.py b/convert2rhel/actions/pre_ponr_changes/yum_variables.py index 8bc503163a..7b87490539 100644 --- a/convert2rhel/actions/pre_ponr_changes/yum_variables.py +++ b/convert2rhel/actions/pre_ponr_changes/yum_variables.py @@ -13,16 +13,13 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import shutil -from convert2rhel import actions -from convert2rhel import backup +from convert2rhel import actions, backup, pkghandler from convert2rhel.backup.files import InstalledFile, RestorableFile from convert2rhel.logger import root_logger -from convert2rhel import pkghandler from convert2rhel.repo import DEFAULT_DNF_VARS_DIR, DEFAULT_YUM_VARS_DIR from convert2rhel.systeminfo import system_info from convert2rhel.toolopts.config import loggerinst @@ -45,7 +42,7 @@ def run(self): """ logger.task("Back up yum variables") - super(BackUpYumVariables, self).run() + super().run() logger.debug("Getting a list of files owned by packages affecting variables in .repo files.") yum_var_affecting_pkgs = [] @@ -119,33 +116,29 @@ def run(self): but also after a successful conversion. With such a flag we would add a new post-conversion Action to run the backup controller restoration but only for the activities recorded with this flag. """ - super(RestoreYumVarFiles, self).run() + super().run() backed_up_yum_var_dirs = backup.get_backed_up_yum_var_dirs() loggerinst.task("Restoring yum variable files") loggerinst.info( - "We need to restore {0} yum variables as they are oftentimes necessary for accessing the {0} repositories.".format( - system_info.name - ) + f"We need to restore {system_info.name} yum variables as they are oftentimes necessary for accessing the {system_info.name} repositories." ) for orig_yum_var_dir, backed_up_yum_var_dir in backed_up_yum_var_dirs.items(): if not os.path.exists(backed_up_yum_var_dir): - logger.info("No file from {} backed up. Nothing to restore.".format(orig_yum_var_dir)) + logger.info(f"No file from {orig_yum_var_dir} backed up. Nothing to restore.") continue for backed_up_yum_var_filename in os.listdir(backed_up_yum_var_dir): backed_up_yum_var_filepath = os.path.join(backed_up_yum_var_dir, backed_up_yum_var_filename) try: shutil.copy2(backed_up_yum_var_filepath, orig_yum_var_dir) - logger.debug("Copied {} from backup to {}.".format(backed_up_yum_var_filepath, orig_yum_var_dir)) - except (OSError, IOError) as err: + logger.debug(f"Copied {backed_up_yum_var_filepath} from backup to {orig_yum_var_dir}.") + except OSError as err: # IOError for py2 and OSError for py3 # Not being able to restore the yum variables might or might not cause problems down the road. No # need to stop the conversion because of that. The warning message below should be enough of a clue # for resolving subsequent yum errors. logger.warning( - "Couldn't copy {} to {}. Error: {}".format( - backed_up_yum_var_filepath, orig_yum_var_dir, err.strerror - ) + f"Couldn't copy {backed_up_yum_var_filepath} to {orig_yum_var_dir}. Error: {err.strerror}" ) return restored_file = InstalledFile( diff --git a/convert2rhel/actions/report.py b/convert2rhel/actions/report.py index 6fd9998189..f8b9058d84 100644 --- a/convert2rhel/actions/report.py +++ b/convert2rhel/actions/report.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import copy import json @@ -30,7 +29,6 @@ ) from convert2rhel.logger import colorize, root_logger - logger = root_logger.getChild(__name__) #: The filename to store the results of running preassessment @@ -295,7 +293,7 @@ def format_report_section_heading(status_code): status_header = STATUS_HEADER[status_code] highlight = "=" * 10 - heading = "{highlight} {status_header} {highlight}".format(highlight=highlight, status_header=status_header) + heading = f"{highlight} {status_header} {highlight}" return heading diff --git a/convert2rhel/actions/system_checks/__init__.py b/convert2rhel/actions/system_checks/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/actions/system_checks/__init__.py +++ b/convert2rhel/actions/system_checks/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/actions/system_checks/check_firewalld_availability.py b/convert2rhel/actions/system_checks/check_firewalld_availability.py index 34dc7b44bd..55a21355ab 100644 --- a/convert2rhel/actions/system_checks/check_firewalld_availability.py +++ b/convert2rhel/actions/system_checks/check_firewalld_availability.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os import re @@ -23,7 +21,6 @@ from convert2rhel.logger import root_logger from convert2rhel.systeminfo import system_info - logger = root_logger.getChild(__name__) # Path to the firewalld config file. @@ -43,17 +40,17 @@ def _is_modules_cleanup_enabled(): """ # Return True is the config file does not exist. if not os.path.exists(FIREWALLD_CONFIG_FILE): - logger.debug("{} does not exist.".format(FIREWALLD_CONFIG_FILE)) + logger.debug(f"{FIREWALLD_CONFIG_FILE} does not exist.") return True contents = [] with open(FIREWALLD_CONFIG_FILE, mode="r") as handler: - contents = [line.strip() for line in handler.readlines() if line.strip()] + contents = [line.strip() for line in handler if line.strip()] # 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("{} is empty.".format(FIREWALLD_CONFIG_FILE)) + logger.debug(f"{FIREWALLD_CONFIG_FILE} is empty.") return True # If the CleanupModulesOnExit is not present inside the contents list, we @@ -71,12 +68,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 {}".format(FIREWALLD_CONFIG_FILE)) + logger.debug(f"CleanupModulesOnExit option enabled in {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 {}".format(FIREWALLD_CONFIG_FILE)) + logger.debug(f"CleanupModulesOnExit option is disabled in {FIREWALLD_CONFIG_FILE}") return False @@ -85,7 +82,7 @@ class CheckFirewalldAvailability(actions.Action): def run(self): """Error out if the firewalld service is running on the system.""" - super(CheckFirewalldAvailability, self).run() + super().run() logger.task("Check that firewalld is running") if system_info.id == "oracle" and system_info.version.major == 8 and system_info.version.minor >= 8: diff --git a/convert2rhel/actions/system_checks/convert2rhel_latest.py b/convert2rhel/actions/system_checks/convert2rhel_latest.py index 60309d3d47..b323a6dcec 100644 --- a/convert2rhel/actions/system_checks/convert2rhel_latest.py +++ b/convert2rhel/actions/system_checks/convert2rhel_latest.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os.path @@ -29,7 +27,6 @@ from convert2rhel.toolopts import tool_opts from convert2rhel.utils import warn_deprecated_env - logger = root_logger.getChild(__name__) C2R_REPOFILE_URLS = { @@ -47,7 +44,7 @@ def run(self): """Make sure that we are running the latest downstream version of convert2rhel""" logger.task("Check if this is the latest version of Convert2RHEL") - super(Convert2rhelLatest, self).run() + super().run() repofile_path = self._download_convert2rhel_repofile() if not repofile_path: @@ -55,8 +52,8 @@ def run(self): cmd = [ "repoquery", - "--releasever={}".format(system_info.version.major), - "--setopt=reposdir={}".format(os.path.dirname(repofile_path)), + f"--releasever={system_info.version.major}", + f"--setopt=reposdir={os.path.dirname(repofile_path)}", "--setopt=exclude=", "--qf", "C2R %{NAME}-%{EPOCH}:%{VERSION}-%{RELEASE}.%{ARCH}", @@ -68,7 +65,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{}".format(raw_output_convert2rhel_versions) + f"repoquery failed with the following output:\n{raw_output_convert2rhel_versions}" ) logger.warning(diagnosis) self.add_message( @@ -95,7 +92,7 @@ def run(self): continue convert2rhel_versions.append(parsed_pkg) - logger.debug("Found {} convert2rhel package(s)".format(len(convert2rhel_versions))) + logger.debug(f"Found {len(convert2rhel_versions)} convert2rhel package(s)") # 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. @@ -109,7 +106,7 @@ def run(self): if ver_compare > 0: latest_available_version = (package_version[1], package_version[2], package_version[3]) - logger.debug("Found {} to be latest available version".format(latest_available_version[1])) + logger.debug(f"Found {latest_available_version[1]} to be latest available version") 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,9 +129,7 @@ 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 ({}) is the latest but ignore the rpm release.".format( - running_convert2rhel_version - ) + f"Couldn't determine the rpm release; We will check that the version of convert2rhel ({running_convert2rhel_version}) is the latest but ignore the rpm release." ) else: @@ -149,9 +144,7 @@ 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 ({}) is the latest but ignore the rpm release.".format( - running_convert2rhel_version - ) + f" We will check that the version of convert2rhel ({running_convert2rhel_version}) is the latest but ignore the rpm release." ) # Otherwise use the NEVRA from above to compare with the latest packaged version @@ -175,10 +168,8 @@ def run(self): warn_deprecated_env("CONVERT2RHEL_ALLOW_OLDER_VERSION") if tool_opts.allow_older_version: diagnosis = ( - "You are currently running {} and the latest version of convert2rhel is {}.\n" - "You have set the option to allow older convert2rhel version, continuing conversion".format( - formatted_convert2rhel_version, formatted_available_version - ) + f"You are currently running {formatted_convert2rhel_version} and the latest version of convert2rhel is {formatted_available_version}.\n" + "You have set the option to allow older convert2rhel version, continuing conversion" ) logger.warning(diagnosis) self.add_message( @@ -195,10 +186,8 @@ def run(self): title="Outdated convert2rhel version detected", description="An outdated convert2rhel version has been detected", diagnosis=( - "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 - ) + f"You are currently running {formatted_convert2rhel_version} and the latest version of convert2rhel is {formatted_available_version}.\n" + "Only the latest version is supported for conversion." ), remediations="If you want to disregard this check, set the allow_older_version inhibitor" " override in the /etc/convert2rhel.ini config file to true.", @@ -243,7 +232,7 @@ def _download_convert2rhel_repofile(self): def _format_EVR(epoch, version, release): - return "{}".format(version) + return f"{version}" def _extract_convert2rhel_versions(raw_versions): @@ -265,7 +254,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: {}".format(raw_version)) + logger.debug(f"Got a line without the C2R identifier: {raw_version}") precise_raw_version = parsed_versions return precise_raw_version diff --git a/convert2rhel/actions/system_checks/dbus.py b/convert2rhel/actions/system_checks/dbus.py index ac23576ca8..7f439b9009 100644 --- a/convert2rhel/actions/system_checks/dbus.py +++ b/convert2rhel/actions/system_checks/dbus.py @@ -13,14 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions, subscription from convert2rhel.logger import root_logger from convert2rhel.systeminfo import system_info - logger = root_logger.getChild(__name__) @@ -29,7 +26,7 @@ class DbusIsRunning(actions.Action): def run(self): """Error out if we need to register with rhsm and the dbus daemon is not running.""" - super(DbusIsRunning, self).run() + super().run() logger.task("Check that DBus Daemon is running") if not subscription.should_subscribe(): diff --git a/convert2rhel/actions/system_checks/duplicate_packages.py b/convert2rhel/actions/system_checks/duplicate_packages.py index 2d1ad50843..f7708fbe85 100644 --- a/convert2rhel/actions/system_checks/duplicate_packages.py +++ b/convert2rhel/actions/system_checks/duplicate_packages.py @@ -13,14 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions, utils from convert2rhel.logger import root_logger from convert2rhel.systeminfo import system_info - logger = root_logger.getChild(__name__) @@ -29,7 +26,7 @@ class DuplicatePackages(actions.Action): def run(self): """Ensure that there are no duplicate system packages installed.""" - super(DuplicatePackages, self).run() + super().run() logger.task("Check if there are any duplicate installed packages on the system") output, ret_code = utils.run_subprocess(["/usr/bin/package-cleanup", "--dupes", "--quiet"], print_output=False) diff --git a/convert2rhel/actions/system_checks/efi.py b/convert2rhel/actions/system_checks/efi.py index 39293d0dc6..82a3e9caea 100644 --- a/convert2rhel/actions/system_checks/efi.py +++ b/convert2rhel/actions/system_checks/efi.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os.path @@ -22,7 +20,6 @@ from convert2rhel.logger import root_logger from convert2rhel.systeminfo import system_info - logger = root_logger.getChild(__name__) @@ -31,7 +28,7 @@ class Efi(actions.Action): def run(self): """Inhibit the conversion when we are not able to handle UEFI.""" - super(Efi, self).run() + super().run() logger.task("Check the firmware interface type (BIOS/UEFI)") if not grub.is_efi(): @@ -87,8 +84,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 '{}' is not referring to any binary UEFI" - " file located on local EFI System Partition (ESP).".format(efiboot_info.current_bootnum) + f"The current UEFI bootloader '{efiboot_info.current_bootnum}' is not referring to any binary UEFI" + " file located on local EFI System Partition (ESP)." ) self.add_message( level="WARNING", @@ -96,8 +93,8 @@ def run(self): title="UEFI bootloader mismatch", description="There was a UEFI bootloader mismatch.", diagnosis=( - "The current UEFI bootloader '{}' is not referring to any binary UEFI" - " file located on local EFI System Partition (ESP).".format(efiboot_info.current_bootnum) + f"The current UEFI bootloader '{efiboot_info.current_bootnum}' is not referring to any binary UEFI" + " file located on local EFI System Partition (ESP)." ), ) # TODO(pstodulk): print warning when multiple orig. UEFI entries point diff --git a/convert2rhel/actions/system_checks/els.py b/convert2rhel/actions/system_checks/els.py index fcd45d2bdb..034f3d548d 100644 --- a/convert2rhel/actions/system_checks/els.py +++ b/convert2rhel/actions/system_checks/els.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import datetime @@ -22,7 +21,6 @@ from convert2rhel.systeminfo import ELS_RELEASE_DATE, system_info from convert2rhel.toolopts import tool_opts - logger = root_logger.getChild(__name__) @@ -31,7 +29,7 @@ class ElsSystemCheck(actions.Action): def run(self): """Warn the user if their system is under ELS and past the ELS release date without using the --els cli option.""" - super(ElsSystemCheck, self).run() + super().run() if system_info.version.major == 7: current_datetime = datetime.date.today() @@ -47,4 +45,3 @@ def run(self): description="Current system version is under Extended Lifecycle Support (ELS). You may want to consider using the --els" " command line option to land on a system patched with the latest security errata.", ) - return diff --git a/convert2rhel/actions/system_checks/eus.py b/convert2rhel/actions/system_checks/eus.py index e40e6635ff..a1d9bc04ee 100644 --- a/convert2rhel/actions/system_checks/eus.py +++ b/convert2rhel/actions/system_checks/eus.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import datetime @@ -22,7 +21,6 @@ from convert2rhel.systeminfo import EUS_MINOR_VERSIONS, system_info from convert2rhel.toolopts import tool_opts - logger = root_logger.getChild(__name__) @@ -31,9 +29,9 @@ class EusSystemCheck(actions.Action): 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() + super().run() - current_version = "{}.{}".format(system_info.version.major, system_info.version.minor) + current_version = f"{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) @@ -50,4 +48,3 @@ def run(self): description="Current system version is under Extended Update Support (EUS). You may want to consider using the --eus" " command line option to land on a system patched with the latest security errata.", ) - return diff --git a/convert2rhel/actions/system_checks/grub_validity.py b/convert2rhel/actions/system_checks/grub_validity.py index e8b5304d25..0b1e82f4a2 100644 --- a/convert2rhel/actions/system_checks/grub_validity.py +++ b/convert2rhel/actions/system_checks/grub_validity.py @@ -13,12 +13,10 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from convert2rhel import actions, utils from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) @@ -30,7 +28,7 @@ def run(self): Execute grub2-mkconfig and report an error if it fails to execute. A failure means that the grub file is invalid. """ - super(GrubValidity, self).run() + super().run() logger.task("Check if the grub file is valid") output, ret_code = utils.run_subprocess(["grub2-mkconfig"], print_output=False) diff --git a/convert2rhel/actions/system_checks/is_loaded_kernel_latest.py b/convert2rhel/actions/system_checks/is_loaded_kernel_latest.py index 02e023b132..4ee602fb37 100644 --- a/convert2rhel/actions/system_checks/is_loaded_kernel_latest.py +++ b/convert2rhel/actions/system_checks/is_loaded_kernel_latest.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions, repo from convert2rhel.logger import root_logger @@ -23,7 +21,6 @@ from convert2rhel.toolopts import tool_opts from convert2rhel.utils import run_subprocess, warn_deprecated_env - logger = root_logger.getChild(__name__) @@ -34,7 +31,7 @@ class IsLoadedKernelLatest(actions.Action): # but we don't do that in an Action class def run(self): """Check if the loaded kernel is behind or of the same version as in yum repos.""" - super(IsLoadedKernelLatest, self).run() + super().run() logger.task("Check if the loaded kernel version is the most recent") if system_info.id == "oracle" and system_info.eus_system: @@ -124,7 +121,7 @@ def run(self): # 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: {}".format(line)) + logger.debug(f"Got a line without the C2R identifier: {line}") # If we don't have any packages, then something went wrong, bail out by default if not packages: @@ -134,9 +131,7 @@ def run(self): title="Kernel currency check failed", description="Please refer to the diagnosis for further information", diagnosis=( - "Could not find any {} from repositories to compare against the loaded kernel.".format( - package_to_check - ) + f"Could not find any {package_to_check} from repositories to compare against the loaded kernel." ), remediations=( "Please check if you have any vendor repositories enabled to proceed with the conversion.\n" @@ -153,8 +148,8 @@ def run(self): 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 = "{}-{}".format(package_to_check, latest_kernel) - loaded_kernel_pkg = "{}-{}".format(package_to_check, loaded_kernel) + latest_kernel_pkg = f"{package_to_check}-{latest_kernel}" + loaded_kernel_pkg = f"{package_to_check}-{loaded_kernel}" try: match = compare_package_versions(latest_kernel_pkg, loaded_kernel_pkg) except ValueError as exc: @@ -175,15 +170,15 @@ def run(self): 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 {}: {}\n" - " Loaded kernel version: {}".format(repoid, latest_kernel, loaded_kernel) + f" Latest kernel version available in {repoid}: {latest_kernel}\n" + f" Loaded kernel version: {loaded_kernel}" ), remediations=( "To proceed with the conversion, update the kernel version by executing the following step:\n\n" - "1. yum install {}-{} -y\n" + f"1. yum install {package_to_check}-{latest_kernel} -y\n" "2. reboot\n" "If you wish to ignore this message, set the skip_kernel_currency_check inhibitor override in" - " the /etc/convert2rhel.ini config file to true.".format(package_to_check, latest_kernel) + " the /etc/convert2rhel.ini config file to true." ), ) return diff --git a/convert2rhel/actions/system_checks/package_updates.py b/convert2rhel/actions/system_checks/package_updates.py index 0572fcba9f..cdbe8527b4 100644 --- a/convert2rhel/actions/system_checks/package_updates.py +++ b/convert2rhel/actions/system_checks/package_updates.py @@ -13,15 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions, pkgmanager, utils from convert2rhel.logger import root_logger from convert2rhel.pkghandler import get_total_packages_to_update from convert2rhel.systeminfo import system_info - logger = root_logger.getChild(__name__) @@ -30,7 +27,7 @@ class PackageUpdates(actions.Action): def run(self): """Ensure that the system packages installed are up-to-date.""" - super(PackageUpdates, self).run() + super().run() logger.task("Check if the installed packages are up-to-date") if system_info.id == "oracle" and system_info.eus_system: @@ -63,7 +60,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. {}".format(str(e)) + f" before proceeding with the conversion. {e!s}" ) logger.warning(package_up_to_date_error_message) diff --git a/convert2rhel/actions/system_checks/readonly_mounts.py b/convert2rhel/actions/system_checks/readonly_mounts.py index 447fe9f0c3..37287bc9d8 100644 --- a/convert2rhel/actions/system_checks/readonly_mounts.py +++ b/convert2rhel/actions/system_checks/readonly_mounts.py @@ -13,14 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions from convert2rhel.logger import root_logger from convert2rhel.utils import get_file_content - logger = root_logger.getChild(__name__) @@ -38,8 +35,8 @@ def readonly_mount_detection(mount_point): if file_mount_point == mount_point: if "ro" in flags: return True - logger.debug("{} mount point is not read-only.".format(file_mount_point)) - logger.info("Read-only {} mount point not detected.".format(mount_point)) + logger.debug(f"{file_mount_point} mount point is not read-only.") + logger.info(f"Read-only {mount_point} mount point not detected.") return False @@ -47,7 +44,7 @@ class ReadonlyMountMnt(actions.Action): id = "READ_ONLY_MOUNTS_MNT" def run(self): - super(ReadonlyMountMnt, self).run() + super().run() logger.task("Check if /mnt is read-write") if readonly_mount_detection("/mnt"): @@ -66,7 +63,7 @@ class ReadonlyMountSys(actions.Action): id = "READ_ONLY_MOUNTS_SYS" def run(self): - super(ReadonlyMountSys, self).run() + super().run() logger.task("Check if /sys is read-write") if readonly_mount_detection("/sys"): diff --git a/convert2rhel/actions/system_checks/rhel_compatible_kernel.py b/convert2rhel/actions/system_checks/rhel_compatible_kernel.py index e3967fed12..ca004242b2 100644 --- a/convert2rhel/actions/system_checks/rhel_compatible_kernel.py +++ b/convert2rhel/actions/system_checks/rhel_compatible_kernel.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import actions from convert2rhel.logger import root_logger @@ -22,7 +20,6 @@ from convert2rhel.systeminfo import system_info from convert2rhel.utils import run_subprocess - logger = root_logger.getChild(__name__) # The kernel version stays the same throughout a RHEL major version @@ -58,7 +55,7 @@ def run(self): By requesting that, we can be confident that the RHEL kernel will provide the same capabilities as on the original system. """ - super(RhelCompatibleKernel, self).run() + super().run() logger.task("Check kernel compatibility with RHEL") for check_function in (_bad_kernel_version, _bad_kernel_package_signature, _bad_kernel_substring): try: @@ -88,23 +85,21 @@ 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. {}".format( - bad_kernel_message - ) + f"The booted kernel version is incompatible with the standard RHEL kernel. {bad_kernel_message}" ), remediations=( - "To proceed with the conversion, boot into a kernel that is available in the {0} {1} base repository" + f"To proceed with the conversion, boot into a kernel that is available in the {system_info.name} {system_info.version.major} base repository" " by executing the following steps:\n\n" - "1. Ensure that the {0} {1} base repository is enabled\n" + f"1. Ensure that the {system_info.name} {system_info.version.major} base repository is enabled\n" "2. Run: yum install kernel\n" "3. (optional) Run: grubby --set-default " - '/boot/vmlinuz-`rpm -q --qf "%{{BUILDTIME}}\\t%{{EVR}}.%{{ARCH}}\\n" kernel | sort -nr | head -1 | cut -f2`\n' + '/boot/vmlinuz-`rpm -q --qf "%{BUILDTIME}\\t%{EVR}.%{ARCH}\\n" kernel | sort -nr | head -1 | cut -f2`\n' "4. Reboot the machine and if step 3 was not applied choose the kernel" - " installed in step 2 manually".format(system_info.name, system_info.version.major) + " installed in step 2 manually" ), ) return - logger.info("The booted kernel {} is compatible with RHEL.".format(system_info.booted_kernel)) + logger.info(f"The booted kernel {system_info.booted_kernel} is compatible with RHEL.") def _bad_kernel_version(kernel_release): @@ -139,7 +134,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-{}".format(kernel_release) + vmlinuz_path = f"/boot/vmlinuz-{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) @@ -162,7 +157,7 @@ def _bad_kernel_package_signature(kernel_release): {"os_vendor": os_vendor}, ) - logger.debug("The booted kernel is signed by {}.".format(os_vendor)) + logger.debug(f"The booted kernel is signed by {os_vendor}.") return False diff --git a/convert2rhel/actions/system_checks/tainted_kmods.py b/convert2rhel/actions/system_checks/tainted_kmods.py index 5f56293f58..db0c145f9d 100644 --- a/convert2rhel/actions/system_checks/tainted_kmods.py +++ b/convert2rhel/actions/system_checks/tainted_kmods.py @@ -13,14 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from convert2rhel import actions from convert2rhel.logger import root_logger from convert2rhel.toolopts import tool_opts from convert2rhel.utils import run_subprocess, warn_deprecated_env - logger = root_logger.getChild(__name__) LINK_KMODS_RH_POLICY = "https://access.redhat.com/third-party-software-support" @@ -39,16 +37,16 @@ def run(self): system76_io 16384 0 - Live 0x0000000000000000 (OE) <<<<<< Tainted system76_acpi 16384 0 - Live 0x0000000000000000 (OE) <<<<<< Tainted """ - super(TaintedKmods, self).run() + super().run() logger.task("Check if loaded kernel modules are not tainted") unsigned_modules, _ = run_subprocess(["grep", "(", "/proc/modules"]) module_names = "\n ".join([mod.split(" ")[0] for mod in unsigned_modules.splitlines()]) warn_deprecated_env("CONVERT2RHEL_TAINTED_KERNEL_MODULE_CHECK_SKIP") diagnosis = ( - "Tainted kernel modules detected:\n {0}\n" + f"Tainted kernel modules detected:\n {module_names}\n" "Third-party components are not supported per our " - "software support policy:\n{1}\n".format(module_names, LINK_KMODS_RH_POLICY) + f"software support policy:\n{LINK_KMODS_RH_POLICY}\n" ) if unsigned_modules: @@ -60,15 +58,13 @@ def run(self): description="Please refer to the diagnosis for further information", diagnosis=diagnosis, remediations=( - "Prevent the modules from loading by following {0}" + f"Prevent the modules from loading by following {LINK_PREVENT_KMODS_FROM_LOADING}" " and run convert2rhel again to continue with the conversion." " Although it is not recommended, you can disregard this message by setting the" " tainted_kernel_module_check_skip inhibitor override in the /etc/convert2rhel.ini" " config file to true. Overriding this check can be dangerous" " so it is recommended that you do a system backup beforehand." - " For information on what a tainted kernel module is, please refer to this documentation {1}".format( - LINK_PREVENT_KMODS_FROM_LOADING, LINK_TAINTED_KMOD_DOCS - ) + f" For information on what a tainted kernel module is, please refer to this documentation {LINK_TAINTED_KMOD_DOCS}" ), ) return @@ -90,11 +86,9 @@ def run(self): description="Please refer to the diagnosis for further information", diagnosis=diagnosis, remediations=( - "Prevent the modules from loading by following {0}" + f"Prevent the modules from loading by following {LINK_PREVENT_KMODS_FROM_LOADING}" " and run convert2rhel again to continue with the conversion." - " For information on what a tainted kernel module is, please refer to this documentation {1}".format( - LINK_PREVENT_KMODS_FROM_LOADING, LINK_TAINTED_KMOD_DOCS - ) + f" For information on what a tainted kernel module is, please refer to this documentation {LINK_TAINTED_KMOD_DOCS}" ), ) return diff --git a/convert2rhel/applock.py b/convert2rhel/applock.py index cdead1cb09..b5bd27c9f2 100644 --- a/convert2rhel/applock.py +++ b/convert2rhel/applock.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import errno import os @@ -23,7 +21,6 @@ from convert2rhel.logger import root_logger - _DEFAULT_LOCK_DIR = "/var/run/lock" logger = root_logger.getChild(__name__) @@ -32,7 +29,7 @@ class ApplicationLockedError(Exception): """Raised when this application is already locked.""" def __init__(self, message): - super(ApplicationLockedError, self).__init__(message) + super().__init__(message) self.message = message @@ -99,7 +96,7 @@ def _try_create(self): if exc.errno == errno.EEXIST: return False raise exc - logger.debug("{}.".format(self)) + logger.debug(f"{self}.") return True @property @@ -139,14 +136,14 @@ def try_to_lock(self, _recursive=False): self._locked = True return if _recursive: - raise ApplicationLockedError("Cannot lock {}".format(self._name)) + raise ApplicationLockedError(f"Cannot lock {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 {} is corrupt".format(self._pidfile)) + raise ApplicationLockedError(f"Lock file {self._pidfile} is corrupt") if self._pid_exists(pid): raise ApplicationLockedError("%s locked by process %d" % (self._pidfile, pid)) @@ -167,7 +164,7 @@ def unlock(self): return os.unlink(self._pidfile) self._locked = False - logger.debug("{}.".format(self)) + logger.debug(f"{self}.") def __enter__(self): self.try_to_lock() diff --git a/convert2rhel/backup/__init__.py b/convert2rhel/backup/__init__.py index 01a16a189e..755a1c1ecd 100644 --- a/convert2rhel/backup/__init__.py +++ b/convert2rhel/backup/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import abc import hashlib @@ -24,10 +22,9 @@ import six from convert2rhel.logger import root_logger -from convert2rhel.repo import DEFAULT_YUM_REPOFILE_DIR, DEFAULT_YUM_VARS_DIR, DEFAULT_DNF_VARS_DIR +from convert2rhel.repo import DEFAULT_DNF_VARS_DIR, DEFAULT_YUM_REPOFILE_DIR, DEFAULT_YUM_VARS_DIR from convert2rhel.utils import TMP_DIR - # Directory for temporary backing up files, packages and other relevant stuff. BACKUP_DIR = os.path.join(TMP_DIR, "backup") @@ -81,13 +78,13 @@ def push(self, restorable): :arg restorable: RestorableChange object that can be restored later. """ if not isinstance(restorable, RestorableChange): - raise TypeError("`{}` is not a RestorableChange object".format(restorable)) + raise TypeError(f"`{restorable}` is not a RestorableChange object") # Check if the restorable is already backed up # if it is, we skip it for r in self._restorables: if r == restorable: - logger.debug("Skipping: {} has already been backed up".format(restorable.__class__.__name__)) + logger.debug(f"Skipping: {restorable.__class__.__name__} has already been backed up") return restorable.enable() @@ -142,7 +139,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 {}: {}".format(restorable.__class__.__name__, str(e)) + message = f"Error while rolling back a {restorable.__class__.__name__}: {e!s}" 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 fe5b5225a6..0f9bde8ddf 100644 --- a/convert2rhel/backup/certs.py +++ b/convert2rhel/backup/certs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import errno import os @@ -26,7 +24,6 @@ from convert2rhel.logger import root_logger from convert2rhel.utils import files - logger = root_logger.getChild(__name__) @@ -40,7 +37,7 @@ def __init__(self, keyfile): :arg keyfile: Filepath for a GPG key. The RestorableRpmKey instance will be able to import this into the rpmdb when enabled and remove it when restored. """ - super(RestorableRpmKey, self).__init__() + super().__init__() self.previously_installed = None self.keyfile = keyfile self.keyid = utils.find_keyid(keyfile) @@ -54,43 +51,43 @@ 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 {}: {}".format(self.keyfile, output)) + raise utils.ImportGPGKeyError(f"Failed to import the GPG key {self.keyfile}: {output}") self.previously_installed = False else: self.previously_installed = True - super(RestorableRpmKey, self).enable() + super().enable() @property def installed(self): """Whether the GPG key has been imported into the rpmdb.""" - output, status = utils.run_subprocess(["rpm", "-q", "gpg-pubkey-{}".format(self.keyid)], print_output=False) + output, status = utils.run_subprocess(["rpm", "-q", f"gpg-pubkey-{self.keyid}"], print_output=False) if status == 0: return True - if status == 1 and "package gpg-pubkey-{} is not installed".format(self.keyid) in output: + if status == 1 and f"package gpg-pubkey-{self.keyid} is not installed" in output: return False raise utils.ImportGPGKeyError( - "Searching the rpmdb for the gpg key {} failed: Code {}: {}".format(self.keyid, status, output) + f"Searching the rpmdb for the gpg key {self.keyid} failed: Code {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-{}".format(self.keyid)]) + utils.run_subprocess(["rpm", "-e", f"gpg-pubkey-{self.keyid}"]) - super(RestorableRpmKey, self).restore() + super().restore() class RestorablePEMCert(RestorableChange): """Handling certificates needed for verifying Red Hat services.""" def __init__(self, source_cert_dir, target_cert_dir): - super(RestorablePEMCert, self).__init__() + super().__init__() self._target_cert_dir = target_cert_dir self._source_cert_dir = source_cert_dir @@ -112,27 +109,25 @@ def enable(self): return if os.path.exists(self._target_cert_path): - logger.info("Certificate already present at {}. Skipping copy.".format(self._target_cert_path)) + logger.info(f"Certificate already present at {self._target_cert_path}. Skipping copy.") self.previously_installed = True else: try: files.mkdir_p(self._target_cert_dir) shutil.copy2(self._source_cert_path, self._target_cert_dir) - except (OSError, IOError) as err: + except OSError as err: # IOError for py2 and OSError for py3 - logger.critical_no_exit("Error({0}): {1}".format(err.errno, err.strerror)) + logger.critical_no_exit(f"Error({err.errno}): {err.strerror}") raise exceptions.CriticalError( 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 {} to {}. Errno: {}, Error: {}".format( - self._get_source_cert_path, self._target_cert_dir, err.errno, err.strerror - ), + diagnosis=f"Failed to install certificate {self._get_source_cert_path} to {self._target_cert_dir}. Errno: {err.errno}, Error: {err.strerror}", ) - logger.info("Certificate {} copied to {}.".format(self._cert_filename, self._target_cert_dir)) + logger.info(f"Certificate {self._cert_filename} copied to {self._target_cert_dir}.") - super(RestorablePEMCert, self).enable() + super().enable() def restore(self): """Remove certificate (.pem), which was copied to system's cert dir.""" @@ -141,9 +136,9 @@ def restore(self): if self.enabled and not self.previously_installed: self._restore() else: - logger.info("Certificate {} was present before conversion. Skipping removal.".format(self._cert_filename)) + logger.info(f"Certificate {self._cert_filename} was present before conversion. Skipping removal.") - super(RestorablePEMCert, self).restore() + super().restore() def _restore(self): """The actual code to remove the certificate. Done in a helper method so we can handle all @@ -172,16 +167,14 @@ 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 {}".format(self._target_cert_path)) + logger.info(f"Certificate already removed from {self._target_cert_path}") else: logger.warning( - "Unable to determine if a package owns certificate {}. Skipping removal.".format( - self._target_cert_path - ) + f"Unable to determine if a package owns certificate {self._target_cert_path}. Skipping removal." ) else: logger.info( - "A package was installed that owns the certificate {}. Skipping removal.".format(self._target_cert_path) + f"A package was installed that owns the certificate {self._target_cert_path}. Skipping removal." ) # Not safe to remove the certificate because the file might be owned by @@ -191,7 +184,7 @@ def _restore(self): try: os.remove(self._target_cert_path) - logger.info("Certificate {} removed".format(self._target_cert_path)) + logger.info(f"Certificate {self._target_cert_path} removed") 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 @@ -205,12 +198,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 {}.".format(cert_dir)) + logger.critical(f"Error: Could not access {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 {}.".format(cert_dir)) + logger.critical(f"Error: No certificate (.pem) found in {cert_dir}.") return pem_filename diff --git a/convert2rhel/backup/files.py b/convert2rhel/backup/files.py index 2ca1e48c82..a09b260f27 100644 --- a/convert2rhel/backup/files.py +++ b/convert2rhel/backup/files.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import hashlib import os @@ -25,13 +23,12 @@ from convert2rhel.backup import BACKUP_DIR, RestorableChange from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) class RestorableFile(RestorableChange): def __init__(self, filepath): - super(RestorableFile, self).__init__() + super().__init__() # The filepath we want to back up needs to start with at least a `/`, # otherwise, let's error out and warn the developer/user that the # filepath is not what we expect. This is mostly intended to be an @@ -53,16 +50,16 @@ def enable(self): if self.enabled: return - logger.info("Backing up {}.".format(self.filepath)) + logger.info(f"Backing up {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 {} to {}.".format(self.filepath, backup_path)) - except (OSError, IOError) as err: + logger.debug(f"Copied {self.filepath} to {backup_path}.") + except OSError as err: # IOError for py2 and OSError for py3 - logger.critical_no_exit("Error({}): {}".format(err.errno, err.strerror)) + logger.critical_no_exit(f"Error({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,16 +69,14 @@ 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 {}. Errno: {}, Error: {}".format( - self.filepath, err.errno, err.strerror - ), + diagnosis=f"Failed to backup {self.filepath}. Errno: {err.errno}, Error: {err.strerror}", ) else: logger.info("Can't find %s.", self.filepath) return # Set the enabled value - super(RestorableFile, self).enable() + super().enable() def _hash_backup_path(self): """Hash the backup path for a given file based on its directory path. @@ -122,12 +117,12 @@ def restore(self, rollback=True): :raises IOError: When the backed up file is missing. """ if rollback: - logger.task("Restore {} from backup".format(self.filepath)) + logger.task(f"Restore {self.filepath} from backup") else: - logger.info("Restoring {} from backup".format(self.filepath)) + logger.info(f"Restoring {self.filepath} from backup") if not self.enabled: - logger.info("{} hasn't been backed up.".format(self.filepath)) + logger.info(f"{self.filepath} hasn't been backed up.") return # Possible exceptions will be handled in the BackupController @@ -137,10 +132,10 @@ def restore(self, rollback=True): os.remove(self.backup_path) if rollback: - logger.info("File {} restored.".format(self.filepath)) - super(RestorableFile, self).restore() + logger.info(f"File {self.filepath} restored.") + super().restore() else: - logger.debug("File {} restored.".format(self.filepath)) + logger.debug(f"File {self.filepath} restored.") # not setting enabled to false since this is not being rollback # restoring the backed up file for conversion purposes @@ -148,9 +143,9 @@ def remove(self): """Remove restored file from original place, backup isn't removed""" try: os.remove(self.filepath) - logger.debug("File {} removed.".format(self.filepath)) - except (OSError, IOError): - logger.debug("Couldn't remove restored file {}".format(self.filepath)) + logger.debug(f"File {self.filepath} removed.") + except OSError: + logger.debug(f"Couldn't remove restored file {self.filepath}") def __eq__(self, value): if hash(self) == hash(value): @@ -158,7 +153,7 @@ def __eq__(self, value): return False def __hash__(self): - return hash(self.filepath) if self.filepath else super(RestorableFile, self).__hash__() + return hash(self.filepath) if self.filepath else super().__hash__() class MissingFile(RestorableChange): @@ -168,7 +163,7 @@ class MissingFile(RestorableChange): """ def __init__(self, filepath): - super(MissingFile, self).__init__() + super().__init__() self.filepath = filepath def enable(self): @@ -176,15 +171,11 @@ def enable(self): return if os.path.isfile(self.filepath): - logger.debug( - "The file {filepath} is present on the system before conversion, skipping it.".format( - filepath=self.filepath - ) - ) + logger.debug(f"The file {self.filepath} is present on the system before conversion, skipping it.") return - logger.info("Marking file {filepath} as missing on system.".format(filepath=self.filepath)) - super(MissingFile, self).enable() + logger.info(f"Marking file {self.filepath} as missing on system.") + super().enable() def restore(self): """Remove the file if it was created during conversion. @@ -198,16 +189,16 @@ def restore(self): if not self.enabled: return - logger.task("Remove file created during conversion {filepath}".format(filepath=self.filepath)) + logger.task(f"Remove file created during conversion {self.filepath}") if not os.path.isfile(self.filepath): - logger.info("File {filepath} wasn't created during conversion".format(filepath=self.filepath)) + logger.info(f"File {self.filepath} wasn't created during conversion") else: # Possible exceptions will be handled in the BackupController os.remove(self.filepath) - logger.info("File {filepath} removed".format(filepath=self.filepath)) + logger.info(f"File {self.filepath} removed") - super(MissingFile, self).restore() + super().restore() class InstalledFile(RestorableChange): @@ -217,15 +208,15 @@ class InstalledFile(RestorableChange): """ def __init__(self, filepath): - super(InstalledFile, self).__init__() + super().__init__() self.filepath = filepath def enable(self): if self.enabled: return - logger.info("Marking file {filepath} as installed on the system.".format(filepath=self.filepath)) - super(InstalledFile, self).enable() + logger.info(f"Marking file {self.filepath} as installed on the system.") + super().enable() def restore(self): """Remove the file if it was installed during the conversion. @@ -239,13 +230,13 @@ def restore(self): if not self.enabled: return - logger.task("Remove {filepath} installed during the conversion".format(filepath=self.filepath)) + logger.task(f"Remove {self.filepath} installed during the conversion") if not os.path.isfile(self.filepath): - logger.info("File {filepath} wasn't installed during conversion.".format(filepath=self.filepath)) + logger.info(f"File {self.filepath} wasn't installed during conversion.") else: # Possible exceptions will be handled in the BackupController os.remove(self.filepath) - logger.info("File {filepath} removed.".format(filepath=self.filepath)) + logger.info(f"File {self.filepath} removed.") - super(InstalledFile, self).restore() + super().restore() diff --git a/convert2rhel/backup/packages.py b/convert2rhel/backup/packages.py index 98d167208c..d2955d7308 100644 --- a/convert2rhel/backup/packages.py +++ b/convert2rhel/backup/packages.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os @@ -28,7 +25,6 @@ from convert2rhel.logger import root_logger from convert2rhel.pkgmanager import call_yum_cmd - logger = root_logger.getChild(__name__) @@ -47,7 +43,7 @@ def __init__(self, pkgs, reposdir=None, set_releasever=False, custom_releasever= :param custom_releasever str: Custom releasever in case it need to be overwritten and it differs from the `py:system_info.releasever`. """ - super(RestorablePackage, self).__init__() + super().__init__() self.pkgs = pkgs self.reposdir = reposdir @@ -81,11 +77,11 @@ def enable(self): return if not os.path.isdir(BACKUP_DIR): - logger.warning("Can't access {}".format(BACKUP_DIR)) + logger.warning(f"Can't access {BACKUP_DIR}") return logger.info("Backing up the packages: {}.".format(",".join(self.pkgs))) - logger.debug("Using repository files stored in {}.".format(self.reposdir)) + logger.debug(f"Using repository files stored in {self.reposdir}.") if self.reposdir: # Check if the reposdir exists and if the directory is empty @@ -110,7 +106,7 @@ def enable(self): # TODO(r0x0d): Maybe we want to set the enabled value only when we # backup something? # Set the enabled value - super(RestorablePackage, self).enable() + super().enable() def restore(self): """Restore system to the original state.""" @@ -129,12 +125,12 @@ 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 {} package.".format(utils.format_sequence_as_message(self.pkgs)), + diagnosis=f"Couldn't find a backup for {utils.format_sequence_as_message(self.pkgs)} package.", ) self._install_local_rpms(replace=True, critical=True) - super(RestorablePackage, self).restore() + super().restore() def _install_local_rpms(self, replace=False, critical=True): """Install packages locally available.""" @@ -156,7 +152,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 {} packages.".format(pkgs_as_str)) + logger.critical_no_exit(f"Error: Couldn't install {pkgs_as_str} packages.") raise exceptions.CriticalError( id_="FAILED_TO_INSTALL_PACKAGES", title="Couldn't install packages.", @@ -170,7 +166,7 @@ def _install_local_rpms(self, replace=False, critical=True): % (pkgs_as_str, cmd, output, ret_code), ) - logger.warning("Couldn't install {} packages.".format(pkgs_as_str)) + logger.warning(f"Couldn't install {pkgs_as_str} packages.") return False return True @@ -228,7 +224,7 @@ def __init__( self.set_releasever = set_releasever self.custom_releasever = custom_releasever - super(RestorablePackageSet, self).__init__() + super().__init__() def enable(self): if self.enabled: @@ -236,7 +232,7 @@ def enable(self): self._enable() - super(RestorablePackageSet, self).enable() + super().enable() def _enable(self): """ @@ -249,7 +245,7 @@ def _enable(self): formatted_pkgs_sequence = utils.format_sequence_as_message(self.pkgs_to_install) - logger.debug("RPMs scheduled for installation: {}".format(formatted_pkgs_sequence)) + logger.debug(f"RPMs scheduled for installation: {formatted_pkgs_sequence}") output, ret_code = call_yum_cmd( command="install", @@ -267,35 +263,33 @@ def _enable(self): if ret_code: logger.critical_no_exit( - "Failed to install scheduled packages. Check the yum output below for details:\n\n {}".format(output) + f"Failed to install scheduled packages. Check the yum output below for details:\n\n {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 {}. Output: {}, Status: {}".format( - formatted_pkgs_sequence, output, ret_code - ), + diagnosis=f"Failed to install packages {formatted_pkgs_sequence}. Output: {output}, Status: {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{}".format(formatted_pkgs_sequence)) + logger.info(f"\nPackages we installed or updated:\n{formatted_pkgs_sequence}") # We could rely on these always being installed/updated when # self.enabled is True but putting the values into separate attributes # is more friendly if outside code needs to inspect the values. self.installed_pkgs = self.pkgs_to_install[:] - super(RestorablePackageSet, self).enable() + super().enable() def restore(self): if not self.enabled: return logger.task("Remove installed packages") - logger.info("Removing set of installed pkgs: {}".format(utils.format_sequence_as_message(self.installed_pkgs))) + logger.info(f"Removing set of installed pkgs: {utils.format_sequence_as_message(self.installed_pkgs)}") utils.remove_pkgs(self.installed_pkgs, critical=False) - super(RestorablePackageSet, self).restore() + super().restore() diff --git a/convert2rhel/backup/subscription.py b/convert2rhel/backup/subscription.py index ed61e28971..9affd6cbbc 100644 --- a/convert2rhel/backup/subscription.py +++ b/convert2rhel/backup/subscription.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import re @@ -24,7 +21,6 @@ from convert2rhel.backup import RestorableChange from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) @@ -35,7 +31,7 @@ class RestorableSystemSubscription(RestorableChange): # We need this __init__ because it is an abstractmethod in the base class def __init__(self): - super(RestorableSystemSubscription, self).__init__() + super().__init__() def enable(self): """Register and attach a specific subscription to OS.""" @@ -45,7 +41,7 @@ def enable(self): subscription.register_system() subscription.attach_subscription() - super(RestorableSystemSubscription, self).enable() + super().enable() def restore(self): """Rollback subscription related changes""" @@ -61,7 +57,7 @@ def restore(self): except OSError: logger.warning("subscription-manager not installed, skipping") - super(RestorableSystemSubscription, self).restore() + super().restore() class RestorableAutoAttachmentSubscription(RestorableChange): @@ -70,7 +66,7 @@ class RestorableAutoAttachmentSubscription(RestorableChange): """ def __init__(self): - super(RestorableAutoAttachmentSubscription, self).__init__() + super().__init__() self._is_attached = False def enable(self): @@ -78,13 +74,13 @@ def enable(self): return self._is_attached = subscription.auto_attach_subscription() - super(RestorableAutoAttachmentSubscription, self).enable() + super().enable() def restore(self): if self._is_attached: logger.task("Removing auto-attached subscription") subscription.remove_subscription() - super(RestorableAutoAttachmentSubscription, self).restore() + super().restore() class RestorableDisableRepositories(RestorableChange): @@ -99,7 +95,7 @@ class RestorableDisableRepositories(RestorableChange): ENABLED_REPOS_PATTERN = re.compile(r"Repo ID:\s+(?P\S+)") def __init__(self): - super(RestorableDisableRepositories, self).__init__() + super().__init__() self._repos_to_enable = [] def _get_enabled_repositories(self): @@ -129,7 +125,7 @@ def enable(self): ) subscription.disable_repos() - super(RestorableDisableRepositories, self).enable() + super().enable() def restore(self): if not self.enabled: @@ -146,4 +142,4 @@ def restore(self): subscription.disable_repos() subscription.submgr_enable_repos(self._repos_to_enable) - super(RestorableDisableRepositories, self).restore() + super().restore() diff --git a/convert2rhel/breadcrumbs.py b/convert2rhel/breadcrumbs.py index a2ee5aa43f..738a510e73 100644 --- a/convert2rhel/breadcrumbs.py +++ b/convert2rhel/breadcrumbs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2021 Red Hat, Inc. # @@ -15,22 +14,19 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import json import os import re import sys - from datetime import datetime from convert2rhel import pkghandler, utils from convert2rhel.logger import root_logger -from convert2rhel.systeminfo import system_info, SystemInfo +from convert2rhel.systeminfo import SystemInfo, system_info from convert2rhel.toolopts import tool_opts from convert2rhel.utils import files - # Path to the migration results of the old breadcrumbs. MIGRATION_RESULTS_FILE = "/etc/migration-results" @@ -205,7 +201,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 '{}'. Creating a new one...".format(RHSM_CUSTOM_FACTS_FOLDER)) + logger.debug(f"No RHSM facts folder found at '{RHSM_CUSTOM_FACTS_FOLDER}'. Creating a new one...") # 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 diff --git a/convert2rhel/checks.py b/convert2rhel/checks.py index e76af0fc15..393249e520 100644 --- a/convert2rhel/checks.py +++ b/convert2rhel/checks.py @@ -13,15 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os from convert2rhel.logger import root_logger from convert2rhel.utils import run_subprocess - logger = root_logger.getChild(__name__) diff --git a/convert2rhel/cli.py b/convert2rhel/cli.py index 3ae5251b86..cc73a90960 100644 --- a/convert2rhel/cli.py +++ b/convert2rhel/cli.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import argparse import logging @@ -26,7 +23,6 @@ from convert2rhel.toolopts import tool_opts from convert2rhel.toolopts.config import CliConfig, FileConfig - loggerinst = logging.getLogger(__name__) ARGS_WITH_VALUES = [ @@ -69,12 +65,12 @@ def usage(subcommand_to_print=""): usage = ( "\n" " convert2rhel [--version] [-h]\n" - " convert2rhel {subcommand} [-u username] [-p password | -c conf_file_path] [--pool pool_id | -a] [--disablerepo repoid]" + f" convert2rhel {subcommand_to_print} [-u username] [-p password | -c conf_file_path] [--pool pool_id | -a] [--disablerepo repoid]" " [--enablerepo repoid] [--serverurl url] [--no-rpm-va] [--eus] [--els] [--debug] [--restart] [-y]\n" - " convert2rhel {subcommand} [--no-rhsm] [--disablerepo repoid] [--enablerepo repoid] [--no-rpm-va] [--eus] [--els] [--debug] [--restart] [-y]\n" - " convert2rhel {subcommand} [-k activation_key | -c conf_file_path] [-o organization] [--pool pool_id | -a] [--disablerepo repoid] [--enablerepo" + f" convert2rhel {subcommand_to_print} [--no-rhsm] [--disablerepo repoid] [--enablerepo repoid] [--no-rpm-va] [--eus] [--els] [--debug] [--restart] [-y]\n" + f" convert2rhel {subcommand_to_print} [-k activation_key | -c conf_file_path] [-o organization] [--pool pool_id | -a] [--disablerepo repoid] [--enablerepo" " repoid] [--serverurl url] [--no-rpm-va] [--eus] [--els] [--debug] [--restart] [-y]\n" - ).format(subcommand=subcommand_to_print) + ) if subcommand_not_used_on_cli: usage = usage + "\n Subcommands: analyze, convert" @@ -130,11 +126,11 @@ 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 {} and {}. At the end of the conversion, these logs are compared" + f" stored in log files {utils.rpm.PRE_RPM_VA_LOG_FILENAME} and {utils.rpm.POST_RPM_VA_LOG_FILENAME}. 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 incomplete_rollback option needs to be set to true in the /etc/convert2rhel.ini config file to" - " use this argument.".format(utils.rpm.PRE_RPM_VA_LOG_FILENAME, utils.rpm.POST_RPM_VA_LOG_FILENAME), + " use this argument.", ) self._shared_options_parser.add_argument( "--eus", @@ -145,8 +141,7 @@ def _register_options(self): self._shared_options_parser.add_argument( "--els", action="store_true", - help="Explicitly recognize the system as els, utilizing els repos." - " This option is meant for el7 systems.", + help="Explicitly recognize the system as els, utilizing els repos. This option is meant for el7 systems.", ) self._shared_options_parser.add_argument( "--enablerepo", @@ -296,7 +291,7 @@ def _log_command_used(): and the logfile """ command = " ".join(utils.hide_secrets(sys.argv)) - loggerinst.info("convert2rhel command used:\n{0}".format(command)) + loggerinst.info(f"convert2rhel command used:\n{command}") def _add_default_command(argv): diff --git a/convert2rhel/exceptions.py b/convert2rhel/exceptions.py index 426d224f57..3568f84b57 100644 --- a/convert2rhel/exceptions.py +++ b/convert2rhel/exceptions.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -14,7 +13,6 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type """ This module can be used for exceptions that are used across files. It is not necessary to use it for every exception but it is especially useful to break circular imports. @@ -50,12 +48,4 @@ def __init__(self, id_=None, title=None, description=None, diagnosis=None, remed self.variables = variables or {} def __repr__(self): - return "{}({!r}, {!r}, description={!r}, diagnosis={!r}, remediations={!r}, variables={!r})".format( - self.__class__.__name__, - self.id, - self.title, - self.description, - self.diagnosis, - self.remediations, - self.variables, - ) + return f"{self.__class__.__name__}({self.id!r}, {self.title!r}, description={self.description!r}, diagnosis={self.diagnosis!r}, remediations={self.remediations!r}, variables={self.variables!r})" diff --git a/convert2rhel/grub.py b/convert2rhel/grub.py index ce8f59bbc0..f3e85eda35 100644 --- a/convert2rhel/grub.py +++ b/convert2rhel/grub.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2021 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os import re @@ -24,7 +21,6 @@ from convert2rhel import systeminfo, utils from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) GRUB2_BIOS_ENTRYPOINT = "/boot/grub2" @@ -59,7 +55,7 @@ class BootloaderError(Exception): """The generic error related to this module.""" def __init__(self, message): - super(BootloaderError, self).__init__(message) + super().__init__(message) self.message = message @@ -105,8 +101,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 {}. Output:\n{}".format(ecode, stdout)) - raise BootloaderError("Unable to get device information for {}.".format(directory)) + logger.error(f"grub2-probe returned {ecode}. Output:\n{stdout}") + raise BootloaderError(f"Unable to get device information for {directory}.") return stdout.strip() @@ -146,8 +142,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{}\n-----".format(output)) - raise BootloaderError("Unable to get a block device for '{}'.".format(device)) + logger.debug(f"lsblk output:\n-----\n{output}\n-----") + raise BootloaderError(f"Unable to get a block device for '{device}'.") return output.strip().splitlines()[-1].strip() @@ -168,12 +164,12 @@ def get_device_number(device): ) output = output.strip() if ecode: - logger.debug("blkid output:\n-----\n{}\n-----".format(output)) - raise BootloaderError("Unable to get information about the '{}' device".format(device)) + logger.debug(f"blkid output:\n-----\n{output}\n-----") + raise BootloaderError(f"Unable to get information about the '{device}' 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 '{}' device has no PART_ENTRY_NUMBER".format(device)) + raise BootloaderError(f"The '{device}' device has no PART_ENTRY_NUMBER") partition_number = output.split("PART_ENTRY_NUMBER=")[-1].replace('"', "") return int(partition_number) @@ -314,10 +310,10 @@ def _parse_boot_order(self, bootmgr_output): def _print_loaded_info(self): msg = "Bootloader setup:" - msg += "\nCurrent boot: {}".format(self.current_bootnum) + msg += f"\nCurrent boot: {self.current_bootnum}" msg += "\nBoot order: {}\nBoot entries:".format(", ".join(self.boot_order)) for bootnum, entry in self.entries.items(): - msg += "\n- {}: {}".format(bootnum, entry.label.rstrip()) + msg += f"\n- {bootnum}: {entry.label.rstrip()}" logger.debug(msg) @@ -357,24 +353,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: {}".format(str(blk_dev))) - logger.debug("ESP device number: {}".format(str(dev_number))) + logger.debug(f"Block device: {blk_dev!s}") + logger.debug(f"ESP device number: {dev_number!s}") 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: {}".format(tmp_efi_path)) + logger.debug(f"The new UEFI binary: {tmp_efi_path}") break if not efi_path: raise BootloaderError("Unable to detect any RHEL UEFI binary file.") - label = "Red Hat Enterprise Linux {}".format(str(systeminfo.system_info.version.major)) - logger.info("Adding '{}' UEFI bootloader entry.".format(label)) + label = f"Red Hat Enterprise Linux {systeminfo.system_info.version.major!s}" + logger.info(f"Adding '{label}' UEFI bootloader entry.") if _is_rhel_in_boot_entries(efibootinfo_orig, efi_path, label): - logger.info("The '{}' UEFI bootloader entry is already present.".format(label)) + logger.info(f"The '{label}' UEFI bootloader entry is already present.") return efibootinfo_orig # The new boot entry is being set as first in the boot order @@ -393,7 +389,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{}\n-----".format(stdout)) + logger.debug(f"efibootmgr output:\n-----\n{stdout}\n-----") raise BootloaderError("Unable to add a new UEFI bootloader entry for RHEL.") # check that our new entry exists @@ -402,7 +398,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 '{}' bootloader entry has been added.".format(label)) + logger.info(f"The '{label}' bootloader entry has been added.") return efibootinfo_new @@ -423,25 +419,21 @@ 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 '{}' ({}) has been removed already.".format( - efibootinfo_orig.current_bootnum, efibootinfo_orig.entries[efibootinfo_orig.current_bootnum].label - ) + f"The original, currenly used bootloader entry '{efibootinfo_orig.current_bootnum}' ({efibootinfo_orig.entries[efibootinfo_orig.current_bootnum].label}) has been removed already." ) return if orig_boot_entry != efibootinfo_orig.entries[orig_boot_entry.boot_number]: logger.warning( - "The original, currenly used bootloader entry '{}' ({}) has been modified. Skipping the removal.".format( - orig_boot_entry.boot_number, orig_boot_entry.label - ) + f"The original, currenly used bootloader entry '{orig_boot_entry.boot_number}' ({orig_boot_entry.label}) has been modified. Skipping the removal." ) 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 '{}' ({}):" - " Unable to get path of its UEFI binary file.".format(orig_boot_entry.boot_number, orig_boot_entry.label) + f"Skipping the removal of the original, currenly used bootloader entry '{orig_boot_entry.boot_number}' ({orig_boot_entry.label}):" + " Unable to get path of its UEFI binary file." ) return @@ -449,10 +441,8 @@ 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 '{}' ({}):" - " Its UEFI binary file still exists: {}".format( - orig_boot_entry.boot_number, orig_boot_entry.label, efibin_path_orig - ) + f"Skipping the removal of the original, currenly used bootloader entry '{orig_boot_entry.boot_number}' ({orig_boot_entry.label}):" + f" Its UEFI binary file still exists: {efibin_path_orig}" ) return _, ecode = utils.run_subprocess(["/usr/sbin/efibootmgr", "-Bb", orig_boot_entry.boot_number], print_output=False) @@ -462,9 +452,7 @@ 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 '{}' ({}) has been successful.".format( - orig_boot_entry.boot_number, orig_boot_entry.label - ) + f"The removal of the original, currenly used UEFI bootloader entry '{orig_boot_entry.boot_number}' ({orig_boot_entry.label}) has been successful." ) @@ -512,12 +500,12 @@ def get_grub_config_file(): def _log_critical_error(title): logger.critical( - "{}\n" + f"{title}\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 {} directory and that\n" + f"are present in the {RHEL_EFIDIR_CANONICAL_PATH} 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'.".format(title, RHEL_EFIDIR_CANONICAL_PATH) + "The entry should point to '\\EFI\\redhat\\shimx64.efi'." ) diff --git a/convert2rhel/i18n.py b/convert2rhel/i18n.py index ca7a2a3a96..46d83318fe 100644 --- a/convert2rhel/i18n.py +++ b/convert2rhel/i18n.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2021 Red Hat, Inc. # @@ -22,7 +21,6 @@ the future, this file should point us towards all the locations that we may need to change. """ -__metaclass__ = type # # Display locales diff --git a/convert2rhel/initialize.py b/convert2rhel/initialize.py index 806b80677d..2fdb4fbf51 100644 --- a/convert2rhel/initialize.py +++ b/convert2rhel/initialize.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging import os @@ -23,7 +21,6 @@ from convert2rhel import i18n from convert2rhel import logger as logger_module - loggerinst = logger_module.root_logger.getChild(__name__) diff --git a/convert2rhel/logger.py b/convert2rhel/logger.py index b9182f928b..8f5020f807 100644 --- a/convert2rhel/logger.py +++ b/convert2rhel/logger.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,13 +14,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging import os import shutil import sys - from logging.handlers import BufferingHandler from time import gmtime, strftime @@ -70,7 +67,7 @@ def __init__(self, capacity, handler_name="file_handler"): :param int capacity: Buffer size for the handler :param str handler_name: Handler to flush buffer to, defaults to "file_handler" """ - super(LogfileBufferHandler, self).__init__(capacity) + super().__init__(capacity) # the FileLogger handler that we are logging to self._handler_name = handler_name self.set_name("logfile_buffer_handler") @@ -101,7 +98,7 @@ def shouldFlush(self, record): :param logging.LogRecord record: The record to log :return bool: Always returns false """ - if super(LogfileBufferHandler, self).shouldFlush(record): + if super().shouldFlush(record): self.buffer = self.buffer[1:] return False @@ -213,7 +210,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 = "{}/{}-{}.{}".format(archive_log_dir, file_name, formatted_time, suffix) + archive_log_file = f"{archive_log_dir}/{file_name}-{formatted_time}.{suffix}" shutil.move(current_log_file, archive_log_file) @@ -282,12 +279,10 @@ def format(self, record): if is_task: log_phase_name = "" if ConversionPhases.current_phase and ConversionPhases.current_phase.log_name: - log_phase_name = "{}: ".format(ConversionPhases.current_phase.log_name) + log_phase_name = f"{ConversionPhases.current_phase.log_name}: " asterisks = "*" * (90 - len(log_phase_name) - len(record.msg) - 25) - fmt_orig = "\n[%(asctime)s] TASK - [{log_phase_name}%(message)s] {asterisks}".format( - log_phase_name=log_phase_name, asterisks=asterisks - ) + fmt_orig = f"\n[%(asctime)s] TASK - [{log_phase_name}%(message)s] {asterisks}" self.datefmt = "%Y-%m-%dT%H:%M:%S%z" elif record.levelno >= logging.WARNING: @@ -307,7 +302,7 @@ def format(self, record): # Overwriting the style _fmt gets the result we want self._style._fmt = self._fmt - return super(CustomFormatter, self).format(record) + return super().format(record) def _getLogLevelColor(self, record, is_task=False): if is_task: @@ -336,7 +331,7 @@ class CustomLogger(logging.Logger): """ def __init__(self, name, level=0): - super(CustomLogger, self).__init__(name, level) + super().__init__(name, level) def critical_no_exit(self, message, *args, **kwargs): return self.critical(message, extra={"no_exit": True}, *args, **kwargs) diff --git a/convert2rhel/main.py b/convert2rhel/main.py index 704149be1f..9783f7dc91 100644 --- a/convert2rhel/main.py +++ b/convert2rhel/main.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,14 +14,23 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os -from convert2rhel import actions, applock, backup, breadcrumbs, cli, exceptions +from convert2rhel import ( + actions, + applock, + backup, + breadcrumbs, + cli, + exceptions, + pkghandler, + pkgmanager, + subscription, + systeminfo, + utils, +) from convert2rhel import logger as logger_module -from convert2rhel import pkghandler, pkgmanager, subscription, systeminfo, utils from convert2rhel.actions import level_for_raw_action_data, report from convert2rhel.phase import ConversionPhase, ConversionPhases # noqa: F401 ignoring due to type comments from convert2rhel.toolopts import tool_opts @@ -87,8 +95,8 @@ 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: {}".format(e)) + except OSError as e: + loggerinst.warning(f"Unable to archive previous log: {e}") logger_module.add_file_handler(log_name, log_dir) @@ -248,10 +256,10 @@ def _raise_for_skipped_failures(results): if failures: # The report will be handled in the error handler, after rollback. message = ( - "The {method} process failed.\n\n" - "A problem was encountered during {method} and a rollback will be " + f"The {tool_opts.activity} process failed.\n\n" + f"A problem was encountered during {tool_opts.activity} and a rollback will be " "initiated to restore the system as the previous state." - ).format(method=tool_opts.activity) + ) raise _InhibitorsFound(message) @@ -364,7 +372,6 @@ def show_eula(): loggerinst.info(eula_text) else: loggerinst.critical("EULA file not found.") - return # @@ -409,8 +416,6 @@ def rollback_changes(): else: raise - return - def provide_status_after_rollback(pre_conversion_results, include_all_reports): """Print after-rollback messages and determine if there is a report to print or diff --git a/convert2rhel/phase.py b/convert2rhel/phase.py index 31df918006..42a5ad8a58 100644 --- a/convert2rhel/phase.py +++ b/convert2rhel/phase.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -58,7 +57,7 @@ class ConversionPhases: @classmethod def get(cls, key): # type: (str) -> ConversionPhase - return next((phase for phase in cls.__dict__ if isinstance(phase, ConversionPhase) and phase.name == key)) + return next(phase for phase in cls.__dict__ if isinstance(phase, ConversionPhase) and phase.name == key) @classmethod def has(cls, key): # type: (str) -> bool @@ -78,7 +77,7 @@ def set_current(cls, phase): # type: (str|ConversionPhase|None) -> None elif isinstance(phase, ConversionPhase) and phase.name in cls.__dict__: cls.current_phase = phase else: - raise NotImplementedError("The {} phase is not implemented in the {} class".format(phase, cls.__name__)) + raise NotImplementedError(f"The {phase} phase is not implemented in the {cls.__name__} class") if cls.current_phase: cls.current_phase.last_stage = previous_phase @@ -91,4 +90,6 @@ def is_current(cls, phase): # type: (str|ConversionPhase|list[str|ConversionPha return cls.current_phase == phase elif isinstance(phase, list): return any(cls.is_current(phase_single) for phase_single in phase) - raise TypeError("Unexpected type, wanted str, {0}, or a list of str or {0}".format(ConversionPhase.__name__)) + raise TypeError( + f"Unexpected type, wanted str, {ConversionPhase.__name__}, or a list of str or {ConversionPhase.__name__}" + ) diff --git a/convert2rhel/pkghandler.py b/convert2rhel/pkghandler.py index 1775ea647e..caa418567d 100644 --- a/convert2rhel/pkghandler.py +++ b/convert2rhel/pkghandler.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,13 +14,10 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os import os.path import re - from collections import namedtuple import rpm @@ -33,7 +29,6 @@ from convert2rhel.systeminfo import system_info from convert2rhel.toolopts import tool_opts - logger = root_logger.getChild(__name__) # Limit the number of loops over yum command calls for the case there was @@ -114,7 +109,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 ["{}.{}".format(pkg.nevra.name, pkg.nevra.arch) for pkg in pkgs_w_key_ids if pkg.key_id in key_ids] + return [f"{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 +191,7 @@ def get_rpm_header(pkg_obj): return rpm_hdr # Package not found in the rpm db - logger.critical("Unable to find package '{}' in the rpm database.".format(pkg_obj.name)) + logger.critical(f"Unable to find package '{pkg_obj.name}' in the rpm database.") def get_installed_pkg_objects(name=None, version=None, release=None, arch=None): @@ -217,13 +212,13 @@ def _get_installed_pkg_objects_yum(name=None, version=None, release=None, arch=N if name: pattern = name if version: - pattern += "-{}".format(version) + pattern += f"-{version}" if release: - pattern += "-{}".format(release) + pattern += f"-{release}" if arch: - pattern += ".{}".format(arch) + pattern += f".{arch}" return yum_base.rpmdb.returnPackages(patterns=[pattern]) @@ -297,7 +292,7 @@ def get_files_owned_by_package(installed_pkg_name): """Get a list of files that are owned by an installed package.""" output, ret_code = utils.run_subprocess(["/usr/bin/rpm", "-ql", installed_pkg_name]) if ret_code != 0: - logger.warning("Failed to list files for package {0}: {1}".format(installed_pkg_name, output)) + logger.warning(f"Failed to list files for package {installed_pkg_name}: {output}") return [] return output.decode("utf-8").splitlines() if isinstance(output, bytes) else output.splitlines() @@ -481,12 +476,7 @@ def get_pkg_nvra(pkg_obj): :rtype: str """ nevra = _get_nevra_from_pkg_obj(pkg_obj) - return "{}-{}-{}.{}".format( - nevra.name, - nevra.version, - nevra.release, - nevra.arch, - ) + return f"{nevra.name}-{nevra.version}-{nevra.release}.{nevra.arch}" def get_pkg_nevra(pkg_obj, include_zero_epoch=False): @@ -509,21 +499,9 @@ 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 "{}{}-{}-{}.{}".format( - epoch, - nevra.name, - nevra.version, - nevra.release, - nevra.arch, - ) + return f"{epoch}{nevra.name}-{nevra.version}-{nevra.release}.{nevra.arch}" - return "{}-{}{}-{}.{}".format( - nevra.name, - epoch, - nevra.version, - nevra.release, - nevra.arch, - ) + return f"{nevra.name}-{epoch}{nevra.version}-{nevra.release}.{nevra.arch}" def get_packager(pkg_obj): @@ -575,7 +553,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("{} {} {}".format(pkg, temp, str(len(pkg_objects)))) + logger.info(f"{pkg} {temp} {len(pkg_objects)!s}") return pkgs_to_remove @@ -592,7 +570,7 @@ def get_system_packages_for_replacement(): key_ids = system_info.key_ids_orig_os packages_with_key_ids = get_installed_pkg_information() - return ["{}.{}".format(pkg.nevra.name, pkg.nevra.arch) for pkg in packages_with_key_ids if pkg.key_id in key_ids] + return [f"{pkg.nevra.name}.{pkg.nevra.arch}" for pkg in packages_with_key_ids if pkg.key_id in key_ids] def install_gpg_keys(): @@ -604,7 +582,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 {}".format(str(e))) + logger.critical(f"Importing the GPG key into rpm failed:\n {e!s}") logger.info("GPG key %s imported successfuly.", gpg_key) @@ -623,15 +601,15 @@ def handle_no_newer_rhel_kernel_available(): # of them - the one that has the same version as the available RHEL # kernel older = all_available[-1] - utils.remove_pkgs(pkgs_to_remove=["kernel-{}".format(older)]) - pkgmanager.call_yum_cmd(command="install", args=["kernel-{}".format(older)]) + utils.remove_pkgs(pkgs_to_remove=[f"kernel-{older}"]) + pkgmanager.call_yum_cmd(command="install", args=[f"kernel-{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-{}".format(available_to_install[-1])]) + pkgmanager.call_yum_cmd(command="install", args=[f"kernel-{available_to_install[-1]}"]) def get_kernel_availability(): @@ -664,7 +642,7 @@ def replace_non_rhel_installed_kernel(version): ) utils.ask_to_continue() - pkg = "kernel-{}".format(version) + pkg = f"kernel-{version}" # For downloading the RHEL kernel we need to use the RHEL repositories. repos_to_enable = system_info.get_enabled_rhel_repos() @@ -677,7 +655,7 @@ def replace_non_rhel_installed_kernel(version): if not path: logger.critical("Unable to download the RHEL kernel package.") - logger.info("Replacing {} {} with RHEL kernel with the same NEVRA ... ".format(system_info.name, pkg)) + logger.info(f"Replacing {system_info.name} {pkg} with RHEL kernel with the same NEVRA ... ") 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. @@ -687,14 +665,14 @@ def replace_non_rhel_installed_kernel(version): "--force", "--nodeps", "--replacepkgs", - "{}*".format(os.path.join(utils.TMP_DIR, pkg)), + f"{os.path.join(utils.TMP_DIR, pkg)}*", ], print_output=False, ) if ret_code != 0: - logger.critical("Unable to replace the kernel package: {}".format(output)) + logger.critical(f"Unable to replace the kernel package: {output}") - logger.info("\nRHEL {} installed.\n".format(pkg)) + logger.info(f"\nRHEL {pkg} installed.\n") def update_rhel_kernel(): @@ -867,17 +845,13 @@ 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 ('{}' and '{}') do not match. Can only compare versions for the same packages.".format( - version1_components[0], version2_components[0] - ) + f"The package names ('{version1_components[0]}' and '{version2_components[0]}') do not match. Can only compare versions for the same packages." ) # 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 ('{}' 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] - ) + f"The arches ('{version1_components[4]}' and '{version2_components[4]}') 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." ) # create list containing EVR for comparison @@ -932,15 +906,15 @@ 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 : {}".format(name) if name else "name : [None]") + errors.append(f"name : {name}" if name else "name : [None]") if epoch is not None and not PKG_EPOCH.match(epoch): - errors.append("epoch : {}".format(epoch)) + errors.append(f"epoch : {epoch}") if version is None or not PKG_VERSION.match(version): - errors.append("version : {}".format(version) if version else "version : [None]") + errors.append(f"version : {version}" if version else "version : [None]") if release is None or not PKG_RELEASE.match(release): - errors.append("release : {}".format(release) if release else "release : [None]") + errors.append(f"release : {release}" if release else "release : [None]") if arch is not None and arch not in PKG_ARCH: - errors.append("arch : {}".format(arch)) + errors.append(f"arch : {arch}") if errors: raise ValueError("The following field(s) are invalid - {}".format(", ".join(errors))) @@ -961,8 +935,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 - {}, 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) + f"Invalid package - {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," ) @@ -996,7 +970,7 @@ def _parse_pkg_with_yum(pkg): if arch not in PKG_ARCH: temp_release = arch arch = None - release = "{}.{}".format(release, temp_release) + release = f"{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)) @@ -1050,8 +1024,8 @@ def _parse_pkg_with_dnf(pkg): # therefore the package entered is invalid and/or in the wrong format if no_arch_data is None: raise ValueError( - "Invalid package - {}, packages need to be in one of the following" - " formats: NEVRA, NEVR, NVRA, NVR, ENVRA, ENVR.".format(pkg) + f"Invalid package - {pkg}, packages need to be in one of the following" + " formats: NEVRA, NEVR, NVRA, NVR, ENVRA, ENVR." ) name = no_arch_data.name @@ -1081,7 +1055,7 @@ def get_highest_package_version(pkgs): name, nevra_list = pkgs if not nevra_list: - logger.debug("The list of {} packages is empty.".format(name)) + logger.debug(f"The list of {name} packages is empty.") raise ValueError highest_version = nevra_list[0] diff --git a/convert2rhel/pkgmanager/__init__.py b/convert2rhel/pkgmanager/__init__.py index 76f1eaf1db..20e32ead57 100644 --- a/convert2rhel/pkgmanager/__init__.py +++ b/convert2rhel/pkgmanager/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from contextlib import contextmanager @@ -25,13 +22,12 @@ from convert2rhel.systeminfo import system_info from convert2rhel.toolopts import tool_opts - logger = root_logger.getChild(__name__) try: # this is used in pkghandler.py to parse version strings in the _parse_pkg_with_yum function from rpmUtils.miscutils import splitFilename # type: ignore # noqa: F401 - from yum import * # type: ignore # noqa: F403 + from yum import * # type: ignore from yum.callbacks import DownloadBaseCallback as DownloadProgress # type: ignore # This is added here to prevent a generic try-except in the @@ -44,8 +40,7 @@ # WARNING: if there is a bug in the yum import section, we might try to import dnf incorrectly except ImportError: import hawkey # noqa: F401 - - from dnf import * # noqa: F403 + from dnf import * from dnf.callback import Depsolve, DownloadProgress # noqa: F401 # This is added here to prevent a generic try-except in the @@ -98,10 +93,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{}".format(output)) + logger.debug(f"Output of yum clean metadata:\n{output}") if ret_code != 0: - logger.warning("Failed to clean yum metadata:\n{}".format(output)) + logger.warning(f"Failed to clean yum metadata:\n{output}") return logger.info("Cached repositories metadata cleaned successfully.") @@ -221,16 +216,16 @@ def call_yum_cmd( repos_to_disable = tool_opts.disablerepo for repo in repos_to_disable: - cmd.append("--disablerepo={}".format(repo)) + cmd.append(f"--disablerepo={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={}".format(custom_releasever)) + cmd.append(f"--releasever={custom_releasever}") else: - cmd.append("--releasever={}".format(system_info.releasever)) + cmd.append(f"--releasever={system_info.releasever}") # Without the release package installed, dnf can't determine the modularity platform ID. if system_info.version.major >= 8: @@ -243,13 +238,13 @@ def call_yum_cmd( # When using subscription-manager for the conversion, use those repos for the yum call that have been enabled # through subscription-manager repos_to_enable = system_info.get_enabled_rhel_repos() - logger.debug("Custom epos in yum cmd: {repos_to_enable}".format(repos_to_enable=repos_to_enable)) + logger.debug(f"Custom epos in yum cmd: {repos_to_enable}") for repo in repos_to_enable: - cmd.append("--enablerepo={}".format(repo)) + cmd.append(f"--enablerepo={repo}") if setopts: - opts = ["--setopt={}".format(opt) for opt in setopts] + opts = [f"--setopt={opt}" for opt in setopts] cmd.extend(opts) cmd.extend(args) diff --git a/convert2rhel/pkgmanager/handlers/__init__.py b/convert2rhel/pkgmanager/handlers/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/pkgmanager/handlers/__init__.py +++ b/convert2rhel/pkgmanager/handlers/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/pkgmanager/handlers/base.py b/convert2rhel/pkgmanager/handlers/base.py index 7a987da57e..85fe00e745 100644 --- a/convert2rhel/pkgmanager/handlers/base.py +++ b/convert2rhel/pkgmanager/handlers/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import abc @@ -49,4 +47,3 @@ def run_transaction(self, validate_transaction=False): :param validate_transaction: Determines if the transaction needs to be tested or not. :type validate_transaction: bool """ - pass diff --git a/convert2rhel/pkgmanager/handlers/dnf/__init__.py b/convert2rhel/pkgmanager/handlers/dnf/__init__.py index 1651f3aa3a..b6cd451130 100644 --- a/convert2rhel/pkgmanager/handlers/dnf/__init__.py +++ b/convert2rhel/pkgmanager/handlers/dnf/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - from convert2rhel import exceptions, pkgmanager from convert2rhel.logger import root_logger @@ -29,7 +26,6 @@ ) from convert2rhel.systeminfo import system_info - logger = root_logger.getChild(__name__) """Instance of the logger used in this module.""" @@ -107,13 +103,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: {}".format(e)) + logger.debug(f"Loading repository metadata failed: {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 {}.".format(str(e)), + diagnosis=f"Loading repository metadata failed with error {e!s}.", ) def _swap_base_os_specific_packages(self): @@ -127,10 +123,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 {} installed for later swap.".format(old_package)) + logger.debug(f"Checking if {old_package} installed for later swap.") is_installed = system_info.is_rpm_installed(old_package) if is_installed: - logger.debug("Package {} will be swapped to {} during conversion.".format(old_package, new_package)) + logger.debug(f"Package {old_package} will be swapped to {new_package} during conversion.") # 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 +183,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: {}".format(e)) + logger.debug(f"Got the following exception message: {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 {}.".format(str(e)), + diagnosis=f"Resolve dependencies failed with error {e!s}.", ) 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: {}".format(e)) + logger.debug(f"Got the following exception message: {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 {}.".format(str(e)), + diagnosis=f"Package download failed with error {e!s}.", ) def _process_transaction(self, validate_transaction): @@ -222,7 +218,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 {} packages. This process may take some time to finish.".format(system_info.name)) + logger.info(f"Replacing {system_info.name} packages. This process may take some time to finish.") try: self._base.do_transaction(display=TransactionDisplayCallback()) @@ -236,7 +232,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: {}".format(str(e)), + diagnosis=f"Transaction processing failed with error: {e!s}", ) if validate_transaction: diff --git a/convert2rhel/pkgmanager/handlers/dnf/callback.py b/convert2rhel/pkgmanager/handlers/dnf/callback.py index 0155a409d1..c6adb084fa 100644 --- a/convert2rhel/pkgmanager/handlers/dnf/callback.py +++ b/convert2rhel/pkgmanager/handlers/dnf/callback.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -58,13 +57,11 @@ # License above taken from the original code at: # # https://github.com/rpm-software-management/dnf/blob/4.7.0/dnf/cli/output.py -__metaclass__ = type from convert2rhel import pkgmanager from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) """Instance of the logger used in this module.""" @@ -101,7 +98,7 @@ def pkg_added(self, pkg, mode): message = self._DEPSOLVE_MODES[mode] except KeyError: message = None - logger.debug("Unknown operation ({}) for package '{}'.".format(mode, pkg)) + logger.debug(f"Unknown operation ({mode}) for package '{pkg}'.") if message: logger.info(message, pkg) @@ -204,7 +201,7 @@ def end(self, payload, status, err_msg): self.total_drpm, package, ) - message = "{} - {}".format(message, err_msg) + message = f"{message} - {err_msg}" else: message = "(%d/%d) [%s]: %s" % ( self.done_files, @@ -225,7 +222,7 @@ class TransactionDisplayCallback(pkgmanager.TransactionDisplay): def __init__(self): """Constructor for the transaction display progress in DNF.""" - super(TransactionDisplayCallback, self).__init__() + super().__init__() self.last_package_seen = None def progress(self, package, action, ti_done, ti_total, ts_done, ts_total): @@ -259,7 +256,7 @@ def progress(self, package, action, ti_done, ti_total, ts_done, ts_total): # different. package = str(package) - message = "{}: {} [{}/{}]".format(pkgmanager.transaction.ACTIONS.get(action), package, ts_done, ts_total) + message = f"{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 2f893be13f..9d0bceaf1c 100644 --- a/convert2rhel/pkgmanager/handlers/yum/__init__.py +++ b/convert2rhel/pkgmanager/handlers/yum/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import re @@ -28,7 +26,6 @@ from convert2rhel.systeminfo import system_info from convert2rhel.utils import remove_pkgs - logger = root_logger.getChild(__name__) """Instance of the logger used in this module.""" @@ -159,13 +156,13 @@ def _enable_repos(self): for repo in enabled_repos: self._base.repos.enableRepo(repo) except pkgmanager.Errors.RepoError as e: - logger.debug("Loading repository metadata failed: {}".format(e)) + logger.debug(f"Loading repository metadata failed: {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 {}.".format(str(e)), + diagnosis=f"Loading repository metadata failed with error {e!s}.", ) def _swap_base_os_specific_packages(self): @@ -179,10 +176,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 {} installed for later swap.".format(old_package)) + logger.debug(f"Checking if {old_package} installed for later swap.") is_installed = system_info.is_rpm_installed(old_package) if is_installed: - logger.debug("Package {} will be swapped to {} during conversion.".format(old_package, new_package)) + logger.debug(f"Package {old_package} will be swapped to {new_package} during conversion.") # 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) @@ -233,7 +230,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 {}.".format(str(e)), + diagnosis=f"Repository mirrors failed with error {e!s}.", ) def _resolve_dependencies(self): diff --git a/convert2rhel/pkgmanager/handlers/yum/callback.py b/convert2rhel/pkgmanager/handlers/yum/callback.py index 413ac0438c..ec9e58ce74 100644 --- a/convert2rhel/pkgmanager/handlers/yum/callback.py +++ b/convert2rhel/pkgmanager/handlers/yum/callback.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -56,20 +55,17 @@ # # https://github.com/rpm-software-management/yum/blob/master/yum/callbacks.py -__metaclass__ = type - from convert2rhel import pkgmanager from convert2rhel.logger import root_logger - 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): +class PackageDownloadCallback(pkgmanager.DownloadProgress): """Package download callback for YUM transaction.""" def __init__(self): @@ -78,7 +74,7 @@ def __init__(self): We initialize a few properties here for keeping track of progression of the downloaded files. """ - super(PackageDownloadCallback, self).__init__() + super().__init__() # Same strategy as used in yum.rpmtrans.SimpleCliCallBack. We # hold the last package name to not print it twice, avoiding # spamming msgs. @@ -114,12 +110,12 @@ def updateProgress(self, name, frac, fread, ftime): self.last_package_seen = name -class TransactionDisplayCallback(pkgmanager.TransactionDisplay, object): +class TransactionDisplayCallback(pkgmanager.TransactionDisplay): """Transaction display callback for YUM transaction.""" def __init__(self): """Constructor that overrides initialization for SimpleCliCallBack().""" - super(TransactionDisplayCallback, self).__init__() + super().__init__() # Hold the last package name to not print it twice, avoiding # spamming msgs. self.last_package_seen = None diff --git a/convert2rhel/redhatrelease.py b/convert2rhel/redhatrelease.py index 108be40fb0..beaeec2c48 100644 --- a/convert2rhel/redhatrelease.py +++ b/convert2rhel/redhatrelease.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os import re @@ -25,7 +22,6 @@ from convert2rhel.backup.files import RestorableFile from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) OS_RELEASE_FILEPATH = "/etc/os-release" @@ -46,8 +42,8 @@ def get_system_release_content(): filepath = get_system_release_filepath() try: return utils.get_file_content(filepath) - except EnvironmentError as err: - logger.critical("{}\n{} file is essential for running this tool.".format(err, filepath)) + except OSError as err: + logger.critical(f"{err}\n{filepath} file is essential for running this tool.") class PkgManagerConf: @@ -79,12 +75,10 @@ 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("{} patched.".format(self._pkg_manager_conf_path)) + logger.info(f"{self._pkg_manager_conf_path} patched.") else: logger.info("Skipping patching, package manager configuration file has not been modified.") - return - def _comment_out_distroverpkg_tag(self): if re.search(r"^distroverpkg=", self._pkg_manager_conf_content, re.MULTILINE): self._pkg_manager_conf_content = re.sub(r"\n(distroverpkg=).*", r"\n#\1", self._pkg_manager_conf_content) @@ -99,9 +93,7 @@ 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.*? {}$".format(self._pkg_manager_conf_path), output, re.MULTILINE) else False - ) + return True if re.search(rf"^.{{2}}5.*? {self._pkg_manager_conf_path}$", output, re.MULTILINE) else False # Code to be executed upon module import diff --git a/convert2rhel/repo.py b/convert2rhel/repo.py index 145527cdbb..9cc27dc84d 100644 --- a/convert2rhel/repo.py +++ b/convert2rhel/repo.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,23 +14,20 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os.path -import tempfile import re - +import tempfile from contextlib import closing from six.moves import urllib from convert2rhel import exceptions from convert2rhel.logger import root_logger +from convert2rhel.pkgmanager import TYPE, call_yum_cmd from convert2rhel.systeminfo import system_info from convert2rhel.toolopts import tool_opts from convert2rhel.utils import TMP_DIR, store_content_to_file -from convert2rhel.pkgmanager import TYPE, call_yum_cmd - DEFAULT_YUM_REPOFILE_DIR = os.path.normcase("/etc/yum.repos.d") DEFAULT_YUM_VARS_DIR = os.path.normcase("/etc/yum/vars") @@ -60,14 +56,14 @@ def get_rhel_repoids(): return repos_needed -class DisableReposDuringAnalysis(object): +class DisableReposDuringAnalysis: _instance = None _repos_to_disable = None def __new__(cls): """Singleton pattern""" if cls._instance is None: - cls._instance = super(DisableReposDuringAnalysis, cls).__new__(cls) + cls._instance = super().__new__(cls) # Cannot call the _set_rhel_repos_to_disable() directly due Python 2 support cls._instance._initialized = False @@ -151,9 +147,9 @@ def _get_valid_custom_repos(repos_to_check): if problematic_reponame_line: reponame = problematic_reponame_line.group(1) logger.debug( - "Removed the {reponame} repository from the list of repositories to disable in certain" + f"Removed the {reponame} repository from the list of repositories to disable in certain" " pre-conversion analysis checks as it is inaccessible at the moment and yum fails when trying to" - " disable an inaccessible repository.".format(reponame=reponame) + " disable an inaccessible repository." ) repos_to_check.remove(reponame) return _get_valid_custom_repos(repos_to_check) @@ -191,9 +187,7 @@ 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: {}".format( - repofile_url - ) + description = f"The requested repository file seems to be empty. No content received when checking for url: {repofile_url}" logger.critical_no_exit(description) raise exceptions.CriticalError( id_="REPOSITORY_FILE_EMPTY_CONTENT", @@ -201,14 +195,14 @@ def download_repofile(repofile_url): description=description, ) - logger.info("Successfully downloaded a repository file from {}.".format(repofile_url)) + logger.info(f"Successfully downloaded a repository file from {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 {}.".format(repofile_url), - diagnosis="Reason: {}.".format(err.reason), + description=f"Failed to download a repository file from {repofile_url}.", + diagnosis=f"Reason: {err.reason}.", ) @@ -224,20 +218,20 @@ def write_temporary_repofile(contents): """ try: repofile_dir = tempfile.mkdtemp(prefix="downloaded_repofiles.", dir=TMP_DIR) - except (OSError, IOError) as err: + except OSError as err: 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 {}.\n" - "Reason: {}".format(TMP_DIR, str(err)), + description=f"Failed to create a temporary directory for storing a repository file under {TMP_DIR}.\n" + f"Reason: {err!s}", ) with tempfile.NamedTemporaryFile(mode="w", suffix=".repo", delete=False, dir=repofile_dir) as f: try: store_content_to_file(filename=f.name, content=contents) return f.name - except (OSError, IOError) as err: + except OSError as err: raise exceptions.CriticalError( id_="STORE_REPOFILE_FAILED", title="Failed to store a repository file", - description="Failed to write a repository file contents to {}.\n" "Reason: {}".format(f.name, str(err)), + description=f"Failed to write a repository file contents to {f.name}.\nReason: {err!s}", ) diff --git a/convert2rhel/subscription.py b/convert2rhel/subscription.py index d9fb946669..b7e1ce74db 100644 --- a/convert2rhel/subscription.py +++ b/convert2rhel/subscription.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,12 +14,10 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import json import os import re - from functools import partial from time import sleep @@ -36,7 +33,6 @@ from convert2rhel.toolopts import tool_opts from convert2rhel.utils.subscription import _should_subscribe - logger = root_logger.getChild(__name__) # We need to translate config settings between names used for the subscription-manager DBus API and @@ -102,7 +98,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{}".format(output)) + raise SubscriptionRemovalError(f"Subscription removal result\n{output}") else: logger.info("Subscription removal successful.") @@ -140,7 +136,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{}".format(output)) + raise UnregisterError(f"System unregistration result:\n{output}") else: logger.info("System unregistered successfully.") @@ -208,17 +204,15 @@ def register_system(): # -release package in one of the steps before # RHELC-16 os_release_file.restore(rollback=False) - except (OSError, IOError) as e: + except OSError as e: logger.critical_no_exit( - "Failed to restore the /etc/os-release file needed for subscribing the system with message: {}".format( - str(e) - ) + f"Failed to restore the /etc/os-release file needed for subscribing the system with message: {e!s}" ) 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 {}.".format(str(e)), + diagnosis=f"The restore failed with error {e!s}.", ) try: @@ -233,7 +227,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: {}".format(str(e))) + logger.info(f"System registration failed with error: {e!s}") troublesome_exception = e sleep(REGISTRATION_ATTEMPT_DELAYS[attempt]) attempt += 1 @@ -248,11 +242,9 @@ 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 {}.".format(str(troublesome_exception)), + diagnosis=f"System registration failed with error {troublesome_exception!s}.", ) - return None - def refresh_subscription_info(): """ @@ -266,7 +258,7 @@ def refresh_subscription_info(): if ret_code != 0: raise RefreshSubscriptionManagerError( - "Asking subscription-manager to reexamine its configuration failed: {}; output: {}".format(ret_code, output) + f"Asking subscription-manager to reexamine its configuration failed: {ret_code}; output: {output}" ) logger.info("subscription-manager has reloaded its configuration.") @@ -277,7 +269,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: {}; output: {}".format(ret_code, output)) + raise StopRhsmError(f"Stopping RHSM failed with code: {ret_code}; output: {output}") logger.info("RHSM service stopped.") @@ -559,11 +551,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("--{}={}".format(CONNECT_OPT_NAME_TO_CONFIG_KEY[option], value)) + sub_man_config_command.append(f"--{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: {}".format(output)) + raise ValueError(f"Error setting the subscription-manager connection configuration: {output}") logger.info("Successfully set RHSM connection configuration.") @@ -720,7 +712,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{}".format(sub_raw_attrs)) + logger.critical(f"Cannot parse the subscription pool ID from string:\n{sub_raw_attrs}") def verify_rhsm_installed(): @@ -749,12 +741,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{}".format(output)) + logger.critical_no_exit(f"Could not disable subscription-manager repositories:\n{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: {}.".format(output), + diagnosis=f"Failed to disable repositories: {output}.", ) logger.info("Repositories disabled.") @@ -790,11 +782,11 @@ 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_to_enable in repos_to_enable: - enable_cmd.append("--enable={}".format(repo_to_enable)) + enable_cmd.append(f"--enable={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{}".format(output) + description = f"Repositories were not possible to enable through subscription-manager:\n{output}" logger.critical_no_exit(description) raise exceptions.CriticalError( id_="FAILED_TO_ENABLE_RHSM_REPOSITORIES", @@ -835,10 +827,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: {}".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(f"Need the following packages: {utils.format_sequence_as_message(subscription_manager_pkgs)}") + logger.debug(f"Detected the following packages: {utils.format_sequence_as_message(installed_submgr_pkgs)}") - logger.debug("Packages we will install: {}".format(utils.format_sequence_as_message(to_install_pkgs))) + logger.debug(f"Packages we will install: {utils.format_sequence_as_message(to_install_pkgs)}") return to_install_pkgs @@ -932,9 +924,9 @@ def get_rhsm_facts(): with open(RHSM_FACTS_FILE, mode="r") as handler: rhsm_facts = json.load(handler) logger.info("RHSM facts loaded.") - except (IOError, ValueError) as e: + except (OSError, ValueError) as e: logger.critical_no_exit( - "Failed to get the RHSM facts : {}.".format(e), + f"Failed to get the RHSM facts : {e}.", ) return rhsm_facts diff --git a/convert2rhel/systeminfo.py b/convert2rhel/systeminfo.py index 3fe27daead..fcf975f321 100644 --- a/convert2rhel/systeminfo.py +++ b/convert2rhel/systeminfo.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,24 +14,20 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import os import re import time - from collections import namedtuple from six.moves import configparser from convert2rhel import utils -from convert2rhel.logger import root_logger, LOG_DIR +from convert2rhel.logger import LOG_DIR, root_logger from convert2rhel.toolopts import tool_opts from convert2rhel.utils import run_subprocess from convert2rhel.utils.rpm import PRE_RPM_VA_LOG_FILENAME - # Number of times to retry checking the status of dbus CHECK_DBUS_STATUS_RETRIES = 3 @@ -98,9 +93,9 @@ def __repr__(self): :rtype: str """ if self.minor: - return "{major}.{minor}".format(major=self.major, minor=self.minor) + return f"{self.major}.{self.minor}" - return "{major}".format(major=self.major) + return f"{self.major}" class SystemInfo: @@ -236,9 +231,7 @@ def parse_system_release_content(system_release_file_content): ) if not matched: - logger.critical_no_exit( - "Couldn't parse the /etc/system-release content: {}".format(system_release_file_content) - ) + logger.critical_no_exit(f"Couldn't parse the /etc/system-release content: {system_release_file_content}") return {} name = matched.group("name") @@ -329,9 +322,7 @@ def _get_cfg_opt(self, option_name): if option_name in self.cfg_content: return self.cfg_content[option_name] else: - logger.error( - "Internal error: {} option not found in {} config file.".format(option_name, self.cfg_filename) - ) + logger.error(f"Internal error: {option_name} option not found in {self.cfg_filename} config file.") def _get_gpg_key_ids(self): return self._get_cfg_opt("gpg_key_ids").split() @@ -352,10 +343,8 @@ def _get_swap_pkgs(self): if old_package in pkgs_to_swap: logger.warning( - "Package {old_package} redefined in swap packages list.\n" - "Old package {old_package} will be swapped by {newest_package} instead of {new_package}.".format( - old_package=old_package, new_package=pkgs_to_swap[old_package], newest_package=new_package - ) + f"Package {old_package} redefined in swap packages list.\n" + f"Old package {old_package} will be swapped by {new_package} instead of {pkgs_to_swap[old_package]}." ) pkgs_to_swap.update({old_package: new_package}) @@ -389,10 +378,8 @@ def _get_releasever(self): return releasever_cfg or RELEASE_VER_MAPPING[repr(self.version)] except KeyError: logger.critical( - "{os_name} of version {current_version} is not allowed for conversion.\n" - "Allowed versions are: {allowed_versions}".format( - os_name=self.name, current_version=self.version, allowed_versions=list(RELEASE_VER_MAPPING.keys()) - ) + f"{self.name} of version {self.version} is not allowed for conversion.\n" + f"Allowed versions are: {list(RELEASE_VER_MAPPING.keys())}" ) def _get_kmods_to_ignore(self): @@ -400,7 +387,7 @@ def _get_kmods_to_ignore(self): def _get_booted_kernel(self): kernel_vra = run_subprocess(["uname", "-r"], print_output=False)[0].rstrip() - logger.debug("Booted kernel VRA (version, release, architecture): {0}".format(kernel_vra)) + logger.debug(f"Booted kernel VRA (version, release, architecture): {kernel_vra}") return kernel_vra def generate_rpm_va(self, log_filename=PRE_RPM_VA_LOG_FILENAME): @@ -423,7 +410,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(LOG_DIR, log_filename) utils.store_content_to_file(output_file, rpm_va) - logger.info("The 'rpm -Va' output has been stored in the {} file.".format(output_file)) + logger.info(f"The 'rpm -Va' output has been stored in the {output_file} file.") @staticmethod def is_rpm_installed(name): diff --git a/convert2rhel/toolopts/__init__.py b/convert2rhel/toolopts/__init__.py index 6094dd7610..6834aff96b 100644 --- a/convert2rhel/toolopts/__init__.py +++ b/convert2rhel/toolopts/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -14,13 +13,11 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging from convert2rhel.utils.subscription import setup_rhsm_parts - loggerinst = logging.getLogger(__name__) diff --git a/convert2rhel/toolopts/config.py b/convert2rhel/toolopts/config.py index 8c6cac6635..1e4f0e73bc 100644 --- a/convert2rhel/toolopts/config.py +++ b/convert2rhel/toolopts/config.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -14,7 +13,6 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import abc import copy @@ -22,10 +20,8 @@ import os import six - from six.moves import configparser - loggerinst = logging.getLogger(__name__) #: Map name of the convert2rhel mode to run in from the command line to the @@ -72,7 +68,7 @@ class FileConfig(BaseConfig): DEFAULT_CONFIG_FILES = ["~/.convert2rhel.ini", "/etc/convert2rhel.ini"] def __init__(self, custom_config): - super(FileConfig, self).__init__() + super().__init__() # Subscription Manager self.username = None # type: str | None @@ -155,20 +151,18 @@ def _parse_options_from_config(self, paths): found_opts = {} for path in reversed(paths): - loggerinst.debug("Checking configuration file at {}".format(path)) + loggerinst.debug(f"Checking configuration file at {path}") # Check for correct permissions on file if not oct(os.stat(path).st_mode)[-4:].endswith("00"): - loggerinst.critical("The {} file must only be accessible by the owner (0600)".format(path)) + loggerinst.critical(f"The {path} file must only be accessible by the owner (0600)") 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 '{}'".format(supported_header)) + loggerinst.debug(f"Checking for header '{supported_header}'") if supported_header not in config_file.sections(): - loggerinst.warning( - "Couldn't find header '{}' in the configuration file {}.".format(supported_header, path) - ) + loggerinst.warning(f"Couldn't find header '{supported_header}' in the configuration file {path}.") continue options = self._get_options_value(config_file, supported_header, supported_opts) found_opts.update(options) @@ -191,12 +185,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 {}. It seems to be empty or commented.".format(header)) + loggerinst.debug(f"No options found for {header}. It seems to be empty or commented.") return options for option in conf_options: if option.lower() not in supported_opts: - loggerinst.warning("Unsupported option '{}' in '{}'".format(option, header)) + loggerinst.warning(f"Unsupported option '{option}' in '{header}'") continue # This is the only header that can contain boolean values for now. @@ -205,7 +199,7 @@ def _get_options_value(self, config_file, header, supported_opts): else: options[option] = config_file.get(header, option) - loggerinst.debug("Found {} in {}".format(option, header)) + loggerinst.debug(f"Found {option} in {header}") return options @@ -214,7 +208,7 @@ class CliConfig(BaseConfig): SOURCE = "command line" def __init__(self, opts): - super(CliConfig, self).__init__() + super().__init__() self.debug = False # type: bool self.username = None # type: str | None @@ -308,7 +302,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{}".format(repo) + message += f"\n{repo}" message += "\nThis ambiguity may have unintended consequences." loggerinst.warning(message) diff --git a/convert2rhel/unit_tests/README.md b/convert2rhel/unit_tests/README.md index dd91db3478..768437532c 100644 --- a/convert2rhel/unit_tests/README.md +++ b/convert2rhel/unit_tests/README.md @@ -44,6 +44,7 @@ that needs to be mocked: import mock import package_handler + def test_check_for_yum_updates(monkeypatch): packages_to_update_mock = mock.Mock(return_value=["package-1", "package-2"]) monkeypatch.setattr(package_handler, "get_packages_to_update", value=packages_to_update_mock) @@ -59,6 +60,7 @@ dependencies: import os import file_handler + def test_archive_old_files(tmpdir): tmpdir = str(tmpdir) some_dir = os.path.join(tmpdir, "some_dir") diff --git a/convert2rhel/unit_tests/__init__.py b/convert2rhel/unit_tests/__init__.py index 7a81447429..fe1ff0c1fd 100644 --- a/convert2rhel/unit_tests/__init__.py +++ b/convert2rhel/unit_tests/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -14,7 +13,6 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import collections import functools @@ -43,10 +41,8 @@ from convert2rhel.pkghandler import PackageInformation, PackageNevra from convert2rhel.utils import run_subprocess - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) -from six.moves import mock as six_mock # noqa: E402 - +from six.moves import mock as six_mock TMP_DIR = "/tmp/convert2rhel_test/" NONEXISTING_DIR = os.path.join(TMP_DIR, "nonexisting_dir/") @@ -160,7 +156,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 = "{}_orig".format(orig_obj) + orig_obj_attr = f"{orig_obj}_orig" setattr(class_or_module, orig_obj_attr, orig_obj_saved) # Call the decorated test function return_value = None @@ -205,7 +201,7 @@ def is_rpm_based_os(): """Check if the OS is rpm based.""" try: run_subprocess(["rpm"]) - except EnvironmentError: + except OSError: return False else: return True @@ -250,7 +246,7 @@ def __init__(self, **kwargs): def __getattr__(self, name): # Need to use a base class's methods for looking up attributes which might not exist # to avoid infinite recursion. (This could be called before self._mock has been created) - _mock = super(MockFunctionObject, self).__getattribute__("_mock") + _mock = super().__getattribute__("_mock") return getattr(_mock, name) def __call__(self, *args, **kwargs): @@ -264,10 +260,10 @@ class SysExitCallableObject(MockFunctionObject): def __init__(self, msg, **kwargs): self.msg = msg - super(SysExitCallableObject, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, *args, **kwargs): - super(SysExitCallableObject, self).__call__(*args, **kwargs) + super().__call__(*args, **kwargs) return sys.exit(self.msg) @@ -284,10 +280,10 @@ def __init__(self, id_, title, description=None, diagnosis=None, remediations=No self.remediations = remediations self.variables = {} if variables is None else variables - super(CriticalErrorCallableObject, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, *args, **kwargs): - super(CriticalErrorCallableObject, self).__call__(*args, **kwargs) + super().__call__(*args, **kwargs) raise exceptions.CriticalError( self.id, self.title, @@ -325,7 +321,7 @@ class RestorablePackageMocked(MockFunctionObject): def __init__(self, **kwargs): self.pkgs = None - super(RestorablePackageMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, pkgs, reposdir, set_releasever, custom_releasever, *args, **kwargs): self.pkgs = pkgs @@ -333,9 +329,7 @@ def __call__(self, pkgs, reposdir, set_releasever, custom_releasever, *args, **k self.set_releasever = set_releasever self.custom_releasever = custom_releasever - return super(RestorablePackageMocked, self).__call__( - pkgs, reposdir, set_releasever, custom_releasever, *args, **kwargs - ) + return super().__call__(pkgs, reposdir, set_releasever, custom_releasever, *args, **kwargs) # @@ -409,13 +403,13 @@ def __init__(self, return_code=0, return_string="Test output", fail_once=False, if fail_once: side_effect = itertools.chain([(return_string, 1)], side_effect) - super(CallYumCmdMocked, self).__init__(side_effect=side_effect, **kwargs) + super().__init__(side_effect=side_effect, **kwargs) def __call__(self, command, *other_args, **kwargs): self.command = command self.args = kwargs.get("args", []) - return super(CallYumCmdMocked, self).__call__(command, *other_args, **kwargs) + return super().__call__(command, *other_args, **kwargs) class ClearVersionlockMocked(MockFunctionObject): @@ -495,7 +489,7 @@ def __init__(self, pkg_selection=None, **kwargs): if pkg_selection is not None: kwargs["return_value"] = self.prebaked_pkgs[pkg_selection] - super(GetInstalledPkgInformationMocked, self).__init__(**kwargs) + super().__init__(**kwargs) class GetInstalledPkgsWDifferentKeyIdMocked(GetInstalledPkgInformationMocked): @@ -613,12 +607,12 @@ class RemovePkgsMocked(MockFunctionObject): def __init__(self, **kwargs): self.pkgs = None - super(RemovePkgsMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, pkgs_to_remove, *args, **kwargs): self.pkgs = pkgs_to_remove - return super(RemovePkgsMocked, self).__call__(pkgs_to_remove, *args, **kwargs) + return super().__call__(pkgs_to_remove, *args, **kwargs) class DownloadPkgMocked(MockFunctionObject): @@ -637,7 +631,7 @@ def __init__(self, **kwargs): self.enable_repos = [] self.disable_repos = [] - super(DownloadPkgMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, pkg, *args, **kwargs): self.pkg = pkg @@ -645,7 +639,7 @@ def __call__(self, pkg, *args, **kwargs): self.enable_repos = kwargs.get("enable_repos", []) self.disable_repos = kwargs.get("disable_repos", []) - return super(DownloadPkgMocked, self).__call__(pkg, *args, **kwargs) + return super().__call__(pkg, *args, **kwargs) class PromptUserMocked(MockFunctionObject): @@ -658,10 +652,10 @@ def __init__(self, retries=0, **kwargs): if "return_value" not in kwargs: kwargs["return_value"] = "test" - super(PromptUserMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, question, *args, **kwargs): - return_value = super(PromptUserMocked, self).__call__(question, *args, **kwargs) + return_value = super().__call__(question, *args, **kwargs) self.prompts[question] += 1 # Emulate the user not providing a valid value until retries times. @@ -697,13 +691,13 @@ def __init__(self, return_code=None, return_string=None, **kwargs): return_string = "Test output" if return_string is None else return_string kwargs["return_value"] = (return_string, return_code) - super(RunSubprocessMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, cmd, *args, **kwargs): self.cmd = cmd self.cmds.append(cmd) - return super(RunSubprocessMocked, self).__call__(cmd, *args, **kwargs) + return super().__call__(cmd, *args, **kwargs) class RunCmdInPtyMocked(RunSubprocessMocked): @@ -723,13 +717,13 @@ def __init__(self, **kwargs): self.filename = None self.content = None - super(StoreContentToFileMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, filename, content, *args, **kwargs): self.filename = filename self.content = content - super(StoreContentToFileMocked, self).__call__(filename, content, *args, **kwargs) + super().__call__(filename, content, *args, **kwargs) return True @@ -858,41 +852,41 @@ def set_default_efi_entries(self): class MinimalRestorable(backup.RestorableChange): def __init__(self): self.called = collections.defaultdict(int) - super(MinimalRestorable, self).__init__() + super().__init__() def enable(self): self.called["enable"] += 1 - super(MinimalRestorable, self).enable() + super().enable() def restore(self): self.called["restore"] += 1 - super(MinimalRestorable, self).restore() + super().restore() class FilePathRestorable(MinimalRestorable): def __init__(self, filepath=None): self.backup_path = filepath - super(FilePathRestorable, self).__init__() + super().__init__() def __eq__(self, value): if self.backup_path: return self.backup_path == value.backup_path - return super(FilePathRestorable, self).__eq__(value) + return super().__eq__(value) class ErrorOnRestoreRestorable(MinimalRestorable): def __init__(self, exception=None): self.exception = exception or Exception() - super(ErrorOnRestoreRestorable, self).__init__() + super().__init__() def restore(self): - super(ErrorOnRestoreRestorable, self).restore() + super().restore() raise self.exception class RestorablePackageMock(MinimalRestorable): def __init__(self, pkg_name=None, reposdir=None, set_releasever=False, custom_releasever=None): - super(RestorablePackageMock, self).__init__() + super().__init__() self.pkg_name = pkg_name self.reposdir = reposdir diff --git a/convert2rhel/unit_tests/actions/__init__.py b/convert2rhel/unit_tests/actions/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/__init__.py +++ b/convert2rhel/unit_tests/actions/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/actions_test.py b/convert2rhel/unit_tests/actions/actions_test.py index 4737da09f8..666879ff20 100644 --- a/convert2rhel/unit_tests/actions/actions_test.py +++ b/convert2rhel/unit_tests/actions/actions_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # @@ -15,17 +14,14 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os.path import re - from collections import defaultdict import pytest import six - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -40,14 +36,13 @@ class _ActionForTesting(actions.Action): id = None def __init__(self, **kwargs): - super(_ActionForTesting, self).__init__() + super().__init__() for attr_name, attr_value in kwargs.items(): setattr(self, attr_name, attr_value) def run(self): - super(_ActionForTesting, self).run() - pass + super().run() class TestAction: @@ -230,14 +225,12 @@ 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 "{}.{}.".format(actions.__name__, directory) == "convert2rhel.actions.post_ponr": + if f"{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)], "{}.{}.".format(actions.__name__, directory) - ) + actions.get_actions([os.path.join(rootdir, directory)], f"{actions.__name__}.{directory}.") ) for filename in (os.path.join(rootdir, filename) for filename in filenames): @@ -281,7 +274,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.{}.".format(test_dir_name)) + for m in actions.get_actions([test_data], f"convert2rhel.unit_tests.actions.data.{test_dir_name}.") ) assert computed_action_names == sorted(expected_action_names) diff --git a/convert2rhel/unit_tests/actions/conversion/list_non_red_hat_pkgs_left_test.py b/convert2rhel/unit_tests/actions/conversion/list_non_red_hat_pkgs_left_test.py index 7e8c7337b0..fca1afa124 100644 --- a/convert2rhel/unit_tests/actions/conversion/list_non_red_hat_pkgs_left_test.py +++ b/convert2rhel/unit_tests/actions/conversion/list_non_red_hat_pkgs_left_test.py @@ -13,15 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import pytest import six from convert2rhel.actions.conversion import list_non_red_hat_pkgs_left - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from convert2rhel import pkghandler diff --git a/convert2rhel/unit_tests/actions/conversion/lock_releasever_test.py b/convert2rhel/unit_tests/actions/conversion/lock_releasever_test.py index 1e8980e22e..f51c323274 100644 --- a/convert2rhel/unit_tests/actions/conversion/lock_releasever_test.py +++ b/convert2rhel/unit_tests/actions/conversion/lock_releasever_test.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import pytest import six @@ -25,7 +23,6 @@ from convert2rhel.unit_tests import RunSubprocessMocked from convert2rhel.unit_tests.conftest import centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from convert2rhel import unit_tests @@ -52,7 +49,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={}".format(system_info.releasever)] + cmd = ["subscription-manager", "release", f"--set={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/pkg_manager_config_test.py b/convert2rhel/unit_tests/actions/conversion/pkg_manager_config_test.py index 0546ca47b2..bf6765d9cf 100644 --- a/convert2rhel/unit_tests/actions/conversion/pkg_manager_config_test.py +++ b/convert2rhel/unit_tests/actions/conversion/pkg_manager_config_test.py @@ -13,14 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six from convert2rhel import redhatrelease from convert2rhel.actions.conversion import pkg_manager_config - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock 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 e88c8d0313..3057148cf5 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 @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import glob import os import re @@ -36,7 +35,6 @@ ) from convert2rhel.unit_tests.conftest import centos7, centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -414,7 +412,7 @@ def test_fix_default_kernel_converting_success( monkeypatch.setattr( utils, "get_file_content", - lambda _: "UPDATEDEFAULT=yes\nDEFAULTKERNEL={}\n".format(old_kernel), + lambda _: f"UPDATEDEFAULT=yes\nDEFAULTKERNEL={old_kernel}\n", ) monkeypatch.setattr(utils, "store_content_to_file", StoreContentToFileMocked()) @@ -428,10 +426,10 @@ def test_fix_default_kernel_converting_success( kernel_file_lines = content.splitlines() assert "/etc/sysconfig/kernel" == filename - assert "DEFAULTKERNEL={}".format(new_kernel) in kernel_file_lines + assert f"DEFAULTKERNEL={new_kernel}" in kernel_file_lines for kernel_name in not_default_kernels: - assert "DEFAULTKERNEL={}".format(kernel_name) not in kernel_file_lines + assert f"DEFAULTKERNEL={kernel_name}" not in kernel_file_lines @centos7 def test_fix_default_kernel_with_no_incorrect_kernel( @@ -490,7 +488,7 @@ def exists_mocked(path): (filename, content), _ = utils.store_content_to_file.call_args assert filename == "/etc/sysconfig/kernel" - assert "DEFAULTKERNEL={}".format(expected_default_kernel) in content + assert f"DEFAULTKERNEL={expected_default_kernel}" in content assert "UPDATEDEFAULT=yes" in content assert any(m.id == "MISSING_KERNEL_SYSCONFIG_CREATED" for m in fix_default_kernel_instance.messages) diff --git a/convert2rhel/unit_tests/actions/conversion/set_efi_config_test.py b/convert2rhel/unit_tests/actions/conversion/set_efi_config_test.py index 30f9a0185d..5734420813 100644 --- a/convert2rhel/unit_tests/actions/conversion/set_efi_config_test.py +++ b/convert2rhel/unit_tests/actions/conversion/set_efi_config_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import shutil @@ -24,7 +23,6 @@ from convert2rhel.actions.conversion import set_efi_config from convert2rhel.unit_tests.conftest import centos7 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -200,7 +198,7 @@ def test_move_grub_files_io_error( move_grub_files_instance, ): monkeypatch.setattr(shutil, "move", mock.Mock()) - shutil.move.side_effect = IOError(13, "Permission denied") + shutil.move.side_effect = OSError(13, "Permission denied") monkeypatch.setattr(os.path, "exists", mock.Mock(side_effect=[False, True, True, True, False, True, False])) monkeypatch.setattr(grub, "is_efi", mock.Mock(return_value=True)) diff --git a/convert2rhel/unit_tests/actions/conversion/transaction_test.py b/convert2rhel/unit_tests/actions/conversion/transaction_test.py index 637d5a4099..9860842046 100644 --- a/convert2rhel/unit_tests/actions/conversion/transaction_test.py +++ b/convert2rhel/unit_tests/actions/conversion/transaction_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six @@ -23,7 +22,6 @@ from convert2rhel.pkgmanager.handlers.base import TransactionHandlerBase from convert2rhel.unit_tests.conftest import all_systems - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/actions/data/__init__.py b/convert2rhel/unit_tests/actions/data/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/__init__.py +++ b/convert2rhel/unit_tests/actions/data/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/aliased_action_name/__init__.py b/convert2rhel/unit_tests/actions/data/aliased_action_name/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/aliased_action_name/__init__.py +++ b/convert2rhel/unit_tests/actions/data/aliased_action_name/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/aliased_action_name/test.py b/convert2rhel/unit_tests/actions/data/aliased_action_name/test.py index bbe44f6135..c82516043c 100644 --- a/convert2rhel/unit_tests/actions/data/aliased_action_name/test.py +++ b/convert2rhel/unit_tests/actions/data/aliased_action_name/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel.actions import Action as Foo diff --git a/convert2rhel/unit_tests/actions/data/extraneous_files/__init__.py b/convert2rhel/unit_tests/actions/data/extraneous_files/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/extraneous_files/__init__.py +++ b/convert2rhel/unit_tests/actions/data/extraneous_files/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/extraneous_files/test.py b/convert2rhel/unit_tests/actions/data/extraneous_files/test.py index d260abc229..d3e9d28576 100644 --- a/convert2rhel/unit_tests/actions/data/extraneous_files/test.py +++ b/convert2rhel/unit_tests/actions/data/extraneous_files/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions diff --git a/convert2rhel/unit_tests/actions/data/ignore__init__/__init__.py b/convert2rhel/unit_tests/actions/data/ignore__init__/__init__.py index 16f03cb709..1ac7f780a6 100644 --- a/convert2rhel/unit_tests/actions/data/ignore__init__/__init__.py +++ b/convert2rhel/unit_tests/actions/data/ignore__init__/__init__.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions diff --git a/convert2rhel/unit_tests/actions/data/ignore__init__/test.py b/convert2rhel/unit_tests/actions/data/ignore__init__/test.py index d260abc229..d3e9d28576 100644 --- a/convert2rhel/unit_tests/actions/data/ignore__init__/test.py +++ b/convert2rhel/unit_tests/actions/data/ignore__init__/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions diff --git a/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/__init__.py b/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/__init__.py +++ b/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/test1.py b/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/test1.py index a69749595d..db85213e86 100644 --- a/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/test1.py +++ b/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/test1.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions diff --git a/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/test2.py b/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/test2.py index 94422fcb3d..ff28b42844 100644 --- a/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/test2.py +++ b/convert2rhel/unit_tests/actions/data/multiple_actions_multiple_files/test2.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions diff --git a/convert2rhel/unit_tests/actions/data/multiple_actions_one_file/__init__.py b/convert2rhel/unit_tests/actions/data/multiple_actions_one_file/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/multiple_actions_one_file/__init__.py +++ b/convert2rhel/unit_tests/actions/data/multiple_actions_one_file/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/multiple_actions_one_file/test.py b/convert2rhel/unit_tests/actions/data/multiple_actions_one_file/test.py index 0a4a227edc..a8d7fe3970 100644 --- a/convert2rhel/unit_tests/actions/data/multiple_actions_one_file/test.py +++ b/convert2rhel/unit_tests/actions/data/multiple_actions_one_file/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions diff --git a/convert2rhel/unit_tests/actions/data/not_action_itself/__init__.py b/convert2rhel/unit_tests/actions/data/not_action_itself/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/not_action_itself/__init__.py +++ b/convert2rhel/unit_tests/actions/data/not_action_itself/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/not_action_itself/test.py b/convert2rhel/unit_tests/actions/data/not_action_itself/test.py index 2916d8b6e1..b3b36d37d3 100644 --- a/convert2rhel/unit_tests/actions/data/not_action_itself/test.py +++ b/convert2rhel/unit_tests/actions/data/not_action_itself/test.py @@ -1,8 +1,5 @@ -__metaclass__ = type - from convert2rhel import actions - AlternateName = actions.Action diff --git a/convert2rhel/unit_tests/actions/data/only_subclasses_of_action/__init__.py b/convert2rhel/unit_tests/actions/data/only_subclasses_of_action/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/only_subclasses_of_action/__init__.py +++ b/convert2rhel/unit_tests/actions/data/only_subclasses_of_action/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/only_subclasses_of_action/test.py b/convert2rhel/unit_tests/actions/data/only_subclasses_of_action/test.py index 919310d717..aeeb91791a 100644 --- a/convert2rhel/unit_tests/actions/data/only_subclasses_of_action/test.py +++ b/convert2rhel/unit_tests/actions/data/only_subclasses_of_action/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/__init__.py b/convert2rhel/unit_tests/actions/data/stage_tests/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/__init__.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/action_exceptions/__init__.py b/convert2rhel/unit_tests/actions/data/stage_tests/action_exceptions/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/action_exceptions/__init__.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/action_exceptions/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/action_exceptions/test.py b/convert2rhel/unit_tests/actions/data/stage_tests/action_exceptions/test.py index f8e5bc7d9f..c540a96e2d 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/action_exceptions/test.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/action_exceptions/test.py @@ -1,10 +1,6 @@ -__metaclass__ = type - - from convert2rhel import actions from convert2rhel.logger import root_logger - logger = root_logger.getChild(__name__) @@ -13,7 +9,7 @@ class DivideByZeroTest(actions.Action): dependencies = ("SUCCESSTEST",) def run(self): - super(DivideByZeroTest, self).run() + super().run() return 1 / 0 @@ -22,7 +18,7 @@ class LogCriticalTest(actions.Action): dependencies = ("SUCCESSTEST",) def run(self): - super(LogCriticalTest, self).run() + super().run() logger.critical("Critical log will cause a SystemExit.") @@ -30,5 +26,4 @@ class SuccessTest(actions.Action): id = "SUCCESSTEST" def run(self): - super(SuccessTest, self).run() - return + super().run() diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/all_status_actions/__init__.py b/convert2rhel/unit_tests/actions/data/stage_tests/all_status_actions/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/all_status_actions/__init__.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/all_status_actions/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/all_status_actions/test.py b/convert2rhel/unit_tests/actions/data/stage_tests/all_status_actions/test.py index 7433fdf404..5953cd4df5 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/all_status_actions/test.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/all_status_actions/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions @@ -8,7 +6,7 @@ class ErrorTest(actions.Action): dependencies = ("SUCCESSTEST",) def run(self): - super(ErrorTest, self).run() + super().run() self.set_result( level="ERROR", id="ERROR_ID", @@ -24,7 +22,7 @@ class OverridableTest(actions.Action): dependencies = ("SUCCESSTEST",) def run(self): - super(OverridableTest, self).run() + super().run() self.set_result( level="OVERRIDABLE", id="OVERRIDABLE_ID", @@ -41,8 +39,7 @@ class SkipSingleTest(actions.Action): dependencies = ("ERRORTEST",) def run(self): - super(SkipSingleTest, self).run() - return + super().run() # Skip because of multiple dependencies have failed @@ -51,15 +48,14 @@ class SkipMultipleTest(actions.Action): dependencies = ("ERRORTEST", "OVERRIDABLETEST") def run(self): - super(SkipMultipleTest, self).run() - return + super().run() class WarningTest(actions.Action): id = "WARNINGTEST" def run(self): - super(WarningTest, self).run() + super().run() self.add_message( level="WARNING", id="WARNING_ID", @@ -74,5 +70,4 @@ class SuccessTest(actions.Action): id = "SUCCESSTEST" def run(self): - super(SuccessTest, self).run() - return + super().run() diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/bad_deps1/__init__.py b/convert2rhel/unit_tests/actions/data/stage_tests/bad_deps1/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/bad_deps1/__init__.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/bad_deps1/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/bad_deps1/test.py b/convert2rhel/unit_tests/actions/data/stage_tests/bad_deps1/test.py index c554184b6d..1a6ccac7f1 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/bad_deps1/test.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/bad_deps1/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions @@ -8,8 +6,7 @@ class BadTest1(actions.Action): dependencies = ("BADTEST2",) def run(self): - super(BadTest1, self).run() - return + super().run() class BadTest2(actions.Action): @@ -17,5 +14,4 @@ class BadTest2(actions.Action): dependencies = ("BADTEST1",) def run(self): - super(BadTest2, self).run() - return + super().run() diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/deps_on_1/__init__.py b/convert2rhel/unit_tests/actions/data/stage_tests/deps_on_1/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/deps_on_1/__init__.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/deps_on_1/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/deps_on_1/test.py b/convert2rhel/unit_tests/actions/data/stage_tests/deps_on_1/test.py index dcbb428d5e..9dd1b9a041 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/deps_on_1/test.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/deps_on_1/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions @@ -8,8 +6,7 @@ class TestI(actions.Action): dependencies = ("REALTEST",) def run(self): - super(TestI, self).run() - return + super().run() class TestII(actions.Action): @@ -17,5 +14,4 @@ class TestII(actions.Action): dependencies = ("REALTEST", "FOURTHTEST") def run(self): - super(TestII, self).run() - return + super().run() diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/good_deps1/__init__.py b/convert2rhel/unit_tests/actions/data/stage_tests/good_deps1/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/good_deps1/__init__.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/good_deps1/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/good_deps1/test.py b/convert2rhel/unit_tests/actions/data/stage_tests/good_deps1/test.py index 1205a66d48..9ca6264a13 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/good_deps1/test.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/good_deps1/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions @@ -7,8 +5,7 @@ class RealTest(actions.Action): id = "REALTEST" def run(self): - super(RealTest, self).run() - return + super().run() class SecondTest(actions.Action): @@ -16,8 +13,7 @@ class SecondTest(actions.Action): dependencies = ("REALTEST",) def run(self): - super(SecondTest, self).run() - return + super().run() class ThirdTest(actions.Action): @@ -25,8 +21,7 @@ class ThirdTest(actions.Action): dependencies = ("REALTEST",) def run(self): - super(ThirdTest, self).run() - return + super().run() class FourthTest(actions.Action): @@ -34,5 +29,4 @@ class FourthTest(actions.Action): dependencies = ("SECONDTEST", "THIRDTEST") def run(self): - super(FourthTest, self).run() - return + super().run() diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/good_deps_failed_actions/__init__.py b/convert2rhel/unit_tests/actions/data/stage_tests/good_deps_failed_actions/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/good_deps_failed_actions/__init__.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/good_deps_failed_actions/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/data/stage_tests/good_deps_failed_actions/test.py b/convert2rhel/unit_tests/actions/data/stage_tests/good_deps_failed_actions/test.py index e8c0c45a8f..748682522d 100644 --- a/convert2rhel/unit_tests/actions/data/stage_tests/good_deps_failed_actions/test.py +++ b/convert2rhel/unit_tests/actions/data/stage_tests/good_deps_failed_actions/test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - from convert2rhel import actions @@ -8,15 +6,14 @@ class ATest(actions.Action): dependencies = ("BTEST",) def run(self): - super(ATest, self).run() - return + super().run() class BTest(actions.Action): id = "BTEST" def run(self): - super(BTest, self).run() + super().run() self.set_status( level=actions.STATUS_CODES["ERROR"], id="BTEST_FAILURE", diff --git a/convert2rhel/unit_tests/actions/post_conversion/breadcrumbs_finish_collection_test.py b/convert2rhel/unit_tests/actions/post_conversion/breadcrumbs_finish_collection_test.py index d196c01ba9..6ed638911f 100644 --- a/convert2rhel/unit_tests/actions/post_conversion/breadcrumbs_finish_collection_test.py +++ b/convert2rhel/unit_tests/actions/post_conversion/breadcrumbs_finish_collection_test.py @@ -13,14 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six from convert2rhel.actions.post_conversion import breadcrumbs_finish_collection - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/actions/post_conversion/hostmetering_test.py b/convert2rhel/unit_tests/actions/post_conversion/hostmetering_test.py index 3386ab4fd9..86d746c5aa 100644 --- a/convert2rhel/unit_tests/actions/post_conversion/hostmetering_test.py +++ b/convert2rhel/unit_tests/actions/post_conversion/hostmetering_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six @@ -25,7 +23,6 @@ from convert2rhel.systeminfo import Version, system_info from convert2rhel.unit_tests import RunSubprocessMocked, assert_actions_result, run_subprocess_side_effect - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -137,7 +134,7 @@ def test_configure_host_metering( monkeypatch.setattr(toolopts, "tool_opts", global_tool_opts) monkeypatch.setenv("CONVERT2RHEL_CONFIGURE_HOST_METERING", envvar) monkeypatch.setattr(system_info, "version", os_version) - fake_release = "CentOS Linux release {version} (Core)".format(version=repr(os_version)) + fake_release = f"CentOS Linux release {os_version!r} (Core)" monkeypatch.setattr(hostmetering.SystemInfo, "get_system_release_file_content", staticmethod(lambda: fake_release)) monkeypatch.setattr(hostmetering, "get_rhsm_facts", mock.Mock(return_value=rhsm_facts)) yum_mock = mock.Mock(return_value=(0, "")) @@ -347,7 +344,7 @@ def test_configure_host_metering_messages_and_results( monkeypatch.setenv("CONVERT2RHEL_CONFIGURE_HOST_METERING", env_var) monkeypatch.setattr(system_info, "version", os_version) if os_version: - fake_release = "CentOS Linux release {version} (Core)".format(version=repr(os_version)) + fake_release = f"CentOS Linux release {os_version!r} (Core)" monkeypatch.setattr( hostmetering.SystemInfo, "get_system_release_file_content", staticmethod(lambda: fake_release) ) 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 5d2abceb49..1cc22eebf9 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 @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os @@ -25,7 +24,6 @@ from convert2rhel.unit_tests import RunSubprocessMocked from convert2rhel.unit_tests.conftest import centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -132,10 +130,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-{} -y\n" + f"1. yum reinstall kernel-core-{latest_installed_kernel} -y\n" "2. grub2-mkconfig -o /boot/grub2/grub.cfg\n" "3. reboot" - ).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 1c182d9478..19b4f724a3 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 @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging @@ -24,7 +23,6 @@ from convert2rhel.actions.post_conversion import modified_rpm_files_diff from convert2rhel.systeminfo import system_info - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock 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 64377157f7..c8f5e2fc2f 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 @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging import os @@ -35,7 +34,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 {} removed".format(path) in caplog.text + assert f"Temporary folder {path} removed" in caplog.text assert not os.path.isdir(path) @@ -45,7 +44,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 {} removed".format(path) not in caplog.text + assert f"Temporary folder {path} removed" not in caplog.text def test_remove_tmp_dir_failure(remove_tmp_dir_instance, monkeypatch, tmpdir, caplog): @@ -55,15 +54,15 @@ 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 {} is left untouched. You may remove the folder manually" - " after you ensure there is no preserved data you would need.".format(path) + f"The folder {path} is left untouched. You may remove the folder manually" + " after you ensure there is no preserved data you would need." ) expected = set( ( actions.ActionMessage( id="UNSUCCESSFUL_REMOVE_TMP_DIR", level="WARNING", - title="Temporary folder {tmp_dir} wasn't removed.".format(tmp_dir=path), + title=f"Temporary folder {path} wasn't removed.", description=expected_message, ), ), diff --git a/convert2rhel/unit_tests/actions/post_conversion/rhsm_custom_facts_config_test.py b/convert2rhel/unit_tests/actions/post_conversion/rhsm_custom_facts_config_test.py index b7947a2add..0ea020a405 100644 --- a/convert2rhel/unit_tests/actions/post_conversion/rhsm_custom_facts_config_test.py +++ b/convert2rhel/unit_tests/actions/post_conversion/rhsm_custom_facts_config_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six @@ -22,7 +21,6 @@ from convert2rhel.actions.post_conversion.rhsm_custom_facts_config import RHSMCustomFactsConfig from convert2rhel.unit_tests import RunSubprocessMocked - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock 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 7ba2a65a3d..110bf9deb0 100644 --- a/convert2rhel/unit_tests/actions/post_conversion/update_grub_test.py +++ b/convert2rhel/unit_tests/actions/post_conversion/update_grub_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from collections import namedtuple @@ -24,7 +23,6 @@ from convert2rhel.actions.post_conversion import update_grub from convert2rhel.unit_tests import RunSubprocessMocked, run_subprocess_side_effect - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -65,7 +63,7 @@ def test_update_grub( ( "/usr/sbin/grub2-mkconfig", "-o", - "{}".format(config_path), + f"{config_path}", ), ( "output", @@ -201,7 +199,7 @@ def test_update_grub_action_messages( ( "/usr/sbin/grub2-mkconfig", "-o", - "{}".format(config_path), + f"{config_path}", ), ( "output", @@ -244,7 +242,7 @@ def test_update_grub_error(update_grub_instance, monkeypatch, get_partition_erro level="ERROR", id="FAILED_TO_IDENTIFY_GRUB2_BLOCK_DEVICE", title="Failed to identify GRUB2 block device", - description="The block device could not be identified, please look at the diagnosis " "for more information.", + description="The block device could not be identified, please look at the diagnosis for more information.", diagnosis=diagnosis, ) @@ -267,7 +265,7 @@ def test_update_grub_error(update_grub_instance, monkeypatch, get_partition_erro pytest.param( 2, 'GRUB_TERMINAL="ec2-console"\n', - 'GRUB_TERMINAL="console"\n{}\n{}\n'.format(_GRUB_DISTRIBUTOR_OPT, _GRUB_DISABLE_SUBMENU_OPT), + f'GRUB_TERMINAL="console"\n{_GRUB_DISTRIBUTOR_OPT}\n{_GRUB_DISABLE_SUBMENU_OPT}\n', "Successfully updated /etc/default/grub.", True, id="al2_replace_ec2_console_add_missing_opts", @@ -275,7 +273,7 @@ def test_update_grub_error(update_grub_instance, monkeypatch, get_partition_erro pytest.param( 2, 'GRUB_TERMINAL="console"\n', - 'GRUB_TERMINAL="console"\n{}\n{}\n'.format(_GRUB_DISTRIBUTOR_OPT, _GRUB_DISABLE_SUBMENU_OPT), + f'GRUB_TERMINAL="console"\n{_GRUB_DISTRIBUTOR_OPT}\n{_GRUB_DISABLE_SUBMENU_OPT}\n', "Successfully updated /etc/default/grub.", True, id="al2_console_already_set_add_missing_opts", diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/__init__.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/__init__.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type 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 735c13f149..d6fc6e97b0 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 @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import hashlib import os @@ -29,7 +27,6 @@ from convert2rhel.unit_tests import CriticalErrorCallableObject from convert2rhel.utils.rpm import PRE_RPM_VA_LOG_FILENAME - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -220,7 +217,7 @@ def test_get_changed_package_file_system_exit( monkeypatch.setattr(backup_system, "LOG_DIR", str(tmp_path)) rpm_va_path = os.path.join(tmp_path, PRE_RPM_VA_LOG_FILENAME) - message = "Missing file {} in it's location".format(rpm_va_path) + message = f"Missing file {rpm_va_path} in it's location" with pytest.raises(SystemExit, match=message): backup_package_files_action._get_changed_package_files() @@ -316,8 +313,8 @@ 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 {}".format(path)) - except (OSError, IOError): + f.write(f"Content for testing of file {path}") + except OSError: # case with invalid filepath pass @@ -344,13 +341,13 @@ 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 {}".format(original_file_path) + assert f.read() == f"Content for testing of file {original_file_path}" # Remove the original file try: os.remove(original_file_path) removed_paths.append(original_file_path) # FileNotFound on Python 3+, due compatibility with Python 2.7 using OSError - except (OSError, IOError): + except OSError: # If the path is present multiple times in the 'rpm -Va' output # it's possible, the path was already removed. If not, that's fail. if original_file_path not in removed_paths: @@ -358,7 +355,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 {}".format(original_file_path)) + f.write(f"Content for testing of file {original_file_path}") else: assert not os.path.isfile(backed_up_file_path) @@ -374,7 +371,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 {}".format(original_file_path) + assert f.read() == f"Content for testing of file {original_file_path}" elif status == "missing": assert not os.path.isfile(original_file_path) @@ -449,4 +446,4 @@ def test_backup_repository_no_repofile_presence(self, tmpdir, monkeypatch, caplo backup_repository = backup_repository_action backup_repository.run() - assert ("Repository folder {} seems to be empty.".format(etc)) in caplog.text + assert (f"Repository folder {etc} seems to be empty.") in caplog.text diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/custom_repos_are_valid_test.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/custom_repos_are_valid_test.py index 1936f9e79b..1332109f73 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/custom_repos_are_valid_test.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/custom_repos_are_valid_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest 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 a8fcf23823..aaae961b10 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 @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os @@ -32,11 +31,9 @@ ) from convert2rhel.unit_tests.conftest import centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock - AMZN2_EXTRAS_REPOFILE_PATH = "/etc/yum.repos.d/amzn2-extras.repo" @@ -274,8 +271,8 @@ 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 {} 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 + assert f"Removing the following {len(pkgs_to_remove)} packages" in caplog.records[-3].message + assert f"Successfully removed {len(pkgs_to_remove)} packages" in caplog.records[-1].message @pytest.mark.parametrize("dir_exists", (True, False)) @@ -348,10 +345,7 @@ def test_cleanup_amzn2_extras_repofile_kept_when_file_owned(monkeypatch, caplog) handle_packages._cleanup_amzn2_extras_repofile() assert utils.run_subprocess.call_count == 2 - assert ( - "Keeping {} as it is still owned by amazon-linux-extras-2.0.3.".format(AMZN2_EXTRAS_REPOFILE_PATH) - in caplog.text - ) + assert f"Keeping {AMZN2_EXTRAS_REPOFILE_PATH} as it is still owned by amazon-linux-extras-2.0.3." in caplog.text remove_mock.assert_not_called() @@ -386,4 +380,4 @@ def test_cleanup_amzn2_extras_repofile_remove_failure(monkeypatch, caplog): handle_packages._cleanup_amzn2_extras_repofile() - assert "Failed to remove leftover repository file {}".format(AMZN2_EXTRAS_REPOFILE_PATH) in caplog.text + assert f"Failed to remove leftover repository file {AMZN2_EXTRAS_REPOFILE_PATH}" in caplog.text 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 e7b1cc3c7f..a7859e09ba 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 @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import re @@ -32,11 +31,9 @@ from convert2rhel.unit_tests.conftest import centos7, centos8 from convert2rhel.utils import run_subprocess - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock - MODINFO_STUB = ( "/lib/modules/5.8.0-7642-generic/kernel/lib/a.ko.xz\n" "/lib/modules/5.8.0-7642-generic/kernel/lib/b.ko.xz\n" @@ -162,7 +159,7 @@ def test_ensure_compatibility_of_kmods( ), ( HOST_MODULES_STUB_BAD, - "kernel-core-0:4.18.0-240.10.1.el8_3.x86_64\n" "kernel-core-0:4.19.0-240.10.1.el8_3.i486\n", + "kernel-core-0:4.18.0-240.10.1.el8_3.x86_64\nkernel-core-0:4.19.0-240.10.1.el8_3.i486\n", ("", 0), "CANNOT_COMPARE_PACKAGE_VERSIONS", "ERROR", diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/special_cases_test.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/special_cases_test.py index c1c8a5988d..7bbc829067 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/special_cases_test.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/special_cases_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six @@ -23,7 +22,6 @@ from convert2rhel.unit_tests import run_subprocess_side_effect from convert2rhel.unit_tests.conftest import centos8, oracle8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/subscription_test.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/subscription_test.py index 29c0072d63..0c554a308e 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/subscription_test.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/subscription_test.py @@ -13,11 +13,9 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os.path import shutil - from collections import namedtuple from functools import partial @@ -33,7 +31,6 @@ from convert2rhel.unit_tests import AutoAttachSubscriptionMocked, RefreshSubscriptionManagerMocked, RunSubprocessMocked from convert2rhel.utils import subscription as subscription_utils - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/test_yum_variables.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/test_yum_variables.py index dac6a9ddf3..d3e9dea003 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/test_yum_variables.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/test_yum_variables.py @@ -45,7 +45,7 @@ def test_get_yum_var_files_owned_by_pkgs(monkeypatch, pkg_names, owned_files, ex action = yum_variables.BackUpYumVariables() def mock_get_files_owned_by_package(pkg): - return [file for file in owned_files if "/{}_".format(pkg) in file] + return [file for file in owned_files if f"/{pkg}_" in file] monkeypatch.setattr(pkghandler, "get_files_owned_by_package", mock_get_files_owned_by_package) diff --git a/convert2rhel/unit_tests/actions/pre_ponr_changes/transaction_test.py b/convert2rhel/unit_tests/actions/pre_ponr_changes/transaction_test.py index ab22c283b9..127cf9fe34 100644 --- a/convert2rhel/unit_tests/actions/pre_ponr_changes/transaction_test.py +++ b/convert2rhel/unit_tests/actions/pre_ponr_changes/transaction_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six @@ -23,7 +22,6 @@ from convert2rhel.pkgmanager.handlers.base import TransactionHandlerBase from convert2rhel.unit_tests.conftest import all_systems - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/actions/report_test.py b/convert2rhel/unit_tests/actions/report_test.py index ac508adeef..53aad29b95 100644 --- a/convert2rhel/unit_tests/actions/report_test.py +++ b/convert2rhel/unit_tests/actions/report_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import json import os.path @@ -25,11 +24,9 @@ from convert2rhel.actions import STATUS_CODE, report from convert2rhel.logger import bcolors - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock - #: _LONG_MESSAGE since we do line wrapping _LONG_MESSAGE = { "title": "Will Robinson! Will Robinson!", @@ -1199,12 +1196,8 @@ def test_messages_summary_ordering(results, include_all_reports, expected_result }, } }, - "{begin}(ERROR) ErrorAction::ERROR - Error\n Description: Action error\n Diagnosis: User error\n Remediations: move on{end}".format( - begin=bcolors.FAIL, end=bcolors.ENDC - ), - "{begin}(WARNING) ErrorAction::WARNING_ID - Warning\n Description: Action warning\n Diagnosis: User warning\n Remediations: move on{end}".format( - begin=bcolors.WARNING, end=bcolors.ENDC - ), + f"{bcolors.FAIL}(ERROR) ErrorAction::ERROR - Error\n Description: Action error\n Diagnosis: User error\n Remediations: move on{bcolors.ENDC}", + f"{bcolors.WARNING}(WARNING) ErrorAction::WARNING_ID - Warning\n Description: Action warning\n Diagnosis: User warning\n Remediations: move on{bcolors.ENDC}", ), ( { @@ -1231,12 +1224,8 @@ def test_messages_summary_ordering(results, include_all_reports, expected_result }, } }, - "{begin}(OVERRIDABLE) OverridableAction::OVERRIDABLE - Overridable\n Description: Action overridable\n Diagnosis: User overridable\n Remediations: move on{end}".format( - begin=bcolors.FAIL, end=bcolors.ENDC - ), - "{begin}(WARNING) OverridableAction::WARNING_ID - Warning\n Description: Action warning\n Diagnosis: User warning\n Remediations: move on{end}".format( - begin=bcolors.WARNING, end=bcolors.ENDC - ), + f"{bcolors.FAIL}(OVERRIDABLE) OverridableAction::OVERRIDABLE - Overridable\n Description: Action overridable\n Diagnosis: User overridable\n Remediations: move on{bcolors.ENDC}", + f"{bcolors.WARNING}(WARNING) OverridableAction::WARNING_ID - Warning\n Description: Action warning\n Diagnosis: User warning\n Remediations: move on{bcolors.ENDC}", ), ( { @@ -1263,12 +1252,8 @@ def test_messages_summary_ordering(results, include_all_reports, expected_result }, } }, - "{begin}(SKIP) SkipAction::SKIP - Skip\n Description: Action skip\n Diagnosis: User skip\n Remediations: move on{end}".format( - begin=bcolors.FAIL, end=bcolors.ENDC - ), - "{begin}(WARNING) SkipAction::WARNING_ID - Warning\n Description: Action warning\n Diagnosis: User warning\n Remediations: move on{end}".format( - begin=bcolors.WARNING, end=bcolors.ENDC - ), + f"{bcolors.FAIL}(SKIP) SkipAction::SKIP - Skip\n Description: Action skip\n Diagnosis: User skip\n Remediations: move on{bcolors.ENDC}", + f"{bcolors.WARNING}(WARNING) SkipAction::WARNING_ID - Warning\n Description: Action warning\n Diagnosis: User warning\n Remediations: move on{bcolors.ENDC}", ), ( { @@ -1295,10 +1280,8 @@ def test_messages_summary_ordering(results, include_all_reports, expected_result }, } }, - "{begin}(SUCCESS) SuccessfulAction::SUCCESS - N/A{end}".format(begin=bcolors.OKGREEN, end=bcolors.ENDC), - "{begin}(WARNING) SuccessfulAction::WARNING_ID - Warning\n Description: Action warning\n Diagnosis: User warning\n Remediations: move on{end}".format( - begin=bcolors.WARNING, end=bcolors.ENDC - ), + f"{bcolors.OKGREEN}(SUCCESS) SuccessfulAction::SUCCESS - N/A{bcolors.ENDC}", + f"{bcolors.WARNING}(WARNING) SuccessfulAction::WARNING_ID - Warning\n Description: Action warning\n Diagnosis: User warning\n Remediations: move on{bcolors.ENDC}", ), ), ) diff --git a/convert2rhel/unit_tests/actions/system_checks/__init__.py b/convert2rhel/unit_tests/actions/system_checks/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/actions/system_checks/__init__.py +++ b/convert2rhel/unit_tests/actions/system_checks/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/actions/system_checks/check_firewalld_availability_test.py b/convert2rhel/unit_tests/actions/system_checks/check_firewalld_availability_test.py index 140c38d5fa..1e0fe9d8c9 100644 --- a/convert2rhel/unit_tests/actions/system_checks/check_firewalld_availability_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/check_firewalld_availability_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest 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 dc3b973ff7..8e7752a0fc 100644 --- a/convert2rhel/unit_tests/actions/system_checks/convert2rhel_latest_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/convert2rhel_latest_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # @@ -15,14 +14,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import pytest import six - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -158,8 +155,8 @@ def test_convert2rhel_latest_outdated_version_inhibitor( id="OUT_OF_DATE", title="Outdated convert2rhel version detected", diagnosis=( - "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) + f"You are currently running {running_version} and the latest version of convert2rhel is {latest_version}.\n" + "Only the latest version is supported for conversion." ), remediations="If you want to disregard this check, set the allow_older_version inhibitor" " override in the /etc/convert2rhel.ini config file to true.", @@ -245,10 +242,8 @@ def test_convert2rhel_latest_log_check_env( running_version, latest_version = prepare_convert2rhel_latest_action log_msg = ( - "You are currently running {} and the latest version of convert2rhel is {}.\n" - "You have set the option to allow older convert2rhel version, continuing conversion".format( - running_version, latest_version - ) + f"You are currently running {running_version} and the latest version of convert2rhel is {latest_version}.\n" + "You have set the option to allow older convert2rhel version, continuing conversion" ) assert log_msg in caplog.text @@ -489,8 +484,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 {} and the latest version of convert2rhel is {}.\n" - "Only the latest version is supported for conversion.".format(running_version, latest_version) + f"You are currently running {running_version} and the latest version of convert2rhel is {latest_version}.\n" + "Only the latest version is supported for conversion." ), remediations="If you want to disregard this check, then set the environment variable 'CONVERT2RHEL_ALLOW_OLDER_VERSION=1' to continue.", ) @@ -558,9 +553,7 @@ 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 ({}) is the latest but ignore the rpm release.".format( - running_version - ) + f" We will check that the version of convert2rhel ({running_version}) is the latest but ignore the rpm release." ) assert log_msg in caplog.text @@ -626,9 +619,7 @@ 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 ({}) is the latest but ignore the rpm release.".format( - running_version - ) + log_msg = f"Couldn't determine the rpm release; We will check that the version of convert2rhel ({running_version}) is the latest but ignore the rpm release." assert log_msg in caplog.text @@ -675,8 +666,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 {} and the latest version of convert2rhel is {}.\n" - "Only the latest version is supported for conversion.".format(running_version, latest_version) + f"You are currently running {running_version} and the latest version of convert2rhel is {latest_version}.\n" + "Only the latest version is supported for conversion." ), remediations="If you want to disregard this check, set the allow_older_version inhibitor" " override in the /etc/convert2rhel.ini config file to true.", diff --git a/convert2rhel/unit_tests/actions/system_checks/dbus_test.py b/convert2rhel/unit_tests/actions/system_checks/dbus_test.py index 390f7a0223..b59ffea525 100644 --- a/convert2rhel/unit_tests/actions/system_checks/dbus_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/dbus_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest 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 7c2734a129..370d2a3dc3 100644 --- a/convert2rhel/unit_tests/actions/system_checks/duplicate_packages_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/duplicate_packages_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import pytest diff --git a/convert2rhel/unit_tests/actions/system_checks/efi_test.py b/convert2rhel/unit_tests/actions/system_checks/efi_test.py index de13ac77ed..88dad7bc10 100644 --- a/convert2rhel/unit_tests/actions/system_checks/efi_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/efi_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # @@ -15,21 +14,17 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os - from collections import namedtuple import pytest - from six.moves import mock from convert2rhel import actions, grub, systeminfo, unit_tests from convert2rhel.actions.system_checks import efi from convert2rhel.unit_tests import EFIBootInfoMocked - ExpectedMessage = namedtuple("ExpectedMessage", ("id", "title", "description", "diagnosis", "remediations", "log_msg")) diff --git a/convert2rhel/unit_tests/actions/system_checks/els_test.py b/convert2rhel/unit_tests/actions/system_checks/els_test.py index 1ee0f2e48d..3aceebbae9 100644 --- a/convert2rhel/unit_tests/actions/system_checks/els_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/els_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import datetime diff --git a/convert2rhel/unit_tests/actions/system_checks/eus_test.py b/convert2rhel/unit_tests/actions/system_checks/eus_test.py index 0f13be28d4..3de8c4c2d8 100644 --- a/convert2rhel/unit_tests/actions/system_checks/eus_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/eus_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import datetime diff --git a/convert2rhel/unit_tests/actions/system_checks/grub_validity_test.py b/convert2rhel/unit_tests/actions/system_checks/grub_validity_test.py index afb34337c3..ac6015bb64 100644 --- a/convert2rhel/unit_tests/actions/system_checks/grub_validity_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/grub_validity_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import pytest 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 b6f8d2f627..8011f91569 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 @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -15,10 +14,8 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os - from collections import namedtuple import pytest @@ -30,7 +27,6 @@ from convert2rhel.unit_tests.conftest import centos7, centos8, oracle8 from convert2rhel.utils import run_subprocess - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/actions/system_checks/package_updates_test.py b/convert2rhel/unit_tests/actions/system_checks/package_updates_test.py index 16e829946b..b2f17649cc 100644 --- a/convert2rhel/unit_tests/actions/system_checks/package_updates_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/package_updates_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import pytest import six @@ -25,7 +22,6 @@ from convert2rhel.actions.system_checks import package_updates from convert2rhel.unit_tests.conftest import centos8, oracle8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -64,7 +60,7 @@ def test_check_package_updates_skip_on_not_latest_ol(pretend_os, caplog, package @centos8 def test_check_package_updates(pretend_os, monkeypatch, caplog, package_updates_action, global_tool_opts): - monkeypatch.setattr(package_updates, "get_total_packages_to_update", value=lambda: []) + monkeypatch.setattr(package_updates, "get_total_packages_to_update", value=list) package_updates_action.run() assert "System is up-to-date." in caplog.records[-1].message diff --git a/convert2rhel/unit_tests/actions/system_checks/readonly_mounts_test.py b/convert2rhel/unit_tests/actions/system_checks/readonly_mounts_test.py index 950c504c48..dacd83c786 100644 --- a/convert2rhel/unit_tests/actions/system_checks/readonly_mounts_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/readonly_mounts_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # @@ -15,17 +14,14 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import six from convert2rhel import unit_tests from convert2rhel.actions.system_checks import readonly_mounts - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) import pytest - from six.moves import mock 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 42e239dc8e..9fb28dd9b0 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 @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from collections import namedtuple @@ -32,7 +30,6 @@ from convert2rhel.unit_tests import RunSubprocessMocked, create_pkg_information from convert2rhel.unit_tests.conftest import centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -83,16 +80,14 @@ def test_check_rhel_compatible_kernel_failure( description="Please refer to the diagnosis for further information", diagnosis="The booted kernel version is incompatible with the standard RHEL kernel", remediations=( - "To proceed with the conversion, boot into a kernel that is available in the {0} {1} base repository" + f"To proceed with the conversion, boot into a kernel that is available in the {rhel_compatible_kernel.system_info.name} {rhel_compatible_kernel.system_info.version.major} base repository" " by executing the following steps:\n\n" - "1. Ensure that the {0} {1} base repository is enabled\n" + f"1. Ensure that the {rhel_compatible_kernel.system_info.name} {rhel_compatible_kernel.system_info.version.major} base repository is enabled\n" "2. Run: yum install kernel\n" "3. (optional) Run: grubby --set-default " - '/boot/vmlinuz-`rpm -q --qf "%{{BUILDTIME}}\\t%{{EVR}}.%{{ARCH}}\\n" kernel | sort -nr | head -1 | cut -f2`\n' + '/boot/vmlinuz-`rpm -q --qf "%{BUILDTIME}\\t%{EVR}.%{ARCH}\\n" kernel | sort -nr | head -1 | cut -f2`\n' "4. Reboot the machine and if step 3 was not applied choose the kernel" - " installed in step 2 manually".format( - rhel_compatible_kernel.system_info.name, rhel_compatible_kernel.system_info.version.major - ) + " installed in step 2 manually" ), ) @@ -295,7 +290,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-{}".format(kernel_release)], + ["rpm", "-qf", "--qf", "%{NEVRA}", f"/boot/vmlinuz-{kernel_release}"], print_output=False, ) @@ -349,7 +344,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-{}".format(kernel_release)], + ["rpm", "-qf", "--qf", "%{NEVRA}", f"/boot/vmlinuz-{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 3bc26a10c3..fbe045b813 100644 --- a/convert2rhel/unit_tests/actions/system_checks/tainted_kmods_test.py +++ b/convert2rhel/unit_tests/actions/system_checks/tainted_kmods_test.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os @@ -28,7 +27,6 @@ LINK_TAINTED_KMOD_DOCS, ) - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -75,18 +73,16 @@ 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{}\n".format(LINK_KMODS_RH_POLICY) + f" policy:\n{LINK_KMODS_RH_POLICY}\n" ), remediations=( - "Prevent the modules from loading by following {0}" + f"Prevent the modules from loading by following {LINK_PREVENT_KMODS_FROM_LOADING}" " and run convert2rhel again to continue with the conversion." " Although it is not recommended, you can disregard this message by setting the" " tainted_kernel_module_check_skip inhibitor override in the /etc/convert2rhel.ini" " config file to true. Overriding this check can be dangerous" " so it is recommended that you do a system backup beforehand." - " For information on what a tainted kernel module is, please refer to this documentation {1}".format( - LINK_PREVENT_KMODS_FROM_LOADING, LINK_TAINTED_KMOD_DOCS - ) + f" For information on what a tainted kernel module is, please refer to this documentation {LINK_TAINTED_KMOD_DOCS}" ), ) @@ -132,14 +128,12 @@ 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{}\n".format(LINK_KMODS_RH_POLICY) + f" policy:\n{LINK_KMODS_RH_POLICY}\n" ), remediations=( - "Prevent the modules from loading by following {0}" + f"Prevent the modules from loading by following {LINK_PREVENT_KMODS_FROM_LOADING}" " and run convert2rhel again to continue with the conversion." - " For information on what a tainted kernel module is, please refer to this documentation {1}".format( - LINK_PREVENT_KMODS_FROM_LOADING, LINK_TAINTED_KMOD_DOCS - ) + f" For information on what a tainted kernel module is, please refer to this documentation {LINK_TAINTED_KMOD_DOCS}" ), ), actions.ActionMessage( diff --git a/convert2rhel/unit_tests/applock_test.py b/convert2rhel/unit_tests/applock_test.py index 2898ba6ee3..b69ee8d11f 100644 --- a/convert2rhel/unit_tests/applock_test.py +++ b/convert2rhel/unit_tests/applock_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2023 Red Hat, Inc. # @@ -14,7 +13,6 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import subprocess diff --git a/convert2rhel/unit_tests/backup/backup_test.py b/convert2rhel/unit_tests/backup/backup_test.py index 047735518b..89b17993a7 100644 --- a/convert2rhel/unit_tests/backup/backup_test.py +++ b/convert2rhel/unit_tests/backup/backup_test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - import hashlib import pytest @@ -155,6 +153,6 @@ def test_get_backed_up_yum_var_dirs(monkeypatch): result = backup.get_backed_up_yum_var_dirs() assert result == { - "/etc/yum/vars": "/var/lib/convert2rhel/backup/{}".format(hashlib.md5("/etc/yum/vars".encode()).hexdigest()), - "/etc/dnf/vars": "/var/lib/convert2rhel/backup/{}".format(hashlib.md5("/etc/dnf/vars".encode()).hexdigest()), + "/etc/yum/vars": "/var/lib/convert2rhel/backup/{}".format(hashlib.md5(b"/etc/yum/vars").hexdigest()), + "/etc/dnf/vars": "/var/lib/convert2rhel/backup/{}".format(hashlib.md5(b"/etc/dnf/vars").hexdigest()), } diff --git a/convert2rhel/unit_tests/backup/certs_test.py b/convert2rhel/unit_tests/backup/certs_test.py index a575ab5e0f..96079678ec 100644 --- a/convert2rhel/unit_tests/backup/certs_test.py +++ b/convert2rhel/unit_tests/backup/certs_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,13 +14,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import shutil import pytest - from six.moves import mock from convert2rhel import exceptions, unit_tests, utils @@ -31,7 +28,6 @@ from convert2rhel.unit_tests import RunSubprocessMocked from convert2rhel.utils import files - # Directory with all the tool data BASE_DATA_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), "../../data/")) @@ -46,7 +42,7 @@ class RunSubprocessWithEmptyRpmdb(RunSubprocessMocked): def __call__(self, *args, **kwargs): # Call the super class for recordkeeping (update how we were # called) - super(RunSubprocessWithEmptyRpmdb, self).__call__(*args, **kwargs) + super().__call__(*args, **kwargs) if args[0][0] == "rpm": args[0].extend(["--dbpath", rpmdb]) @@ -199,7 +195,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 {}. Skipping copy.".format(system_cert_with_target_path._target_cert_path) + f"Certificate already present at {system_cert_with_target_path._target_cert_path}. Skipping copy." == caplog.messages[-1] ) @@ -222,7 +218,7 @@ def test_restore_cert(self, caplog, monkeypatch, system_cert_with_target_path): system_cert_with_target_path.restore() - assert "Certificate {} removed".format(system_cert_with_target_path._target_cert_path) in caplog.messages[-1] + assert f"Certificate {system_cert_with_target_path._target_cert_path} removed" 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,9 +227,7 @@ def test_restore_cert_previously_installed(self, caplog, monkeypatch, system_cer system_cert_with_target_path.restore() assert ( - "Certificate {} was present before conversion. Skipping removal.".format( - system_cert_with_target_path._cert_filename - ) + f"Certificate {system_cert_with_target_path._cert_filename} was present before conversion. Skipping removal." in caplog.messages[-1] ) diff --git a/convert2rhel/unit_tests/backup/files_test.py b/convert2rhel/unit_tests/backup/files_test.py index 65dc64c7e8..195822ad2d 100644 --- a/convert2rhel/unit_tests/backup/files_test.py +++ b/convert2rhel/unit_tests/backup/files_test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - import hashlib import os @@ -294,7 +292,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 = "{}/{}/{}".format(backup_dir, hashlib.md5(path.encode()).hexdigest(), name) + expected = f"{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 13c1779b08..1d1772f40c 100644 --- a/convert2rhel/unit_tests/backup/packages_test.py +++ b/convert2rhel/unit_tests/backup/packages_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os @@ -35,7 +33,6 @@ ) from convert2rhel.unit_tests.conftest import centos7 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -57,7 +54,7 @@ def __init__(self, destdir=None, **kwargs): if "return_value" not in kwargs: kwargs["return_value"] = ["/path/to.rpm"] - super(DownloadPkgsMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, pkgs, dest, *args, **kwargs): self.pkgs = pkgs @@ -67,7 +64,7 @@ def __call__(self, pkgs, dest, *args, **kwargs): if self.destdir and not os.path.exists(self.destdir): os.mkdir(self.destdir, 0o700) - return super(DownloadPkgsMocked, self).__call__(pkgs, dest, *args, **kwargs) + return super().__call__(pkgs, dest, *args, **kwargs) class TestRestorablePackage: @@ -173,7 +170,7 @@ def test_restorable_package_backup_without_dir(self, monkeypatch, tmpdir, caplog rp = RestorablePackage(pkgs=["pkg-1"]) rp.enable() - assert "Can't access {}".format(backup_dir) in caplog.records[-1].message + assert f"Can't access {backup_dir}" in caplog.records[-1].message def test_install_local_rpms_package_install_warning(self, monkeypatch, caplog): pkg_name = "pkg-1" @@ -190,7 +187,7 @@ def test_install_local_rpms_package_install_warning(self, monkeypatch, caplog): assert not result assert run_subprocess_mock.call_count == 1 - assert "Couldn't install {} packages.".format(pkg_name) in caplog.records[-1].message + assert f"Couldn't install {pkg_name} packages." in caplog.records[-1].message def test_test_install_local_rpms_system_exit(self, monkeypatch, caplog): pkg_name = ["pkg-1"] diff --git a/convert2rhel/unit_tests/backup/subscription_test.py b/convert2rhel/unit_tests/backup/subscription_test.py index 42ec3bcd40..4fb0c5bbbe 100644 --- a/convert2rhel/unit_tests/backup/subscription_test.py +++ b/convert2rhel/unit_tests/backup/subscription_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import errno @@ -28,7 +26,6 @@ RestorableSystemSubscription, ) - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/breadcrumbs_test.py b/convert2rhel/unit_tests/breadcrumbs_test.py index 653574e88f..b64fb02a5f 100644 --- a/convert2rhel/unit_tests/breadcrumbs_test.py +++ b/convert2rhel/unit_tests/breadcrumbs_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2021 Red Hat, Inc. # @@ -15,19 +14,16 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import json import pytest import six - from convert2rhel import breadcrumbs, pkghandler, pkgmanager from convert2rhel.unit_tests import create_pkg_information, create_pkg_obj from convert2rhel.unit_tests.conftest import centos7 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -241,18 +237,18 @@ def test_save_rhsm_facts(pretend_os, monkeypatch, tmpdir, caplog): ) breadcrumbs.breadcrumbs._save_rhsm_facts() - assert "Writing RHSM custom facts to '{}'".format(rhsm_file) in caplog.records[-1].message + assert f"Writing RHSM custom facts to '{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 = "{}/convert2rhel.facts".format(rhsm_folder) + rhsm_file = f"{rhsm_folder}/convert2rhel.facts" 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 '{}'.".format(rhsm_folder) in caplog.records[-2].message - assert "Writing RHSM custom facts to '{}'".format(rhsm_file) in caplog.records[-1].message + assert f"No RHSM facts folder found at '{rhsm_folder}'." in caplog.records[-2].message + assert f"Writing RHSM custom facts to '{rhsm_file}'" in caplog.records[-1].message def test_save_migration_results(tmpdir, monkeypatch, caplog): @@ -263,7 +259,7 @@ def test_save_migration_results(tmpdir, monkeypatch, caplog): breadcrumbs.breadcrumbs._save_migration_results() - assert "Writing breadcrumbs to '{}'.".format(migration_results) in caplog.records[-1].message + assert f"Writing breadcrumbs to '{migration_results}'." in caplog.records[-1].message assert write_obj_to_array_json_mock.call_count == 1 diff --git a/convert2rhel/unit_tests/checks_test.py b/convert2rhel/unit_tests/checks_test.py index 074be28400..ff5e2d2933 100644 --- a/convert2rhel/unit_tests/checks_test.py +++ b/convert2rhel/unit_tests/checks_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # @@ -14,7 +13,6 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os @@ -45,7 +43,7 @@ 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: {}".format(subprocess_output[0]) in caplog.records[-1].message + assert f"Output of lsinitrd: {subprocess_output[0]}" in caplog.records[-1].message def test_is_initramfs_file_valid_unicodedecodeerror(monkeypatch): diff --git a/convert2rhel/unit_tests/cli_test.py b/convert2rhel/unit_tests/cli_test.py index 8f15676cad..cc34b13dce 100644 --- a/convert2rhel/unit_tests/cli_test.py +++ b/convert2rhel/unit_tests/cli_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import sys @@ -25,7 +23,6 @@ from convert2rhel import cli, toolopts - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -122,7 +119,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: {}\nError: ".format(serverurl) + f"Supplied serverurl: {serverurl}\nError: " ) assert message in caplog.records[-1].message assert caplog.records[-1].levelname == "CRITICAL" @@ -143,8 +140,7 @@ def test_serverurl_with_no_rhsm_credentials(self, caplog, monkeypatch): cli.CLI() message = ( - "Ignoring the --serverurl option. It has no effect when no credentials to" - " subscribe the system were given." + "Ignoring the --serverurl option. It has no effect when no credentials to subscribe the system were given." ) assert message in caplog.text diff --git a/convert2rhel/unit_tests/conftest.py b/convert2rhel/unit_tests/conftest.py index daf0cc9161..0641561225 100644 --- a/convert2rhel/unit_tests/conftest.py +++ b/convert2rhel/unit_tests/conftest.py @@ -1,5 +1,3 @@ -__metaclass__ = type - import logging import os import sys @@ -13,11 +11,9 @@ from convert2rhel.systeminfo import system_info from convert2rhel.unit_tests import MinimalRestorable - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock - # We are injecting a instance of `mock.Mock()` for `Depsolve` class and # `callback` module, as when we run the tests under CentOS 7, it fails by saying # that `pkgmanager.callback.Depsolve` can't be imported as it is an import from @@ -246,7 +242,7 @@ def pretend_os(request, pkg_root, monkeypatch, global_tool_opts): monkeypatch.setattr( utils, "DATA_DIR", - value=str(pkg_root / ("convert2rhel/data/{}/x86_64/".format(system_version_major))), + value=str(pkg_root / (f"convert2rhel/data/{system_version_major}/x86_64/")), ) monkeypatch.setattr( redhatrelease, @@ -256,7 +252,7 @@ def pretend_os(request, pkg_root, monkeypatch, global_tool_opts): monkeypatch.setattr( utils, "get_file_content", - value=lambda _: "{} release {}".format(system_name, system_version), + value=lambda _: f"{system_name} release {system_version}", ) monkeypatch.setattr( system_info, diff --git a/convert2rhel/unit_tests/example_test.py b/convert2rhel/unit_tests/example_test.py index 59d8edc99c..af414943cc 100644 --- a/convert2rhel/unit_tests/example_test.py +++ b/convert2rhel/unit_tests/example_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type """ This is an example test file containing a simple test. @@ -25,7 +23,6 @@ from convert2rhel import unit_tests, utils - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -57,7 +54,7 @@ def __init__(self, ret=("Test", 0), **kwargs): self.prefix = "this ain't " self.ret = ret - super(RunSubprocessMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, *args, **kwargs): """ @@ -73,7 +70,7 @@ def __call__(self, *args, **kwargs): or `side_effect` in `__init__` and returning the results of the superclass's `__call__` method here. """ - super(RunSubprocessMocked, self).__call__(*args, **kwargs) + super().__call__(*args, **kwargs) self.ret = (self.prefix + self.ret[0], self.ret[1]) return self.ret diff --git a/convert2rhel/unit_tests/grub_test.py b/convert2rhel/unit_tests/grub_test.py index 76cf297446..95a05177c5 100644 --- a/convert2rhel/unit_tests/grub_test.py +++ b/convert2rhel/unit_tests/grub_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2021 Red Hat, Inc. # @@ -15,11 +14,9 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import copy import os - from collections import namedtuple import pytest @@ -28,11 +25,9 @@ from convert2rhel import grub, utils from convert2rhel.unit_tests import EFIBootInfoMocked, RunSubprocessMocked - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock - # TODO(pstodulk): put here a real examples of an output.. _SEC_STDOUT_ENABLED = "secure boot enabled" _SEC_STDOUT_DISABLED = "e.g. nothing..." @@ -98,7 +93,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 {}. Output:\n{}".format(subproc[1], subproc[0]) in caplog.records[-1].message + assert f"grub2-probe returned {subproc[1]}. Output:\n{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/initialize_test.py b/convert2rhel/unit_tests/initialize_test.py index 6b0c6fa621..6016062958 100644 --- a/convert2rhel/unit_tests/initialize_test.py +++ b/convert2rhel/unit_tests/initialize_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -15,15 +14,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six -from convert2rhel import applock, initialize +from convert2rhel import applock, initialize, main from convert2rhel import logger as logger_module -from convert2rhel import main - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/logger_test.py b/convert2rhel/unit_tests/logger_test.py index ed7d536312..b86a63170b 100644 --- a/convert2rhel/unit_tests/logger_test.py +++ b/convert2rhel/unit_tests/logger_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging import os diff --git a/convert2rhel/unit_tests/main_test.py b/convert2rhel/unit_tests/main_test.py index 996ce31ee3..2b190de11c 100644 --- a/convert2rhel/unit_tests/main_test.py +++ b/convert2rhel/unit_tests/main_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import sys @@ -23,13 +21,23 @@ import pytest import six - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock -from convert2rhel import actions, applock, backup, cli, exceptions +from convert2rhel import ( + actions, + applock, + backup, + cli, + exceptions, + main, + pkghandler, + pkgmanager, + subscription, + toolopts, + utils, +) from convert2rhel import logger as logger_module -from convert2rhel import main, pkghandler, pkgmanager, subscription, toolopts, utils from convert2rhel.actions import report from convert2rhel.breadcrumbs import breadcrumbs from convert2rhel.systeminfo import system_info diff --git a/convert2rhel/unit_tests/other_test.py b/convert2rhel/unit_tests/other_test.py index 6b27001216..e575017e3b 100644 --- a/convert2rhel/unit_tests/other_test.py +++ b/convert2rhel/unit_tests/other_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,13 +14,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import re from convert2rhel import __version__, logger, pkghandler, utils - RPM_SPEC_VERSION_RE = re.compile(r"^Version: +(.+)$") diff --git a/convert2rhel/unit_tests/pkghandler_test.py b/convert2rhel/unit_tests/pkghandler_test.py index cb3f130b62..afef4d12b4 100644 --- a/convert2rhel/unit_tests/pkghandler_test.py +++ b/convert2rhel/unit_tests/pkghandler_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -14,13 +13,11 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import glob import os import re - from collections import namedtuple import pytest @@ -55,11 +52,9 @@ ) from convert2rhel.unit_tests.conftest import all_systems, centos7, centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock - YUM_KERNEL_LIST_OLDER_AVAILABLE = """Installed Packages kernel.x86_64 4.7.4-200.fc24 @updates Available Packages @@ -131,7 +126,7 @@ class ReturnPackagesObject(unit_tests.MockFunctionObject): """ def __call__(self, *args, **kwargs): - super(ReturnPackagesObject, self).__call__(*args, **kwargs) + super().__call__(*args, **kwargs) patterns = kwargs.get("patterns", None) if patterns: @@ -347,7 +342,7 @@ def test_replace_non_rhel_installed_kernel_rhsm_repos(self, monkeypatch): "--force", "--nodeps", "--replacepkgs", - "{}kernel-4.7.4-200.fc24*".format(utils.TMP_DIR), + f"{utils.TMP_DIR}kernel-4.7.4-200.fc24*", ] def test_replace_non_rhel_installed_kernel_custom_repos(self, monkeypatch, global_tool_opts): @@ -755,13 +750,13 @@ def test_get_total_packages_to_update( if package_manager_type == "dnf": monkeypatch.setattr( pkghandler, - "_get_packages_to_update_{}".format(package_manager_type), + f"_get_packages_to_update_{package_manager_type}", value=lambda disable_repos: packages, ) else: monkeypatch.setattr( pkghandler, - "_get_packages_to_update_{}".format(package_manager_type), + f"_get_packages_to_update_{package_manager_type}", value=lambda disable_repos: packages, ) assert get_total_packages_to_update() == expected diff --git a/convert2rhel/unit_tests/pkgmanager/__init__.py b/convert2rhel/unit_tests/pkgmanager/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/pkgmanager/__init__.py +++ b/convert2rhel/unit_tests/pkgmanager/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/__init__.py b/convert2rhel/unit_tests/pkgmanager/handlers/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/__init__.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/dnf/__init__.py b/convert2rhel/unit_tests/pkgmanager/handlers/dnf/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/dnf/__init__.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/dnf/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/dnf/callback_test.py b/convert2rhel/unit_tests/pkgmanager/handlers/dnf/callback_test.py index 580678312d..4bbddf730f 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/dnf/callback_test.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/dnf/callback_test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - import pytest from convert2rhel import pkgmanager diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/dnf/dnf_test.py b/convert2rhel/unit_tests/pkgmanager/handlers/dnf/dnf_test.py index ceae3ac05d..d137ad09ab 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/dnf/dnf_test.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/dnf/dnf_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -14,7 +13,6 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six @@ -26,7 +24,6 @@ from convert2rhel.unit_tests import create_pkg_information from convert2rhel.unit_tests.conftest import centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/yum/__init__.py b/convert2rhel/unit_tests/pkgmanager/handlers/yum/__init__.py index c819e1d788..e69de29bb2 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/yum/__init__.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/yum/__init__.py @@ -1 +0,0 @@ -__metaclass__ = type diff --git a/convert2rhel/unit_tests/pkgmanager/handlers/yum/callback_test.py b/convert2rhel/unit_tests/pkgmanager/handlers/yum/callback_test.py index f56fa046e8..c16dc05891 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/yum/callback_test.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/yum/callback_test.py @@ -1,5 +1,3 @@ -__metaclass__ = type - import pytest from convert2rhel import pkgmanager @@ -77,7 +75,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: {} [1/1]".format(package) in caplog.records[-1].message + assert f"Installing: {package} [1/1]" 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 228f78470c..1c23beae1f 100644 --- a/convert2rhel/unit_tests/pkgmanager/handlers/yum/yum_test.py +++ b/convert2rhel/unit_tests/pkgmanager/handlers/yum/yum_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -14,7 +13,6 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import hashlib import os @@ -22,7 +20,6 @@ import pytest import six - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -33,7 +30,6 @@ from convert2rhel.unit_tests import RemovePkgsMocked, create_pkg_information, mock_decorator from convert2rhel.unit_tests.conftest import centos7 - SYSTEM_PACKAGES = [ create_pkg_information( packager="test", diff --git a/convert2rhel/unit_tests/pkgmanager/pkgmanager_test.py b/convert2rhel/unit_tests/pkgmanager/pkgmanager_test.py index 59be94da0a..42d620eadd 100644 --- a/convert2rhel/unit_tests/pkgmanager/pkgmanager_test.py +++ b/convert2rhel/unit_tests/pkgmanager/pkgmanager_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2022 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six @@ -25,7 +23,6 @@ from convert2rhel.unit_tests import RunSubprocessMocked, run_subprocess_side_effect from convert2rhel.unit_tests.conftest import centos7, centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -264,7 +261,7 @@ def test_call_yum_cmd_setopts_override(self, setopts, pretend_os, monkeypatch, c ] for setopt in setopts: - expected_cmd.append("--setopt={}".format(setopt)) + expected_cmd.append(f"--setopt={setopt}") expected_cmd.append("pkg") assert utils.run_subprocess.cmd == expected_cmd diff --git a/convert2rhel/unit_tests/redhatrelease_test.py b/convert2rhel/unit_tests/redhatrelease_test.py index f47ede87e3..1b07097e7b 100644 --- a/convert2rhel/unit_tests/redhatrelease_test.py +++ b/convert2rhel/unit_tests/redhatrelease_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,24 +14,26 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import pytest import six - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock -from convert2rhel import unit_tests # Imports unit_tests/__init__.py -from convert2rhel import pkgmanager, redhatrelease, systeminfo, utils +from convert2rhel import ( + pkgmanager, + redhatrelease, + systeminfo, + unit_tests, # Imports unit_tests/__init__.py + utils, +) from convert2rhel.redhatrelease import PkgManagerConf, get_system_release_filepath from convert2rhel.systeminfo import system_info - PKG_MANAGER_CONF_WITHOUT_DISTROVERPKG = """[main] installonly_limit=3 diff --git a/convert2rhel/unit_tests/repo_test.py b/convert2rhel/unit_tests/repo_test.py index 192282b4e1..fcd5b19060 100644 --- a/convert2rhel/unit_tests/repo_test.py +++ b/convert2rhel/unit_tests/repo_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,17 +14,15 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os import pytest +from six.moves import mock, urllib from convert2rhel import exceptions, repo from convert2rhel.unit_tests.conftest import centos7, centos8 -from six.moves import mock, urllib - @pytest.mark.parametrize( ("is_eus_release", "expected"), diff --git a/convert2rhel/unit_tests/subscription_test.py b/convert2rhel/unit_tests/subscription_test.py index 56bbaa6225..5f380a0231 100644 --- a/convert2rhel/unit_tests/subscription_test.py +++ b/convert2rhel/unit_tests/subscription_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,11 +14,9 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import json import os - from collections import namedtuple import dbus @@ -41,7 +38,6 @@ ) from convert2rhel.unit_tests.conftest import centos7, centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -802,9 +798,7 @@ def test_registration_succeeds_but_dbus_returns_noreply(self, monkeypatch, mocke utils, "run_subprocess", RunSubprocessMocked( - return_string=( - "system identity: 1234-56-78-9abc\n" "name: abc-123\n" "org name: Test\n" "org ID: 12345678910\n" - ) + return_string=("system identity: 1234-56-78-9abc\nname: abc-123\norg name: Test\norg ID: 12345678910\n") ), ) @@ -892,7 +886,7 @@ def test_unregister_system_failure(self, output, ret_code, expected, monkeypatch with pytest.raises( subscription.UnregisterError, - match="System unregistration result:\n{}".format(output), + match=f"System unregistration result:\n{output}", ): subscription.unregister_system() @@ -1000,7 +994,7 @@ def test_enable_repos_rhel_repoids( monkeypatch.setattr(subscription, "system_info", global_system_info) cmd_mock = ["subscription-manager", "repos"] for repo_to_enable in rhel_repoids: - cmd_mock.append("--enable={}".format(repo_to_enable)) + cmd_mock.append(f"--enable={repo_to_enable}") run_subprocess_mock = RunSubprocessMocked( side_effect=unit_tests.run_subprocess_side_effect( @@ -1064,7 +1058,7 @@ def test_enable_repos_toolopts_enablerepo( monkeypatch.setattr(subscription, "system_info", global_system_info) cmd_mock = ["subscription-manager", "repos"] for repo_to_enable in toolopts_enablerepo: - cmd_mock.append("--enable={}".format(repo_to_enable)) + cmd_mock.append(f"--enable={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 d8433816f9..e83340be4d 100644 --- a/convert2rhel/unit_tests/systeminfo_test.py +++ b/convert2rhel/unit_tests/systeminfo_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging import os @@ -29,7 +27,6 @@ from convert2rhel.unit_tests import RunSubprocessMocked from convert2rhel.unit_tests.conftest import all_systems, centos8 - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -161,7 +158,7 @@ def test_get_dbus_status_in_progress(monkeypatch, states, expected): side_effects = [] for state in states: - side_effects.append(("ActiveState={}\n".format(state), 0)) + side_effects.append((f"ActiveState={state}\n", 0)) run_subprocess_mocked = RunSubprocessMocked(side_effect=side_effects) monkeypatch.setattr(utils, "run_subprocess", run_subprocess_mocked) diff --git a/convert2rhel/unit_tests/toolopts/config_test.py b/convert2rhel/unit_tests/toolopts/config_test.py index 5762669014..667f914e00 100644 --- a/convert2rhel/unit_tests/toolopts/config_test.py +++ b/convert2rhel/unit_tests/toolopts/config_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import os diff --git a/convert2rhel/unit_tests/toolopts/toolopts_test.py b/convert2rhel/unit_tests/toolopts/toolopts_test.py index 95414eb614..9a56095646 100644 --- a/convert2rhel/unit_tests/toolopts/toolopts_test.py +++ b/convert2rhel/unit_tests/toolopts/toolopts_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,14 +14,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import pytest import six from convert2rhel import toolopts - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock diff --git a/convert2rhel/unit_tests/utils/subscription_test.py b/convert2rhel/unit_tests/utils/subscription_test.py index f51d685c51..ef5acdb2c9 100644 --- a/convert2rhel/unit_tests/utils/subscription_test.py +++ b/convert2rhel/unit_tests/utils/subscription_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type from collections import namedtuple @@ -23,7 +21,6 @@ from convert2rhel.utils import subscription - UrlParts = namedtuple("UrlParts", ("scheme", "hostname", "port")) diff --git a/convert2rhel/unit_tests/utils/utils_test.py b/convert2rhel/unit_tests/utils/utils_test.py index 559b86892c..6e751ca460 100644 --- a/convert2rhel/unit_tests/utils/utils_test.py +++ b/convert2rhel/unit_tests/utils/utils_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import getpass import json @@ -24,7 +22,6 @@ import re import shutil import sys - from pickle import PicklingError import pexpect @@ -33,7 +30,6 @@ from convert2rhel.utils import prompt_user - six.add_move(six.MovedModule("mock", "mock", "unittest.mock")) from six.moves import mock @@ -42,22 +38,21 @@ from convert2rhel.systeminfo import system_info from convert2rhel.unit_tests import RunCmdInPtyMocked, RunSubprocessMocked, conftest, is_rpm_based_os - DOWNLOADED_RPM_NVRA = "kernel-4.18.0-193.28.1.el8_2.x86_64" -DOWNLOADED_RPM_NEVRA = "7:{}".format(DOWNLOADED_RPM_NVRA) -DOWNLOADED_RPM_FILENAME = "{}.rpm".format(DOWNLOADED_RPM_NVRA) +DOWNLOADED_RPM_NEVRA = f"7:{DOWNLOADED_RPM_NVRA}" +DOWNLOADED_RPM_FILENAME = f"{DOWNLOADED_RPM_NVRA}.rpm" YUMDOWNLOADER_OUTPUTS = ( - "{0} 97% [================================================- ] 6.8 MB/s | 21 MB 00:00:00 ETA\n" + f"{DOWNLOADED_RPM_FILENAME} 97% [================================================- ] 6.8 MB/s | 21 MB 00:00:00 ETA\n" "rpmdb time: 0.000\n" - "{0} | 21 MB 00:00:01\n" - "== Rebuilding _local repo. with 1 new packages ==".format(DOWNLOADED_RPM_FILENAME), + f"{DOWNLOADED_RPM_FILENAME} | 21 MB 00:00:01\n" + "== Rebuilding _local repo. with 1 new packages ==", "Last metadata expiration check: 2:47:36 ago on Thu 22 Oct 2020 06:07:08 PM CEST.\n" - "{} 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), + f"{DOWNLOADED_RPM_FILENAME} 2.7 MB/s | 2.8 MB 00:01", + f"/var/lib/convert2rhel/{DOWNLOADED_RPM_FILENAME} already exists and appears to be complete", + f"rpmdb time: 0.000\nusing local copy of {DOWNLOADED_RPM_NEVRA}", + f"rpmdb time: 0.000\nusing local copy of {DOWNLOADED_RPM_NEVRA}\r\n", + f"[SKIPPED] {DOWNLOADED_RPM_FILENAME}: Already downloaded", ) @@ -66,21 +61,21 @@ class GetEUIDMocked(unit_tests.MockFunctionObject): def __init__(self, uid, **kwargs): self.uid = uid - super(GetEUIDMocked, self).__init__(**kwargs) + super().__init__(**kwargs) def __call__(self, *args, **kwargs): - super(GetEUIDMocked, self).__call__(*args, **kwargs) + super().__call__(*args, **kwargs) return self.uid class FakeSecondCallToRunSubprocessMocked(RunSubprocessMocked): def __init__(self, second_call_return_code, *args, **kwargs): - super(FakeSecondCallToRunSubprocessMocked, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.real_run_subprocess = utils.run_subprocess self.second_call_return_code = second_call_return_code def __call__(self, *args, **kwargs): - fake_return_val = super(FakeSecondCallToRunSubprocessMocked, self).__call__(*args, **kwargs) + fake_return_val = super().__call__(*args, **kwargs) if self.call_count == 1: # Set this so it looks like run_subprocess failed on the next call @@ -152,7 +147,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({}("Ask for password: "))'.format(prompt_cmd)], + [sys.executable, "-c", f'print({prompt_cmd}("Ask for password: "))'], expect_script=(("password: *", "Foo bar\n"),), ) @@ -397,7 +392,7 @@ def test_find_keyid_no_gpg_output(self, monkeypatch): with pytest.raises( utils.ImportGPGKeyError, - match="Unable to determine the gpg keyid for the rpm key file: {}".format(self.gpg_key), + match=f"Unable to determine the gpg keyid for the rpm key file: {self.gpg_key}", ): utils.find_keyid(self.gpg_key) @@ -499,8 +494,8 @@ def test_download_pkg_success_with_all_params(self, monkeypatch): "yumdownloader", "-v", "--setopt=exclude=", - "--destdir={}".format(dest), - "--setopt=reposdir={}".format(reposdir), + f"--destdir={dest}", + f"--setopt=reposdir={reposdir}", "--disablerepo=*", "--enablerepo=repo1", "--enablerepo=repo2", @@ -972,7 +967,7 @@ def return_with_parameter(something): @staticmethod def return_with_both_args_and_kwargs(args, kwargs): - return "{}, {}".format(args, kwargs) + return f"{args}, {kwargs}" @staticmethod def raise_bare_system_exit_exception(): diff --git a/convert2rhel/utils/__init__.py b/convert2rhel/utils/__init__.py index 12476da336..658c35e82d 100644 --- a/convert2rhel/utils/__init__.py +++ b/convert2rhel/utils/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -15,7 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import fcntl import getpass @@ -30,19 +28,16 @@ import tempfile import termios import traceback - from functools import wraps import pexpect import rpm - from six import moves from convert2rhel import exceptions, i18n from convert2rhel.logger import root_logger from convert2rhel.toolopts import tool_opts - logger = root_logger.getChild(__name__) # A string we're using to replace sensitive information (like an RHSM password) in logs, terminal output, etc. @@ -78,8 +73,6 @@ class UnableToSerialize(Exception): serialized with Pickle inside the Process subclass. """ - pass - class Process(multiprocessing.Process): """Overrides the implementation of the multiprocessing.Process class. @@ -127,7 +120,7 @@ def run(self): try: self._cconn.send(e) except pickle.PicklingError: - self._cconn.send(UnableToSerialize("Child process raised {}: {}".format(type(e), str(e)))) + self._cconn.send(UnableToSerialize(f"Child process raised {type(e)}: {e!s}")) @property def exception(self): @@ -469,7 +462,7 @@ class PexpectSpawnWithDimensions(pexpect.spawn): def __init__(self, *args, **kwargs): try: # With pexpect-2.4+, dimensions is a valid keyword arg - super(PexpectSpawnWithDimensions, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) except TypeError: # # This is a kludge to give us a dimensions kwarg on pexpect 2.3 or less. @@ -494,7 +487,7 @@ def _setwinsize(rows, cols): self.setwinsize = _setwinsize # Call pexpect.spawn.__init__() which will use the monkeypatched setwinsize() - super(PexpectSpawnWithDimensions, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Restore the real setwinsize self.setwinsize = real_setwinsize @@ -556,11 +549,11 @@ def remove_tmp_dir(): """Remove temporary folder (TMP_DIR), not needed post-conversion.""" try: shutil.rmtree(TMP_DIR) - logger.info("Temporary folder {} removed".format(TMP_DIR)) + logger.info(f"Temporary folder {TMP_DIR} removed") except OSError as err: - logger.warning("Failed removing temporary folder {}\nError ({}): {}".format(TMP_DIR, err.errno, err.strerror)) + logger.warning(f"Failed removing temporary folder {TMP_DIR}\nError ({err.errno}): {err.strerror}") except TypeError: - logger.warning("TypeError error while removing temporary folder {}".format(TMP_DIR)) + logger.warning(f"TypeError error while removing temporary folder {TMP_DIR}") class DictWListValues(dict): @@ -570,7 +563,7 @@ def __getitem__(self, item): if item not in iter(self.keys()): self[item] = [] - return super(DictWListValues, self).__getitem__(item) + return super().__getitem__(item) def download_pkgs( @@ -631,29 +624,29 @@ def download_pkg( """ from convert2rhel.systeminfo import system_info - logger.debug("Downloading the {} package.".format(pkg)) + logger.debug(f"Downloading the {pkg} package.") # On RHEL 7, it's necessary to invoke yumdownloader with -v, otherwise there's no output to stdout. - cmd = ["yumdownloader", "-v", "--setopt=exclude=", "--destdir={}".format(dest)] + cmd = ["yumdownloader", "-v", "--setopt=exclude=", f"--destdir={dest}"] if reposdir: - cmd.append("--setopt=reposdir={}".format(reposdir)) + cmd.append(f"--setopt=reposdir={reposdir}") if isinstance(disable_repos, list): for repo in disable_repos: - cmd.append("--disablerepo={}".format(repo)) + cmd.append(f"--disablerepo={repo}") if isinstance(enable_repos, list): for repo in enable_repos: - cmd.append("--enablerepo={}".format(repo)) + cmd.append(f"--enablerepo={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={}".format(custom_releasever)) + cmd.append(f"--releasever={custom_releasever}") else: - cmd.append("--releasever={}".format(system_info.releasever)) + cmd.append(f"--releasever={system_info.releasever}") if system_info.version.major >= 8: cmd.append("--setopt=module_platform_id=platform:el" + str(system_info.version.major)) @@ -670,8 +663,8 @@ def download_pkg( report_on_a_download_error(output, pkg) return None - logger.info("Successfully downloaded the {} package.".format(pkg)) - logger.debug("Path of the downloaded package: {}".format(path)) + logger.info(f"Successfully downloaded the {pkg} package.") + logger.debug(f"Path of the downloaded package: {path}") return path @@ -701,7 +694,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: {}".format(nvra)) + logger.info(f"Removing package: {nvra}") _, ret_code = run_subprocess(["rpm", "-e", "--nodeps", nvra]) if ret_code != 0: pkgs_failed_to_remove.append(nevra) @@ -711,15 +704,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 {}.".format(pkgs_as_str)) + logger.critical_no_exit(f"Error: Couldn't remove {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 {}.".format(pkgs_as_str), + diagnosis=f"Couldn't remove {pkgs_as_str}.", ) else: - logger.warning("Couldn't remove {}.".format(pkgs_as_str)) + logger.warning(f"Couldn't remove {pkgs_as_str}.") return pkgs_removed @@ -749,7 +742,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{}".format(output)) + logger.warning(f"Output from the yumdownloader call:\n{output}") # Note: Using toolopts here is a temporary solution. We need to # restructure this to raise an exception on error and have the caller @@ -781,28 +774,28 @@ def report_on_a_download_error(output, pkg): warn_deprecated_env("CONVERT2RHEL_INCOMPLETE_ROLLBACK") if not tool_opts.incomplete_rollback: logger.critical( - "Couldn't download the {} package. This means we will not be able to do a" + f"Couldn't download the {pkg} 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 {} repositories are enabled" + f"Check to make sure that the {system_info.name} repositories are enabled" " and the package is updated to its latest version.\n" "If you would rather disregard this check set the incomplete_rollback option in the" - " /etc/convert2rhel.ini config file to true.".format(pkg, system_info.name) + " /etc/convert2rhel.ini config file to true." ) else: logger.warning( - "Couldn't download the {} package. This means we will not be able to do a" + f"Couldn't download the {pkg} package. This means we will not be able to do a" " complete rollback and may put the system in a broken state.\n" "You have set the incomplete rollback inhibitor override, continuing" - " conversion.".format(pkg) + " conversion." ) else: logger.critical( - "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" + f"Couldn't download the {pkg} package which is needed to do a rollback of this action." + f" Check to make sure that the {system_info.name} 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 incomplete_rollback option in the /etc/convert2rhel.ini config file to true," - " but not during a pre-conversion analysis.".format(pkg, system_info.name) + " but not during a pre-conversion analysis." ) @@ -815,7 +808,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{}".format(cmd)) + logger.warning(f"The output of running yumdownloader is unexpectedly empty. Command:\n{cmd}") return None rpm_name_match = re.search(r"\S+\.rpm", output) @@ -828,7 +821,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{}\nOutput:\n{}".format(cmd, output) + f"Command:\n{cmd}\nOutput:\n{output}" ) return None @@ -887,7 +880,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: {}".format(output)) + raise ImportGPGKeyError(f"Failed to import the rpm gpg key into a temporary keyring: {output}") # Step 2: Print the information about the keys in the temporary keyfile. # --with-colons give us guaranteed machine parsable, stable output. @@ -905,7 +898,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: {}".format(output)) + raise ImportGPGKeyError(f"Failed to read the temporary keyring with the rpm gpg key: {output}") finally: # Try five times to work around a race condition: # @@ -915,7 +908,7 @@ def find_keyid(keyfile): # occurs. This will cause a FileNotFoundError (OSError on Python # 2). If we encounter that, try to run shutil.rmtree again since # we should now be able to remove all the files that were left. - for _dummy in range(0, 5): + for _dummy in range(5): try: # Remove the temporary keyring. We can't use the context manager # for this because it isn't available on Python-2.7 (RHEL7) @@ -931,9 +924,7 @@ 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 {} that held Red Hat gpg public keys.".format(temporary_dir) - ) + logger.info(f"Failed to remove temporary directory {temporary_dir} that held Red Hat gpg public keys.") keyid = None for line in output.splitlines(): @@ -946,7 +937,7 @@ def find_keyid(keyfile): break if not keyid: - raise ImportGPGKeyError("Unable to determine the gpg keyid for the rpm key file: {}".format(keyfile)) + raise ImportGPGKeyError(f"Unable to determine the gpg keyid for the rpm key file: {keyfile}") return keyid.lower() @@ -1030,14 +1021,12 @@ def hide_secrets( # Handle the case where the secret option and its parameter are both in one argument ("--password=SECRET") for option in secret_options: if arg.startswith(option + "="): - arg = "{0}={1}".format(option, OBFUSCATION_STRING) + arg = f"{option}={OBFUSCATION_STRING}" sanitized_list.append(arg) if hide_next: - logger.debug( - "Passed arguments had an option, '{0}', without an expected secret parameter".format(sanitized_list[-1]) - ) + logger.debug(f"Passed arguments had an option, '{sanitized_list[-1]}', without an expected secret parameter") return sanitized_list @@ -1132,11 +1121,11 @@ def warn_deprecated_env(env_name): if env_name not in os.environ: # Nothing to do here. - return None + return root_logger.warning( - "The environment variable {} is deprecated and is set to be removed on Convert2RHEL 2.4.0.\n" - "Please, use the configuration file instead.".format(env_name) + f"The environment variable {env_name} is deprecated and is set to be removed on Convert2RHEL 2.4.0.\n" + "Please, use the configuration file instead." ) key = env_var_to_toolopts_map[env_name] value = os.getenv(env_name, None) diff --git a/convert2rhel/utils/files.py b/convert2rhel/utils/files.py index 72ac25dfbb..c974a5c33d 100644 --- a/convert2rhel/utils/files.py +++ b/convert2rhel/utils/files.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,8 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type - import errno import os diff --git a/convert2rhel/utils/rpm.py b/convert2rhel/utils/rpm.py index e548b34340..d1ca7435a4 100644 --- a/convert2rhel/utils/rpm.py +++ b/convert2rhel/utils/rpm.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type # For a list of modified rpm files before the conversion starts PRE_RPM_VA_LOG_FILENAME = "rpm_va.log" diff --git a/convert2rhel/utils/subscription.py b/convert2rhel/utils/subscription.py index d255b21021..ec1d8f7c9b 100644 --- a/convert2rhel/utils/subscription.py +++ b/convert2rhel/utils/subscription.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,14 +14,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -__metaclass__ = type import logging import re from six.moves import urllib - loggerinst = logging.getLogger(__name__) @@ -60,7 +57,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: {}\nError: {}".format(opts.serverurl, e) + f"Supplied serverurl: {opts.serverurl}\nError: {e}" ) rhsm_parts["rhsm_hostname"] = url_parts.hostname @@ -88,7 +85,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://{}".format(serverurl) + serverurl = f"https://{serverurl}" url_parts = urllib.parse.urlsplit(serverurl, allow_fragments=False) @@ -104,9 +101,7 @@ def _validate_serverurl_parsing(url_parts): :returns: url_parts If the check was successful. """ if url_parts.scheme not in ("https", "http"): - raise ValueError( - "Subscription manager must be accessed over http or https. {} is not valid".format(url_parts.scheme) - ) + raise ValueError(f"Subscription manager must be accessed over http or https. {url_parts.scheme} is not valid") if not url_parts.hostname: raise ValueError("A hostname must be specified in a subscription-manager serverurl") diff --git a/man/__init__.py b/man/__init__.py index 69e9a7ac2f..305cb314d7 100644 --- a/man/__init__.py +++ b/man/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2018 Red Hat, Inc. # diff --git a/setup.py b/setup.py index fc507ed6cf..5745a99250 100755 --- a/setup.py +++ b/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2016 Red Hat, Inc. # @@ -36,15 +35,13 @@ def get_version(): return re.findall( r'^__version__ = "([^"]+)"$', f.read(), - re.M, + re.MULTILINE, )[0] except IndexError: raise ValueError( - ( - "Unable to extract the version from {} file. Make sure the " - "first line has the following form: `__version__ = " - '"some.version.here"`' - ).format(version_source) + f"Unable to extract the version from {version_source} file. Make sure the " + "first line has the following form: `__version__ = " + '"some.version.here"`' ) diff --git a/tests/integration/common/checks-after-conversion/test_flag_system_as_converted.py b/tests/integration/common/checks-after-conversion/test_flag_system_as_converted.py index 3aad4351a5..fa3a81af89 100644 --- a/tests/integration/common/checks-after-conversion/test_flag_system_as_converted.py +++ b/tests/integration/common/checks-after-conversion/test_flag_system_as_converted.py @@ -2,7 +2,6 @@ from test_helpers.common_functions import load_json_schema - C2R_MIGRATION_RESULTS_SCHEMA = load_json_schema(path="artifacts/c2r_migration_results_schema.json") C2R_RHSM_CUSTOM_FACTS_SCHEMA = load_json_schema(path="artifacts/c2r_facts_schema.json") diff --git a/tests/integration/common/checks-after-conversion/test_grub_default.py b/tests/integration/common/checks-after-conversion/test_grub_default.py index f86c85c91d..ba53473dd9 100644 --- a/tests/integration/common/checks-after-conversion/test_grub_default.py +++ b/tests/integration/common/checks-after-conversion/test_grub_default.py @@ -1,6 +1,7 @@ import re import pytest + from test_helpers.common_functions import log_file 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 f7df41adec..15da4bc867 100644 --- a/tests/integration/common/checks-after-conversion/test_release_version.py +++ b/tests/integration/common/checks-after-conversion/test_release_version.py @@ -66,4 +66,4 @@ def test_correct_distro(): break else: # We did not find a known destination_distro - assert False, "Unknown destination distro '{}'".format(destination_distro) + assert False, f"Unknown destination distro '{destination_distro}'" diff --git a/tests/integration/common/checks-after-conversion/test_verify_strings_in_log.py b/tests/integration/common/checks-after-conversion/test_verify_strings_in_log.py index 88d5b0a0b0..988220b424 100644 --- a/tests/integration/common/checks-after-conversion/test_verify_strings_in_log.py +++ b/tests/integration/common/checks-after-conversion/test_verify_strings_in_log.py @@ -2,6 +2,7 @@ import re import pytest + from test_helpers.common_functions import get_log_file_data log_data = get_log_file_data() @@ -46,14 +47,14 @@ def test_check_empty_exclude_in_critical_commands(log_file_data=log_data): """ number_of_repoquery_calls = len(re.findall("Calling command 'repoquery", log_file_data)) number_of_repoquery_calls_with_exclude = len( - re.findall("Calling command 'repoquery.*--setopt=exclude=\s.*", log_file_data) + re.findall(r"Calling command 'repoquery.*--setopt=exclude=\s.*", log_file_data) ) assert number_of_repoquery_calls != 0 assert number_of_repoquery_calls == number_of_repoquery_calls_with_exclude number_of_yumdownloader_calls = len(re.findall("Calling command 'yumdownloader", log_file_data)) number_of_yumdownloader_calls_with_exclude = len( - re.findall("Calling command 'yumdownloader.*--setopt=exclude=\s.*", log_file_data) + re.findall(r"Calling command 'yumdownloader.*--setopt=exclude=\s.*", log_file_data) ) assert number_of_yumdownloader_calls == number_of_yumdownloader_calls_with_exclude diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index b6eeb74a4b..039692b56c 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -4,16 +4,13 @@ import os import sys import warnings - from contextlib import contextmanager from typing import ContextManager import pexpect import pytest - from _pytest.warning_types import PytestUnknownMarkWarning - try: from pathlib import Path except ImportError: @@ -31,7 +28,6 @@ from test_helpers.vars import SYSTEM_RELEASE_ENV, TEST_VARS from test_helpers.workarounds import workaround_grub_setup - logging.basicConfig(level=os.environ.get("DEBUG", "INFO"), stream=sys.stderr) logger = logging.getLogger(__name__) @@ -191,15 +187,7 @@ def factory( action.id == "REMOVE_EXCLUDED_PACKAGES" and action["result"].id == "EXCLUDED_PACKAGE_REMOVAL_FAILED" and "unknown" in action["result"].description - ): - message.extend( - ( - "== Action caught SystemExit while removing packages:", - "{}: {}".format(action.id, action["result"]), - ) - ) - - elif ( + ) or ( action.id == "REMOVE_EXCLUDED_PACKAGES" and action["result"].id == "REPOSITORY_FILE_PACKAGE_REMOVAL_FAILED" and "unknown" in action["result"].description diff --git a/tests/integration/test_helpers/common_functions.py b/tests/integration/test_helpers/common_functions.py index b27bcdf3f8..b65cc43eb0 100644 --- a/tests/integration/test_helpers/common_functions.py +++ b/tests/integration/test_helpers/common_functions.py @@ -3,7 +3,6 @@ import re import shutil import tarfile - from collections import namedtuple import pytest @@ -43,12 +42,12 @@ class SystemInformationRelease: if is_stream: distribution = "stream" version = namedtuple("Version", ["major", "minor"])(int(match_version.group(1)), "latest") - system_release = "{}-{}-{}".format(distribution, version.major, version.minor) + system_release = f"{distribution}-{version.major}-{version.minor}" else: version = namedtuple("Version", ["major", "minor"])( int(match_version.group(1)), int(match_version.group(2)) ) - system_release = "{}-{}.{}".format(distribution, version.major, version.minor) + system_release = f"{distribution}-{version.major}.{version.minor}" # Check if the release is a EUS candidate is_eus = False diff --git a/tests/integration/test_helpers/satellite.py b/tests/integration/test_helpers/satellite.py index a0098c3a05..b47bad39d0 100644 --- a/tests/integration/test_helpers/satellite.py +++ b/tests/integration/test_helpers/satellite.py @@ -1,6 +1,6 @@ import pytest - from dotenv import dotenv_values + from test_helpers.common_functions import SystemInformationRelease from test_helpers.shell import live_shell from test_helpers.subscription_manager import SubscriptionManager @@ -30,9 +30,9 @@ def get_satellite_curl_command(self): return self._sat_reg_commands.get(self.key) def _curl_the_satellite_script(self, curl_command): - assert ( - self.shell(f"{curl_command} -o {self._sat_script_location}", silent=True).returncode == 0 - ), "Failed to curl the satellite script to the machine." + assert self.shell(f"{curl_command} -o {self._sat_script_location}", silent=True).returncode == 0, ( + "Failed to curl the satellite script to the machine." + ) # [danmyway] This is just a mitigation of rhn-client-tools pkg obsoleting subscription-manager during upgrade # TODO remove when https://github.com/theforeman/foreman/pull/10280 gets merged and or foreman 3.12 is out diff --git a/tests/integration/test_helpers/shell.py b/tests/integration/test_helpers/shell.py index de41fc0469..94c1d54b66 100644 --- a/tests/integration/test_helpers/shell.py +++ b/tests/integration/test_helpers/shell.py @@ -1,5 +1,4 @@ import subprocess - from collections import namedtuple import click @@ -18,7 +17,7 @@ def factory(command, silent=False, hide_command=False): click.echo("This shell call is set to hide_command=True, so it won't show the called command.") if not silent and not hide_command: click.echo( - "\nExecuting a command:\n{}\n\n".format(command), + f"\nExecuting a command:\n{command}\n\n", color="green", ) # pylint: disable=consider-using-with diff --git a/tests/integration/test_helpers/vars.py b/tests/integration/test_helpers/vars.py index 8fafaecf9a..b1b94e8d1f 100644 --- a/tests/integration/test_helpers/vars.py +++ b/tests/integration/test_helpers/vars.py @@ -2,7 +2,6 @@ from dotenv import dotenv_values - TEST_VARS = dotenv_values("/var/tmp/.env") SAT_REG_FILE = dotenv_values("/var/tmp/.env_sat_reg") SYSTEM_RELEASE_ENV = os.environ["SYSTEM_RELEASE_ENV"] diff --git a/tests/integration/tier0/destructive/amazon-linux2-supported-kernels/prepare_boot_target_kernel.py b/tests/integration/tier0/destructive/amazon-linux2-supported-kernels/prepare_boot_target_kernel.py index 883c004702..f83305b060 100644 --- a/tests/integration/tier0/destructive/amazon-linux2-supported-kernels/prepare_boot_target_kernel.py +++ b/tests/integration/tier0/destructive/amazon-linux2-supported-kernels/prepare_boot_target_kernel.py @@ -11,7 +11,7 @@ def test_upgrade_amzn2_kernel(shell): target_kernel = os.environ.get("C2R_AL2_TARGET_KERNEL") enabled_kernel = shell( - "amazon-linux-extras | grep -oP 'kernel-[\d.]+=\S+\s+enabled' | grep -oP 'kernel-[\d.]+'" + r"amazon-linux-extras | grep -oP 'kernel-[\d.]+=\S+\s+enabled' | grep -oP 'kernel-[\d.]+'" ).output.strip() if enabled_kernel != target_kernel: @@ -19,7 +19,7 @@ def test_upgrade_amzn2_kernel(shell): assert shell(f"amazon-linux-extras install -y {target_kernel}").returncode == 0 vmlinuz = shell( - "rpm -q --last kernel | head -1 | cut -d ' ' -f1 | sed 's/kernel-/\/boot\/vmlinux-/'" + r"rpm -q --last kernel | head -1 | cut -d ' ' -f1 | sed 's/kernel-/\/boot\/vmlinux-/'" ).output.strip() assert shell(f"grubby --set-default {vmlinuz}").returncode == 0 assert shell("grub2-mkconfig -o /boot/grub2/grub.cfg").returncode == 0 diff --git a/tests/integration/tier0/destructive/conversion-method/test_config_file.py b/tests/integration/tier0/destructive/conversion-method/test_config_file.py index 15b949d183..3a941af555 100644 --- a/tests/integration/tier0/destructive/conversion-method/test_config_file.py +++ b/tests/integration/tier0/destructive/conversion-method/test_config_file.py @@ -1,10 +1,8 @@ import os - from collections import namedtuple from conftest import TEST_VARS - Config = namedtuple("Config", "path content") diff --git a/tests/integration/tier0/destructive/conversion-method/test_custom_repos.py b/tests/integration/tier0/destructive/conversion-method/test_custom_repos.py index 30ffb8ea6d..e5096fc801 100644 --- a/tests/integration/tier0/destructive/conversion-method/test_custom_repos.py +++ b/tests/integration/tier0/destructive/conversion-method/test_custom_repos.py @@ -16,12 +16,12 @@ def test_system_conversion_using_custom_repositories(shell, convert2rhel): if SystemInformationRelease.is_eus: shell("touch /eus_repos_used") - with convert2rhel("-y --no-rhsm {} --debug".format(enable_repo_opt_c2r)) as c2r: + with convert2rhel(f"-y --no-rhsm {enable_repo_opt_c2r} --debug") as c2r: c2r.expect("Conversion successful!") assert c2r.exitstatus == 0 enable_repo_opt_yum = " ".join(f"--enable {repo}" for repo in get_custom_repos_names()) - shell("yum-config-manager {}".format(enable_repo_opt_yum)) + shell(f"yum-config-manager {enable_repo_opt_yum}") if SYSTEM_RELEASE_ENV == "amazon2": # The conversion transaction may remove or replace python3, diff --git a/tests/integration/tier0/destructive/isolated-system-conversion/prepare_system.py b/tests/integration/tier0/destructive/isolated-system-conversion/prepare_system.py index eddceed790..a90868d898 100644 --- a/tests/integration/tier0/destructive/isolated-system-conversion/prepare_system.py +++ b/tests/integration/tier0/destructive/isolated-system-conversion/prepare_system.py @@ -18,7 +18,7 @@ def configure_connection(): with open("/etc/dnsmasq.conf", "a") as f: # Satellite url f.write("address=/{}/{}\n".format(TEST_VARS["SATELLITE_URL"], satellite_ip)) - f.write("address=/{}/{}\n".format(satellite_fqdn, satellite_ip)) + f.write(f"address=/{satellite_fqdn}/{satellite_ip}\n") # Everything else is resolved to localhost f.write("address=/#/127.0.0.1") diff --git a/tests/integration/tier0/destructive/single-yum-transaction/test_check_for_latest_packages.py b/tests/integration/tier0/destructive/single-yum-transaction/test_check_for_latest_packages.py index 9897fffb23..1f5fd942a2 100644 --- a/tests/integration/tier0/destructive/single-yum-transaction/test_check_for_latest_packages.py +++ b/tests/integration/tier0/destructive/single-yum-transaction/test_check_for_latest_packages.py @@ -1,7 +1,6 @@ import re from conftest import SYSTEM_RELEASE_ENV, TEST_VARS - from test_helpers.common_functions import SystemInformationRelease 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 e4e190c27a..9bea9ff982 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 @@ -20,7 +20,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 {} transaction set.".format(pkgmanager), timeout=600) + c2r.expect(f"Successfully validated the {pkgmanager} transaction set.", 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/assessment-report/test_assessment_report.py b/tests/integration/tier0/non-destructive/assessment-report/test_assessment_report.py index 77dc142330..a6bfdf43c1 100644 --- a/tests/integration/tier0/non-destructive/assessment-report/test_assessment_report.py +++ b/tests/integration/tier0/non-destructive/assessment-report/test_assessment_report.py @@ -2,12 +2,11 @@ import re import jsonschema - from pexpect import EOF + from test_helpers.common_functions import load_json_schema from test_helpers.vars import TEST_VARS - PRE_CONVERSION_REPORT_JSON = "/var/log/convert2rhel/convert2rhel-pre-conversion.json" PRE_CONVERSION_REPORT_TXT = "/var/log/convert2rhel/convert2rhel-pre-conversion.txt" PRE_CONVERSION_REPORT_JSON_SCHEMA = load_json_schema(path="../../../../../schemas/assessment-schema-1.2.json") diff --git a/tests/integration/tier0/non-destructive/basic-sanity-checks/test_basic_sanity_checks.py b/tests/integration/tier0/non-destructive/basic-sanity-checks/test_basic_sanity_checks.py index 812d60b760..af7d96cadd 100644 --- a/tests/integration/tier0/non-destructive/basic-sanity-checks/test_basic_sanity_checks.py +++ b/tests/integration/tier0/non-destructive/basic-sanity-checks/test_basic_sanity_checks.py @@ -6,7 +6,6 @@ import pytest - CONVERT2RHEL_FACTS_FILE = "/etc/rhsm/facts/convert2rhel.facts" @@ -81,7 +80,7 @@ def _update_c2r_version(version): with open(path_to_version, "w") as version_file_to_update: # Update the version version_pattern = r'__version__ = "(\d+\.\d+\.\d+)"' - updated_version_content = re.sub(version_pattern, '__version__ = "{}"'.format(version), old_version_content) + updated_version_content = re.sub(version_pattern, f'__version__ = "{version}"', old_version_content) version_file_to_update.write(updated_version_content) yield _update_c2r_version 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 af0022a322..b10df3c757 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 @@ -1,13 +1,11 @@ import os import shutil - from collections import namedtuple import pytest from conftest import TEST_VARS - Config = namedtuple("Config", "path content") diff --git a/tests/integration/tier0/non-destructive/duplicate-pkgs/test_duplicate_pkgs.py b/tests/integration/tier0/non-destructive/duplicate-pkgs/test_duplicate_pkgs.py index 6031056b80..ffdffe6eea 100644 --- a/tests/integration/tier0/non-destructive/duplicate-pkgs/test_duplicate_pkgs.py +++ b/tests/integration/tier0/non-destructive/duplicate-pkgs/test_duplicate_pkgs.py @@ -2,7 +2,6 @@ from conftest import SYSTEM_RELEASE_ENV, TEST_VARS - DUPLICATE_PKG_URL_MAPPING = { "centos-7": "https://vault.centos.org/7.4.1708/os/x86_64/Packages/python2-cryptography-1.7.2-1.el7.x86_64.rpm", "oracle-7": "https://yum.oracle.com/repo/OracleLinux/OL7/latest/x86_64/getPackage/abrt-2.1.11-50.0.1.el7.x86_64.rpm", diff --git a/tests/integration/tier0/non-destructive/enabled-repositories-after-analysis/test_enabled_repositories_after_analysis.py b/tests/integration/tier0/non-destructive/enabled-repositories-after-analysis/test_enabled_repositories_after_analysis.py index 6a49a5c1ef..e32772f229 100644 --- a/tests/integration/tier0/non-destructive/enabled-repositories-after-analysis/test_enabled_repositories_after_analysis.py +++ b/tests/integration/tier0/non-destructive/enabled-repositories-after-analysis/test_enabled_repositories_after_analysis.py @@ -1,6 +1,5 @@ import pytest - RHEL_CERTIFICATE_69_PEM = "/usr/share/convert2rhel/rhel-certs/69.pem" diff --git a/tests/integration/tier0/non-destructive/file-backup/test_file_backup.py b/tests/integration/tier0/non-destructive/file-backup/test_file_backup.py index 8c380f3657..569464c4f8 100644 --- a/tests/integration/tier0/non-destructive/file-backup/test_file_backup.py +++ b/tests/integration/tier0/non-destructive/file-backup/test_file_backup.py @@ -3,7 +3,6 @@ import pytest - MODIFIED_CONTENT = """\n#This is just a placeholder test #to verify the file won't be changed # after the rollback""" diff --git a/tests/integration/tier0/non-destructive/firewalld-inhibitor/test_firewalld_inhibitor.py b/tests/integration/tier0/non-destructive/firewalld-inhibitor/test_firewalld_inhibitor.py index ec21bd95d4..93179508c5 100644 --- a/tests/integration/tier0/non-destructive/firewalld-inhibitor/test_firewalld_inhibitor.py +++ b/tests/integration/tier0/non-destructive/firewalld-inhibitor/test_firewalld_inhibitor.py @@ -4,7 +4,6 @@ from conftest import TEST_VARS - FIREWALLD_CONFIG_FILE = "/etc/firewalld/firewalld.conf" diff --git a/tests/integration/tier0/non-destructive/grub/test_invalid_changed_to_grub.py b/tests/integration/tier0/non-destructive/grub/test_invalid_changed_to_grub.py index c0d30f57af..bb7701703f 100644 --- a/tests/integration/tier0/non-destructive/grub/test_invalid_changed_to_grub.py +++ b/tests/integration/tier0/non-destructive/grub/test_invalid_changed_to_grub.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import fileinput import os.path @@ -7,7 +5,6 @@ from conftest import TEST_VARS - target_line = "GRUB_CMDLINE_LINUX" diff --git a/tests/integration/tier0/non-destructive/kernel-modules/test_unsupported_kmod.py b/tests/integration/tier0/non-destructive/kernel-modules/test_unsupported_kmod.py index e4d843a500..e097f91e12 100644 --- a/tests/integration/tier0/non-destructive/kernel-modules/test_unsupported_kmod.py +++ b/tests/integration/tier0/non-destructive/kernel-modules/test_unsupported_kmod.py @@ -4,7 +4,6 @@ from conftest import TEST_VARS - ORIGIN_KMOD_LOCATION = Path("/lib/modules/$(uname -r)/kernel/drivers/net/bonding/bonding.ko.xz") CUSTOM_KMOD_DIRECTORY = ORIGIN_KMOD_LOCATION.parent / "custom_module_location" 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 f2c3aa2d7e..00c5a8f8bc 100644 --- a/tests/integration/tier0/non-destructive/kernel/test_custom_kernel.py +++ b/tests/integration/tier0/non-destructive/kernel/test_custom_kernel.py @@ -67,7 +67,7 @@ def custom_kernel(shell, workaround_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) > {}".format(kernel_info_storage)) + shell(f"echo $(uname -r) > {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 @@ -140,9 +140,7 @@ def test_custom_kernel(convert2rhel, shell, custom_kernel): c2r.expect("Continue with the system conversion?") c2r.sendline("y") - c2r.expect( - "WARNING - Custom kernel detected. The booted kernel needs to be signed by {}".format(os_vendor) - ) + c2r.expect(f"WARNING - Custom kernel detected. The booted kernel needs to be signed by {os_vendor}") c2r.expect_exact("RHEL_COMPATIBLE_KERNEL::INVALID_KERNEL_PACKAGE_SIGNATURE") c2r.sendcontrol("c") diff --git a/tests/integration/tier0/non-destructive/logged-command/test_logged_command.py b/tests/integration/tier0/non-destructive/logged-command/test_logged_command.py index 1a11fd6ded..9deb2b95c8 100644 --- a/tests/integration/tier0/non-destructive/logged-command/test_logged_command.py +++ b/tests/integration/tier0/non-destructive/logged-command/test_logged_command.py @@ -1,7 +1,6 @@ import json import os.path - C2R_LOG = "/var/log/convert2rhel/convert2rhel.log" C2R_FACTS = "/etc/rhsm/facts/convert2rhel.facts" @@ -22,13 +21,9 @@ def test_logfile_starts_with_command(convert2rhel): activation_key = "a-map-of-a-key" organization = "SoMe_NumberS-8_a_lettER" - command_long = "--debug --serverurl {} --username {} --password {} --activationkey {} --org {}".format( - serverurl, username, password, activation_key, organization - ) - command_short = "--debug --serverurl {} -u {} -p {} -k {} -o {}".format( - serverurl, username, password, activation_key, organization - ) - command_verification = "convert2rhel --debug --serverurl {}".format(serverurl) + command_long = f"--debug --serverurl {serverurl} --username {username} --password {password} --activationkey {activation_key} --org {organization}" + command_short = f"--debug --serverurl {serverurl} -u {username} -p {password} -k {activation_key} -o {organization}" + command_verification = f"convert2rhel --debug --serverurl {serverurl}" commands = [command_long, command_short] diff --git a/tests/integration/tier0/non-destructive/rollback-handling/test_rollback_handling.py b/tests/integration/tier0/non-destructive/rollback-handling/test_rollback_handling.py index 12089d728f..579812a49a 100644 --- a/tests/integration/tier0/non-destructive/rollback-handling/test_rollback_handling.py +++ b/tests/integration/tier0/non-destructive/rollback-handling/test_rollback_handling.py @@ -280,7 +280,7 @@ def test_rollback_failure_returncode(shell, convert2rhel, immutable_os_release_f Use fake credentials to cause the inhibition. """ - with convert2rhel("{} --debug -y --username happy_hippo --password hippo_is_hungry".format(c2r_mode)) as c2r: + with convert2rhel(f"{c2r_mode} --debug -y --username happy_hippo --password hippo_is_hungry") as c2r: c2r.expect("WARNING - Error while rolling back") c2r.expect("CRITICAL - Rollback of system wasn't completed successfully.") assert c2r.exitstatus == 1 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 4e5f5abe1f..d4d1152892 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 @@ -6,7 +6,6 @@ from conftest import SYSTEM_RELEASE_ENV, TEST_VARS, SystemInformationRelease - PKI_ENTITLEMENT_CERTS_PATH = "/etc/pki/entitlement" SERVER_SUB = "CentOS Linux" @@ -54,7 +53,7 @@ def remove_entitlement_certs(): try: os.unlink(cert_path) except Exception as e: - print("Failed to delete {}. Reason: {}".format(cert_path, e)) + print(f"Failed to delete {cert_path}. Reason: {e}") def test_package_download_error(convert2rhel, shell, yum_cache): @@ -80,8 +79,8 @@ def test_package_download_error(convert2rhel, shell, yum_cache): TEST_VARS["RHSM_SCA_PASSWORD"], ) ) as c2r: - c2r.expect("Validate the {} transaction".format(PKGMANAGER)) - c2r.expect("Adding {} packages to the {} transaction set.".format(SERVER_SUB, PKGMANAGER)) + c2r.expect(f"Validate the {PKGMANAGER} transaction") + c2r.expect(f"Adding {SERVER_SUB} packages to the {PKGMANAGER} transaction set.") if SYSTEM_RELEASE_ENV in ("centos-7", "oracle-7", "amazon2"): # Remove the repomd.xml for rhel-7-server-rpms repo diff --git a/tests/integration/tier1/destructive/changed-grub-file/test_valid_changed_grub.py b/tests/integration/tier1/destructive/changed-grub-file/test_valid_changed_grub.py index e8cfe3e275..52335104d0 100644 --- a/tests/integration/tier1/destructive/changed-grub-file/test_valid_changed_grub.py +++ b/tests/integration/tier1/destructive/changed-grub-file/test_valid_changed_grub.py @@ -1,10 +1,7 @@ -from __future__ import print_function - import fileinput from conftest import TEST_VARS - target_line = "GRUB_CMDLINE_LINUX" diff --git a/tests/integration/tier1/destructive/changed-yum-conf/test_patch_yum_conf.py b/tests/integration/tier1/destructive/changed-yum-conf/test_patch_yum_conf.py index 4dee747eae..7036a5f6bd 100644 --- a/tests/integration/tier1/destructive/changed-yum-conf/test_patch_yum_conf.py +++ b/tests/integration/tier1/destructive/changed-yum-conf/test_patch_yum_conf.py @@ -20,7 +20,7 @@ def test_yum_conf_patch(convert2rhel, shell): TEST_VARS["RHSM_SCA_PASSWORD"], ) ) as c2r: - c2r.expect("{} patched.".format(pkgmanager_conf)) + c2r.expect(f"{pkgmanager_conf} patched.") assert c2r.exitstatus == 0 # The tsflags will prevent updating the RHEL-8.5 versions to RHEL-8.6 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 4576feca10..6603255cb0 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 @@ -52,21 +52,19 @@ 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 {}'".format(boot_device)) == 0 + assert c2r.expect(f"Calling command '/usr/sbin/blkid -p -s PART_ENTRY_NUMBER {boot_device}'") == 0 # This assertion should always match what comes from boot_partition. - assert c2r.expect("Block device: {}".format(boot_device_name)) == 0 - assert c2r.expect("ESP device number: {}".format(boot_partition)) == 0 + assert c2r.expect(f"Block device: {boot_device_name}") == 0 + assert c2r.expect(f"ESP device number: {boot_partition}") == 0 - assert c2r.expect("Adding 'Red Hat Enterprise Linux {}' UEFI bootloader entry.".format(rhel_version)) == 0 + assert c2r.expect(f"Adding 'Red Hat Enterprise Linux {rhel_version}' UEFI bootloader entry.") == 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 {} --part {}".format( - boot_device_name, boot_partition - ) + f"Calling command '/usr/sbin/efibootmgr --create --disk {boot_device_name} --part {boot_partition}" ) == 0 ) diff --git a/tests/integration/tier1/destructive/firewalld-disabled-ol8/test_firewalld_disabled_ol8.py b/tests/integration/tier1/destructive/firewalld-disabled-ol8/test_firewalld_disabled_ol8.py index 88e8ff7794..431b16f35f 100644 --- a/tests/integration/tier1/destructive/firewalld-disabled-ol8/test_firewalld_disabled_ol8.py +++ b/tests/integration/tier1/destructive/firewalld-disabled-ol8/test_firewalld_disabled_ol8.py @@ -4,7 +4,6 @@ from conftest import TEST_VARS - FIREWALLD_CONFIG_FILE = "/etc/firewalld/firewalld.conf" diff --git a/tests/integration/tier1/destructive/host-metering/test_host_metering_enabled.py b/tests/integration/tier1/destructive/host-metering/test_host_metering_enabled.py index 2f9d9a0109..0f00288c0a 100644 --- a/tests/integration/tier1/destructive/host-metering/test_host_metering_enabled.py +++ b/tests/integration/tier1/destructive/host-metering/test_host_metering_enabled.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # diff --git a/tests/integration/tier1/destructive/host-metering/test_run_conversion_with_metering.py b/tests/integration/tier1/destructive/host-metering/test_run_conversion_with_metering.py index 68f7060cb6..df45f99665 100644 --- a/tests/integration/tier1/destructive/host-metering/test_run_conversion_with_metering.py +++ b/tests/integration/tier1/destructive/host-metering/test_run_conversion_with_metering.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright(C) 2024 Red Hat, Inc. # @@ -15,9 +14,10 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -from conftest import TEST_VARS import configparser +from conftest import TEST_VARS + def setup_test_metering_endpoint(): """ 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 1d440eda34..3e4b7bbe24 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 @@ -3,7 +3,6 @@ from conftest import TEST_VARS, SystemInformationRelease - INITRAMFS_FILE = "/boot/initramfs-%s.img" BACKUP_INITRAMFS_FILE = "/boot/initramfs-%s.backup.img" @@ -13,7 +12,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("{}-".format(kernel_name))[-1] + latest_installed_kernel = latest_installed_kernel.split(f"{kernel_name}-")[-1] return latest_installed_kernel.strip() @@ -26,10 +25,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 {} {}".format(initramfs_file, initramfs_backup)).returncode == 0 + assert shell(f"cp {initramfs_file} {initramfs_backup}").returncode == 0 # Corrupt the file - cmd = ["dd", "if=/dev/urandom", "bs=1024", "count=1", "of={}".format(initramfs_file)] + cmd = ["dd", "if=/dev/urandom", "bs=1024", "count=1", f"of={initramfs_file}"] subprocess.run(cmd, check=False) @@ -42,10 +41,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 {}".format(initramfs_file)).returncode == 0 + assert shell(f"rm -rf {initramfs_file}").returncode == 0 # Move the backup to be the original one again - assert shell("mv {} {}".format(initramfs_backup, initramfs_file)).returncode == 0 + assert shell(f"mv {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 7133929b50..f795e013b5 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 @@ -3,7 +3,6 @@ from conftest import TEST_VARS, SystemInformationRelease - INITRAMFS_FILE = "/boot/initramfs-%s.img" VMLINUZ_FILE = "/boot/vmlinuz-%s" @@ -13,7 +12,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("{}-".format(kernel_name))[-1] + latest_installed_kernel = latest_installed_kernel.split(f"{kernel_name}-")[-1] return latest_installed_kernel.strip() @@ -28,8 +27,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 {}".format(initramfs_file)).returncode == 0 - assert shell("rm -f {}".format(vmlinuz_file)).returncode == 0 + assert shell(f"rm -f {initramfs_file}").returncode == 0 + assert shell(f"rm -f {vmlinuz_file}").returncode == 0 def test_handling_missing_kernel_boot_files(convert2rhel, shell): @@ -78,7 +77,7 @@ def test_handling_missing_kernel_boot_files(convert2rhel, shell): # assert that the rest of the conversion has succeeded. # We'll do that the same way we're telling the user in a warning message how to fix the problem. # That is by reinstalling the RHEL kernel and re-running grub2-mkconfig. - reinstall_command = "yum reinstall {}-{} -y".format(kernel_name, kernel_version) + reinstall_command = f"yum reinstall {kernel_name}-{kernel_version} -y" assert shell(reinstall_command).returncode == 0 assert shell("grub2-mkconfig -o /boot/grub2/grub.cfg").returncode == 0 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 7e71ceb328..a94493ca44 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 @@ -23,7 +23,7 @@ def one_kernel(shell): r"baseurl = http://rhsm-pulp.corp.redhat.com/content/dist/rhel/server/7/$releasever/$basearch/os/" ) new_url = "baseurl=http://rhsm-pulp.corp.redhat.com/content/dist/rhel/server/7/7.9/x86_64/os/" - shell('sed -i "s+{}+{}+g" /etc/yum.repos.d/rhel7.repo'.format(original_url, new_url)) + shell(f'sed -i "s+{original_url}+{new_url}+g" /etc/yum.repos.d/rhel7.repo') shell("tmt-reboot -t 600") if os.environ["TMT_REBOOT_COUNT"] == "1": @@ -72,7 +72,7 @@ def test_one_kernel_scenario(shell, convert2rhel, one_kernel): # from Testing Farm shell("rm /etc/yum.repos.d/copr_build-convert2rhel-1.repo") - with convert2rhel("-y --no-rhsm {} --debug".format(enable_repo_opt)) as c2r: + with convert2rhel(f"-y --no-rhsm {enable_repo_opt} --debug") as c2r: c2r.expect("Conversion successful!") assert c2r.exitstatus == 0 @@ -82,11 +82,11 @@ def test_one_kernel_scenario(shell, convert2rhel, one_kernel): r"baseurl = https://rhsm-pulp.corp.redhat.com/content/dist/rhel/server/7/\$releasever/\$basearch/os/" ) new_url = "baseurl=https://rhsm-pulp.corp.redhat.com/content/dist/rhel/server/7/7.9/x86_64/os/" - shell('sed -i "s+{}+{}+g" /etc/yum.repos.d/rhel7.repo'.format(new_url, original_url)) + shell(f'sed -i "s+{new_url}+{original_url}+g" /etc/yum.repos.d/rhel7.repo') enable_repo_opt = ( "--enable rhel-7-server-rpms --enable rhel-7-server-optional-rpms --enable rhel-7-server-extras-rpms" ) - shell("yum-config-manager {}".format(enable_repo_opt)) + shell(f"yum-config-manager {enable_repo_opt}") assert shell("yum install -y python3 --enablerepo=*").returncode == 0 diff --git a/tests/integration/tier1/destructive/proxy-conversion/test_proxy_conversion.py b/tests/integration/tier1/destructive/proxy-conversion/test_proxy_conversion.py index d2071b6394..8613b412e9 100644 --- a/tests/integration/tier1/destructive/proxy-conversion/test_proxy_conversion.py +++ b/tests/integration/tier1/destructive/proxy-conversion/test_proxy_conversion.py @@ -1,6 +1,7 @@ import socket import pytest + from conftest import TEST_VARS, SubscriptionManager diff --git a/tests/integration/tier1/destructive/system-not-up-to-date/test_system_not_up_to_date.py b/tests/integration/tier1/destructive/system-not-up-to-date/test_system_not_up_to_date.py index 6b6fbdf9e3..3f29c9dc99 100644 --- a/tests/integration/tier1/destructive/system-not-up-to-date/test_system_not_up_to_date.py +++ b/tests/integration/tier1/destructive/system-not-up-to-date/test_system_not_up_to_date.py @@ -29,7 +29,7 @@ def downgrade_and_versionlock(shell): os_key = f"{SystemInformationRelease.distribution}-{SystemInformationRelease.version.major}" if re.match(r"^(almalinux|centos|rocky)-[89]", os_key): - assert shell("yum install -y {}".format(older_packages_mapping.get(os_key))).returncode == 0 + assert shell(f"yum install -y {older_packages_mapping.get(os_key)}").returncode == 0 else: assert shell("yum install openldap wpa_supplicant sqlite -y").returncode == 0 # Try to downgrade some packages.