Files
chemenu/tools/chemenu/tests/test_legacy_settings.py
T
torbenandClaude Opus 5.5 0fce67e6b9
CI / verify (push) Successful in 8m31s
CI / pwsh (push) Successful in 2m51s
Converters / converters (push) Successful in 9m42s
Release / converters (push) Successful in 26s
Release / release (push) Successful in 41s
Release / wiki-mirror (push) Skipped
tools, instructions: Abhängigkeiten - Tests biegen config-Pfade über set_config_path um (pytest 9.2), Teardown-Wache; Befehlsreferenz mit typer 0.29 neu erzeugt, typer>=0.29.1, kein click mehr in Tests (#243); 10.2.0-beta.2
Files changed:
- CHANGES.md
- VERSION
- docs/reference/commands/configuration.md
- docs/reference/commands/content-migrations.md
- docs/reference/commands/distribution-and-versioning.md
- docs/reference/commands/exports.md
- docs/reference/commands/finding-and-checking.md
- docs/reference/commands/git.md
- docs/reference/commands/pages.md
- docs/reference/commands/raw-material-and-uploads.md
- docs/reference/commands/types-instructions-and-docs.md
- instructions/dev/testing-conventions.md
- tools/chemenu/config.py
- tools/chemenu/tests/conftest.py
- tools/chemenu/tests/test_api.py
- tools/chemenu/tests/test_backup.py
- tools/chemenu/tests/test_cite_cmd.py
- tools/chemenu/tests/test_collect.py
- tools/chemenu/tests/test_config_shapes.py
- tools/chemenu/tests/test_conventions.py
- tools/chemenu/tests/test_corpus_cache.py
- tools/chemenu/tests/test_dist_cmd.py
- tools/chemenu/tests/test_dist_upgrade.py
- tools/chemenu/tests/test_docs_verify.py
- tools/chemenu/tests/test_doctor.py
- tools/chemenu/tests/test_export_guidelines.py
- tools/chemenu/tests/test_export_run.py
- tools/chemenu/tests/test_git_publish.py
- tools/chemenu/tests/test_hermetic_env.py
- tools/chemenu/tests/test_install_doc.py
- tools/chemenu/tests/test_instructions_cmd.py
- tools/chemenu/tests/test_kb_collections.py
- tools/chemenu/tests/test_legacy_settings.py
- tools/chemenu/tests/test_lint.py
- tools/chemenu/tests/test_log_append.py
- tools/chemenu/tests/test_migrate_cmd.py
- tools/chemenu/tests/test_new_page.py
- tools/chemenu/tests/test_page_ops.py
- tools/chemenu/tests/test_pipeline_l0.py
- tools/chemenu/tests/test_preflight.py
- tools/chemenu/tests/test_provenance.py
- tools/chemenu/tests/test_reference_doc.py
- tools/chemenu/tests/test_review.py
- tools/chemenu/tests/test_settings.py
- tools/chemenu/tests/test_task_cmd.py
- tools/chemenu/tests/test_telemetry_policy.py
- tools/chemenu/tests/test_toc.py
- tools/chemenu/tests/test_touch.py
- tools/chemenu/tests/test_upload_cmd.py
- tools/chemenu/tests/test_version_cmd.py
- tools/chemenu/tests/test_work_cmd.py
- tools/requirements.txt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015uxGFdBAmyA23g1isCtGEY
2026-11-18 15:52:24 +01:00

440 lines
20 KiB
Python

"""The move out of the per-feature settings files of earlier versions
(`chemenu.legacy_settings`, `wikitool config migrate`), and what a leftover of
them does to a command.
The old files are written here by hand, in the shapes they had. Their readers
no longer exist, so "the same effective value" is held against literals that
state what each old file meant - including the defaults of every field it left
out - and read back through the readers the commands use today.
"""
from __future__ import annotations
import json
import subprocess
from dataclasses import asdict
from pathlib import Path
import pytest
from typer.testing import CliRunner
from chemenu import config, config_shapes, legacy_settings, settings, upload
from chemenu.cli import app
from chemenu.tasks import caldav, config as tasks_config, superproductivity
from chemenu.telemetry import policy
from chemenu.tests.conftest import set_config_path
runner = CliRunner()
TOKEN = "sekrit-token-value-0451"
APP_PASSWORD = "sekrit-app-password-0815"
THRESHOLDS = {"stalled_waiting_days": 14, "unpaged_project_weeks": 3, "someday_stale_months": 5}
# name -> (old files by file name, what is in effect afterwards)
_MCP_CHANNEL = {"name": "mcp", "handler": "mcp", "path": None, "settle_seconds": 60,
"command_name": "", "command": ()}
CASES = {
"telemetry-full": (
{".wikitool-telemetry.json": {"schema": 1, "enabled": False, "max_session_bytes": 1000,
"keep_sessions": 9}},
{"telemetry": {"enabled": False, "max_session_bytes": 1000, "keep_sessions": 9}},
),
"telemetry-defaults": (
{".wikitool-telemetry.json": {"keep_sessions": 12}},
{"telemetry": {"enabled": True, "max_session_bytes": 5 * 1024 * 1024, "keep_sessions": 12}},
),
"telemetry-coerced": (
{".wikitool-telemetry.json": {"enabled": 0, "keep_sessions": "7"}},
{"telemetry": {"enabled": False, "max_session_bytes": 5 * 1024 * 1024, "keep_sessions": 7}},
),
"remotes": (
{".wikitool-remotes.json": {"schema": 1, "allowed_push_urls": ["ssh://git@example.net/a.git",
"ssh://git@example.net/b.git"]}},
{"remotes": ["ssh://git@example.net/a.git", "ssh://git@example.net/b.git"]},
),
"upload-full": (
{".wikitool-upload.json": {
"schema": 1, "identity_header": "X-Forwarded-User", "max_bytes": 2048,
"allowed_extensions": [".md", ".txt"],
"quota": {"submissions_per_day": 4, "bytes_per_day": 9000}}},
{"upload": {**_MCP_CHANNEL, "identity_header": "X-Forwarded-User", "max_bytes": 2048,
"allowed_extensions": (".md", ".txt"), "submissions_per_day": 4,
"bytes_per_day": 9000}},
),
"upload-defaults": (
{".wikitool-upload.json": {"max_bytes": 100, "allowed_extensions": [".md"],
"quota": {"submissions_per_day": 1, "bytes_per_day": 5}}},
{"upload": "identity-header-by-default"},
),
"superproductivity-api": (
{".wikitool-tasks.json": {
"schema": 1, "provider": "superproductivity", "thresholds": THRESHOLDS,
"superproductivity": {"access": "api", "api_base_url": "http://127.0.0.1:3876",
"api_token": TOKEN}}},
{"tasks": {"provider": "superproductivity", "thresholds": THRESHOLDS,
"provider_values": {"access": "api", "api_base_url": "http://127.0.0.1:3876",
"api_token": TOKEN, "backups_dir": None}}},
),
"superproductivity-snapshot": (
{".wikitool-tasks.json": {
"schema": 1, "provider": "superproductivity", "thresholds": THRESHOLDS,
"superproductivity": {"access": "snapshot", "backups_dir": "/var/backups/sp"}}},
{"tasks": {"provider": "superproductivity", "thresholds": THRESHOLDS,
"provider_values": {"access": "snapshot", "api_base_url": "http://127.0.0.1:3876",
"api_token": None, "backups_dir": "/var/backups/sp"}}},
),
"caldav": (
{".wikitool-tasks.json": {
"schema": 1, "provider": "caldav", "thresholds": THRESHOLDS,
"caldav": {"url": "https://dav.example.net/u/cal", "username": "anna",
"app_password": APP_PASSWORD, "inbox_list": "Eingang",
"someday_list": "Irgendwann", "exclude_lists": ["Privat", "Archiv"]}}},
{"tasks": {"provider": "caldav", "thresholds": THRESHOLDS,
"provider_values": {"url": "https://dav.example.net/u/cal/", "username": "anna",
"app_password": APP_PASSWORD, "inbox_list": "Eingang",
"someday_list": "Irgendwann",
"exclude_lists": ("Privat", "Archiv")}}},
),
"everything-at-once": (
{
".wikitool-telemetry.json": {"enabled": False},
".wikitool-remotes.json": {"allowed_push_urls": ["ssh://git@example.net/a.git"]},
".wikitool-upload.json": {"max_bytes": 100, "allowed_extensions": [".md"],
"quota": {"submissions_per_day": 1, "bytes_per_day": 5}},
".wikitool-tasks.json": {
"provider": "caldav", "thresholds": THRESHOLDS,
"caldav": {"url": "https://dav.example.net/u/", "username": "anna",
"app_password": APP_PASSWORD, "inbox_list": "Inbox",
"someday_list": "Someday"}},
},
{
"telemetry": {"enabled": False, "max_session_bytes": 5 * 1024 * 1024, "keep_sessions": 250},
"remotes": ["ssh://git@example.net/a.git"],
"upload": "identity-header-by-default",
"tasks": {"provider": "caldav", "thresholds": THRESHOLDS,
"provider_values": {"url": "https://dav.example.net/u/", "username": "anna",
"app_password": APP_PASSWORD, "inbox_list": "Inbox",
"someday_list": "Someday", "exclude_lists": ()}},
},
),
}
def _default(section: str, name: str):
return settings.sections()[section].field(name).default
@pytest.fixture
def checkout(tmp_path, monkeypatch):
"""A git checkout under `tmp_path/work`, with the secrets file kept outside it."""
root = tmp_path / "work"
root.mkdir()
set_config_path(monkeypatch, "ROOT", root)
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
subprocess.run(["git", "init", "-b", "main"], cwd=root, check=True, capture_output=True)
subprocess.run(["git", "config", "user.email", "a@example.net"], cwd=root, check=True)
subprocess.run(["git", "config", "user.name", "A"], cwd=root, check=True)
policy.reset_cache()
yield root
policy.reset_cache()
def _write_old(root: Path, files: dict) -> dict[str, bytes]:
for name, data in files.items():
(root / name).write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
return {name: (root / name).read_bytes() for name in files}
def _snapshot(root: Path, extra: Path | None = None) -> dict[str, bytes]:
found = {str(p.relative_to(root)): p.read_bytes() for p in root.rglob("*")
if p.is_file() and ".git" not in p.relative_to(root).parts}
if extra is not None and extra.exists():
found.update({f"<xdg>/{p.relative_to(extra)}": p.read_bytes() for p in extra.rglob("*") if p.is_file()})
return found
def _effective(root: Path) -> dict:
"""What is in effect for `root`, read through the readers the commands use."""
policy.reset_cache()
pol = policy.resolve(root)
out: dict = {"telemetry": {"enabled": pol.enabled, "max_session_bytes": pol.max_session_bytes,
"keep_sessions": pol.keep_sessions}}
remotes = settings.load(root, only=("remotes",)).section("remotes")
out["remotes"] = list(remotes["allowed_push_urls"]) if remotes.configured else None
cfg = upload.read_config(root)
out["upload"] = None if cfg is None else asdict(cfg)
tasks = tasks_config.read_config(root)
if tasks is None:
out["tasks"] = None
else:
section = tasks.provider_config
if tasks.provider == "caldav":
values = asdict(caldav.CalDAVConfig.from_section(section))
else:
values = asdict(superproductivity.SuperProductivityConfig.from_section(section))
values["backups_dir"] = None if values["backups_dir"] is None else str(values["backups_dir"])
out["tasks"] = {"provider": tasks.provider, "thresholds": asdict(tasks.thresholds),
"provider_values": values}
return out
def _expected(case: dict) -> dict:
"""The `_effective` shape for what a case says is in effect; a feature the
case does not mention is at its defaults."""
out: dict = {
"telemetry": {"enabled": True, "max_session_bytes": 5 * 1024 * 1024, "keep_sessions": 250},
"remotes": None, "upload": None, "tasks": None,
}
for key, value in case.items():
if key == "upload" and isinstance(value, str):
value = {
**_MCP_CHANNEL,
"identity_header": upload.DEFAULT_IDENTITY_HEADER,
"max_bytes": 100, "allowed_extensions": (".md",),
"submissions_per_day": 1, "bytes_per_day": 5,
}
out[key] = value
return out
def _normal(effective: dict) -> dict:
"""Tuples and lists compare equal."""
return json.loads(json.dumps(effective))
# --- a: the same effective value after the move -------------------------------
@pytest.mark.parametrize("case", CASES)
def test_every_shape_keeps_its_effective_value(checkout, case):
files, expected = CASES[case]
_write_old(checkout, files)
result = legacy_settings.migrate(checkout)
assert sorted(result.removed) == sorted(files)
assert _normal(_effective(checkout)) == _normal(_expected(expected))
def test_the_old_upload_file_becomes_the_mcp_channel_of_the_intake_section(checkout):
_write_old(checkout, CASES["upload-full"][0])
legacy_settings.migrate(checkout)
data = json.loads((checkout / config.LOCAL_SETTINGS_FILENAME).read_text(encoding="utf-8"))
assert "upload" not in data
assert data["intake"] == {"channels": {"mcp": {
"handler": "mcp", "identity_header": "X-Forwarded-User", "max_bytes": 2048,
"allowed_extensions": [".md", ".txt"],
"quota_submissions_per_day": 4, "quota_bytes_per_day": 9000}}}
# --- b: only the tools file remains; no secret in the tree or the index -------
def test_after_the_move_no_old_file_is_left_and_no_secret_is_in_the_tree_or_the_index(checkout, tmp_path):
files, _ = CASES["everything-at-once"]
files = {**files, ".wikitool-tasks.json": CASES["superproductivity-api"][0][".wikitool-tasks.json"]}
_write_old(checkout, files)
(checkout / ".wikitool-tools.json").write_text('{"schema": 1}', encoding="utf-8")
legacy_settings.migrate(checkout)
assert legacy_settings.present(checkout) == []
assert (checkout / ".wikitool-tools.json").exists()
subprocess.run(["git", "add", "-A", "-f"], cwd=checkout, check=True, capture_output=True)
for secret in (TOKEN, APP_PASSWORD):
grep = subprocess.run(["git", "grep", "--cached", "-n", secret], cwd=checkout,
capture_output=True, text=True)
assert grep.returncode == 1, grep.stdout
for path in checkout.rglob("*"):
if path.is_file() and ".git" not in path.relative_to(checkout).parts:
assert secret not in path.read_text(encoding="utf-8", errors="ignore"), path
secrets_files = list((tmp_path / "xdg").rglob("secrets.json"))
assert len(secrets_files) == 1
assert TOKEN in secrets_files[0].read_text(encoding="utf-8")
def test_the_output_names_settings_and_never_a_secret_value(checkout):
_write_old(checkout, CASES["superproductivity-api"][0])
result = runner.invoke(app, ["config", "migrate"])
assert result.exit_code == 0, result.output
assert TOKEN not in result.output
assert "superproductivity.api_token" in result.output
# --- c: an abort leaves the old files byte-identical --------------------------
@pytest.mark.parametrize("fail_on_write", [2, 3])
def test_a_fault_after_the_first_write_leaves_everything_as_it_was(checkout, tmp_path, monkeypatch, fail_on_write):
files = {
".wikitool-remotes.json": {"allowed_push_urls": ["ssh://git@example.net/a.git"]},
".wikitool-tasks.json": CASES["superproductivity-api"][0][".wikitool-tasks.json"],
}
_write_old(checkout, files)
(checkout / "wikitool.json").write_text(
json.dumps({"schema": 1, "instance_id": "inst-1"}) + "\n", encoding="utf-8")
before = _snapshot(checkout, tmp_path / "xdg")
real, calls = legacy_settings._write, []
def broken(path, data):
calls.append(path)
if len(calls) == fail_on_write:
raise OSError("disk full")
real(path, data)
monkeypatch.setattr(legacy_settings, "_write", broken)
with pytest.raises(legacy_settings.ValidationError) as caught:
legacy_settings.migrate(checkout)
assert "Nothing was changed" in str(caught.value)
assert len(calls) == fail_on_write
assert _snapshot(checkout, tmp_path / "xdg") == before
def test_a_broken_old_file_changes_nothing_and_names_the_file(checkout, tmp_path):
_write_old(checkout, {".wikitool-remotes.json": {"allowed_push_urls": ["ssh://git@example.net/a.git"]}})
(checkout / ".wikitool-upload.json").write_text('{"max_bytes": "many"}', encoding="utf-8")
before = _snapshot(checkout, tmp_path / "xdg")
result = runner.invoke(app, ["config", "migrate"])
assert result.exit_code == 1
assert ".wikitool-upload.json" in result.output
assert _snapshot(checkout, tmp_path / "xdg") == before
def test_a_value_that_collides_with_the_new_settings_changes_nothing(checkout, tmp_path):
_write_old(checkout, {".wikitool-remotes.json": {"allowed_push_urls": ["ssh://git@example.net/a.git"]}})
(checkout / ".wikitool-local.json").write_text(
json.dumps({"schema": 1, "remotes": {"allowed_push_urls": ["ssh://git@example.net/other.git"]}}),
encoding="utf-8")
before = _snapshot(checkout, tmp_path / "xdg")
with pytest.raises(legacy_settings.ValidationError, match="already holds a different value"):
legacy_settings.migrate(checkout)
assert _snapshot(checkout, tmp_path / "xdg") == before
# --- d: a second run changes nothing ------------------------------------------
def test_a_second_run_exits_0_and_changes_no_file(checkout, tmp_path):
_write_old(checkout, CASES["everything-at-once"][0])
first = runner.invoke(app, ["config", "migrate"])
assert first.exit_code == 0, first.output
after_first = _snapshot(checkout, tmp_path / "xdg")
second = runner.invoke(app, ["config", "migrate"])
assert second.exit_code == 0, second.output
assert "Nothing to migrate" in second.output
assert _snapshot(checkout, tmp_path / "xdg") == after_first
def test_a_migrated_setting_that_is_already_there_with_the_same_value_is_not_a_collision(checkout):
_write_old(checkout, {".wikitool-remotes.json": {"allowed_push_urls": ["ssh://git@example.net/a.git"]}})
(checkout / ".wikitool-local.json").write_text(
json.dumps({"schema": 1, "remotes": {"allowed_push_urls": ["ssh://git@example.net/a.git"]}}),
encoding="utf-8")
result = legacy_settings.migrate(checkout)
assert result.removed == [".wikitool-remotes.json"]
# --- e: a leftover is exit 42, FAIL in doctor, silent in the hook -------------
@pytest.mark.parametrize("args,name", [
(["task", "list", "--project", "x"], ".wikitool-tasks.json"),
(["task", "new", "--title", "x", "--inbox"], ".wikitool-tasks.json"),
(["review"], ".wikitool-tasks.json"),
(["publish", "--message", "x"], ".wikitool-remotes.json"),
])
def test_a_leftover_makes_the_command_that_needs_the_setting_exit_42(checkout, monkeypatch, args, name):
(checkout / "kb").mkdir()
set_config_path(monkeypatch, "KB_DIR", checkout / "kb")
(checkout / name).write_text("{}", encoding="utf-8")
result = runner.invoke(app, args)
assert result.exit_code == 42, result.output
assert "tools/wikitool config migrate" in " ".join(result.output.split())
def test_a_tracker_profile_makes_the_old_tasks_file_beside_it_irrelevant(checkout, monkeypatch):
(checkout / ".wikitool-tasks.json").write_text("{}", encoding="utf-8")
profile = checkout / "profile.json"
profile.write_text(json.dumps({"schema": 1, "tasks": {"provider": "caldav", **THRESHOLDS},
"caldav": {"url": "http://127.0.0.1:1/", "username": "u",
"app_password": {"ref": "profile_pw"},
"inbox_list": "I", "someday_list": "S"}}), encoding="utf-8")
monkeypatch.setenv("WIKITOOL_TASKS_CONFIG", str(profile))
monkeypatch.setenv("WIKITOOL_SECRET_PROFILE_PW", "pw")
assert tasks_config.read_config(checkout).provider == "caldav"
def test_the_mcp_server_refuses_to_start_on_an_old_upload_file(checkout, capsys):
pytest.importorskip("mcp")
from chemenu.mcp.__main__ import main
(checkout / ".wikitool-upload.json").write_text('{"max_bytes": 100}', encoding="utf-8")
assert main(["--root", str(checkout)]) == 1
assert "tools/wikitool config migrate" in capsys.readouterr().err
def test_doctor_reports_each_old_file_as_a_fail(checkout):
from chemenu.commands import doctor
_write_old(checkout, {name: {} for name in legacy_settings.FILES.values()})
checks = [c for c in doctor.check_legacy_settings()]
assert [c.status for c in checks] == ["FAIL"] * 4
assert all("tools/wikitool config migrate" in (c.fix or "") for c in checks)
def test_the_telemetry_hook_neither_reads_nor_refuses_over_an_old_file(checkout):
(checkout / ".wikitool-telemetry.json").write_text('{"enabled": false}', encoding="utf-8")
assert policy.resolve(checkout).enabled is True
# --- g: `config set` and the gate flags ---------------------------------------
@pytest.mark.parametrize("key,value", [
("intake.channels", '{"mcp": {"handler": "mcp"}}'),
("remotes.allowed_push_urls", '["ssh://git@example.net/a.git"]'),
])
def test_config_set_on_a_gated_section_exits_42_and_writes_nothing(checkout, key, value):
result = runner.invoke(app, ["config", "set", key, value])
assert result.exit_code == 42, result.output
assert not (checkout / config.LOCAL_SETTINGS_FILENAME).exists()
def test_config_set_on_telemetry_writes_the_local_file(checkout):
result = runner.invoke(app, ["config", "set", "telemetry.keep_sessions", "7"])
assert result.exit_code == 0, result.output
data = json.loads((checkout / config.LOCAL_SETTINGS_FILENAME).read_text(encoding="utf-8"))
assert data["telemetry"] == {"keep_sessions": 7}
# --- h: the access-path rules of Super Productivity ---------------------------
@pytest.mark.parametrize("section,message", [
({"access": "api"}, "api_token"),
({"access": "api", "api_token": "t", "backups_dir": "/x"}, "backups_dir"),
({"access": "snapshot", "backups_dir": "/x", "api_token": "t"}, "api_token"),
({"access": "snapshot"}, "backups_dir"),
])
def test_a_superproductivity_section_with_the_wrong_fields_for_its_access_fails(checkout, section, message):
_write_old(checkout, {".wikitool-tasks.json": {
"provider": "superproductivity", "thresholds": THRESHOLDS, "superproductivity": section}})
with pytest.raises(legacy_settings.ValidationError, match=message):
legacy_settings.migrate(checkout)
assert (checkout / ".wikitool-tasks.json").exists()
# ... and exactly so when it is read from the new settings
from chemenu.tests.conftest import write_settings
(checkout / ".wikitool-tasks.json").unlink()
mp = pytest.MonkeyPatch()
try:
write_settings(checkout, mp, tasks={"provider": "superproductivity", **THRESHOLDS},
superproductivity=section)
with pytest.raises(legacy_settings.ChemenuError, match=message):
superproductivity.SuperProductivityConfig.from_section(
tasks_config.read_config(checkout).provider_config)
finally:
mp.undo()