Skip to content

Commit

Permalink
Merge pull request avocado-framework#6041 from clebergnu/avocado_util…
Browse files Browse the repository at this point in the history
…s_lint_warnings

Avocado utils lint warnings
  • Loading branch information
richtja authored Oct 29, 2024
2 parents 3b1f5cb + f8537a5 commit 16c39ea
Show file tree
Hide file tree
Showing 25 changed files with 667 additions and 109 deletions.
541 changes: 541 additions & 0 deletions .pylintrc_utils

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions avocado-static-checks.conf
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
[lint]
avocado/utils:.pylintrc_utils
.:.pylintrc
4 changes: 2 additions & 2 deletions avocado/utils/ar.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ def __next__(self):
member = struct.unpack(
FILE_HEADER_FMT, open_file.read(FILE_HEADER_SIZE)
)
except struct.error:
raise StopIteration
except struct.error as exc:
raise StopIteration from exc

# No support for extended file names
identifier = member[0].decode("ascii").strip()
Expand Down
4 changes: 2 additions & 2 deletions avocado/utils/archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,15 +297,15 @@ def _update_zip_extra_attrs(self, dst_dir):
os.remove(dst)
os.symlink(src, dst)
except Exception as e:
LOG.warning(f"Failed to update symlink '{dst}': {str(e)}")
LOG.warning("Failed to update symlink '%s': %s", dst, e)
continue
continue # Don't override any other attributes on links
mode = attr & 511 # Mask only permissions
if mode and mode != 436: # If mode is stored and is not default
try:
os.chmod(dst, mode)
except Exception as e:
LOG.warning(f"Failed to update permissions for '{dst}': {str(e)}")
LOG.warning("Failed to update permissions for '%s'", e)

def close(self):
"""
Expand Down
16 changes: 8 additions & 8 deletions avocado/utils/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,8 +485,8 @@ def get_metadata(self):
"""
try:
asset_file = self.find_asset_file()
except OSError:
raise OSError("Metadata not available.")
except OSError as exc:
raise OSError("Metadata not available.") from exc

basename = os.path.splitext(asset_file)[0]
metadata_file = f"{basename}_metadata.json"
Expand Down Expand Up @@ -588,21 +588,21 @@ def get_assets_by_size(cls, size_filter, cache_dirs):
try:
op = re.match("^(\\D+)(\\d+)$", size_filter).group(1)
value = int(re.match("^(\\D+)(\\d+)$", size_filter).group(2))
except (AttributeError, ValueError):
except (AttributeError, ValueError) as exc:
msg = (
"Invalid syntax. You need to pass an comparison operatator",
" and a value. Ex: '>=200'",
)
raise OSError(msg)
raise OSError(msg) from exc

try:
method = SUPPORTED_OPERATORS[op]
except KeyError:
except KeyError as exc:
msg = (
"Operator not supported. Currented valid values are: ",
", ".join(SUPPORTED_OPERATORS),
)
raise OSError(msg)
raise OSError(msg) from exc

result = []
for file_path in cls.get_all_assets(cache_dirs):
Expand Down Expand Up @@ -689,9 +689,9 @@ def remove_asset_by_path(cls, asset_path):
filename = f"{asset_path}-CHECKSUM"
os.remove(filename)
except FileNotFoundError:
LOG.error(f"File not found: {asset_path} or its checksum file.")
LOG.error("File not found: %s or its checksum file.", asset_path)
except Exception as e:
LOG.error(f"An error occurred while removing files: {e}")
LOG.error("An error occurred while removing files: %s", e)

