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

@ -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,
testrun_uid=testrun_uid,
worker_id=worker_id)
return env_config
return EnvConfig(pytestconfig=pytestconfig,
testrun_uid=testrun_uid,
worker_id=worker_id)
@pytest.fixture(scope='session', autouse=True)

View file

@ -52,12 +52,11 @@ 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'
return f'{val:0.000f}B'
@classmethod
def fmt_mbs(cls, val):
@ -65,10 +64,9 @@ 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'
return f'{val:.3g} B/s'
@classmethod
def fmt_speed(cls, val):
@ -76,10 +74,9 @@ 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'
return f'{val:.3f} B/s'
@classmethod
def fmt_speed_result(cls, val, limit):
@ -88,10 +85,9 @@ 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}%'
return f'{val:.3f} B/s, {pct:+.1f}%'
@classmethod
def fmt_reqs(cls, val):
@ -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,8 +364,7 @@ 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)
return Card.mk_mbs_cell(samples, profiles, errors)
def dl_serial(self, url: str, count: int, nsamples: int = 1):
samples = []
@ -397,8 +392,7 @@ 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)
return Card.mk_mbs_cell(samples, profiles, errors)
def dl_parallel(self, url: str, count: int, nsamples: int = 1):
samples = []
@ -431,8 +425,7 @@ 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)
return Card.mk_mbs_cell(samples, profiles, errors)
def downloads(self, count: int, fsizes: List[int], meta: Dict[str, Any]) -> Dict[str, Any]:
nsamples = meta['samples']

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,10 +144,9 @@ 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}")
raise Exception(f"unknown key type: {self._pkey}")
@property
def private_key(self) -> Any:

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,18 +528,15 @@ 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']
return ['http/1.1', 'h2']
return ['http/1.1']
@staticmethod
def http_h1_h2_protos() -> List[str]:
# http 1+2 protocols we can test
if Env.have_h2_curl():
return ['http/1.1', 'h2']
else:
return ['http/1.1']
return ['http/1.1']
@staticmethod
def http_mplx_protos() -> List[str]:
@ -547,10 +544,8 @@ class Env:
if Env.have_h2_curl():
if Env.have_h3():
return ['h2', 'h3']
else:
return ['h2']
else:
return []
return ['h2']
return []
@staticmethod
def have_h3() -> bool:

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,12 +503,11 @@ class Httpd:
' Require user proxy',
' </Proxy>',
]
else:
return [
' <Proxy "*">',
' Require ip 127.0.0.1',
' </Proxy>',
]
return [
' <Proxy "*">',
' Require ip 127.0.0.1',
' </Proxy>',
]
def _get_log_level(self):
if self.env.verbose > 3:

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)