tests: enable more ruff checks

- Checks for missing explicit `return` statements at the end of functions
that can return non-`None` values.
- Checks for classes that inherit from `object`.
- Checks for useless expressions.
- Within an `except*` clause, raise exceptions with `raise ... from err`
or `raise ... from None` to distinguish them from errors in exception
handling
- Checks for variable assignments that immediately precede a `return` of the
assigned variable.
- Checks for `else` statements with a `return` statement in the preceding
`if` block.
- Checks for unnecessary parentheses on raised exceptions.

Closes: #21258
This commit is contained in:
Dan Fandrich 2026-04-02 17:49:37 -07:00
parent 698eee1b95
commit 4c1b6f5494
22 changed files with 72 additions and 84 deletions

View file

@ -27,4 +27,7 @@
# locations, or all Python files found in the current directory tree by
# default.
ruff check --extend-select=B007,B016,C405,C416,COM818,D200,D213,D204,D401,D415,FURB129,N818,PERF401,PERF403,PIE790,PIE808,PLW0127,Q004,RUF010,SIM101,SIM117,SIM118,TRY400,TRY401 "$@"
ruff check --extend-select=B007,B016,C405,C416,COM818,D200,D213,D204,D401,\
D415,FURB129,N818,PERF401,PERF403,PIE790,PIE808,PLW0127,Q004,RUF010,SIM101,\
SIM117,SIM118,TRY400,TRY401,RET503,RET504,UP004,B018,B904,RSE102,RET505 \
"$@"

View file

@ -157,7 +157,7 @@ def setup_logging(options):
root_logger.addHandler(stdout_handler)
class ScriptRC(object):
class ScriptRC:
"""Enum for script return codes."""
SUCCESS = 0

View file

