Skip to content

Commit

Permalink
Make Ruff and MyPy happier
Browse files Browse the repository at this point in the history
+ as bonus fix bug in Downgrade class base
  • Loading branch information
mimi1vx committed Feb 6, 2025
1 parent 4758e7e commit 44ed6b1
Show file tree
Hide file tree
Showing 28 changed files with 121 additions and 116 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ name: ci
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-22.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v43
- name: Install dependencies
run: |
sudo apt-get update
Expand Down
1 change: 0 additions & 1 deletion mtui/commands/commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@


class Commit(Command):

"""
Commits testing template to the SVN. This can be run after the
testing has finished an the template is in the final state.
Expand Down
1 change: 0 additions & 1 deletion mtui/commands/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@


class Config(Command):

"""
Display and manipulate (TODO) configuration in runtime.
"""
Expand Down
2 changes: 1 addition & 1 deletion mtui/commands/reloadoqa.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from logging import getLogger

from ..connector.openqa import AutoOpenQA, KernelOpenQA
from ..utils import complete_choices, requires_update
from ..utils import requires_update
from . import Command

logger = getLogger("mtui.commands.reloadopenqa")
Expand Down
1 change: 0 additions & 1 deletion mtui/commands/reportbug.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@


class ReportBug(Command):

"""
Open mtui bugzilla with fields common for all mtui bugs prefilled
"""
Expand Down
1 change: 0 additions & 1 deletion mtui/commands/whoami.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@


class Whoami(Command):

"""
Display current user name and session pid.
Expand Down
1 change: 0 additions & 1 deletion mtui/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ class InvalidOptionNameError(RuntimeError):


class Config:

"""Read and store the variables from mtui config files"""

def __init__(self, path, refhosts=RefhostsFactory):
Expand Down
36 changes: 21 additions & 15 deletions mtui/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@


class CommandTimeout(Exception):

