"""Tijdzone automatisch: waar de zone vandaan komt, en wat install.sh doorgeeft. In de container ziet Server Up zonder TZ alleen de UTC van het image. Dat is 'onbekend': alleen dan stelt de interface de zone van de browser voor. Een bewust gekozen zone, of een host die echt UTC is, blijft staan. """ import os import subprocess from pathlib import Path import pytest from conftest import login SCRIPT = Path(__file__).resolve().parent.parent / "install.sh" @pytest.fixture def tz(env, monkeypatch, tmp_path): """Een machine zonder TZ, met eigen /etc/timezone en /etc/localtime.""" core = env["core"] from core import paden monkeypatch.delenv("TZ", raising=False) bestand = tmp_path / "timezone" monkeypatch.setattr(core, "_TZ_BESTAND", bestand) monkeypatch.setattr(core, "_LOCALTIME", str(tmp_path / "geen-localtime")) staat = {"container": False} monkeypatch.setattr(paden, "_in_container", lambda: staat["container"]) return {"core": core, "bestand": bestand, "staat": staat} def test_gekozen_zone_wint_altijd(tz, monkeypatch): monkeypatch.setenv("TZ", "Asia/Tokyo") tz["core"].patch({"TIMEZONE": "UTC"}) assert tz["core"].tijdzone_herkomst() == "gekozen" assert tz["core"].tijdzone() == "UTC" def test_tz_uit_de_omgeving_is_de_host(tz, monkeypatch): monkeypatch.setenv("TZ", "UTC") tz["staat"]["container"] = True assert tz["core"].tijdzone_herkomst() == "host" def test_utc_van_het_image_in_een_container_is_onbekend(tz): tz["staat"]["container"] = True tz["bestand"].write_text("Etc/UTC\n") assert tz["core"].host_timezone() == "Etc/UTC" assert tz["core"].tijdzone_herkomst() == "onbekend" def test_gemounte_zone_in_een_container_is_de_host(tz): tz["staat"]["container"] = True tz["bestand"].write_text("Europe/Amsterdam\n") assert tz["core"].tijdzone_herkomst() == "host" def test_utc_buiten_een_container_is_echt(tz): tz["bestand"].write_text("Etc/UTC\n") assert tz["core"].tijdzone_herkomst() == "host" def test_niets_te_vinden_is_onbekend(tz): assert tz["core"].host_timezone() == "UTC" assert tz["core"].tijdzone_herkomst() == "onbekend" def test_localtime_link_in_een_container(tz, monkeypatch, tmp_path): zone = tmp_path / "zoneinfo" / "Europe" / "Berlin" zone.parent.mkdir(parents=True) zone.write_text("") link = tmp_path / "localtime" link.symlink_to(zone) monkeypatch.setattr(tz["core"], "_LOCALTIME", str(link)) tz["staat"]["container"] = True assert tz["core"].host_timezone() == "Europe/Berlin" assert tz["core"].tijdzone_herkomst() == "host" def test_instellingen_geven_de_herkomst_en_bewaren_hem_niet(client, tz): csrf = login(client) tz["staat"]["container"] = True tz["bestand"].write_text("Etc/UTC\n") d = client.get("/api/settings").get_json() assert d["timezone_origin"] == "onbekend" # De interface stuurt alles terug; afgeleide waarden horen niet in config.json. client.put("/api/settings", json=d, headers={"X-CSRF-Token": csrf}) opgeslagen = tz["core"].load() assert "timezone_origin" not in opgeslagen assert "host_timezone" not in opgeslagen @pytest.mark.parametrize("herkomst, gemarkeerd", [ ("onbekend", True), ("host", False), ("gekozen", False)]) def test_tijdzoneveld_vraagt_alleen_bij_onbekend_om_de_browser( tz, monkeypatch, herkomst, gemarkeerd): import app monkeypatch.setattr(tz["core"], "tijdzone_herkomst", lambda: herkomst) velden = app._annotate_fields([{"name": "timezone", "type": "str"}, {"name": "andere", "type": "str"}]) assert bool(velden[0].get("timezone_unknown")) is gemarkeerd assert "timezone_unknown" not in velden[1] # ── install.sh ─────────────────────────────────────────────────────────────── def _sh(tmp_path, fragment, timedatectl=None, env_extra=None): """Laadt install.sh als functies, met een eigen timedatectl op het PATH.""" nep = tmp_path / "nepbin" nep.mkdir(exist_ok=True) td = nep / "timedatectl" td.write_text("#!/bin/sh\n" + (f"printf '%s\\n' '{timedatectl}'\n" if timedatectl is not None else "exit 1\n")) td.chmod(0o755) script = tmp_path / "frag.sh" script.write_text(f"set --\nSU_INSTALL_ALLEEN_FUNCTIES=1 . {SCRIPT}\n{fragment}\n") env = dict(os.environ, PATH=f"{nep}{os.pathsep}{os.environ.get('PATH', '')}", SU_TZ_BESTAND=str(tmp_path / "geen-timezone"), SU_LOCALTIME=str(tmp_path / "geen-localtime")) env.update(env_extra or {}) r = subprocess.run(["sh", str(script)], capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL, env=env) return r.stdout + r.stderr @pytest.mark.parametrize("waarde, geldig", [ ("Europe/Amsterdam", True), ("UTC", True), ("America/Argentina/Salta", True), ("Etc/GMT+2", True), ("n/a", False), ("", False), ("../etc", False), ("Europe/Amsterdam'; rm -rf /", False), ("Europe//X", False), ("Europe/", False), ]) def test_install_sh_tijdzonevorm(tmp_path, waarde, geldig): uit = _sh(tmp_path, 'geldige_tijdzone "$WAARDE" && echo JA || echo NEE', env_extra={"WAARDE": waarde}) assert uit.strip().splitlines()[-1] == ("JA" if geldig else "NEE") def test_install_sh_tijdzone_uit_timedatectl(tmp_path): uit = _sh(tmp_path, 'printf "<%s>\\n" "$(host_tijdzone)"', timedatectl="Europe/Amsterdam") assert "" in uit def test_install_sh_valt_terug_op_de_bestanden(tmp_path): (tmp_path / "timezone").write_text("Europe/Brussels\n") uit = _sh(tmp_path, 'printf "<%s>\\n" "$(host_tijdzone)"', timedatectl="n/a", env_extra={"SU_TZ_BESTAND": str(tmp_path / "timezone")}) assert "" in uit zone = tmp_path / "zoneinfo" / "Europe" / "Paris" zone.parent.mkdir(parents=True) zone.write_text("") (tmp_path / "localtime").symlink_to(zone) uit = _sh(tmp_path, 'printf "<%s>\\n" "$(host_tijdzone)"', env_extra={"SU_LOCALTIME": str(tmp_path / "localtime")}) assert "" in uit def test_install_sh_zonder_bron_geeft_niets(tmp_path): uit = _sh(tmp_path, 'printf "<%s>\\n" "$(host_tijdzone)"') assert "<>" in uit _SCHRIJF = ('DROOG=0; SUDO=""; DOEL="{doel}"; BIND=127.0.0.1; POORT=5000; ' 'BIND_EXPLICIET=0; POORT_EXPLICIET=0; BASE_DIR_EXPLICIET=0; ' 'SU_UID=""; SU_GID=""; BASE_DIR=""\nschrijf_env\n') def test_install_sh_vult_tz_aan_in_een_bestaande_env(tmp_path): doel = tmp_path / "su" doel.mkdir() (doel / ".env").write_text("BIND=0.0.0.0\nPORT=8080\n") _sh(tmp_path, _SCHRIJF.format(doel=doel), timedatectl="Europe/Amsterdam") env = (doel / ".env").read_text() assert "TZ=Europe/Amsterdam" in env.splitlines() assert "BIND=0.0.0.0" in env and "PORT=8080" in env @pytest.mark.parametrize("regel", [ "TZ=Asia/Tokyo", "TZ = UTC", "TZ: UTC", "export TZ=UTC", " TZ=UTC", "\tTZ\t=UTC"]) def test_install_sh_laat_een_bestaande_tz_staan(tmp_path, regel): """Compose leest al deze vormen; een expliciete keuze krijgt er geen tweede TZ achter (Codex).""" doel = tmp_path / "su" doel.mkdir() (doel / ".env").write_text(f"BIND=127.0.0.1\nPORT=5000\n{regel}\n") _sh(tmp_path, _SCHRIJF.format(doel=doel), timedatectl="Europe/Amsterdam") assert "Europe/Amsterdam" not in (doel / ".env").read_text() assert regel in (doel / ".env").read_text() def test_install_sh_uitgecommentarieerde_tz_telt_niet(tmp_path): doel = tmp_path / "su" doel.mkdir() (doel / ".env").write_text("BIND=127.0.0.1\n#TZ=Europe/Amsterdam\n") _sh(tmp_path, _SCHRIJF.format(doel=doel), timedatectl="Europe/Berlin") assert "TZ=Europe/Berlin" in (doel / ".env").read_text().splitlines() def test_install_sh_zet_tz_in_een_nieuwe_env(tmp_path): doel = tmp_path / "su" doel.mkdir() _sh(tmp_path, _SCHRIJF.format(doel=doel), timedatectl="Europe/Amsterdam") assert "TZ=Europe/Amsterdam" in (doel / ".env").read_text().splitlines() def test_compose_geeft_tz_door(): import yaml doc = yaml.safe_load((SCRIPT.parent / "docker-compose.yml").read_text()) assert "TZ=${TZ:-}" in doc["services"]["server-up"]["environment"]