@ -75,10 +75,9 @@ def pytest_report_header(config):
@pytest.fixture(scope='session')
def env_config(pytestconfig, testrun_uid, worker_id) -> EnvConfig:
env_config = EnvConfig(pytestconfig=pytestconfig,
return EnvConfig(pytestconfig=pytestconfig,
testrun_uid=testrun_uid,
worker_id=worker_id)
return env_config
@pytest.fixture(scope='session', autouse=True)

View file

@ -52,11 +52,10 @@ class Card:
def fmt_size(cls, val):
if val >= (1024*1024*1024):
return f'{val / (1024*1024*1024):0.000f}GB'
elif val >= (1024 * 1024):
if val >= (1024 * 1024):
return f'{val / (1024*1024):0.000f}MB'
elif val >= 1024:
if val >= 1024:
return f'{val / 1024:0.000f}KB'
else:
return f'{val:0.000f}B'
@classmethod
@ -65,9 +64,8 @@ class Card:
return '--'
if val >= (1024*1024):
return f'{val/(1024*1024):.3g} MB/s'
elif val >= 1024:
if val >= 1024:
return f'{val / 1024:.3g} KB/s'
else:
return f'{val:.3g} B/s'
@classmethod
@ -76,9 +74,8 @@ class Card:
return '--'
if val >= (10*1024*1024):
return f'{(val/(1024*1024)):.3f} MB/s'
elif val >= (10*1024):
if val >= (10*1024):
return f'{val/1024:.3f} KB/s'
else:
return f'{val:.3f} B/s'
@classmethod
@ -88,9 +85,8 @@ class Card:
pct = ((val / limit) * 100) - 100
if val >= (10*1024*1024):
return f'{(val/(1024*1024)):.3f} MB/s, {pct:+.1f}%'
elif val >= (10*1024):
if val >= (10*1024):
return f'{val/1024:.3f} KB/s, {pct:+.1f}%'
else:
return f'{val:.3f} B/s, {pct:+.1f}%'
@classmethod
@ -255,11 +251,11 @@ class ScoreRunner:
raise Exception(f'unrecognised limit-rate: {self._limit_rate}')
self._limit_rate_num = float(m.group(1))
if m.group(3) == 'g':
self._limit_rate_num *= (1024*1024*1024)
self._limit_rate_num *= 1024*1024*1024
elif m.group(3) == 'm':
self._limit_rate_num *= (1024*1024)
self._limit_rate_num *= 1024*1024
elif m.group(3) == 'k':
self._limit_rate_num *= (1024)
self._limit_rate_num *= 1024
elif m.group(3) == 'b':
pass
else:
@ -368,7 +364,6 @@ class ScoreRunner:
profiles.append(r.profile)
if self._limit_rate:
return Card.mk_speed_cell(samples, profiles, errors, self._limit_rate_num)
else:
return Card.mk_mbs_cell(samples, profiles, errors)
def dl_serial(self, url: str, count: int, nsamples: int = 1):
@ -397,7 +392,6 @@ class ScoreRunner:
profiles.append(r.profile)
if self._limit_rate:
return Card.mk_speed_cell(samples, profiles, errors, self._limit_rate_num)
else:
return Card.mk_mbs_cell(samples, profiles, errors)
def dl_parallel(self, url: str, count: int, nsamples: int = 1):
@ -431,7 +425,6 @@ class ScoreRunner:
profiles.append(r.profile)
if self._limit_rate:
return Card.mk_speed_cell(samples, profiles, errors, self._limit_rate_num)
else:
return Card.mk_mbs_cell(samples, profiles, errors)
def downloads(self, count: int, fsizes: List[int], meta: Dict[str, Any]) -> Dict[str, Any]:

View file

@ -466,7 +466,7 @@ class TestSSLUse:
# clean session file first, then reuse
session_file = os.path.join(env.gen_dir, 'test_17_15.sessions')
if os.path.exists(session_file):
return os.remove(session_file)
os.remove(session_file)
xargs = ['--tls-max', '1.3', '--tlsv1.3', '--ssl-sessions', session_file]
curl = CurlClient(env=env, run_env=run_env)
# tell the server to close the connection after each request

View file

@ -62,11 +62,11 @@ class TestWebsockets:
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def _rmrf(self, path):
if os.path.exists(path):
return shutil.rmtree(path)
shutil.rmtree(path)
@pytest.fixture(autouse=True, scope='class')
def ws_echo(self, env):

View file

@ -143,7 +143,7 @@ class TestVsFTPD:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
# check with `tcpdump` if curl causes any TCP RST packets
@pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available")

View file

@ -148,7 +148,7 @@ class TestVsFTPD:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
# check with `tcpdump` if curl causes any TCP RST packets
@pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available")

View file

@ -161,7 +161,7 @@ class TestFtpsVsFTPD:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
# check with `tcpdump` if curl causes any TCP RST packets
@pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available")

View file

@ -156,11 +156,11 @@ class Caddy:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def _write_config(self):
domain1 = self.env.domain1

View file

@ -101,7 +101,7 @@ class CertificateSpec:
def name(self) -> Optional[str]:
if self._name:
return self._name
elif self.domains:
if self.domains:
return self.domains[0]
return None
@ -109,9 +109,9 @@ class CertificateSpec:
def type(self) -> Optional[str]:
if self.domains and len(self.domains):
return "server"
elif self.client:
if self.client:
return "client"
elif self.name:
if self.name:
return "ca"
return None
@ -144,9 +144,8 @@ class Credentials:
def key_type(self):
if isinstance(self._pkey, RSAPrivateKey):
return f"rsa{self._pkey.key_size}"
elif isinstance(self._pkey, EllipticCurvePrivateKey):
if isinstance(self._pkey, EllipticCurvePrivateKey):
return f"{self._pkey.curve.name}"
else:
raise Exception(f"unknown key type: {self._pkey}")
@property

View file

@ -71,15 +71,15 @@ class LocalClient:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
def _rmrf(self, path):
if os.path.exists(path):
return shutil.rmtree(path)
shutil.rmtree(path)
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def run(self, args):
self._rmf(self._stdoutfile)

View file

@ -673,15 +673,15 @@ class CurlClient:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
def _rmrf(self, path):
if os.path.exists(path):
return shutil.rmtree(path)
shutil.rmtree(path)
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def get_proxy_args(self, proto: str = 'http/1.1',
proxys: bool = True, tunnel: bool = False,
@ -1045,10 +1045,10 @@ class CurlClient:
try:
p.wait(timeout=ptimeout)
break
except subprocess.TimeoutExpired:
except subprocess.TimeoutExpired as e:
if end_at and datetime.now() >= end_at:
p.kill()
raise subprocess.TimeoutExpired(cmd=args, timeout=self._timeout)
raise subprocess.TimeoutExpired(cmd=args, timeout=self._timeout) from e
profile.sample()
ptimeout = 0.01
exitcode = p.returncode
@ -1154,7 +1154,7 @@ class CurlClient:
pass
elif insecure:
args.append('--insecure')
elif active_options and ("--cacert" in active_options or \
elif active_options and ("--cacert" in active_options or
"--capath" in active_options):
pass
elif u.hostname:

View file

@ -145,11 +145,11 @@ class Dante:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def _write_config(self):
conf = [

View file

@ -528,9 +528,7 @@ class Env:
if Env.have_h2_curl():
if Env.have_h3():
return ['http/1.1', 'h2', 'h3']
else:
return ['http/1.1', 'h2']
else:
return ['http/1.1']
@staticmethod
@ -538,7 +536,6 @@ class Env:
# http 1+2 protocols we can test
if Env.have_h2_curl():
return ['http/1.1', 'h2']
else:
return ['http/1.1']
@staticmethod
@ -547,9 +544,7 @@ class Env:
if Env.have_h2_curl():
if Env.have_h3():
return ['h2', 'h3']
else:
return ['h2']
else:
return []
@staticmethod

View file

@ -250,11 +250,11 @@ class Httpd:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def _write_config(self):
domain1 = self.env.domain1
@ -503,7 +503,6 @@ class Httpd:
' Require user proxy',
' </Proxy>',
]
else:
return [
' <Proxy "*">',
' Require ip 127.0.0.1',

View file

@ -193,11 +193,11 @@ class Nghttpx:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def _write_config(self):
with open(self._conf_file, 'w') as fd:

View file

@ -258,11 +258,11 @@ class Sshd:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def _write_config(self):
conf = [

View file

@ -174,11 +174,11 @@ class VsFTPD:
def _rmf(self, path):
if os.path.exists(path):
return os.remove(path)
os.remove(path)
def _mkpath(self, path):
if not os.path.exists(path):
return os.makedirs(path)
os.makedirs(path)
def _write_config(self):
self._mkpath(self._docs_dir)

View file

@ -110,7 +110,7 @@ class NegotiatingTelnetHandler(socketserver.BaseRequestHandler):
except IOError:
log.exception("IOError hit during request")
class Negotiator(object):
class Negotiator:
NO_NEG = 0
START_NEG = 1
WILL = 2
@ -238,7 +238,7 @@ class Negotiator(object):
log.debug("Sending WONT %s", option_str)
self.send_iac([NegTokens.WONT, NegOptions.to_val(option_str)])
class NegBase(object):
class NegBase:
@classmethod
def to_val(cls, name):
return getattr(cls, name)
@ -330,7 +330,7 @@ def setup_logging(options):
stdout_handler.setLevel(logging.DEBUG)
root_logger.addHandler(stdout_handler)
class ScriptRC(object):
class ScriptRC:
"""Enum for script return codes."""
SUCCESS = 0

View file

@ -349,9 +349,9 @@ class TestSmbServer(imp_smbserver.SMBSERVER):
self.write_to_fid(fid, contents)
return fid, filename
except Exception:
except Exception as e:
log.exception("Failed to make test file")
raise SmbError(STATUS_NO_SUCH_FILE, "Failed to make test file")
raise SmbError(STATUS_NO_SUCH_FILE, "Failed to make test file") from e
class SmbError(Exception):
@ -360,7 +360,7 @@ class SmbError(Exception):
self.error_code = error_code
class ScriptRC(object):
class ScriptRC:
"""Enum for script return codes."""
SUCCESS = 0

View file

@ -59,7 +59,7 @@ class ClosingFileHandler(logging.StreamHandler):
self.release()
return result
class TestData(object):
class TestData:
def __init__(self, data_folder):
self.data_folder = data_folder