Files

2303 lines
76 KiB
Python

from __future__ import annotations
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import pytest
ROOT = Path(__file__).resolve().parents[2]
INSTALL = ROOT / "integration" / "dxdesigner795" / "Install.ps1"
LAUNCHER = ROOT / "integration" / "dxdesigner795" / "Start-PartReplacement.ps1"
LAUNCHER_CONTRACT = (
ROOT / "integration" / "dxdesigner795" / "PartReplacementContract.ps1"
)
PATH_SAFETY = ROOT / "integration" / "dxdesigner795" / "PathSafety.ps1"
MENU = ROOT / "integration" / "dxdesigner795" / "MenuAdd.vbs"
MENU_RUNTIME = ROOT / "integration" / "dxdesigner795" / "MenuRuntime.vbs"
MENU_PART_REPLACE_RUNTIME = (
ROOT / "integration" / "dxdesigner795" / "PartReplaceMenuRuntime.vbs"
)
COMMON = ROOT / "integration" / "dxdesigner795" / "BridgeCommon.vbs"
PROBE = ROOT / "integration" / "dxdesigner795" / "PartReplaceProbe.vbs"
BRIDGE = ROOT / "integration" / "dxdesigner795" / "PartReplaceBridge.vbs"
PROFILE_FIXTURE = (
ROOT / "tests" / "fixtures" / "part_replace" / "compatibility-profile-v1.json"
)
def _create_junction(link: Path, target: Path) -> None:
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(link), str(target)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.skip(f"junctions unavailable: {created.stderr or created.stdout}")
def _ps(
script: Path,
*args: str,
env: dict[str, str | None] | None = None,
isolated_console: bool = False,
input_text: str | None = None,
) -> subprocess.CompletedProcess[str]:
process_env = os.environ.copy()
for name, value in (env or {}).items():
if value is None:
process_env.pop(name, None)
else:
process_env[name] = value
startupinfo = None
creationflags = 0
if isolated_console:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
creationflags = subprocess.CREATE_NEW_CONSOLE
return subprocess.run(
[
"powershell",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
str(script),
*args,
],
cwd=ROOT,
check=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
env=process_env,
input=input_text,
startupinfo=startupinfo,
creationflags=creationflags,
)
def _write_json(path: Path, value: object) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(value, ensure_ascii=False, separators=(",", ":")) + "\n",
encoding="utf-8",
newline="",
)
return path
def _valid_profile() -> dict[str, object]:
return json.loads(PROFILE_FIXTURE.read_text(encoding="utf-8"))
def _profile(path: Path, value: dict[str, object] | None = None) -> Path:
return _write_json(path, _valid_profile() if value is None else value)
def _vbs_string(value: str) -> str:
return '"' + value.replace('"', '""') + '"'
def _assert_no_vbscript_host_error(
completed: subprocess.CompletedProcess[str],
) -> None:
output = completed.stdout + completed.stderr
assert "microsoft vbscript" not in output.casefold(), output
def _cscript(script: Path) -> subprocess.CompletedProcess[str]:
completed = subprocess.run(
["cscript", "//nologo", str(script)],
cwd=ROOT,
check=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
_assert_no_vbscript_host_error(completed)
return completed
def _bridge_profile_validation(
profile: Path,
tmp_path: Path,
) -> subprocess.CompletedProcess[str]:
wrapper = tmp_path / "validate-profile.vbs"
wrapper.write_text(
f'''Option Explicit
Dim Fso, Source, Profile, Failure
Set Fso = CreateObject("Scripting.FileSystemObject")
Source = Fso.OpenTextFile({_vbs_string(str(COMMON))}, 1, False, 0).ReadAll
ExecuteGlobal Source
Source = Fso.OpenTextFile({_vbs_string(str(BRIDGE))}, 1, False, 0).ReadAll
ExecuteGlobal Source
Set Profile = DxBridgeParseJson(DxReadUtf8({_vbs_string(str(profile))}))
Set Failure = DxBridgeNewFailure()
If Not DxBridgeValidateProfile(Profile, Failure) Then
WScript.Echo CStr(Failure("code")) & ":" & CStr(Failure("operation"))
WScript.Quit 1
End If
WScript.Echo "profile-valid"
''',
encoding="ascii",
newline="",
)
return _cscript(wrapper)
def _fake_python(tmp_path: Path) -> tuple[Path, Path]:
recorder = tmp_path / "record-python.py"
recorder.write_text(
'''import json
import os
from pathlib import Path
import sys
calls_path = Path(os.environ["DX_TEST_ARGV"])
calls = json.loads(calls_path.read_text(encoding="utf-8")) if calls_path.exists() else []
args = sys.argv[1:]
calls.append(args)
calls_path.write_text(json.dumps(calls, ensure_ascii=False), encoding="utf-8")
if "create" in args:
create_index = args.index("create")
job_id = Path(args[create_index + 1]).name
projects = json.loads(os.environ.get(
"DX_TEST_CREATE_PROJECTS",
'[{"display_name":"one","project_id":"p1","project_path":"C:/fake.prj"}]',
))
print(json.dumps({"job_id": job_id, "projects": projects, "states": {}}, ensure_ascii=False))
elif "prepare-inventory" in args:
index = args.index("prepare-inventory")
job = Path(args[index + 1])
project_id = args[index + 2]
command = job / "mailbox" / project_id / "command.json"
command.parent.mkdir(parents=True, exist_ok=True)
command.write_text("{}\\n", encoding="utf-8")
print("{}")
elif "operator-step" in args:
steps = json.loads(os.environ["DX_TEST_OPERATOR_STEPS"])
operator_index = sum("operator-step" in call for call in calls) - 1
payload = steps[operator_index]
if payload["command"] is not None:
index = args.index("operator-step")
job = Path(args[index + 1])
if payload["command"]["job_id"] == "__JOB_NAME__":
payload["command"]["job_id"] = job.name
command = job / "mailbox" / payload["project"]["project_id"] / "command.json"
command.parent.mkdir(parents=True, exist_ok=True)
command.write_text(
json.dumps(payload["command"], ensure_ascii=False) + "\\n",
encoding="utf-8",
)
print(json.dumps(payload, ensure_ascii=False))
raise SystemExit(0 if payload["complete"] else 4)
elif "status" in args:
raw_status = os.environ.get("DX_TEST_STATUS_RAW")
if raw_status is not None:
print(raw_status)
else:
print(os.environ["DX_TEST_STATUS"])
elif "deploy-profile" in args:
from dx_productivity.part_replace.compatibility_profile import deploy_compatibility_profile
index = args.index("deploy-profile")
deployed = deploy_compatibility_profile(Path(args[index + 1]), Path(args[index + 2]))
print(json.dumps({"compatibility_profile": str(deployed.resolve())}))
elif "discover" in args:
output = Path(args[args.index("--output") + 1])
output.parent.mkdir(parents=True, exist_ok=True)
candidates = json.loads(os.environ.get("DX_TEST_DISCOVERED", "[]"))
output.write_text("".join(item + "\\n" for item in candidates), encoding="utf-8")
for item in candidates:
print(item)
''',
encoding="ascii",
newline="",
)
command = tmp_path / "fake-python.cmd"
python_command = subprocess.list2cmdline((sys.executable, str(recorder)))
command.write_text(f"@{python_command} %*\r\n", encoding="ascii")
return command, tmp_path / "python-argv.json"
def _operator_step_payload(
project: dict[str, str] | None,
*,
action: str | None = None,
command_id: str = "a" * 32,
consumed_action: str | None = None,
job_id: str = "__JOB_NAME__",
) -> dict[str, object]:
if project is None:
return {
"bridge_state": None,
"command": None,
"complete": True,
"consumed_action": consumed_action,
"instruction": None,
"manual_route": None,
"project": None,
"state": None,
}
assert action is not None
return {
"bridge_state": None,
"command": {
"action": action,
"command_id": command_id,
"expected_count": 0,
"expected_fingerprint": "" if action == "inventory" else "0" * 64,
"expected_logical_keys": [],
"format_version": 1,
"job_id": job_id,
"new_part_number": "",
"old_part_number": "",
"project_id": project["project_id"],
"scope": "full_project",
},
"complete": False,
"consumed_action": consumed_action,
"instruction": None,
"manual_route": None,
"project": project,
"state": "inventory_pending" if action == "inventory" else "apply_pending",
}
def _status_payload(
projects: list[dict[str, str]],
*,
job_id: str,
completed_project_ids: set[str] | None = None,
) -> dict[str, object]:
completed = set() if completed_project_ids is None else completed_project_ids
return {
"job_id": job_id,
"projects": [
{
"action": (
"complete" if project["project_id"] in completed else "ingest"
),
"display_name": project["display_name"],
"project_id": project["project_id"],
"project_path": project["project_path"],
"state": (
"verified_saved"
if project["project_id"] in completed
else "inventory_pending"
),
}
for project in projects
],
}
def _test_mode_env(argv: Path | None = None) -> dict[str, str]:
result = {
"DX_PRODUCTIVITY_TEST_MODE": "1",
"PYTHONPATH": str(ROOT / "src"),
}
if argv is not None:
result["DX_TEST_ARGV"] = str(argv)
return result
def _install_arguments(
home: Path,
python: Path,
profile: Path,
settings: Path | None,
*,
test_mode: bool = True,
what_if: bool = False,
) -> list[str]:
scripts = home / "integration" / "dxdesigner795"
scripts.mkdir(parents=True, exist_ok=True)
for script in (
PATH_SAFETY,
LAUNCHER_CONTRACT,
MENU,
MENU_RUNTIME,
MENU_PART_REPLACE_RUNTIME,
COMMON,
PROBE,
BRIDGE,
):
shutil.copyfile(script, scripts / script.name)
arguments = [
"-InstallRoot",
str(home),
"-PythonExecutable",
str(python),
"-CompatibilityProfile",
str(profile),
]
if settings is not None:
arguments.extend(("-SettingsRoot", str(settings)))
if test_mode:
arguments.append("-TestMode")
if what_if:
arguments.append("-WhatIf")
return arguments
def _launcher_arguments(
*,
mapping: Path,
certifications: Path,
projects: Path | None = None,
discovery: Path | None = None,
profile: Path | None = None,
python_executable: Path | None = None,
run_root: Path | None = None,
home: Path | None = None,
settings: Path | None = None,
what_if: bool = False,
) -> list[str]:
if (projects is None) == (discovery is None):
raise ValueError("provide exactly one of projects or discovery")
arguments = ["-Mapping", str(mapping)]
if projects is not None:
arguments.extend(("-Projects", str(projects)))
else:
arguments.extend(("-DiscoveryRoot", str(discovery)))
for flag, path in (
("-CompatibilityProfile", profile),
("-PythonExecutable", python_executable),
("-RunRoot", run_root),
("-DXToolsHome", home),
("-Certifications", certifications),
("-SettingsRoot", settings),
):
if path is not None:
arguments.extend((flag, str(path)))
if what_if:
arguments.append("-WhatIf")
return arguments
def _resume_launcher_arguments(
*,
job: Path,
profile: Path,
python_executable: Path,
run_root: Path,
home: Path,
what_if: bool = False,
) -> list[str]:
arguments = [
"-ResumeJob",
str(job),
"-CompatibilityProfile",
str(profile),
"-PythonExecutable",
str(python_executable),
"-RunRoot",
str(run_root),
"-DXToolsHome",
str(home),
]
if what_if:
arguments.append("-WhatIf")
return arguments
def _user_dxtools_home() -> str:
completed = subprocess.run(
[
"powershell",
"-NoProfile",
"-Command",
'[Environment]::GetEnvironmentVariable("DXTOOLS_HOME", "User")',
],
check=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
assert completed.returncode == 0, completed.stderr
return completed.stdout.rstrip("\r\n")
def test_bridge_accepts_the_complete_installer_profile_fixture(tmp_path: Path) -> None:
# Catches a supposedly valid installer fixture that the real bridge rejects.
profile = _profile(tmp_path / "bridge-profile.json")
completed = _bridge_profile_validation(profile, tmp_path)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert completed.stdout.strip() == "profile-valid"
def test_install_whatif_does_not_start_python_or_write_state(tmp_path: Path) -> None:
# Catches a dry-run that starts package code or alters either configuration boundary.
home = tmp_path / "tool home"
home.mkdir()
profile = _profile(tmp_path / "source profile.json")
fake_python, argv = _fake_python(tmp_path)
settings = tmp_path / "settings"
result = _ps(
INSTALL,
*_install_arguments(home, fake_python, profile, settings, what_if=True),
env=_test_mode_env(argv),
)
deployed = home / "runs" / "compatibility-profile.json"
assert result.returncode == 0, result.stdout + result.stderr
assert f"ProfileSource={profile.resolve()}" in result.stdout
assert f"CompatibilityProfile={deployed.resolve()}" in result.stdout
assert not argv.exists()
assert not settings.exists()
assert not deployed.exists()
def test_launcher_whatif_preserves_unicode_paths_without_python_or_writes(
tmp_path: Path,
) -> None:
# Catches ambient-code-page corruption, Python startup, or runtime publication.
home = tmp_path / "\u5de5\u5177 home"
run_root = home / "runs"
profile = _profile(run_root / "compatibility-profile.json")
mapping = tmp_path / "\u89c4\u5219 file.csv"
projects = tmp_path / "\u5de5\u7a0b list.txt"
certifications = tmp_path / "\u8ba4\u8bc1 evidence.json"
for path in (mapping, projects, certifications):
path.write_text("fixture\n", encoding="utf-8")
fake_python, argv = _fake_python(tmp_path)
wrapper = tmp_path / "cp437-launcher.ps1"
launcher = str(LAUNCHER).replace("'", "''")
wrapper.write_text(
"[Console]::OutputEncoding = [Text.Encoding]::GetEncoding(437)\n"
f"& '{launcher}' @args\n",
encoding="ascii",
newline="",
)
completed = _ps(
wrapper,
*_launcher_arguments(
mapping=mapping,
projects=projects,
certifications=certifications,
profile=profile,
python_executable=fake_python,
run_root=run_root,
home=home,
what_if=True,
),
env={"DX_TEST_ARGV": str(argv)},
isolated_console=True,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert f"Mapping={mapping.resolve()}" in completed.stdout
assert f"Projects={projects.resolve()}" in completed.stdout
assert f"CompatibilityProfile={profile.resolve()}" in completed.stdout
assert f"RunRoot={run_root.resolve()}" in completed.stdout
assert f"DXToolsHome={home.resolve()}" in completed.stdout
assert not argv.exists()
assert not (run_root / "current-part-replacement.json").exists()
assert not list(run_root.glob("part-replace-*"))
@pytest.mark.parametrize(
("test_mode", "settings_kind", "mode_value", "message"),
(
(True, "temp", None, "DX_PRODUCTIVITY_TEST_MODE=1"),
(True, "none", "1", "SettingsRoot"),
(False, "temp", "1", "only with TestMode"),
(True, "workspace", "1", "system temp"),
),
)
def test_install_test_mode_requires_all_three_isolation_gates(
tmp_path: Path,
test_mode: bool,
settings_kind: str,
mode_value: str | None,
message: str,
) -> None:
# Catches any test-only settings path becoming reachable in a normal installation.
home = tmp_path / "home"
home.mkdir()
profile = _profile(tmp_path / "profile.json")
fake_python, argv = _fake_python(tmp_path)
settings = {
"temp": tmp_path / "settings",
"none": None,
"workspace": Path.home() / f".dx-productivity-{tmp_path.name}-settings",
}[settings_kind]
completed = _ps(
INSTALL,
*_install_arguments(home, fake_python, profile, settings, test_mode=test_mode),
env={"DX_PRODUCTIVITY_TEST_MODE": mode_value, "DX_TEST_ARGV": str(argv)},
)
assert completed.returncode != 0
assert message in completed.stdout + completed.stderr
assert not argv.exists()
if settings is not None:
assert not settings.exists()
def test_install_test_mode_requires_a_temporary_install_root(
tmp_path: Path,
) -> None:
# Catches test-only profile deployment being able to target the real workspace.
profile = _profile(tmp_path / "profile.json")
fake_python, argv = _fake_python(tmp_path)
with tempfile.TemporaryDirectory(prefix="dx-productivity-test-", dir=Path.home()) as outside_temp:
completed = _ps(
INSTALL,
*_install_arguments(
Path(outside_temp),
fake_python,
profile,
tmp_path / "settings",
what_if=True,
),
env=_test_mode_env(argv),
)
assert completed.returncode != 0
assert "TestMode InstallRoot" in completed.stdout + completed.stderr
assert not argv.exists()
def test_install_deploys_external_profile_and_launcher_uses_only_deployed_copy(
tmp_path: Path,
) -> None:
# Catches settings or launcher state retaining a caller-owned profile source path.
home = tmp_path / "installed home"
home.mkdir()
source_profile = _profile(tmp_path / "incoming" / "profile.json")
source_bytes = source_profile.read_bytes()
settings = tmp_path / "settings"
fake_python, argv = _fake_python(tmp_path)
before_user_value = _user_dxtools_home()
installed = _ps(
INSTALL,
*_install_arguments(home, fake_python, source_profile, settings),
env=_test_mode_env(argv),
)
assert installed.returncode == 0, installed.stdout + installed.stderr
assert _user_dxtools_home() == before_user_value
deployed = home / "runs" / "compatibility-profile.json"
install_calls = json.loads(argv.read_text(encoding="utf-8"))
assert install_calls == [
[
"-c",
"import sys, dx_productivity; raise SystemExit(0 if sys.version_info[:2] == (3, 12) else 1)",
],
[
"-m",
"dx_productivity",
"deploy-profile",
str(source_profile.resolve()),
str(deployed.resolve()),
],
]
assert deployed.read_bytes() == source_bytes
settings_data = json.loads(
(settings / "DxProductivity" / "settings.json").read_text(encoding="utf-8")
)
assert settings_data == {
"compatibility_profile": str(deployed.resolve()),
"dxtools_home": str(home.resolve()),
"python_executable": str(fake_python.resolve()),
"run_root": str((home / "runs").resolve()),
}
mapping = tmp_path / "mapping.csv"
projects = tmp_path / "projects.txt"
certifications = tmp_path / "certifications.json"
for path in (mapping, projects, certifications):
path.write_text("fixture\n", encoding="utf-8")
launched = _ps(
LAUNCHER,
*_launcher_arguments(
mapping=mapping,
projects=projects,
certifications=certifications,
settings=settings,
),
env={
"DX_TEST_ARGV": str(argv),
"DX_TEST_OPERATOR_STEPS": json.dumps(
[
_operator_step_payload(
{
"display_name": "one",
"project_id": "p1",
"project_path": "C:/fake.prj",
},
action="inventory",
)
]
),
},
input_text="q\n",
)
assert launched.returncode == 0, launched.stdout + launched.stderr
manifest = json.loads(
(home / "runs" / "current-part-replacement.json").read_text(encoding="utf-8")
)
assert manifest["projects"][0]["profile"] == "runs/compatibility-profile.json"
calls = json.loads(argv.read_text(encoding="utf-8"))
assert calls[0][0] == "-c"
assert calls[1][0:3] == ["-m", "dx_productivity", "deploy-profile"]
assert calls[2][:4] == ["-m", "dx_productivity", "--json", "create"]
def test_install_rejects_duplicate_profile_fields_without_replacing_deployed_copy(
tmp_path: Path,
) -> None:
# Catches PowerShell JSON parsing collapsing a duplicate before deployment.
home = tmp_path / "home"
home.mkdir()
deployed = home / "runs" / "compatibility-profile.json"
deployed.parent.mkdir()
deployed.write_bytes(b"previous-profile")
duplicate = PROFILE_FIXTURE.read_bytes().replace(
b'"format_version": 1,',
b'"format_version": 1,\n "format_version": 1,',
1,
)
source = tmp_path / "duplicate.json"
source.write_bytes(duplicate)
fake_python, argv = _fake_python(tmp_path)
completed = _ps(
INSTALL,
*_install_arguments(home, fake_python, source, tmp_path / "settings"),
env=_test_mode_env(argv),
)
assert completed.returncode != 0
assert "compatibility profile" in (completed.stdout + completed.stderr).lower()
assert deployed.read_bytes() == b"previous-profile"
assert not list(deployed.parent.glob(".*.tmp"))
assert not (tmp_path / "settings" / "DxProductivity" / "settings.json").exists()
def test_install_requires_the_complete_runtime_script_layout(tmp_path: Path) -> None:
# Catches publishing settings for a DXTOOLS_HOME whose startup loader cannot run.
home = tmp_path / "incomplete-home"
home.mkdir()
profile = _profile(tmp_path / "profile.json")
fake_python, argv = _fake_python(tmp_path)
completed = _ps(
INSTALL,
"-InstallRoot",
str(home),
"-PythonExecutable",
str(fake_python),
"-CompatibilityProfile",
str(profile),
"-SettingsRoot",
str(tmp_path / "settings"),
"-TestMode",
env=_test_mode_env(argv),
)
assert completed.returncode != 0
assert "MenuRuntime.vbs" in completed.stdout + completed.stderr
assert "PartReplaceMenuRuntime.vbs" in completed.stdout + completed.stderr
assert "PartReplacementContract.ps1" in completed.stdout + completed.stderr
assert not argv.exists()
assert not (home / "runs" / "compatibility-profile.json").exists()
@pytest.mark.skipif(os.name != "nt", reason="Windows junction coverage")
@pytest.mark.parametrize("junction_case", ("settings", "dxtools-home"))
def test_install_rejects_junctions_before_any_publication(
tmp_path: Path,
junction_case: str,
) -> None:
# Catches lexical containment allowing installation through a junction.
source = _profile(tmp_path / "profile.json")
fake_python, argv = _fake_python(tmp_path)
settings = tmp_path / "settings"
home = tmp_path / "home"
junction: Path
target: Path
if junction_case == "settings":
home.mkdir()
target = tmp_path / "outside-settings"
target.mkdir()
junction = tmp_path / "settings-link"
_create_junction(junction, target)
arguments = _install_arguments(home, fake_python, source, junction)
else:
target = tmp_path / "outside-home"
target.mkdir()
arguments = _install_arguments(target, fake_python, source, settings)
junction = tmp_path / "home-link"
_create_junction(junction, target)
arguments[arguments.index("-InstallRoot") + 1] = str(junction)
try:
completed = _ps(
INSTALL,
*arguments,
env=_test_mode_env(argv),
)
finally:
junction.rmdir()
assert completed.returncode != 0
assert "reparse" in (completed.stdout + completed.stderr).lower()
assert not argv.exists()
assert not (target / "DxProductivity" / "settings.json").exists()
assert not (target / "runs" / "compatibility-profile.json").exists()
@pytest.mark.skipif(os.name != "nt", reason="Windows junction coverage")
@pytest.mark.parametrize(
("destination_name", "swap_level"),
(
("settings.json", "parent"),
("current-part-replacement.json", "ancestor"),
),
)
def test_powershell_publication_locks_namespace_through_move_and_cleanup(
tmp_path: Path,
destination_name: str,
swap_level: str,
) -> None:
# Catches final Move/cleanup paths following a parent or ancestor junction swap.
ancestor = tmp_path / "bound" / "ancestor"
parent = ancestor / "parent"
parent.mkdir(parents=True)
destination = parent / destination_name
destination.write_bytes(b"previous-document")
swap_path = parent if swap_level == "parent" else ancestor
displaced = tmp_path / f"displaced-{swap_level}"
outside = tmp_path / f"outside-{swap_level}"
outside_destination = outside / destination.relative_to(swap_path)
outside_destination.parent.mkdir(parents=True)
outside_destination.write_bytes(b"outside-document")
wrapper = tmp_path / f"publish-{swap_level}.ps1"
wrapper.write_text(
f'''$ErrorActionPreference = "Stop"
. {_vbs_string(str(PATH_SAFETY))}
$destination = {_vbs_string(str(destination))}
$swapPath = {_vbs_string(str(swap_path))}
$displaced = {_vbs_string(str(displaced))}
$outside = {_vbs_string(str(outside))}
$hook = {{
param([string]$checkedDestination, [string]$temporary)
$relativeTemporary = $temporary.Substring($swapPath.Length).TrimStart('\\')
$outsideTemporary = Join-Path $outside $relativeTemporary
[IO.Directory]::CreateDirectory((Split-Path -Parent $outsideTemporary)) | Out-Null
[IO.File]::WriteAllBytes(
$outsideTemporary,
[Text.Encoding]::ASCII.GetBytes("outside-temporary")
)
try {{
[IO.Directory]::Move($swapPath, $displaced)
}}
catch {{
throw "directory swap blocked"
}}
& cmd /d /c mklink /J $swapPath $outside | Out-Null
throw "directory swap was not blocked"
}}
$failure = ""
try {{
Write-DxBytesAtomic `
-Destination $destination `
-Bytes ([Text.Encoding]::UTF8.GetBytes("new-document")) `
-AfterValidation $hook
}}
catch {{
$failure = $_.Exception.Message
}}
if ($failure -notmatch "directory swap blocked") {{
throw "publication did not block the directory swap"
}}
$released = $swapPath + ".released"
[IO.Directory]::Move($swapPath, $released)
[IO.Directory]::Move($released, $swapPath)
throw "directory swap blocked; publication handles released"
''',
encoding="ascii",
newline="",
)
completed = _ps(wrapper)
assert completed.returncode != 0
assert "directory swap blocked" in completed.stdout + completed.stderr
assert destination.read_bytes() == b"previous-document"
assert outside_destination.read_bytes() == b"outside-document"
outside_temporaries = list(outside.rglob("*.tmp"))
assert len(outside_temporaries) == 1
assert outside_temporaries[0].read_bytes() == b"outside-temporary"
assert not displaced.exists()
assert not list(parent.glob(".*.tmp"))
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-relative publication")
def test_powershell_publication_binds_the_validated_temp_file_identity(
tmp_path: Path,
) -> None:
# Catches final Replace reopening a substituted staging path and permitting held-file writes.
parent = tmp_path / "bound" / "parent"
parent.mkdir(parents=True)
destination = parent / "settings.json"
displaced = parent / "validated-displaced.tmp"
destination.write_bytes(b"previous-document")
wrapper = tmp_path / "publish-held-identity.ps1"
wrapper.write_text(
f'''$ErrorActionPreference = "Stop"
. {_vbs_string(str(PATH_SAFETY))}
$destination = {_vbs_string(str(destination))}
$parent = {_vbs_string(str(parent))}
$displaced = {_vbs_string(str(displaced))}
$script:replacement = ""
$hook = {{
param([string]$checkedDestination, [string]$temporary)
[IO.File]::Move($temporary, $displaced)
$heldWriteDenied = $false
try {{
[IO.File]::WriteAllBytes(
$displaced,
[Text.Encoding]::ASCII.GetBytes("modified-held-bytes")
)
}}
catch {{
$heldWriteDenied = $true
}}
if (-not $heldWriteDenied) {{
throw "validated staging identity remained writable"
}}
[IO.File]::WriteAllBytes(
$temporary,
[Text.Encoding]::ASCII.GetBytes("external-path-bytes")
)
$script:replacement = $temporary
}}
Write-DxBytesAtomic `
-Destination $destination `
-Bytes ([Text.Encoding]::ASCII.GetBytes("validated-document")) `
-AfterValidation $hook
if ([Text.Encoding]::ASCII.GetString([IO.File]::ReadAllBytes($destination)) `
-ne "validated-document") {{
throw "validated identity was not published"
}}
if ([Text.Encoding]::ASCII.GetString([IO.File]::ReadAllBytes($replacement)) `
-ne "external-path-bytes") {{
throw "substituted path file was changed"
}}
if ([IO.File]::Exists($displaced)) {{
throw "validated staging identity leaked"
}}
$released = $parent + ".released"
[IO.Directory]::Move($parent, $released)
[IO.Directory]::Move($released, $parent)
Write-Output $replacement
''',
encoding="ascii",
newline="",
)
completed = _ps(wrapper)
assert completed.returncode == 0, completed.stdout + completed.stderr
replacement = Path(completed.stdout.strip())
assert destination.read_bytes() == b"validated-document"
assert replacement.read_bytes() == b"external-path-bytes"
assert not displaced.exists()
@pytest.mark.skipif(os.name != "nt", reason="Windows handle cleanup")
def test_powershell_cleanup_failure_releases_handles_and_preserves_primary_error(
tmp_path: Path,
) -> None:
# Catches temporary cleanup bypassing lock disposal or replacing the operation error.
parent = tmp_path / "bound" / "parent"
parent.mkdir(parents=True)
destination = parent / "current-part-replacement.json"
destination.write_bytes(b"previous-document")
wrapper = tmp_path / "publish-cleanup-failure.ps1"
wrapper.write_text(
f'''$ErrorActionPreference = "Stop"
. {_vbs_string(str(PATH_SAFETY))}
$destination = {_vbs_string(str(destination))}
$parent = {_vbs_string(str(parent))}
$script:temporary = ""
function Remove-Item {{ throw "simulated temporary deletion failure" }}
function Remove-DxStagedIdentity {{
param([IntPtr]$Handle)
throw "simulated temporary deletion failure"
}}
$hook = {{
param([string]$checkedDestination, [string]$temporaryPath)
$script:temporary = $temporaryPath
throw "primary operation failure"
}}
$failure = ""
try {{
Write-DxBytesAtomic `
-Destination $destination `
-Bytes ([Text.Encoding]::ASCII.GetBytes("validated-document")) `
-AfterValidation $hook
}}
catch {{
$failure = $_.Exception.Message
}}
if ($failure -notmatch "primary operation failure") {{
throw "primary error was replaced: $failure"
}}
$released = $parent + ".released"
[IO.Directory]::Move($parent, $released)
[IO.Directory]::Move($released, $parent)
if (-not [IO.File]::Exists($temporary)) {{
throw "forced cleanup failure did not retain the staged file"
}}
[IO.File]::Delete($temporary)
Write-Output $failure
''',
encoding="ascii",
newline="",
)
completed = _ps(wrapper)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert completed.stdout.strip() == "primary operation failure"
assert destination.read_bytes() == b"previous-document"
assert not list(parent.glob(".*.tmp"))
@pytest.mark.skipif(os.name != "nt", reason="Windows junction coverage")
@pytest.mark.parametrize("junction_case", ("dxtools-home", "run-root"))
def test_launcher_rejects_junction_runtime_paths_before_python(
tmp_path: Path,
junction_case: str,
) -> None:
# Catches canonical-looking runtime paths resolving through a reparse point.
target = tmp_path / "outside"
target.mkdir()
junction: Path
if junction_case == "dxtools-home":
(target / "runs").mkdir()
_profile(target / "runs" / "compatibility-profile.json")
junction = tmp_path / "home-link"
_create_junction(junction, target)
home = junction
run_root = junction / "runs"
else:
home = tmp_path / "home"
home.mkdir()
_profile(target / "compatibility-profile.json")
junction = home / "runs"
_create_junction(junction, target)
run_root = junction
mapping = tmp_path / "mapping.csv"
projects = tmp_path / "projects.txt"
certifications = tmp_path / "certifications.json"
for path in (mapping, projects, certifications):
path.write_text("fixture\n", encoding="ascii")
fake_python, argv = _fake_python(tmp_path)
try:
completed = _ps(
LAUNCHER,
*_launcher_arguments(
mapping=mapping,
projects=projects,
certifications=certifications,
profile=run_root / "compatibility-profile.json",
python_executable=fake_python,
run_root=run_root,
home=home,
),
env={"DX_TEST_ARGV": str(argv)},
)
finally:
junction.rmdir()
assert completed.returncode != 0
assert "reparse" in (completed.stdout + completed.stderr).lower()
assert not argv.exists()
assert not (target / "current-part-replacement.json").exists()
def test_launcher_invokes_create_then_operator_step_and_publishes_current_binding(
tmp_path: Path,
) -> None:
# Catches shell-built argv, eager multi-command publication, or an unbound manifest.
home = tmp_path / "\u5de5\u5177 home"
run_root = home / "runs"
profile = _profile(run_root / "compatibility-profile.json")
mapping = tmp_path / "\u89c4\u5219 file.csv"
projects = tmp_path / "\u5de5\u7a0b list.txt"
certifications = tmp_path / "\u8ba4\u8bc1 evidence.json"
for path in (mapping, projects, certifications):
path.write_text("fixture\n", encoding="utf-8")
fake_python, argv = _fake_python(tmp_path)
project_records = [
{
"display_name": "one",
"project_id": "p1",
"project_path": "C:/projects/one.prj",
},
{
"display_name": "two",
"project_id": "p2",
"project_path": "C:/projects/two.prj",
},
]
completed = _ps(
LAUNCHER,
*_launcher_arguments(
mapping=mapping,
projects=projects,
certifications=certifications,
profile=profile,
python_executable=fake_python,
run_root=run_root,
home=home,
),
env={
"DX_TEST_ARGV": str(argv),
"DX_TEST_CREATE_PROJECTS": json.dumps(project_records),
"DX_TEST_OPERATOR_STEPS": json.dumps(
[_operator_step_payload(project_records[0], action="inventory")]
),
},
input_text="q\n",
)
assert completed.returncode == 0, completed.stdout + completed.stderr
calls = json.loads(argv.read_text(encoding="utf-8"))
job = calls[0][4]
assert calls == [
[
"-m",
"dx_productivity",
"--json",
"create",
job,
"--mapping",
str(mapping.resolve()),
"--projects",
str(projects.resolve()),
"--certifications",
str(certifications.resolve()),
],
["-m", "dx_productivity", "--json", "operator-step", job],
]
manifest = json.loads(
(run_root / "current-part-replacement.json").read_text(encoding="utf-8")
)
assert manifest == {
"complete": False,
"current_action": "inventory",
"current_command_id": "a" * 32,
"current_project_id": "p1",
"format_version": 2,
"projects": [
{
"project_id": record["project_id"],
"project_path": record["project_path"],
"profile": "runs/compatibility-profile.json",
"command": (
f"runs/{Path(job).name}/mailbox/"
f"{record['project_id']}/command.json"
),
"status": (
f"runs/{Path(job).name}/mailbox/"
f"{record['project_id']}/status.json"
),
"snapshot": (
f"runs/{Path(job).name}/mailbox/"
f"{record['project_id']}/snapshot.json"
),
}
for record in project_records
],
}
assert (home / Path(manifest["projects"][0]["command"])).is_file()
assert not (home / Path(manifest["projects"][1]["command"])).exists()
assert "Run current part replacement step in DxDesigner" in completed.stdout
assert "Q" in completed.stdout
def test_launcher_prompt_loop_advances_until_operator_step_completes(
tmp_path: Path,
) -> None:
# Catches a one-shot launcher that never consumes results or leaves a stale manifest.
home = tmp_path / "home"
run_root = home / "runs"
profile = _profile(run_root / "compatibility-profile.json")
mapping = tmp_path / "mapping.csv"
projects = tmp_path / "projects.txt"
certifications = tmp_path / "certifications.json"
for path in (mapping, projects, certifications):
path.write_text("fixture\n", encoding="ascii")
fake_python, argv = _fake_python(tmp_path)
project = {
"display_name": "one",
"project_id": "p1",
"project_path": "C:/projects/one.prj",
}
steps = [
_operator_step_payload(project, action="inventory"),
_operator_step_payload(
project,
action="close_project",
command_id="b" * 32,
consumed_action="inventory",
),
_operator_step_payload(None, consumed_action="close_project"),
]
completed = _ps(
LAUNCHER,
*_launcher_arguments(
mapping=mapping,
projects=projects,
certifications=certifications,
profile=profile,
python_executable=fake_python,
run_root=run_root,
home=home,
),
env={
"DX_TEST_ARGV": str(argv),
"DX_TEST_CREATE_PROJECTS": json.dumps([project]),
"DX_TEST_OPERATOR_STEPS": json.dumps(steps),
},
input_text="\n\n",
)
assert completed.returncode == 0, completed.stdout + completed.stderr
calls = json.loads(argv.read_text(encoding="utf-8"))
job = calls[0][4]
assert calls[1:] == [
["-m", "dx_productivity", "--json", "operator-step", job],
["-m", "dx_productivity", "--json", "operator-step", job],
["-m", "dx_productivity", "--json", "operator-step", job],
]
assert "inventory" in completed.stdout
assert "close_project" in completed.stdout
assert "Part replacement job complete" in completed.stdout
completed_manifest = json.loads(
(run_root / "current-part-replacement.json").read_text(encoding="utf-8")
)
assert completed_manifest == {
"complete": True,
"current_action": None,
"current_command_id": None,
"current_project_id": None,
"format_version": 2,
"projects": [
{
"command": f"runs/{Path(job).name}/mailbox/p1/command.json",
"profile": "runs/compatibility-profile.json",
"project_id": "p1",
"project_path": "C:/projects/one.prj",
"snapshot": f"runs/{Path(job).name}/mailbox/p1/snapshot.json",
"status": f"runs/{Path(job).name}/mailbox/p1/status.json",
}
],
}
def test_launcher_resumes_paused_job_without_create_and_reuses_pending_command(
tmp_path: Path,
) -> None:
# Catches Q creating an unrecoverable job or resume replacing an idempotent command.
home = tmp_path / "home"
run_root = home / "runs"
profile = _profile(run_root / "compatibility-profile.json")
mapping = tmp_path / "mapping.csv"
projects_path = tmp_path / "projects.txt"
certifications = tmp_path / "certifications.json"
for path in (mapping, projects_path, certifications):
path.write_text("fixture\n", encoding="ascii")
fake_python, argv = _fake_python(tmp_path)
projects = [
{
"display_name": "already complete",
"project_id": "p1",
"project_path": "C:/projects/one.prj",
},
{
"display_name": "current",
"project_id": "p2",
"project_path": "C:/projects/two.prj",
},
]
pending = _operator_step_payload(projects[1], action="inventory")
steps = [pending, pending]
paused = _ps(
LAUNCHER,
*_launcher_arguments(
mapping=mapping,
projects=projects_path,
certifications=certifications,
profile=profile,
python_executable=fake_python,
run_root=run_root,
home=home,
),
env={
"DX_TEST_ARGV": str(argv),
"DX_TEST_CREATE_PROJECTS": json.dumps(projects),
"DX_TEST_OPERATOR_STEPS": json.dumps(steps),
},
input_text="q\n",
)
assert paused.returncode == 0, paused.stdout + paused.stderr
initial_calls = json.loads(argv.read_text(encoding="utf-8"))
job = Path(initial_calls[0][4])
resumed = _ps(
LAUNCHER,
*_resume_launcher_arguments(
job=job,
profile=profile,
python_executable=fake_python,
run_root=run_root,
home=home,
),
env={
"DX_TEST_ARGV": str(argv),
"DX_TEST_STATUS": json.dumps(
_status_payload(
projects,
job_id=job.name,
completed_project_ids={projects[0]["project_id"]},
)
),
"DX_TEST_OPERATOR_STEPS": json.dumps(steps),
},
input_text="q\n",
)
assert resumed.returncode == 0, resumed.stdout + resumed.stderr
calls = json.loads(argv.read_text(encoding="utf-8"))
assert calls == [
initial_calls[0],
["-m", "dx_productivity", "--json", "operator-step", str(job)],
["-m", "dx_productivity", "--json", "status", str(job)],
["-m", "dx_productivity", "--json", "operator-step", str(job)],
]
assert sum("create" in call for call in calls) == 1
manifest = json.loads(
(run_root / "current-part-replacement.json").read_text(encoding="utf-8")
)
assert manifest["current_project_id"] == "p2"
assert manifest["current_command_id"] == "a" * 32
assert [entry["project_id"] for entry in manifest["projects"]] == ["p1", "p2"]
assert not (job / "mailbox" / "p1" / "command.json").exists()
def test_launcher_resume_completes_without_replaying_completed_projects(
tmp_path: Path,
) -> None:
# Catches resume publishing work for a job whose durable projects are complete.
home = tmp_path / "home"
run_root = home / "runs"
profile = _profile(run_root / "compatibility-profile.json")
job = run_root / "part-replace-existing"
job.mkdir()
fake_python, argv = _fake_python(tmp_path)
project = {
"display_name": "complete",
"project_id": "p1",
"project_path": "C:/projects/one.prj",
}
completed = _ps(
LAUNCHER,
*_resume_launcher_arguments(
job=job,
profile=profile,
python_executable=fake_python,
run_root=run_root,
home=home,
),
env={
"DX_TEST_ARGV": str(argv),
"DX_TEST_STATUS": json.dumps(
_status_payload(
[project],
job_id=job.name,
completed_project_ids={"p1"},
)
),
"DX_TEST_OPERATOR_STEPS": json.dumps(
[_operator_step_payload(None)]
),
},
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert json.loads(argv.read_text(encoding="utf-8")) == [
["-m", "dx_productivity", "--json", "status", str(job.resolve())],
[
"-m",
"dx_productivity",
"--json",
"operator-step",
str(job.resolve()),
],
]
manifest = json.loads(
(run_root / "current-part-replacement.json").read_text(encoding="utf-8")
)
assert manifest["complete"] is True
assert manifest["current_project_id"] is None
assert manifest["projects"][0]["project_id"] == "p1"
assert not (job / "mailbox").exists()
@pytest.mark.parametrize("invalid_case", ("mixed", "relative", "outside"))
def test_launcher_resume_rejects_invalid_scope_before_python(
tmp_path: Path,
invalid_case: str,
) -> None:
# Catches resume accepting create inputs or a job outside its deployed run root.
home = tmp_path / "home"
run_root = home / "runs"
profile = _profile(run_root / "compatibility-profile.json")
valid_job = run_root / "part-replace-existing"
valid_job.mkdir()
outside = tmp_path / "outside-job"
outside.mkdir()
fake_python, argv = _fake_python(tmp_path)
job_value = {
"mixed": str(valid_job),
"relative": "part-replace-existing",
"outside": str(outside),
}[invalid_case]
arguments = [
"-ResumeJob",
job_value,
"-CompatibilityProfile",
str(profile),
"-PythonExecutable",
str(fake_python),
"-RunRoot",
str(run_root),
"-DXToolsHome",
str(home),
]
if invalid_case == "mixed":
arguments.extend(("-Mapping", str(tmp_path / "mapping.csv")))
completed = _ps(
LAUNCHER,
*arguments,
env={"DX_TEST_ARGV": str(argv)},
)
assert completed.returncode != 0
assert not argv.exists()
assert not (run_root / "current-part-replacement.json").exists()
@pytest.mark.parametrize(
"invalid_case",
("malformed", "wrong-job-id", "duplicate", "relative-project"),
)
def test_launcher_resume_rejects_invalid_status_before_operator_step(
tmp_path: Path,
invalid_case: str,
) -> None:
# Catches an untrusted status projection changing the menu project allowlist.
home = tmp_path / "home"
run_root = home / "runs"
profile = _profile(run_root / "compatibility-profile.json")
job = run_root / "part-replace-existing"
job.mkdir()
fake_python, argv = _fake_python(tmp_path)
project = {
"display_name": "one",
"project_id": "p1",
"project_path": "C:/projects/one.prj",
}
environment = {"DX_TEST_ARGV": str(argv)}
if invalid_case == "malformed":
environment["DX_TEST_STATUS_RAW"] = "{not-json"
else:
status = _status_payload(
[project],
job_id="other-job" if invalid_case == "wrong-job-id" else job.name,
)
if invalid_case == "duplicate":
status["projects"].append(dict(status["projects"][0]))
elif invalid_case == "relative-project":
status["projects"][0]["project_path"] = "relative.prj"
environment["DX_TEST_STATUS"] = json.dumps(status)
completed = _ps(
LAUNCHER,
*_resume_launcher_arguments(
job=job,
profile=profile,
python_executable=fake_python,
run_root=run_root,
home=home,
),
env=environment,
)
assert completed.returncode != 0
calls = json.loads(argv.read_text(encoding="utf-8"))
assert calls == [
["-m", "dx_productivity", "--json", "status", str(job.resolve())]
]
assert not (run_root / "current-part-replacement.json").exists()
def test_launcher_discovery_writes_candidates_and_exits_without_create(
tmp_path: Path,
) -> None:
# Catches discover-only mode falling through into job creation.
home = tmp_path / "home"
run_root = home / "runs"
profile = _profile(run_root / "compatibility-profile.json")
discovery = tmp_path / "candidate root"
discovery.mkdir()
mapping = tmp_path / "map.csv"
certifications = tmp_path / "certifications.json"
mapping.write_text("fixture\n", encoding="ascii")
certifications.write_text("fixture\n", encoding="ascii")
fake_python, argv = _fake_python(tmp_path)
candidates = [
str((discovery / "one.prj").resolve()),
str((discovery / "two.prj").resolve()),
]
completed = _ps(
LAUNCHER,
*_launcher_arguments(
mapping=mapping,
discovery=discovery,
certifications=certifications,
profile=profile,
python_executable=fake_python,
run_root=run_root,
home=home,
),
env={
"DX_TEST_ARGV": str(argv),
"DX_TEST_DISCOVERED": json.dumps(candidates),
},
)
assert completed.returncode == 0, completed.stdout + completed.stderr
calls = json.loads(argv.read_text(encoding="utf-8"))
discovered = run_root / "discovered-projects.txt"
assert calls == [
[
"-m",
"dx_productivity",
"discover",
str(discovery.resolve()),
"--output",
str(discovered.resolve()),
]
]
assert discovered.read_text(encoding="utf-8").splitlines() == candidates
assert not (run_root / "current-part-replacement.json").exists()
assert "Review discovered candidates" in completed.stdout
@pytest.mark.parametrize("wrong_path", ("profile", "run"))
def test_launcher_rejects_non_deployed_runtime_paths(
tmp_path: Path,
wrong_path: str,
) -> None:
# Catches a launcher publishing a profile or manifest where the menu cannot consume it.
home = tmp_path / "home"
canonical_run = home / "runs"
canonical_profile = _profile(canonical_run / "compatibility-profile.json")
supplied_run = canonical_run
supplied_profile = canonical_profile
if wrong_path == "profile":
supplied_profile = _profile(canonical_run / "other-profile.json")
else:
supplied_run = home / "other-runs"
supplied_run.mkdir()
mapping = tmp_path / "map.csv"
projects = tmp_path / "projects.txt"
certifications = tmp_path / "certifications.json"
for path in (mapping, projects, certifications):
path.write_text("fixture\n", encoding="ascii")
fake_python, argv = _fake_python(tmp_path)
completed = _ps(
LAUNCHER,
*_launcher_arguments(
mapping=mapping,
projects=projects,
certifications=certifications,
profile=supplied_profile,
python_executable=fake_python,
run_root=supplied_run,
home=home,
),
env={"DX_TEST_ARGV": str(argv)},
)
assert completed.returncode != 0
assert "deployed" in (completed.stdout + completed.stderr).lower()
assert not argv.exists()
def _menu_host_classes(home: Path, active_project: str) -> str:
return f'''Dim MenuLog
MenuLog = ""
Class FakeControl
Public Tag
Public Caption
Public OnAction
Public Controls
Public Parent
Private Sub Class_Initialize()
Set Controls = New FakeControls
End Sub
Public Sub Delete()
Parent.Remove Me
End Sub
End Class
Class FakeControls
Private Values(49)
Private ValueCount
Public Property Get Count
Count = ValueCount
End Property
Public Function Item(ByVal Index)
Set Item = Values(Index - 1)
End Function
Public Function Add(ByVal ControlType, ByVal Id, ByVal Parameter, ByVal Before, ByVal Temporary)
Dim Result
Set Result = New FakeControl
Set Result.Parent = Me
Set Values(ValueCount) = Result
ValueCount = ValueCount + 1
Set Add = Result
End Function
Public Sub Remove(ByVal Target)
Dim Index, Shift
For Index = 0 To ValueCount - 1
If Values(Index) Is Target Then
For Shift = Index To ValueCount - 2
Set Values(Shift) = Values(Shift + 1)
Next
ValueCount = ValueCount - 1
Set Values(ValueCount) = Nothing
Exit Sub
End If
Next
End Sub
End Class
Class FakeBar
Public Controls
Private Sub Class_Initialize()
Set Controls = New FakeControls
End Sub
End Class
Class FakeCommandBars
Public Bar
Private Sub Class_Initialize()
Set Bar = New FakeBar
End Sub
Public Default Function Item(ByVal Name)
Set Item = Bar
End Function
End Class
Class FakeScripting
Public Function GetEnvVariable(ByVal Name)
If Name = "DXTOOLS_HOME" Then GetEnvVariable = {_vbs_string(str(home))}
End Function
End Class
Class FakeApplication
Public ProjectPath
Private Sub Class_Initialize()
ProjectPath = {_vbs_string(active_project)}
End Sub
End Class
Dim CommandBars
Dim Scripting
Dim Application
Set CommandBars = New FakeCommandBars
Set Scripting = New FakeScripting
Set Application = New FakeApplication
'''
def _install_menu_test_modules(home: Path) -> None:
scripts = home / "integration" / "dxdesigner795"
scripts.mkdir(parents=True, exist_ok=True)
shutil.copyfile(MENU_RUNTIME, scripts / MENU_RUNTIME.name)
shutil.copyfile(
MENU_PART_REPLACE_RUNTIME,
scripts / MENU_PART_REPLACE_RUNTIME.name,
)
shutil.copyfile(COMMON, scripts / COMMON.name)
probe_source = PROBE.read_text(encoding="ascii").replace(
"Sub DxRunPartReplaceProbe(",
"Sub DxMenuRealPartReplaceProbe(",
1,
)
probe_source += '''
Sub DxRunPartReplaceProbe(ByVal RequestRelativePath, ByVal OutputRelativePath)
Dim RootPath, Text, DisposableMarker, OperatorConfirmation, RequestValid
Dim MutatingAuthorized
RootPath = CStr(Scripting.GetEnvVariable("DXTOOLS_HOME"))
Text = DxReadUtf8(DxResolveRunPath(RootPath, RequestRelativePath))
DxProbeParseRequest Text, DisposableMarker, OperatorConfirmation, RequestValid
MutatingAuthorized = RequestValid And DisposableMarker And OperatorConfirmation
DxWriteUtf8Atomic DxResolveRunPath(RootPath, _
"runs/menu-probe-observed.txt"), Text
DxWriteUtf8Atomic DxResolveRunPath(RootPath, _
"runs/menu-probe-result.txt"), LCase(CStr(RequestValid)) & "|" & _
LCase(CStr(MutatingAuthorized)) & "|false" & vbLf
End Sub
'''
(scripts / PROBE.name).write_text(
probe_source,
encoding="ascii",
newline="",
)
bridge_source = BRIDGE.read_text(encoding="ascii").replace(
"Sub DxRunPartReplaceBridge(",
"Sub DxMenuRealPartReplaceBridge(",
1,
)
bridge_source += '''
Sub DxRunPartReplaceBridge(ByVal RequestedAction, ByVal ProfileRelativePath, _
ByVal CommandRelativePath, ByVal StatusRelativePath, _
ByVal SnapshotRelativePath, ByVal ProjectPathArgument)
Dim RootPath, Text
RootPath = CStr(Scripting.GetEnvVariable("DXTOOLS_HOME"))
Text = CStr(RequestedAction) & "|" & CStr(ProfileRelativePath) & "|" & _
CStr(CommandRelativePath) & "|" & CStr(StatusRelativePath) & "|" & _
CStr(SnapshotRelativePath) & "|" & CStr(ProjectPathArgument) & vbLf
DxWriteUtf8Atomic DxResolveRunPath(RootPath, _
"runs/menu-bridge-call.txt"), Text
End Sub
'''
(scripts / BRIDGE.name).write_text(
bridge_source,
encoding="ascii",
newline="",
)
def _menu_test_home(tmp_path: Path) -> Path:
home = tmp_path / "home"
(home / "runs").mkdir(parents=True)
_install_menu_test_modules(home)
return home
def _run_menu_handler(
tmp_path: Path,
home: Path,
statement: str,
*,
active_project: str,
) -> subprocess.CompletedProcess[str]:
wrapper_count = len(list(tmp_path.glob("menu-handler-*")))
wrapper = tmp_path / f"menu-handler-{wrapper_count}.vbs"
wrapper.write_text(
"Option Explicit\n"
+ _menu_host_classes(home, active_project)
+ f'''Dim Fso, Source, ErrorNumber, ErrorDescription
Set Fso = CreateObject("Scripting.FileSystemObject")
Source = Fso.OpenTextFile({_vbs_string(str(MENU))}, 1, False, 0).ReadAll
ExecuteGlobal Source
On Error Resume Next
{statement}
ErrorNumber = Err.Number
ErrorDescription = Err.Description
Err.Clear
On Error GoTo 0
WScript.Echo CStr(ErrorNumber) & "|" & CStr(ErrorDescription)
''',
encoding="ascii",
newline="",
)
return _cscript(wrapper)
def _manifest_entry(project_path: str, suffix: str = "p1") -> dict[str, str]:
return {
"project_id": suffix,
"project_path": project_path,
"profile": "runs/compatibility-profile.json",
"command": f"runs/job/mailbox/{suffix}/command.json",
"status": f"runs/job/mailbox/{suffix}/status.json",
"snapshot": f"runs/job/mailbox/{suffix}/snapshot.json",
}
_MENU_COMMAND_ID = "a" * 32
def _write_manifest(
home: Path,
entries: list[dict[str, str]],
*,
current_project_id: str | None = None,
current_action: str | None = "inventory",
current_command_id: str | None = _MENU_COMMAND_ID,
complete: bool = False,
) -> None:
if current_project_id is None and entries:
current_project_id = entries[0]["project_id"]
_write_json(
home / "runs" / "current-part-replacement.json",
{
"complete": complete,
"current_action": current_action,
"current_command_id": current_command_id,
"current_project_id": current_project_id,
"format_version": 2,
"projects": entries,
},
)
def _bridge_command(
action: str,
project_id: str = "p1",
*,
command_id: str = _MENU_COMMAND_ID,
) -> dict[str, object]:
replacement_lineage = action in {"replace_part", "save", "undo"}
return {
"action": action,
"command_id": command_id,
"expected_count": 1 if replacement_lineage else 0,
"expected_fingerprint": "" if action == "inventory" else "0" * 64,
"expected_logical_keys": ["/MAIN|U1"] if replacement_lineage else [],
"format_version": 1,
"job_id": "job-1",
"new_part_number": "NEW-1" if replacement_lineage else "",
"old_part_number": "OLD-1" if replacement_lineage else "",
"project_id": project_id,
"scope": "full_project",
}
def _replacement_command(project_id: str = "p1") -> dict[str, object]:
return _bridge_command("replace_part", project_id)
def _manual_status(
manual_route: str,
*,
command: dict[str, object] | None = None,
command_id: str = _MENU_COMMAND_ID,
) -> dict[str, object]:
current = _replacement_command() if command is None else command
return {
"command_id": command_id,
"details": [
["action", current["action"]],
["expected_count", str(current["expected_count"])],
["instruction", "complete the native action"],
["job_id", "job-1"],
["manual_route", manual_route],
["new_part_number", current["new_part_number"]],
["old_part_number", current["old_part_number"]],
],
"error_code": None,
"error_message": None,
"format_version": 1,
"project_id": current["project_id"],
"snapshot_path": None,
"state": (
"manual_project_open_required"
if manual_route == "manual_project_open"
else "manual_action_required"
),
}
def test_startup_import_twice_replaces_only_exact_tag_and_wires_actions(
tmp_path: Path,
) -> None:
# Catches declarations in the loader making a second same-host import fail.
home = _menu_test_home(tmp_path)
state = tmp_path / "command-bars-state.txt"
state.write_text(
"DX_PRODUCTIVITY_PART_REPLACE\n"
"DX_PRODUCTIVITY_PART_REPLACE_OTHER\n",
encoding="ascii",
)
wrapper = tmp_path / "menu-startup.vbs"
wrapper.write_text(
"Option Explicit\n"
+ _menu_host_classes(home, "C:/active.prj")
+ f'''Dim Fso, MenuSource, StateText, Tags, Tag, LoadedControl
Dim Index, Control, ExactCount, Output
Set Fso = CreateObject("Scripting.FileSystemObject")
StateText = Fso.OpenTextFile({_vbs_string(str(state))}, 1, False, 0).ReadAll
Tags = Split(Replace(StateText, vbCr, ""), vbLf)
For Each Tag In Tags
If Len(CStr(Tag)) > 0 Then
Set LoadedControl = CommandBars.Bar.Controls.Add( _
10, Empty, Empty, Empty, True)
LoadedControl.Tag = CStr(Tag)
End If
Next
MenuSource = Fso.OpenTextFile({_vbs_string(str(MENU))}, 1, False, 0).ReadAll
ExecuteGlobal MenuSource
ExecuteGlobal MenuSource
ExactCount = 0
Output = ""
For Index = 1 To CommandBars.Bar.Controls.Count
Set Control = CommandBars.Bar.Controls.Item(Index)
Output = Output & Control.Tag & vbLf
If Control.Tag = "DX_PRODUCTIVITY_PART_REPLACE" Then
ExactCount = ExactCount + 1
If Control.Caption <> "Dx Productivity" Then WScript.Quit 11
If Control.Controls.Count <> 3 Then WScript.Quit 12
If Control.Controls.Item(1).OnAction <> _
"DxPartReplacementMenuProbe" Then WScript.Quit 13
If Control.Controls.Item(2).OnAction <> _
"DxPartReplacementMenuInventory" Then WScript.Quit 14
If Control.Controls.Item(3).OnAction <> _
"DxPartReplacementMenuContinue" Then WScript.Quit 15
End If
Next
If ExactCount <> 1 Then WScript.Quit 16
If CommandBars.Bar.Controls.Count <> 2 Then WScript.Quit 17
If CommandBars.Bar.Controls.Item(1).Tag <> _
"DX_PRODUCTIVITY_PART_REPLACE_OTHER" Then WScript.Quit 18
DxPartReplacementMenuProbe
Fso.OpenTextFile({_vbs_string(str(state))}, 2, True, 0).Write Output
WScript.Echo "menu-valid"
''',
encoding="ascii",
newline="",
)
completed = _cscript(wrapper)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert completed.stdout.strip() == "menu-valid"
assert (home / "runs" / "menu-probe-result.txt").read_text(
encoding="utf-8-sig"
) == "true|false|false\n"
assert MENU.read_bytes().isascii()
assert MENU_PART_REPLACE_RUNTIME.read_bytes().isascii()
def test_probe_handler_writes_exact_valid_nonmutating_request(tmp_path: Path) -> None:
# Catches reordered request fields making the probe mark a safe request invalid.
home = _menu_test_home(tmp_path)
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuProbe",
active_project="C:/active.prj",
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert completed.stdout.startswith("0|")
assert (home / "runs" / "menu-probe-observed.txt").read_text(
encoding="utf-8-sig"
) == (
'{"disposable_project_marker":false,"format_version":1,'
'"operator_confirmation":false}\n'
)
assert (home / "runs" / "menu-probe-result.txt").read_text(
encoding="utf-8-sig"
) == "true|false|false\n"
def test_inventory_handler_dispatches_the_unique_active_project(tmp_path: Path) -> None:
# Catches inventory dispatch using the first manifest record instead of the active project.
home = _menu_test_home(tmp_path)
first = str((tmp_path / "one.prj").resolve())
active = str((tmp_path / "active.prj").resolve())
_write_manifest(
home,
[_manifest_entry(first, "p1"), _manifest_entry(active, "p2")],
current_project_id="p2",
)
_write_json(
home / Path(_manifest_entry(active, "p2")["command"]),
_bridge_command("inventory", "p2"),
)
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuInventory",
active_project=active,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert completed.stdout.startswith("0|")
assert (home / "runs" / "menu-bridge-call.txt").read_text(
encoding="utf-8-sig"
) == (
"inventory|runs/compatibility-profile.json|"
"runs/job/mailbox/p2/command.json|"
"runs/job/mailbox/p2/status.json|"
"runs/job/mailbox/p2/snapshot.json|\n"
)
@pytest.mark.parametrize(
"action",
(
"inventory",
"close_project",
"close_without_save",
"open_project",
"replace_part",
"undo",
"save",
"packager",
"erc",
"netlist",
),
)
def test_continue_dispatches_every_manifest_selected_bridge_action(
tmp_path: Path,
action: str,
) -> None:
# Catches a menu dispatcher that implements only inventory or Replace Part.
home = _menu_test_home(tmp_path)
target = str((tmp_path / "active.prj").resolve())
entry = _manifest_entry(target)
_write_manifest(home, [entry], current_action=action)
_write_json(home / Path(entry["command"]), _bridge_command(action))
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuContinue",
active_project="" if action == "open_project" else target,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert completed.stdout.startswith("0|")
project_argument = target if action == "open_project" else ""
assert (home / "runs" / "menu-bridge-call.txt").read_text(
encoding="utf-8-sig"
) == (
f"{action}|runs/compatibility-profile.json|"
"runs/job/mailbox/p1/command.json|"
"runs/job/mailbox/p1/status.json|"
f"runs/job/mailbox/p1/snapshot.json|{project_argument}\n"
)
@pytest.mark.parametrize(
"stale_binding",
("complete", "project", "command-id", "action", "command-project"),
)
def test_menu_rejects_stale_manifest_command_bindings(
tmp_path: Path,
stale_binding: str,
) -> None:
# Catches dispatch after the launcher advances or completes the durable command.
home = _menu_test_home(tmp_path)
active = str((tmp_path / "active.prj").resolve())
entry = _manifest_entry(active)
command = _bridge_command("inventory")
manifest_options: dict[str, object] = {}
if stale_binding == "complete":
manifest_options = {
"complete": True,
"current_project_id": None,
"current_action": None,
"current_command_id": None,
}
elif stale_binding == "project":
manifest_options["current_project_id"] = "other-project"
elif stale_binding == "command-id":
manifest_options["current_command_id"] = "b" * 32
elif stale_binding == "action":
manifest_options["current_action"] = "save"
else:
command["project_id"] = "other-project"
_write_manifest(home, [entry], **manifest_options)
_write_json(home / Path(entry["command"]), command)
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuContinue",
active_project=active,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert not completed.stdout.startswith("0|")
assert not (home / "runs" / "menu-bridge-call.txt").exists()
@pytest.mark.parametrize(
"action",
(
"inventory",
"close_project",
"close_without_save",
"replace_part",
"undo",
"save",
"packager",
"erc",
"netlist",
),
)
def test_non_open_actions_require_the_exact_active_project(
tmp_path: Path,
action: str,
) -> None:
# Catches a current-command binding being treated as permission to mutate another project.
home = _menu_test_home(tmp_path)
target = str((tmp_path / "target.prj").resolve())
entry = _manifest_entry(target)
_write_manifest(home, [entry], current_action=action)
_write_json(home / Path(entry["command"]), _bridge_command(action))
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuContinue",
active_project=str((tmp_path / "other.prj").resolve()),
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert not completed.stdout.startswith("0|")
assert not (home / "runs" / "menu-bridge-call.txt").exists()
@pytest.mark.parametrize("manifest_case", ("zero", "multiple", "no-active"))
def test_manifest_without_one_active_project_fails_closed(
tmp_path: Path,
manifest_case: str,
) -> None:
# Catches ambiguous or absent active-project routing reaching the bridge.
home = _menu_test_home(tmp_path)
active = str((tmp_path / "active.prj").resolve())
entries: list[dict[str, str]] = []
active_project = active
if manifest_case == "multiple":
entries = [_manifest_entry(active, "p1"), _manifest_entry(active, "p1")]
elif manifest_case == "no-active":
entries = [_manifest_entry(active, "p1")]
active_project = ""
_write_manifest(home, entries)
if entries:
_write_json(
home / Path(entries[0]["command"]),
_bridge_command("inventory"),
)
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuInventory",
active_project=active_project,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert not completed.stdout.startswith("0|")
assert not (home / "runs" / "menu-bridge-call.txt").exists()
@pytest.mark.parametrize(
("action", "manual_route", "active_after_manual"),
(
("undo", "manual_native_undo", "target"),
("save", "manual_native_save", "target"),
("open_project", "manual_project_open", "target"),
("close_project", "manual_close_project", "closed"),
("close_without_save", "manual_close_without_save", "closed"),
),
)
def test_manual_control_continuations_repeat_the_bound_base_action(
tmp_path: Path,
action: str,
manual_route: str,
active_after_manual: str,
) -> None:
# Catches manual control completion being mapped to an invented bridge action.
home = _menu_test_home(tmp_path)
target = str((tmp_path / "active.prj").resolve())
entry = _manifest_entry(target)
command = _bridge_command(action)
_write_manifest(home, [entry], current_action=action)
_write_json(home / Path(entry["command"]), command)
_write_json(
home / Path(entry["status"]),
_manual_status(manual_route, command=command),
)
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuContinue",
active_project=target if active_after_manual == "target" else "",
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert completed.stdout.startswith("0|")
call = (home / "runs" / "menu-bridge-call.txt").read_text(
encoding="utf-8-sig"
)
expected_project_argument = target if action == "open_project" else ""
assert call.startswith(action + "|")
assert call.endswith("|" + expected_project_argument + "\n")
@pytest.mark.parametrize(
("status", "expected_action"),
(
(None, "replace_part"),
(
_manual_status("manual_exact_selection"),
"continue_after_manual_selection",
),
(
_manual_status("manual_native_dialog"),
"continue_after_manual_dialog",
),
),
ids=("initial", "manual-exact-selection", "manual-native-dialog"),
)
def test_continue_handler_dispatches_only_a_valid_next_native_action(
tmp_path: Path,
status: dict[str, object] | None,
expected_action: str,
) -> None:
# Catches Continue guessing a branch instead of validating command/status correlation.
home = _menu_test_home(tmp_path)
active = str((tmp_path / "active.prj").resolve())
entry = _manifest_entry(active)
_write_manifest(home, [entry], current_action="replace_part")
_write_json(home / Path(entry["command"]), _replacement_command())
if status is not None:
_write_json(home / Path(entry["status"]), status)
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuContinue",
active_project=active,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert completed.stdout.startswith("0|")
call = (home / "runs" / "menu-bridge-call.txt").read_text(
encoding="utf-8-sig"
)
assert call.startswith(expected_action + "|")
@pytest.mark.parametrize(
"status_case",
("applied", "blocked", "malformed", "uncorrelated", "malformed-command"),
)
def test_continue_handler_fails_closed_for_noncontinuable_state(
tmp_path: Path,
status_case: str,
) -> None:
# Catches completed, failed, malformed, or stale work being replayed by Continue.
home = _menu_test_home(tmp_path)
active = str((tmp_path / "active.prj").resolve())
entry = _manifest_entry(active)
_write_manifest(home, [entry], current_action="replace_part")
command = _replacement_command()
if status_case == "malformed-command":
command["unexpected"] = True
_write_json(home / Path(entry["command"]), command)
status_path = home / Path(entry["status"])
if status_case == "malformed":
status_path.parent.mkdir(parents=True, exist_ok=True)
status_path.write_text("not json", encoding="ascii")
elif status_case != "malformed-command":
status = _manual_status("manual_exact_selection")
if status_case == "applied":
status["state"] = "applied"
status["snapshot_path"] = "snapshot.json"
status["details"] = [
["action", "replace_part"],
["expected_count", "1"],
["job_id", "job-1"],
]
elif status_case == "blocked":
status["state"] = "blocked"
status["error_code"] = "unsafe"
status["error_message"] = "blocked"
elif status_case == "uncorrelated":
status["command_id"] = "other-command"
_write_json(status_path, status)
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuContinue",
active_project=active,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert not completed.stdout.startswith("0|")
assert not (home / "runs" / "menu-bridge-call.txt").exists()
@pytest.mark.parametrize(
"unsafe_field",
("profile", "command", "status", "snapshot"),
)
def test_menu_rejects_bridge_paths_outside_dxtools_home(
tmp_path: Path,
unsafe_field: str,
) -> None:
# Catches manifest path traversal before either reads or bridge dispatch.
home = _menu_test_home(tmp_path)
active = str((tmp_path / "active.prj").resolve())
entry = _manifest_entry(active)
entry[unsafe_field] = "../outside.json"
_write_manifest(home, [entry])
if unsafe_field != "command":
safe_entry = _manifest_entry(active)
_write_json(
home / Path(safe_entry["command"]),
_bridge_command("inventory"),
)
completed = _run_menu_handler(
tmp_path,
home,
"DxPartReplacementMenuInventory",
active_project=active,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
assert not completed.stdout.startswith("0|")
assert not (home / "runs" / "menu-bridge-call.txt").exists()
def test_powershell_launchers_are_ascii_and_parse_in_windows_powershell() -> None:
# Catches a non-ASCII startup dependency or syntax accepted only by PowerShell 7.
for script in (INSTALL, LAUNCHER, LAUNCHER_CONTRACT):
assert script.read_bytes().isascii()
command = (
"$tokens=$null; $errors=$null; "
"[void][Management.Automation.Language.Parser]::ParseFile("
f"'{script}',[ref]$tokens,[ref]$errors); "
"if($errors.Count){exit 1}"
)
completed = subprocess.run(
["powershell", "-NoProfile", "-Command", command],
check=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
assert completed.returncode == 0, completed.stdout + completed.stderr