"""remote command timeout exception
returns timed out remote command as __str__
Expand All @@ -47,7 +46,6 @@ def __str__(self) -> str:


class Connection:

"""manage SSH and SFTP connections"""

__slots__ = [
Expand Down Expand Up @@ -125,18 +123,22 @@ def connect(self):
# hostkey for the specified host. checking back with a manual
# "ssh root@..." invocation helps in most cases.
self.client.connect(
hostname=opts.get("hostname", self.hostname)
if "proxycommand" not in opts
else self.hostname,
hostname=(
opts.get("hostname", self.hostname)
if "proxycommand" not in opts
else self.hostname
),
port=int(opts.get("port", self.port)),
username=opts.get("user", "root"),
key_filename=opts.get("identityfile", None),
sock=paramiko.ProxyCommand(opts["proxycommand"])
if "proxycommand" in opts
else None,
sock=(
paramiko.ProxyCommand(opts["proxycommand"])
if "proxycommand" in opts
else None
),
)

except (paramiko.AuthenticationException, paramiko.BadHostKeyException) as e:
except (paramiko.AuthenticationException, paramiko.BadHostKeyException):
# if public key auth fails, fallback to a password prompt.
# other than ssh, mtui asks only once for a password. this could
# be changed if there is demand for it.
Expand All @@ -151,15 +153,19 @@ def connect(self):
try:
# try again with password auth instead of public/private key
self.client.connect(
hostname=opts.get("hostname", self.hostname)
if "proxycommand" not in opts
else self.hostname,
hostname=(
opts.get("hostname", self.hostname)
if "proxycommand" not in opts
else self.hostname
),
port=int(opts.get("port", self.port)),
username=opts.get("user", "root"),
password=password,
sock=paramiko.ProxyCommand(opts["proxycommand"])
if "proxycommand" in opts
else None,
sock=(
paramiko.ProxyCommand(opts["proxycommand"])
if "proxycommand" in opts
else None
),
)
except paramiko.AuthenticationException as e:
# if a wrong password was set, don't connect to the host and
Expand Down
2 changes: 2 additions & 0 deletions mtui/connector/openqa/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
from .standard import AutoOpenQA
from .kernel import KernelOpenQA

__all__ = [AutoOpenQA, KernelOpenQA]
9 changes: 5 additions & 4 deletions mtui/connector/openqa/base.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from abc import ABCMeta, abstractmethod
from logging import getLogger
from typing import Self

from openqa_client.client import OpenQA_Client as oqa
import openqa_client.exceptions # type: ignore
from openqa_client.client import OpenQA_Client as oqa # type: ignore

logger = getLogger("mtui.connector.openqa")

Expand Down Expand Up @@ -40,14 +41,14 @@ def _get_jobs(self):
return jobs

@abstractmethod
def _pretty_print(self, *args):
def _pretty_print(self, *args) -> list[str]:
pass

@abstractmethod
def run(self):
def run(self) -> Self:
"""Method to get processed result from openQA, can be used for refresh.
For example when is manually changed type of workflow"""
pass

def __bool__(self):
def __bool__(self) -> bool:
return bool(self.results)
11 changes: 6 additions & 5 deletions mtui/connector/openqa/kernel.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from logging import getLogger
from typing import Self

from ...types.test import Test
from .base import OpenQA
Expand Down Expand Up @@ -50,18 +51,18 @@ def _parse_jobs(jobs):
)
]

def _pretty_print(self):
def _pretty_print(self, *args) -> list[str]:
if not self:
return []
lines = []
lines: list[str] = []
lines.insert(0, f"openQA instance: {self.host} :\n")

for i, l in enumerate(self._result_matrix(self.results), start=1):
lines.insert(i, l)
for i, line in enumerate(self._result_matrix(self.results), start=1):
lines.insert(i, line)

return lines

def run(self):
def run(self) -> Self:
jobs = self._get_jobs()
jobs = self._filter_jobs(jobs)
self.results = self._parse_jobs(jobs)
Expand Down
10 changes: 5 additions & 5 deletions mtui/connector/openqa/standard.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from collections import namedtuple
from logging import getLogger
from os.path import join
from typing import Self

from ...types.urls import URLs
from .base import OpenQA
Expand Down Expand Up @@ -28,11 +28,11 @@ def normalize(x):
if y["test"] in ["qam-incidentinstall", "qam-incidentinstall-ha"]
)

def _pretty_print(self, jobs):
def _pretty_print(self, jobs) -> list[str]:
if not jobs:
logger.debug("No job - no results")
return []
ret = []
ret: list[str] = []
ret.append("Results from openQA incidents jobs:\n")
ret.append("===================================\n")
ret.append("\n")
Expand Down Expand Up @@ -73,7 +73,7 @@ def _get_logs_url(self, jobs):
if job["test"] in ["qam-incidentinstall", "qam-incidentinstall-ha"]
]

def run(self):
def run(self) -> Self:
jobs = self._get_jobs()
if self._has_passed_install_jobs(jobs):
self.results = self._get_logs_url(jobs)
Expand All @@ -83,5 +83,5 @@ def run(self):

return self

def __bool__(self):
def __bool__(self) -> bool:
return bool(self.pp) or bool(self.results)
1 change: 0 additions & 1 deletion mtui/connector/smelt.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import requests

from ..messages import RepositoryError
from ..utils import walk

logger = getLogger("mtui.connector.smelt")
Expand Down
2 changes: 2 additions & 0 deletions mtui/export/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from .auto import AutoExport
from .manual import ManualExport
from .kernel import KernelExport

__all__ = [AutoExport, ManualExport, KernelExport]
4 changes: 2 additions & 2 deletions mtui/export/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ def _writer(self, fn, data):

def installlogs_lines(self, filenames):
o = 0
for l in self.template:
if "HAS_UNTRACKED" in l:
for line in self.template:
if "HAS_UNTRACKED" in line:
break
o += 1

Expand Down
6 changes: 3 additions & 3 deletions mtui/export/manual.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,9 @@ def _fillup_hosts_to_template(self):
if version is not None:
self.template[index] = f"\t{name}-{version}\n"
else:
self.templatet[
index
] = f"\tpackage {name} is not installed\n"
self.templatet[index] = (
f"\tpackage {name} is not installed\n"
)
else:
if version is not None:
self.template.insert(index, f"\t{name}-{version}\n")
Expand Down
25 changes: 14 additions & 11 deletions mtui/hooks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import collections
import subprocess
from abc import ABCMeta, abstractmethod
from collections.abc import Callable
from logging import getLogger
from traceback import format_exc

Expand All @@ -8,8 +9,7 @@
log = getLogger("mtui.script")


class Script:

class Script(metaclass=ABCMeta):
"""
:type subdir: Path
:param subdir: subdirectory in the L{TestReport.scripts_wd} where the
Expand All @@ -21,7 +21,9 @@ class Script:
FIXME: should be an abstract attribute
"""

def __init__(self, tr, path):
subdir: str = ""

def __init__(self, tr, path) -> None:
"""
:type path: str
:param path: absolute path to the script
Expand All @@ -31,24 +33,27 @@ def __init__(self, tr, path):
self.bname = path.stem
self.testreport = tr