@property
def urls(self):
Expand Down
4 changes: 2 additions & 2 deletions avocado/utils/astring.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,12 @@ def strip_console_codes(output, custom_codes=None):
continue
try:
special_code = re.findall(console_codes, tmp_word)[0]
except IndexError:
except IndexError as exc:
if index + tmp_index < len(output):
raise ValueError(
f"{tmp_word} is not included in the known "
f"console codes list {console_codes}"
)
) from exc
continue
if special_code == tmp_word:
continue
Expand Down
6 changes: 3 additions & 3 deletions avocado/utils/cpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def get_family():
except FileNotFoundError as err:
msg = f"Could not find micro-architecture/family, Error: {err}"
LOG.warning(msg)
raise FamilyException(msg)
raise FamilyException(msg) from err
elif arch == "powerpc":
res = []
try:
Expand All @@ -268,15 +268,15 @@ def get_family():
except IndexError as err:
msg = f"Unable to parse cpu family {err}"
LOG.warning(msg)
raise FamilyException(msg)
raise FamilyException(msg) from err
elif arch == "s390":
zfamily_map = {"2964": "z13", "3906": "z14", "8561": "z15", "3931": "z16"}
try:
family = zfamily_map[get_version()].lower()
except KeyError as err:
msg = f"Could not find family for {get_version()}\nError: {err}"
LOG.warning(msg)
raise FamilyException(msg)
raise FamilyException(msg) from err
else:
raise NotImplementedError
return family
Expand Down
12 changes: 6 additions & 6 deletions avocado/utils/data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ def geometric_mean(values):
"""
try:
values = [int(value) for value in values]
except ValueError:
raise ValueError(f"Invalid inputs {values}. Provide valid inputs")
except ValueError as exc:
raise ValueError(f"Invalid inputs {values}. Provide valid inputs") from exc
no_values = len(values)
if no_values == 0:
return None
Expand Down Expand Up @@ -293,12 +293,12 @@ def time_to_seconds(time):
seconds = int(time[:-1]) * mult
else:
seconds = int(time)
except (ValueError, TypeError):
except (ValueError, TypeError) as exc:
raise ValueError(
f"Invalid value '{time}' for time. Use a string "
f"with the number and optionally the time unit "
f"(s, m, h or d)."
)
) from exc
else:
seconds = 0
return seconds
Expand Down Expand Up @@ -339,10 +339,10 @@ def __init__(self, data):
if self._value < 0:
raise ValueError

except ValueError:
except ValueError as exc:
raise InvalidDataSize(
'String not in size + unit format (i.e. "10M", "100k", ...)'
)
) from exc

@property
def value(self):
Expand Down
12 changes: 6 additions & 6 deletions avocado/utils/disk.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,11 @@ def get_disks():
try:
json_result = process.run("lsblk --json --paths --inverse")
except process.CmdError as ce:
raise DiskError(f"Error occurred while executing lsblk command: {ce}")
raise DiskError(f"Error occurred while executing lsblk command: {ce}") from ce
try:
json_data = json.loads(json_result.stdout_text)
except json.JSONDecodeError as je:
raise DiskError(f"Error occurred while parsing JSON data: {je}")
raise DiskError(f"Error occurred while parsing JSON data: {je}") from je
disks = []
for device in json_data["blockdevices"]:
disks.append(device["name"])
Expand Down Expand Up @@ -359,10 +359,10 @@ def create_linux_raw_partition(disk_name, size=None, num_of_par=1):
part_output = process.getoutput(
"sfdisk " + disk_name + " < " + disk_partition_file
)
except:
except Exception as exc:
msg = f"sfdisk partition creation command failed on disk {disk_name}"
LOGGER.warning(msg)
raise DiskError(msg)
raise DiskError(msg) from exc
rescan_disk(disk_name)
if "The partition table has been altered" in part_output:
return get_disk_partitions(disk_name)
Expand Down Expand Up @@ -395,10 +395,10 @@ def delete_partition(partition_name):
+ " "
+ partition_name[disk_index:]
)
except:
except Exception as exc:
msg = f"sfdisk --delete command failed on disk {partition_name}"
LOGGER.warning(msg)
raise DiskError(msg)
raise DiskError(msg) from exc


def clean_disk(disk_name):
Expand Down
4 changes: 2 additions & 2 deletions avocado/utils/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ def url_download_interactive(url, output_file, title="", chunk_size=102400):

try:
file_size = int(input_file.headers["Content-Length"])
except KeyError:
raise ValueError("Could not find file size in HTTP headers")
except KeyError as exc:
raise ValueError("Could not find file size in HTTP headers") from exc

log.info(
"Downloading %s, %s to %s",
Expand Down
6 changes: 3 additions & 3 deletions avocado/utils/filelock.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __enter__(self):
os.close(fd)
self.locked = True
return self
except Exception: # pylint: disable=W0703
except Exception as exc: # pylint: disable=W0703
try:
# Read the file to realize what's happening.
with open(self.filename, "r", encoding="utf-8") as f:
Expand All @@ -80,9 +80,9 @@ def __enter__(self):
# to a running process and we are just waiting for the lock
# to be released.
if self.timeout <= 0:
raise AlreadyLocked("File is already locked.")
raise AlreadyLocked("File is already locked.") from exc
elif time.monotonic() > timelimit:
raise AlreadyLocked("Timeout waiting for the lock.")
raise AlreadyLocked("Timeout waiting for the lock.") from exc
else:
time.sleep(0.1)

Expand Down
4 changes: 2 additions & 2 deletions avocado/utils/gdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ def __init__(self, path=None, *extra_args): # pylint: disable=W1113
if details.errno == 2:
exc = OSError(f"File '{args[0]}' not found")
exc.errno = 2
raise exc
raise exc from details
else:
raise

Expand Down Expand Up @@ -613,7 +613,7 @@ def __init__(
if details.errno == 2:
exc = OSError(f"File '{args[0]}' not found")
exc.errno = 2
raise exc
raise exc from details
else:
raise

Expand Down
2 changes: 1 addition & 1 deletion avocado/utils/genio.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def write_file_or_fail(filename, data):
with open(filename, "w", encoding="utf-8") as file_obj:
file_obj.write(data)
except OSError as details:
raise GenIOError(f"The write to {filename} failed: {details}")
raise GenIOError(f"The write to {filename} failed: {details}") from details


def append_file(filename, data):
Expand Down
4 changes: 2 additions & 2 deletions avocado/utils/linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,6 @@ def is_os_secureboot_enabled():
for line in process.system_output(cmd).decode("utf-8").splitlines():
if "00000002" in line:
return True
except FileNotFoundError:
raise UnsupportedMachineError("lsprop not a supported command")
except FileNotFoundError as exc:
raise UnsupportedMachineError("lsprop not a supported command") from exc
return False
21 changes: 10 additions & 11 deletions avocado/utils/lv_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def vg_ramdisk(
except process.CmdError as ex:
LOGGER.error(ex)
vg_ramdisk_cleanup(ramdisk_filename, vg_ramdisk_dir, vg_name, use_tmpfs)
raise LVException(f"Fail to create vg_ramdisk: {ex}")
raise LVException(f"Fail to create vg_ramdisk: {ex}") from ex

if not disk:
loop_device = result.stdout_text.rstrip()
Expand All @@ -172,7 +172,7 @@ def vg_ramdisk(
vg_ramdisk_cleanup(
ramdisk_filename, vg_ramdisk_dir, vg_name, loop_device, use_tmpfs
)
raise LVException(f"Fail to create vg_ramdisk: {ex}")
raise LVException(f"Fail to create vg_ramdisk: {ex}") from ex
return ramdisk_filename, vg_ramdisk_dir, vg_name, loop_device


Expand Down Expand Up @@ -311,7 +311,6 @@ def vg_list(vg_name=None):
lines = lines[1:]
else:
return vgroups
# TODO: Optimize this
for line in lines:
details = line.split()
details_dict = {}
Expand Down Expand Up @@ -456,7 +455,7 @@ def lv_create(
process.run(tp_cmd, sudo=True)
except process.CmdError as detail:
LOGGER.debug(detail)
raise LVException("Create thin volume pool failed.")
raise LVException("Create thin volume pool failed.") from detail
LOGGER.debug("Created thin volume pool: %s", pool_name)
lv_cmd += f" --virtualsize {lv_size}"
lv_cmd += f" --thin {vg_name}/{pool_name} -y"
Expand All @@ -467,7 +466,7 @@ def lv_create(
process.run(lv_cmd, sudo=True)
except process.CmdError as detail:
LOGGER.error(detail)
raise LVException("Create thin volume failed.")
raise LVException("Create thin volume failed.") from detail
LOGGER.debug("Created thin volume:%s", lv_name)


Expand Down Expand Up @@ -625,12 +624,12 @@ def lv_reactivate(vg_name, lv_name, timeout=10):
time.sleep(timeout)
process.run(f"lvchange -ay /dev/{vg_name}/{lv_name}", sudo=True)
time.sleep(timeout)
except process.CmdError:
except process.CmdError as exc:
log_msg = (
"Failed to reactivate %s - please, nuke the process that uses it first."
)
LOGGER.error(log_msg, lv_name)
raise LVException(f"The Logical volume {lv_name} is still active")
raise LVException(f"The Logical volume {lv_name} is still active") from exc


def lv_mount(vg_name, lv_name, mount_loc, create_filesystem=""):
Expand All @@ -650,7 +649,7 @@ def lv_mount(vg_name, lv_name, mount_loc, create_filesystem=""):
process.run(f"mkfs.{create_filesystem} /dev/{vg_name}/{lv_name}", sudo=True)
process.run(f"mount /dev/{vg_name}/{lv_name} {mount_loc}", sudo=True)
except process.CmdError as ex:
raise LVException(f"Fail to mount logical volume: {ex}")
raise LVException(f"Fail to mount logical volume: {ex}") from ex


def vg_reactivate(vg_name, timeout=10, export=False):
Expand All @@ -675,12 +674,12 @@ def vg_reactivate(vg_name, timeout=10, export=False):

process.run(f"vgchange -ay {vg_name}", sudo=True)
time.sleep(timeout)
except process.CmdError:
except process.CmdError as exc:
log_msg = (
"Failed to reactivate %s - please, nuke the process that uses it first."
)
LOGGER.error(log_msg, vg_name)
raise LVException(f"The Volume group {vg_name} is still active")
raise LVException(f"The Volume group {vg_name} is still active") from exc


def lv_umount(vg_name, lv_name):
Expand All @@ -694,4 +693,4 @@ def lv_umount(vg_name, lv_name):
try:
process.run(f"umount /dev/{vg_name}/{lv_name}", sudo=True)
except process.CmdError as ex:
raise LVException(f"Fail to unmount logical volume: {ex}")
raise LVException(f"Fail to unmount logical volume: {ex}") from ex
6 changes: 3 additions & 3 deletions avocado/utils/multipath.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def get_mpath_from_dm(dm_id):
try:
mpaths = process.run(cmd, ignore_status=True, sudo=True, shell=True).stdout_text
except process.CmdError as ex:
raise MPException(f"Multipathd Command Failed : {ex} ")
raise MPException(f"Multipathd Command Failed : {ex} ") from ex
for mpath in mpaths.splitlines():
if dm_id in mpath:
return mpath.split()[1]
Expand Down Expand Up @@ -139,7 +139,7 @@ def get_multipath_wwid(mpath):
try:
wwids = process.run(cmd, ignore_status=True, sudo=True, shell=True).stdout_text
except process.CmdError as ex:
raise MPException(f"Multipathd Command Failed : {ex} ")
raise MPException(f"Multipathd Command Failed : {ex} ") from ex
for wwid in wwids.splitlines():
if mpath in wwid:
return wwid.split()[1]
Expand All @@ -156,7 +156,7 @@ def is_mpath_dev(mpath):
try:
mpaths = process.run(cmd, ignore_status=True, sudo=True, shell=True).stdout_text
except process.CmdError as ex:
raise MPException(f"Multipath Command Failed : {ex} ")
raise MPException(f"Multipath Command Failed : {ex} ") from ex
if mpath in mpaths.strip("\n").split("\n"):
return True
return False
Expand Down
Loading

0 comments on commit 16c39ea

Please sign in to comment.