Files
omarchy-iso/test/unit/test_region.py
T

143 lines
6.6 KiB
Python

"""The configurator's region reaches the target setup as OMARCHY_REGION."""
import json
import os
import re
import subprocess
import sys
import tempfile
import types
import unittest
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "configs/airootfs/usr/share/omarchy-iso"))
sys.modules.setdefault(
"orchestrator.archinstall_adapter",
types.ModuleType("orchestrator.archinstall_adapter"),
)
from orchestrator import context, phases_impl # noqa: E402
def load_context(root: Path, omarchy_install: dict | None) -> context.InstallContext:
config = {"kernels": ["linux-omarchy"]}
if omarchy_install is not None:
config["omarchy_install"] = omarchy_install
config_path = root / "config.json"
creds_path = root / "creds.json"
config_path.write_text(json.dumps(config))
creds_path.write_text(json.dumps({"users": [{"username": "test"}]}))
with mock.patch.dict(os.environ, {
"OMARCHY_INSTALL_CONFIG": str(config_path),
"OMARCHY_INSTALL_CREDS": str(creds_path),
"OMARCHY_INSTALL_STATE_DIR": str(root / "state"),
}, clear=True):
return context.InstallContext.from_env()
class RegionTest(unittest.TestCase):
def test_context_reads_region(self):
for omarchy_install, expected in [
(None, "global"),
({"mode": "full_disk"}, "global"),
({"mode": "full_disk", "region": "global"}, "global"),
({"mode": "full_disk", "region": "china"}, "china"),
]:
with self.subTest(omarchy_install=omarchy_install), tempfile.TemporaryDirectory() as tmp:
ctx = load_context(Path(tmp), omarchy_install)
self.assertEqual(ctx.omarchy_install["region"], expected)
def test_context_rejects_unknown_region(self):
for region in ("China", "mars", ""):
with self.subTest(region=region), tempfile.TemporaryDirectory() as tmp:
with self.assertRaisesRegex(RuntimeError, "omarchy_install.region must be global or china"):
load_context(Path(tmp), {"mode": "full_disk", "region": region})
def test_target_setup_receives_region(self):
for region in ("global", "china"):
with self.subTest(region=region), tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
ctx = types.SimpleNamespace(
target=root / "mnt",
log_path=root / "install.log",
omarchy_install={"region": region},
username="test",
full_name="",
email="",
state={"omarchy_start_time": "now", "omarchy_start_epoch": 0,
"omarchy_finalizer_header_written": True},
)
with mock.patch.object(phases_impl, "_prepare_target_setup"), \
mock.patch.object(phases_impl.subprocess, "run") as run:
phases_impl._run_target_setup_command(ctx, ["/usr/bin/omarchy-apply-system"])
chroot = next(call.args[0] for call in run.call_args_list if call.args[0][0] == "arch-chroot")
self.assertIn(f"OMARCHY_REGION={region}", chroot)
def run_keyboard_form(self, script: str, **env: str) -> subprocess.CompletedProcess:
configurator = (ROOT / "configs/airootfs/root/configurator").read_text()
language = re.search(r"^apply_region_language\(\) \{\n.*?^\}", configurator, re.M | re.S)
form = re.search(r"^keyboard_form\(\) \{\n.*?^\}", configurator, re.M | re.S)
init = re.search(r'^region="\$\{OMARCHY_INSTALL_REGION:-global\}"$', configurator, re.M)
self.assertIsNotNone(language)
self.assertIsNotNone(form)
self.assertIsNotNone(init)
harness = "\n".join([
"set -euo pipefail",
"OMARCHY_FORM_BACK=1; OMARCHY_FORM_SIGNAL=130; defer_provisioning=false",
"clear_logo() { :; }; say() { :; }; abort() { exit 99; }; tty() { echo /dev/pts/0; }",
"omarchy_text() { printf '%s' \"$1\"; }",
"answers=(" + script + "); step=0",
"answer() { local a=${answers[step]}; step=$((step + 1)); [[ $a == ok:* ]] && eval \"${a#ok:}\" && return 0; return ${a#rc:}; }",
"omarchy_prompt_region() { echo \"region-preselect=$region\"; answer; }",
"omarchy_prompt_keyboard() { echo keyboard-prompt; answer; }",
"confirm_prepare_for_another_owner() { answer; }",
init.group(),
language.group(),
form.group(),
"keyboard_form",
'echo "region=$region defer=$defer_provisioning keyboard=${keyboard:-} lang=${OMARCHY_INSTALL_LANG:-}"',
])
return subprocess.run(["bash", "-c", harness], capture_output=True, text=True,
env={"PATH": os.environ["PATH"], **env})
def lines(self, result: subprocess.CompletedProcess) -> list[str]:
return [line for line in result.stdout.splitlines() if line]
def test_ctrl_c_before_choosing_defers_as_global(self):
out = self.run_keyboard_form("rc:130 ok:true")
self.assertIn("region=global defer=true", out.stdout)
def test_back_from_keyboard_keeps_the_chosen_region(self):
out = self.run_keyboard_form("ok:region=china rc:1 ok:true ok:keyboard=us")
self.assertEqual(self.lines(out), [
"region-preselect=global",
"keyboard-prompt",
"region-preselect=china",
"keyboard-prompt",
"region=china defer=false keyboard=us lang=",
])
def test_china_on_the_vt_hands_over_to_the_cjk_console(self):
out = self.run_keyboard_form("ok:region=china", OMARCHY_CJK_RELAUNCH="10")
self.assertEqual(out.returncode, 10)
self.assertEqual(self.lines(out), ["region-preselect=global"])
def test_cjk_console_reads_chinese_with_a_us_keyboard(self):
out = self.run_keyboard_form("ok:true", OMARCHY_CJK_CONSOLE="1", OMARCHY_VT_RETURN="11",
OMARCHY_INSTALL_REGION="china")
self.assertEqual(out.returncode, 0)
self.assertEqual(self.lines(out), [
"region-preselect=china",
"region=china defer=false keyboard=us lang=zh",
])
def test_global_in_the_cjk_console_returns_to_the_vt(self):
out = self.run_keyboard_form("ok:region=global", OMARCHY_CJK_CONSOLE="1", OMARCHY_VT_RETURN="11",
OMARCHY_INSTALL_REGION="china")
self.assertEqual(out.returncode, 11)
self.assertNotIn("keyboard-prompt", out.stdout)
if __name__ == "__main__":
unittest.main()