Files
computer-playbook/tests/unit/python/utils/cleanup/test_tokens.py
kevinveenbirkenbachandClaude Opus 5 575a5a87ac refactor(layout): sort shipped scripts by language and split the unit suite
Every script a role ships now lives under `files/<language>/`, and the unit
suite is split the same way: `tests/unit/python/` beside new sibling trees for
the other languages. `tests/lint/filesystem/test_role_files_layout.py` keeps it
that way; directories whose shape is dictated from outside carry a `.nocheck`
naming the constraint (Docker build contexts, WordPress mu-plugins, the Joomla
extension, Odoo addons, Playwright suites, the `files/test/test.sh` harness
that `test-e2e-cli` resolves generically).

This cannot be applied in halves. Moving a file and repointing what names it
are the same change: 14 references resolve only at deploy time, so the tree is
green either before or after, never between.

Those 14 were found by static resolution over every reference class, not by the
test suite -- a full `make quality-high` was green while all of them were
broken:

  * 7 `src:` values built from a role variable holding a bare filename
    (svc-bkp-remote-2-local, decidim, espocrm, friendica, joomla, pixelfed x2).
    The variable doubles as the destination name inside the container, so the
    language segment belongs at the call site, not in the variable.
  * `sys-service/tasks/04_base.yml` resolved every consumer's systemd script
    through `first_found(..., errors='strict')` over `files/script.{sh,py}`.
    18 roles ship exactly that and have no template fallback: the play would
    have died on each.
  * `sys-front-inj-javascript` fell back to `<role>/files/javascript.js`; the
    interface now reads `files/javascript/javascript.js`.
  * `sys-front-inj-logout/templates/head_sub.j2` built the cache-busting mtime
    path through `path_absolute(... 'files', ...)`.
  * 4 `ansible.builtin.script:` invocations naming a bare command
    (pull.py, prune.sh, set_postgres_superuser_password.sh, ganesha-serve.sh).
  * `dev-python/files/shell/install.sh` pointed at a sibling role's script.

Depth-dependent paths inside the moved trees were bumped accordingly: 59
`parents[N]` computations, 12 relative climbs, and the per-role recover CLI,
whose path `cli/administration/recover/recoverers.py` still assembled from the
pre-move location.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 01:31:09 +02:00

157 lines
4.9 KiB
Python

"""Unit tests for `utils.cleanup.tokens` (token-store wipe helper)."""
from __future__ import annotations
import io
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from tempfile import TemporaryDirectory
from utils.cache.yaml import _reset_cache_for_tests, load_yaml_any
from utils.cleanup.tokens import main, wipe_tokens
class TokensTestBase(unittest.TestCase):
def setUp(self) -> None:
_reset_cache_for_tests()
self._tmp = TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
self.tokens_file = Path(self._tmp.name) / "tokens.yml"
def _write(self, content: str) -> None:
self.tokens_file.write_text(content, encoding="utf-8")
class TestWipeTokens(TokensTestBase, unittest.TestCase):
def test_removes_matching_entry(self):
self._write(
"users:\n"
" administrator:\n"
" tokens:\n"
" web-app-matomo: T1\n"
" web-app-keycloak: T2\n"
)
removed = wipe_tokens(["web-app-matomo"], tokens_file=self.tokens_file)
self.assertEqual(removed, ["administrator.web-app-matomo"])
on_disk = load_yaml_any(str(self.tokens_file))
self.assertEqual(
on_disk["users"]["administrator"]["tokens"],
{"web-app-keycloak": "T2"},
)
def test_no_match_does_not_rewrite_file(self):
self._write(
"users:\n administrator:\n tokens:\n web-app-keycloak: T2\n"
)
before_mtime = self.tokens_file.stat().st_mtime_ns
removed = wipe_tokens(["web-app-matomo"], tokens_file=self.tokens_file)
self.assertEqual(removed, [])
self.assertEqual(self.tokens_file.stat().st_mtime_ns, before_mtime)
def test_missing_file_returns_empty(self):
removed = wipe_tokens(["web-app-matomo"], tokens_file=self.tokens_file)
self.assertEqual(removed, [])
self.assertFalse(self.tokens_file.exists())
def test_wipes_from_multiple_users(self):
self._write(
"users:\n"
" administrator:\n"
" tokens:\n"
" web-app-matomo: T1\n"
" ci-bot:\n"
" tokens:\n"
" web-app-matomo: T9\n"
" web-app-keycloak: T2\n"
)
removed = wipe_tokens(["web-app-matomo"], tokens_file=self.tokens_file)
self.assertEqual(
sorted(removed),
["administrator.web-app-matomo", "ci-bot.web-app-matomo"],
)
on_disk = load_yaml_any(str(self.tokens_file))
self.assertEqual(on_disk["users"]["administrator"]["tokens"], {})
self.assertEqual(
on_disk["users"]["ci-bot"]["tokens"],
{"web-app-keycloak": "T2"},
)
def test_multiple_app_ids_in_one_call(self):
self._write(
"users:\n"
" administrator:\n"
" tokens:\n"
" web-app-matomo: T1\n"
" web-app-keycloak: T2\n"
" web-app-akaunting: T3\n"
)
removed = wipe_tokens(
["web-app-matomo", "web-app-akaunting"],
tokens_file=self.tokens_file,
)
self.assertEqual(
sorted(removed),
["administrator.web-app-akaunting", "administrator.web-app-matomo"],
)
on_disk = load_yaml_any(str(self.tokens_file))
self.assertEqual(
on_disk["users"]["administrator"]["tokens"],
{"web-app-keycloak": "T2"},
)
def test_user_without_tokens_field_is_skipped(self):
self._write(
"users:\n"
" administrator:\n"
" email: admin@example.org\n"
" ci-bot:\n"
" tokens:\n"
" web-app-matomo: T1\n"
)
removed = wipe_tokens(["web-app-matomo"], tokens_file=self.tokens_file)
self.assertEqual(removed, ["ci-bot.web-app-matomo"])
def test_non_dict_user_entry_is_skipped(self):
self._write(
"users:\n"
" legacy-string-entry: just-a-string\n"
" administrator:\n"
" tokens:\n"
" web-app-matomo: T1\n"
)
removed = wipe_tokens(["web-app-matomo"], tokens_file=self.tokens_file)
self.assertEqual(removed, ["administrator.web-app-matomo"])
class TestMainShim(TokensTestBase, unittest.TestCase):
def test_no_argv_prints_usage_and_returns_2(self):
stderr = io.StringIO()
with redirect_stderr(stderr):
rc = main([])
self.assertEqual(rc, 2)
self.assertIn("usage:", stderr.getvalue())
def test_main_uses_default_path_when_no_override(self):
stdout = io.StringIO()
with redirect_stdout(stdout):
rc = main(["web-app-nonexistent"])
self.assertEqual(rc, 0)
self.assertIn("No token entries to wipe", stdout.getvalue())
if __name__ == "__main__": # pragma: no cover
unittest.main()