mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-13 14:16:46 +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>
181 lines
7.5 KiB
Python
181 lines
7.5 KiB
Python
import os
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
import unittest.mock
|
|
|
|
import yaml
|
|
|
|
from cli.create.credentials import ask_for_confirmation, main
|
|
from utils.handler.vault import VaultHandler
|
|
|
|
|
|
class TestCreateCredentials(unittest.TestCase):
|
|
def test_ask_for_confirmation_yes(self):
|
|
with unittest.mock.patch("builtins.input", return_value="y"):
|
|
self.assertTrue(ask_for_confirmation("test_key"))
|
|
|
|
def test_ask_for_confirmation_no(self):
|
|
with unittest.mock.patch("builtins.input", return_value="n"):
|
|
self.assertFalse(ask_for_confirmation("test_key"))
|
|
|
|
def test_vault_encrypt_string_success(self):
|
|
handler = VaultHandler("dummy_pw_file")
|
|
# Mock subprocess.run to simulate successful vault encryption
|
|
fake_output = "Encrypted data"
|
|
completed = subprocess.CompletedProcess(
|
|
args=["ansible-vault"], returncode=0, stdout=fake_output, stderr=""
|
|
)
|
|
with unittest.mock.patch("subprocess.run", return_value=completed) as proc_run:
|
|
result = handler.encrypt_string("plain_val", "name")
|
|
proc_run.assert_called_once()
|
|
self.assertEqual(result, fake_output)
|
|
|
|
def test_vault_encrypt_string_failure(self):
|
|
handler = VaultHandler("dummy_pw_file")
|
|
# Mock subprocess.run to simulate failure
|
|
completed = subprocess.CompletedProcess(
|
|
args=["ansible-vault"], returncode=1, stdout="", stderr="error"
|
|
)
|
|
with (
|
|
unittest.mock.patch("subprocess.run", return_value=completed),
|
|
self.assertRaises(RuntimeError),
|
|
):
|
|
handler.encrypt_string("plain_val", "name")
|
|
|
|
def test_main_overrides_and_file_writing(self):
|
|
# Setup temporary files for role-path vars and inventory
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
role_path = os.path.join(tmpdir, "role")
|
|
os.makedirs(os.path.join(role_path, "meta"))
|
|
os.makedirs(os.path.join(role_path, "vars"))
|
|
# Create vars/main.yml with application_id
|
|
main_vars = {"application_id": "app_test"}
|
|
with open(os.path.join(role_path, "vars", "main.yml"), "w") as f:
|
|
yaml.dump(main_vars, f)
|
|
# Create config/main.yml with features disabled
|
|
config = {"features": {"central_database": False}}
|
|
with open(os.path.join(role_path, "meta", "services.yml"), "w") as f:
|
|
yaml.dump(config, f)
|
|
# Create schema.yml defining plain credential
|
|
schema = {
|
|
"credentials": {
|
|
"api_key": {
|
|
"description": "API key",
|
|
"algorithm": "plain",
|
|
"validation": {},
|
|
}
|
|
}
|
|
}
|
|
with open(os.path.join(role_path, "meta", "schema.yml"), "w") as f:
|
|
yaml.dump(schema, f)
|
|
# Prepare inventory file
|
|
inventory_file = os.path.join(tmpdir, "inventory.yml")
|
|
with open(inventory_file, "w") as f:
|
|
yaml.dump({}, f)
|
|
vault_pw_file = os.path.join(tmpdir, "pw.txt")
|
|
with open(vault_pw_file, "w") as f:
|
|
f.write("pw")
|
|
|
|
# Simulate ansible-vault encrypt_string output for api_key
|
|
fake_snippet = "!vault |\n $ANSIBLE_VAULT;1.1;AES256\n ENCRYPTEDVALUE"
|
|
completed = subprocess.CompletedProcess(
|
|
args=["ansible-vault"], returncode=0, stdout=fake_snippet, stderr=""
|
|
)
|
|
with unittest.mock.patch("subprocess.run", return_value=completed):
|
|
# Run main with override for credentials.api_key and force to skip prompt
|
|
sys.argv = [
|
|
"create/credentials.py",
|
|
"--role-path",
|
|
role_path,
|
|
"--inventory-file",
|
|
inventory_file,
|
|
"--vault-password-file",
|
|
vault_pw_file,
|
|
"--set",
|
|
"credentials.api_key=SECRET",
|
|
"--force",
|
|
]
|
|
# Should complete without error
|
|
main()
|
|
# Verify inventory file updated with vaulted api_key
|
|
with open(inventory_file) as f:
|
|
data = yaml.safe_load(f)
|
|
creds = data["applications"]["app_test"]["credentials"]
|
|
self.assertIn("api_key", creds)
|
|
# VaultScalar serializes to a vault block, safe_load returns a string containing the vault header
|
|
self.assertIsInstance(creds["api_key"], str)
|
|
self.assertTrue(creds["api_key"].lstrip().startswith("$ANSIBLE_VAULT"))
|
|
|
|
def test_main_plain_algorithm_allow_empty_plain_sets_empty_string_without_vault(
|
|
self,
|
|
):
|
|
"""
|
|
When --allow-empty-plain is used, a 'plain' credential without override
|
|
should be set to "" and *not* encrypted (no ansible-vault calls).
|
|
"""
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
role_path = os.path.join(tmpdir, "role")
|
|
os.makedirs(os.path.join(role_path, "meta"))
|
|
os.makedirs(os.path.join(role_path, "vars"))
|
|
|
|
# vars/main.yml with application_id
|
|
main_vars = {"application_id": "app_empty_plain"}
|
|
with open(os.path.join(role_path, "vars", "main.yml"), "w") as f:
|
|
yaml.dump(main_vars, f)
|
|
|
|
# config/main.yml
|
|
config = {"features": {"central_database": False}}
|
|
with open(os.path.join(role_path, "meta", "services.yml"), "w") as f:
|
|
yaml.dump(config, f)
|
|
|
|
# schema/main.yml: plain credential *without* overrides
|
|
schema = {
|
|
"credentials": {
|
|
"api_key": {
|
|
"description": "API key",
|
|
"algorithm": "plain",
|
|
"validation": {},
|
|
}
|
|
}
|
|
}
|
|
with open(os.path.join(role_path, "meta", "schema.yml"), "w") as f:
|
|
yaml.dump(schema, f)
|
|
|
|
# Empty inventory file
|
|
inventory_file = os.path.join(tmpdir, "inventory.yml")
|
|
with open(inventory_file, "w") as f:
|
|
yaml.dump({}, f)
|
|
|
|
# Vault password file
|
|
vault_pw_file = os.path.join(tmpdir, "pw.txt")
|
|
with open(vault_pw_file, "w") as f:
|
|
f.write("pw")
|
|
|
|
# Ensure ansible-vault is *not* called at all in this scenario
|
|
def fail_run(*_args, **_kwargs):
|
|
raise AssertionError(
|
|
"ansible-vault must not be called for allow_empty_plain + empty plain"
|
|
)
|
|
|
|
with unittest.mock.patch("subprocess.run", side_effect=fail_run):
|
|
sys.argv = [
|
|
"create/credentials.py",
|
|
"--role-path",
|
|
role_path,
|
|
"--inventory-file",
|
|
inventory_file,
|
|
"--vault-password-file",
|
|
vault_pw_file,
|
|
"--allow-empty-plain",
|
|
]
|
|
main()
|
|
|
|
with open(inventory_file) as f:
|
|
data = yaml.safe_load(f)
|
|
creds = data["applications"]["app_empty_plain"]["credentials"]
|
|
# api_key should exist and be an empty string, not a vault block
|
|
self.assertIn("api_key", creds)
|
|
self.assertEqual(creds["api_key"], "")
|