def __repr__(self):
def __repr__(self) -> str:
return "<{0}.{1} {2} for {3}>".format(
self.__module__, self.__class__.__name__, self.path, repr(self.testreport)
)

def __str__(self):
def __str__(self) -> str:
return "{0} script {1}".format(self.subdir, self.name)

def _result(self, cls, bname, t):
return self.testreport.report_wd(
*cls.result_parts(bname, t.hostname), filepath=True
)

@abstractmethod
def _run(self, targets) -> None: ...

@classmethod
def result_parts(cls, *basename):
return ("output/scripts", ".".join((cls.subdir,) + basename))

def run(self, targets):
def run(self, targets) -> None:
"""
:type targets: [{HostsGroup}]
"""
Expand Down Expand Up @@ -112,7 +117,7 @@ def _run_single_target(self, t):
argv = [str(x) for x in argv]

log.debug("running {0}".format(argv))
stdout = stderr = None

try:
ret = subprocess.run(
argv,
Expand All @@ -135,8 +140,6 @@ def _run_single_target(self, t):
else:
logger, msg = log.warning, messages.CompareScriptFailed

assert isinstance(
logger, collections.abc.Callable
), "{0!r} not callable".format(logger)
assert isinstance(logger, Callable), "{0!r} not callable".format(logger)

logger(msg(argv, ret.stdout, ret.stderr, ret.returncode))
5 changes: 0 additions & 5 deletions mtui/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@


class UserMessage(BaseException, metaclass=ABCMeta):

"""
Message to be displayed to the user
"""
Expand All @@ -19,14 +18,12 @@ def __hash__(cls):


class ErrorMessage(UserMessage, RuntimeError):

"""
Program error message to be displayed to the user
"""


class UserError(UserMessage, RuntimeError):

"""
Error, caused by improper usage of the program,
to be displayed to the user
Expand All @@ -38,7 +35,6 @@ class DeprecationMessage(UserMessage):


class NoRefhostsDefinedError(UserError, ValueError):

"""
Thrown when user requests an operation without defined refhosts
"""
Expand All @@ -48,7 +44,6 @@ def __init__(self):


class HostIsNotConnectedError(UserError, ValueError):

"""
Thrown when user requests an operation to be performed on a host
that is not connected.
Expand Down
1 change: 0 additions & 1 deletion mtui/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ class QuitLoop(RuntimeError):


class CmdQueue(list):

"""
Prerun support.
Expand Down
Loading

0 comments on commit 44ed6b1

Please sign in to comment.