mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-09 12:17:13 +00:00
Extends ``[tool.ruff.lint].select`` with six additional rule families:
``RUF`` (ruff-specific), ``SIM`` (flake8-simplify), ``C4``
(flake8-comprehensions), ``PERF`` (perflint), ``RET`` (flake8-return),
``PIE`` (flake8-pie). Adds ``RUF001/002/003`` to ``ignore`` because
those exist for homoglyph-attack detection, not English typography —
the project uses em/en-dashes and ``ℹ`` as a UI-hint glyph in CLI help
output deliberately.
Auto-fixed (~225, mechanical & behavior-preserving)
====================================================
- RUF005: ``a + [b]`` → ``[*a, b]``
- C408: ``dict(k=v)`` → ``{"k": v}``
- C420: ``dict.fromkeys(seq)`` shape simplifications
- SIM103/SIM110/SIM118: truthy-return / dict-key / dict-method
idiom simplifications
- RET504/RET505: drop unneeded final assigns / ``else`` after
``return``
- PIE810: combine ``str.startswith(a) or .startswith(b)``
into one call with a tuple
- RUF010: ``f"{str(x)}"`` → ``f"{x\!s}"``
- RUF100: removed unused ``# noqa`` directives that
became stale (mostly old ``# noqa: E402``
markers that ruff's smart E402 implementation
no longer flags after ``sys.path`` shims)
- RUF015 / RUF013 / RUF022 / RUF046 / RUF059: misc small wins
- I001: re-sorted import blocks where the new
imports above shifted them
Hand-fixed (~140, scripted where mechanical)
============================================
PERF401 (42): scripted AST rewrite of
``for x in iter: target.append(expr)`` (with optional ``if`` guard)
→ ``target.extend(expr for x in iter [if cond])``.
``list.extend(genexp)`` consumes the generator immediately, so the
rewrite is semantically equivalent to the original eager loop.
SIM117 (41): scripted AST combiner for nested ``with`` blocks where
the inner is the only statement of the outer (38 sites). The remaining
3 multi-line ``patch.object(...)`` chains were combined by hand using
the parenthesised ``with (\\n A,\\n B,\\n):`` form.
SIM102 (14): scripted AST combiner for nested ``if`` (10 sites). The
remaining 4 carry an inline ``# noqa: SIM102`` with rationale —
combining would either change semantics (the outer body has siblings
beyond the inner ``if``, e.g. ``cli/encrypt/inventory/__main__.py``
where ``encrypted_value = …`` runs regardless of ``ask_confirmation``)
or hurt readability (long literal whitelists).
RUF012 (9): annotated mutable class attributes with ``ClassVar[…]``
and added ``from typing import ClassVar``.
SIM105 (6): ``try/except: pass`` → ``with contextlib.suppress(…):``
with the necessary ``import contextlib`` added. Verified on
``utils/templating.py`` (3 occurrences in a ``finally`` block) —
cleanup behaviour is identical.
SIM115 (4): wrapped ``tempfile.NamedTemporaryFile(..., delete=False)``
call patterns in a ``with`` block; ``delete=False`` keeps the file
on disk after the block, so callers' ``return f.name`` still works.
PERF402, PERF403, B007, SIM108, SIM103: 5 misc fixes (loop→list-copy,
loop→dict-comprehension, unused-loop-var rename, ternary, return
expression).
Verification
============
- ``ruff check .`` → All checks passed
- ``ruff format --check .`` → 894 files already formatted
- 1621 unit tests → all pass
- Integration suite: 44 baseline failures, 1 skipped (unchanged)
- Sample-audited PERF401 rewrites in ``resolver.py``, ``inventory.py``,
``cache/files.py``, ``ressources/__main__.py``; SIM117 in
``test_main.py``; SIM105 in ``utils/templating.py``; SIM102 noqa
rationales in ``cli/encrypt/inventory/__main__.py``.
182 files changed, +993 / −960. With this and the prior strict-rule
commit the branch satisfies 11 ruff rule families end-to-end.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
160 lines
5.8 KiB
Python
160 lines
5.8 KiB
Python
#
|
|
# Unit tests for plugins/lookup/unit_name.py using Python's built-in unittest.
|
|
#
|
|
# Run with:
|
|
# python -m unittest -v
|
|
#
|
|
# Notes:
|
|
# - These tests do NOT require a full Ansible runtime; we mock the templar.
|
|
# - They validate the naming format and error handling.
|
|
|
|
import unittest
|
|
|
|
from ansible.errors import AnsibleError
|
|
|
|
# Import your lookup plugin (adjust import path if your repo layout differs)
|
|
from plugins.lookup.unit_name import LookupModule
|
|
|
|
|
|
class DummyTemplar:
|
|
"""Minimal templar stub to satisfy the lookup plugin."""
|
|
|
|
def __init__(self, available_variables=None, version="1.2.3"):
|
|
self.available_variables = available_variables or {}
|
|
self._version = version
|
|
|
|
def template(self, s: str, **kwargs):
|
|
# The plugin calls: self._templar.template("{{ lookup('version') }}")
|
|
if "lookup('version')" in s:
|
|
return self._version
|
|
if "{{ SOFTWARE_NAME | lower }}" in s:
|
|
return str(self.available_variables.get("SOFTWARE_NAME", "")).lower()
|
|
return s
|
|
|
|
|
|
class UnitNameLookupTests(unittest.TestCase):
|
|
def _mk_lookup(
|
|
self, software_domain="infinito.nexus", version="1.2.3"
|
|
) -> LookupModule:
|
|
lm = LookupModule()
|
|
|
|
# Inject a dummy templar with variables
|
|
lm._templar = DummyTemplar(
|
|
available_variables={"SOFTWARE_DOMAIN": software_domain},
|
|
version=version,
|
|
)
|
|
|
|
# The plugin calls set_options(); for unit tests we make it a no-op
|
|
lm.set_options = lambda *args, **kwargs: None
|
|
|
|
return lm
|
|
|
|
def test_default_suffix_service(self):
|
|
lm = self._mk_lookup(software_domain="Infinito.Nexus", version="2.0.0")
|
|
res = lm.run(["svc-foo"])
|
|
self.assertEqual(res, ["svc-foo.2.0.0.infinito.nexus.service"])
|
|
|
|
def test_sys_ctl_prefix_is_removed(self):
|
|
lm = self._mk_lookup(software_domain="Infinito.Nexus", version="2.0.0")
|
|
res = lm.run(["sys-ctl-cln-bkps"])
|
|
self.assertEqual(res, ["cln-bkps.2.0.0.infinito.nexus.service"])
|
|
|
|
def test_explicit_timer_suffix_with_dot(self):
|
|
lm = self._mk_lookup(software_domain="infinito.nexus", version="2.0.0")
|
|
res = lm.run(["svc-foo"], suffix=".timer")
|
|
self.assertEqual(res, ["svc-foo.2.0.0.infinito.nexus.timer"])
|
|
|
|
def test_explicit_timer_suffix_without_dot(self):
|
|
lm = self._mk_lookup(software_domain="infinito.nexus", version="2.0.0")
|
|
res = lm.run(["svc-foo"], suffix="timer")
|
|
self.assertEqual(res, ["svc-foo.2.0.0.infinito.nexus.timer"])
|
|
|
|
def test_suffix_false_means_no_suffix(self):
|
|
lm = self._mk_lookup(software_domain="infinito.nexus", version="2.0.0")
|
|
res = lm.run(["svc-foo"], suffix=False)
|
|
self.assertEqual(res, ["svc-foo.2.0.0.infinito.nexus"])
|
|
|
|
def test_template_unit_id_endswith_at(self):
|
|
lm = self._mk_lookup(software_domain="infinito.nexus", version="2.0.0")
|
|
res = lm.run(["alarm@"])
|
|
# Template semantics: "<base>.<ver>.<sw>@.service"
|
|
self.assertEqual(res, ["alarm.2.0.0.infinito.nexus@.service"])
|
|
|
|
def test_template_unit_id_endswith_at_with_sys_ctl_prefix(self):
|
|
lm = self._mk_lookup(software_domain="infinito.nexus", version="2.0.0")
|
|
res = lm.run(["sys-ctl-alm-compose@"], suffix=False)
|
|
self.assertEqual(res, ["alm-compose.2.0.0.infinito.nexus@"])
|
|
|
|
def test_multiple_terms(self):
|
|
lm = self._mk_lookup(software_domain="infinito.nexus", version="2.0.0")
|
|
res = lm.run(["a", "b"], suffix=".timer")
|
|
self.assertEqual(
|
|
res,
|
|
[
|
|
"a.2.0.0.infinito.nexus.timer",
|
|
"b.2.0.0.infinito.nexus.timer",
|
|
],
|
|
)
|
|
|
|
def test_missing_terms_raises(self):
|
|
lm = self._mk_lookup()
|
|
with self.assertRaises(AnsibleError) as ctx:
|
|
lm.run([])
|
|
self.assertIn("at least one term", str(ctx.exception))
|
|
|
|
def test_missing_software_name_raises(self):
|
|
lm = LookupModule()
|
|
lm._templar = DummyTemplar(available_variables={}, version="1.2.3")
|
|
lm.set_options = lambda *args, **kwargs: None
|
|
|
|
with self.assertRaises(AnsibleError) as ctx:
|
|
lm.run(["svc-foo"])
|
|
self.assertIn("SOFTWARE_DOMAIN is not defined", str(ctx.exception))
|
|
|
|
def test_empty_version_raises(self):
|
|
lm = self._mk_lookup(software_domain="infinito.nexus", version=" ")
|
|
with self.assertRaises(AnsibleError) as ctx:
|
|
lm.run(["svc-foo"])
|
|
self.assertIn("lookup('version') returned an empty value", str(ctx.exception))
|
|
|
|
def test_templated_software_domain_is_rendered(self):
|
|
lm = LookupModule()
|
|
lm._templar = DummyTemplar(
|
|
available_variables={
|
|
"SOFTWARE_DOMAIN": "{{ SOFTWARE_NAME | lower }}",
|
|
"SOFTWARE_NAME": "Infinito.Nexus",
|
|
},
|
|
version="2.0.0",
|
|
)
|
|
lm.set_options = lambda *args, **kwargs: None
|
|
|
|
res = lm.run(["svc-foo"])
|
|
self.assertEqual(res, ["svc-foo.2.0.0.infinito.nexus.service"])
|
|
|
|
def test_unresolved_software_domain_template_raises(self):
|
|
lm = LookupModule()
|
|
lm._templar = DummyTemplar(
|
|
available_variables={"SOFTWARE_DOMAIN": "{{ UNKNOWN_VAR | lower }}"},
|
|
version="2.0.0",
|
|
)
|
|
lm.set_options = lambda *args, **kwargs: None
|
|
|
|
with self.assertRaises(AnsibleError) as ctx:
|
|
lm.run(["svc-foo"])
|
|
self.assertIn("unresolved template for 'SOFTWARE_DOMAIN'", str(ctx.exception))
|
|
|
|
def test_version_fallback_direct_lookup_plugin(self):
|
|
lm = self._mk_lookup(
|
|
software_domain="infinito.nexus", version="{{ lookup('version') }}"
|
|
)
|
|
res = lm.run(["svc-foo"])
|
|
|
|
self.assertRegex(
|
|
res[0],
|
|
r"^svc-foo\.[0-9A-Za-z._+-]+\.infinito\.nexus\.service$",
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|