Files
AutoDeploy/tests/test_installer.py

442 lines
18 KiB
Python
Raw Normal View History

import hashlib
import io
import json
2026-07-14 16:30:36 +08:00
import tempfile
import unittest
import zipfile
2026-10-09 09:38:44 +08:00
import ctypes
2026-07-14 16:30:36 +08:00
from pathlib import Path
from subprocess import CompletedProcess
from unittest.mock import patch
2026-07-14 16:30:36 +08:00
2026-10-09 09:38:44 +08:00
import deploy_tool.installer as installer_module
from deploy_tool.installer import (
MAVEN_ARCHIVE_NAME,
MYSQL_INITIAL_ROOT_PASSWORD,
2026-10-09 08:45:18 +08:00
MYSQL_VERSION,
MYSQL_ROOT_PASSWORD,
2026-10-09 09:31:36 +08:00
MYSQL_INSTALLER_SHA256,
MYSQL_INSTALLER_URL,
NODE_DIST_BASE,
2026-10-09 09:31:36 +08:00
build_mysql_installer_command,
build_mysql_server_install_command,
configure_mysql_weak_password_policy,
2026-10-09 09:48:42 +08:00
default_mysql_install_log_path,
2026-10-09 10:23:26 +08:00
default_mysql_server_install_log_path,
run_elevated_command_with_log,
TOMCAT_VERSION,
install_maven,
2026-10-09 09:31:36 +08:00
install_mysql,
install_node,
install_tomcat,
build_install_command,
explain_install_failure,
format_install_output,
recommend_jdk_version,
recommend_node_version,
resolve_node_release,
)
2026-07-14 16:30:36 +08:00
from deploy_tool.scanner import scan_project
class InstallerTests(unittest.TestCase):
def test_recommends_jdk_8_from_maven_source_property(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
backend = root / "server"
(backend / "src" / "main" / "java").mkdir(parents=True)
(backend / "pom.xml").write_text(
"""
<project>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>spring-boot-starter-web</dependency>
</dependencies>
</project>
""",
encoding="utf-8",
)
scan = scan_project(root)
recommendation = recommend_jdk_version(scan)
self.assertEqual(recommendation.version, "8")
self.assertIn("maven.compiler.source", recommendation.reason)
def test_recommends_jdk_17_for_spring_boot_3(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
backend = root / "server"
(backend / "src" / "main" / "java").mkdir(parents=True)
(backend / "pom.xml").write_text(
"""
<project>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
</parent>
</project>
""",
encoding="utf-8",
)
scan = scan_project(root)
recommendation = recommend_jdk_version(scan)
self.assertEqual(recommendation.version, "17")
self.assertIn("Spring Boot 3", recommendation.reason)
def test_defaults_to_jdk_8_without_project_signal(self):
recommendation = recommend_jdk_version(None)
self.assertEqual(recommendation.version, "8")
self.assertIn("默认", recommendation.reason)
def test_builds_jdk_winget_install_command(self):
command = build_install_command("JDK", version="8")
self.assertEqual(
command,
[
"winget",
"install",
"--exact",
"--id",
"EclipseAdoptium.Temurin.8.JDK",
"--accept-source-agreements",
"--accept-package-agreements",
"--disable-interactivity",
],
)
2026-07-14 16:30:36 +08:00
def test_builds_node_winget_install_command(self):
command = build_install_command("Node.js")
self.assertEqual(command[0:5], ["winget", "install", "--exact", "--id", "OpenJS.NodeJS.LTS"])
self.assertIn("--accept-package-agreements", command)
self.assertIn("--disable-interactivity", command)
def test_recommends_node_from_project_engines(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
frontend = root / "web"
frontend.mkdir()
(frontend / "package.json").write_text(
json.dumps(
{
"engines": {"node": ">=18 <21"},
"dependencies": {"vue": "^3.4.0"},
"scripts": {"build": "vite build"},
}
),
encoding="utf-8",
)
recommendation = recommend_node_version(scan_project(root))
self.assertEqual(recommendation.requirements, (">=18 <21",))
self.assertIn("engines.node", recommendation.reason)
def test_resolves_latest_compatible_node_release(self):
index = json.dumps(
[
{"version": "v22.3.0", "lts": "Jod", "files": ["win-x64-zip"]},
{"version": "v20.12.2", "lts": "Iron", "files": ["win-x64-zip"]},
{"version": "v20.11.1", "lts": "Iron", "files": ["win-x64-zip"]},
{"version": "v18.20.0", "lts": "Hydrogen", "files": ["win-x64-zip"]},
]
)
release = resolve_node_release(index, (">=18 <21",))
self.assertEqual(release.version, "20.12.2")
self.assertEqual(resolve_node_release(index, ("lts/iron",)).version, "20.12.2")
def test_installs_verified_node_archive_selected_from_official_index(self):
version = "20.12.2"
directory = f"node-v{version}-win-x64"
archive_name = f"{directory}.zip"
archive_buffer = io.BytesIO()
with zipfile.ZipFile(archive_buffer, "w") as archive:
archive.writestr(f"{directory}/node.exe", "node")
archive.writestr(f"{directory}/npm.cmd", "npm")
archive_bytes = archive_buffer.getvalue()
checksum = hashlib.sha256(archive_bytes).hexdigest()
index_bytes = json.dumps(
[{"version": f"v{version}", "lts": "Iron", "files": ["win-x64-zip"]}]
).encode("utf-8")
def opener(url, timeout):
if url == f"{NODE_DIST_BASE}/index.json":
return io.BytesIO(index_bytes)
if url.endswith("SHASUMS256.txt"):
return io.BytesIO(f"{checksum} {archive_name}\n".encode("ascii"))
return io.BytesIO(archive_bytes)
with tempfile.TemporaryDirectory() as tmp:
messages = []
node, npm, installed_version = install_node((">=18 <21",), messages.append, Path(tmp), opener)
self.assertEqual(installed_version, version)
self.assertTrue(node.exists())
self.assertTrue(npm.exists())
self.assertTrue(any("自动选择 Node.js 20.12.2" in message for message in messages))
2026-10-09 09:31:36 +08:00
def test_builds_unattended_mysql_msi_install_command(self):
2026-10-09 09:48:42 +08:00
command = build_mysql_installer_command(Path("mysql-installer.msi"), Path("mysql-install.log"))
2026-10-09 09:31:36 +08:00
self.assertEqual(command[0:3], ["msiexec.exe", "/i", "mysql-installer.msi"])
2026-10-09 09:48:42 +08:00
self.assertIn("/passive", command)
self.assertNotIn("/qn", command)
self.assertIn("/L*V", command)
self.assertIn("mysql-install.log", command)
2026-10-09 08:45:18 +08:00
self.assertEqual(MYSQL_VERSION, "8.0.43")
self.assertFalse(any("CONSOLEARGS" in argument for argument in command))
2026-10-09 09:31:36 +08:00
self.assertEqual(MYSQL_INSTALLER_SHA256, "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80")
self.assertIn("downloads.mysql.com/archives/", MYSQL_INSTALLER_URL)
def test_builds_tracked_mysql_server_console_command_with_strong_initial_password(self):
command = build_mysql_server_install_command(Path("MySQLInstallerConsole.exe"))
2026-10-09 09:53:46 +08:00
2026-10-09 10:23:26 +08:00
self.assertEqual(command[0:3], ["MySQLInstallerConsole.exe", "community", "--install"])
self.assertIn("server;8.0.43;x64:*:", command[3])
self.assertIn("type=main", command[3])
self.assertNotIn("type=config", command[3])
self.assertIn(f"rootpasswd={MYSQL_INITIAL_ROOT_PASSWORD}", command[3])
self.assertNotIn(f"rootpasswd={MYSQL_ROOT_PASSWORD}", command[3])
self.assertNotIn("root_passwd", command[3])
self.assertIn("--silent", command)
self.assertIn("--auto-handle-prereqs", command)
2026-10-09 09:53:46 +08:00
2026-10-09 09:31:36 +08:00
def test_mysql_is_not_installed_from_stale_winget_manifest(self):
with self.assertRaises(ValueError):
build_install_command("MySQL")
def test_installs_mysql_from_verified_official_archive(self):
installer_bytes = b"verified-mysql-installer"
checksum = hashlib.sha256(installer_bytes).hexdigest()
commands = []
def opener(_url, timeout):
return io.BytesIO(installer_bytes)
def elevated_runner(command):
commands.append(command)
if command[0] == "msiexec.exe":
self.assertTrue(Path(command[2]).exists())
2026-10-09 09:31:36 +08:00
return 0
2026-10-09 09:48:42 +08:00
with tempfile.TemporaryDirectory() as tmp:
install_log = Path(tmp) / "logs" / "mysql-install.log"
with (
patch("deploy_tool.installer.MYSQL_INSTALLER_SHA256", checksum),
patch("deploy_tool.installer.find_mysql_installer_console", return_value=None),
patch(
"deploy_tool.installer.wait_for_mysql_installer_console",
return_value=Path("MySQLInstallerConsole.exe"),
),
2026-10-09 09:48:42 +08:00
patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")),
patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure,
):
messages = []
executable = install_mysql(
messages.append,
opener=opener,
elevated_runner=elevated_runner,
log_path=install_log,
)
2026-10-09 09:31:36 +08:00
self.assertEqual(executable, Path("mysql.exe"))
self.assertEqual(commands[0][0], "msiexec.exe")
2026-10-09 09:48:42 +08:00
self.assertIn("/passive", commands[0])
self.assertIn(str(install_log), commands[0])
self.assertEqual(commands[1][0], "MySQLInstallerConsole.exe")
2026-10-09 10:23:26 +08:00
self.assertEqual(commands[1][1:3], ["community", "--install"])
2026-10-09 09:31:36 +08:00
self.assertTrue(any("校验通过" in message for message in messages))
2026-10-09 09:48:42 +08:00
self.assertTrue(any("进度窗口" in message for message in messages))
self.assertTrue(any(str(install_log) in message for message in messages))
2026-10-09 09:31:36 +08:00
configure.assert_called_once()
2026-07-14 16:30:36 +08:00
def test_reuses_existing_mysql_installer_without_downloading_bundle(self):
commands = []
def elevated_runner(command):
commands.append(command)
return 0
def unexpected_download(_url, _timeout):
self.fail("MySQL bundle should not be downloaded when Installer already exists")
with (
patch(
"deploy_tool.installer.find_mysql_installer_console",
return_value=Path("MySQLInstallerConsole.exe"),
),
patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")),
patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure,
):
messages = []
executable = install_mysql(
messages.append,
opener=unexpected_download,
elevated_runner=elevated_runner,
)
self.assertEqual(executable, Path("mysql.exe"))
self.assertEqual(len(commands), 1)
self.assertEqual(commands[0][0], "MySQLInstallerConsole.exe")
self.assertTrue(any("检测到已有 MySQL Installer" in message for message in messages))
configure.assert_called_once()
2026-10-09 09:48:42 +08:00
def test_uses_persistent_mysql_install_log_location(self):
with patch.dict("os.environ", {"LOCALAPPDATA": r"C:\Users\tester\AppData\Local"}):
log_path = default_mysql_install_log_path()
2026-10-09 10:23:26 +08:00
server_log_path = default_mysql_server_install_log_path()
2026-10-09 09:48:42 +08:00
self.assertEqual(
log_path,
Path(r"C:\Users\tester\AppData\Local") / "AutoDeploy" / "logs" / "mysql-install.log",
)
2026-10-09 10:23:26 +08:00
self.assertEqual(
server_log_path,
Path(r"C:\Users\tester\AppData\Local") / "AutoDeploy" / "logs" / "mysql-server-install.log",
)
def test_elevated_command_logging_uses_temporary_powershell_wrapper(self):
with tempfile.TemporaryDirectory() as tmp:
log_path = Path(tmp) / "mysql-server-install.log"
def inspect_wrapper(command, on_wait=None):
self.assertEqual(command[0], "powershell.exe")
script_path = Path(command[-1])
self.assertTrue(script_path.exists())
script = script_path.read_text(encoding="utf-8-sig")
self.assertIn("'community' '--install'", script)
self.assertIn(str(log_path), script)
return 2
with patch("deploy_tool.installer.run_elevated_command", side_effect=inspect_wrapper):
exit_code = run_elevated_command_with_log(
["MySQLInstallerConsole.exe", "community", "--install"],
log_path,
)
self.assertEqual(exit_code, 2)
2026-10-09 09:48:42 +08:00
2026-10-09 09:38:44 +08:00
def test_windows_elevation_dependency_is_imported(self):
self.assertIs(installer_module.ctypes, ctypes)
def test_persists_six_character_mysql_password_policy(self):
query_result = CompletedProcess(
[],
0,
stdout="validate_password.length\t8\nvalidate_password.policy\tMEDIUM\n",
stderr="",
)
success = CompletedProcess([], 0, stdout="1\n", stderr="")
with patch("deploy_tool.installer.subprocess.run", side_effect=[query_result, success, success]) as run:
messages = []
configure_mysql_weak_password_policy(Path("mysql.exe"), messages.append, attempts=1)
configure_call = run.call_args_list[1]
sql = configure_call.kwargs["input"]
self.assertIn("SET PERSIST validate_password.policy = 'LOW'", sql)
self.assertIn("SET PERSIST validate_password.length = 6", sql)
self.assertIn("ALTER USER 'root'@'localhost' IDENTIFIED BY '123456'", sql)
self.assertEqual(configure_call.kwargs["env"]["MYSQL_PWD"], MYSQL_INITIAL_ROOT_PASSWORD)
self.assertEqual(run.call_args_list[2].kwargs["env"]["MYSQL_PWD"], MYSQL_ROOT_PASSWORD)
self.assertNotIn(MYSQL_ROOT_PASSWORD, configure_call.args[0])
self.assertTrue(any("永久允许 6 位弱密码" in message for message in messages))
def test_mysql_without_validation_component_still_sets_and_verifies_password(self):
no_component = CompletedProcess([], 0, stdout="", stderr="")
success = CompletedProcess([], 0, stdout="1\n", stderr="")
with patch("deploy_tool.installer.subprocess.run", side_effect=[no_component, success, success]) as run:
messages = []
configure_mysql_weak_password_policy(Path("mysql.exe"), messages.append, attempts=1)
sql = run.call_args_list[1].kwargs["input"]
self.assertNotIn("SET PERSIST", sql)
self.assertIn("ALTER USER", sql)
self.assertTrue(any("未启用 validate_password" in message for message in messages))
def test_maven_is_not_offered_as_an_invalid_winget_package(self):
with self.assertRaises(ValueError):
build_install_command("Maven")
def test_installs_maven_from_verified_apache_archive(self):
archive_buffer = io.BytesIO()
with zipfile.ZipFile(archive_buffer, "w") as archive:
archive.writestr("apache-maven-3.10.0/bin/mvn.cmd", "@echo off")
archive_bytes = archive_buffer.getvalue()
checksum = hashlib.sha512(archive_bytes).hexdigest().encode("ascii")
def opener(url, timeout):
return io.BytesIO(checksum if url.endswith(".sha512") else archive_bytes)
with tempfile.TemporaryDirectory() as tmp:
messages = []
executable = install_maven(messages.append, Path(tmp), opener)
self.assertTrue(executable.exists())
self.assertEqual(executable.read_text(), "@echo off")
self.assertTrue(any("校验通过" in message for message in messages))
def test_rejects_maven_archive_with_wrong_checksum(self):
def opener(url, timeout):
payload = ("0" * 128).encode("ascii") if url.endswith(".sha512") else b"not-a-zip"
return io.BytesIO(payload)
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaisesRegex(RuntimeError, "SHA-512"):
install_maven(lambda _message: None, Path(tmp), opener)
self.assertFalse((Path(tmp) / MAVEN_ARCHIVE_NAME.removesuffix("-bin.zip")).exists())
def test_installs_tomcat_from_verified_apache_archive(self):
archive_buffer = io.BytesIO()
with zipfile.ZipFile(archive_buffer, "w") as archive:
archive.writestr(f"apache-tomcat-{TOMCAT_VERSION}/bin/catalina.bat", "@echo off")
archive_bytes = archive_buffer.getvalue()
checksum = hashlib.sha512(archive_bytes).hexdigest().encode("ascii")
def opener(url, timeout):
return io.BytesIO(checksum if url.endswith(".sha512") else archive_bytes)
with tempfile.TemporaryDirectory() as tmp:
executable = install_tomcat(lambda _message: None, Path(tmp), opener)
self.assertTrue(executable.exists())
self.assertEqual(executable.name, "catalina.bat")
2026-07-14 16:30:36 +08:00
def test_formats_winget_progress_without_garbled_bar(self):
raw = "████████████▒▒▒▒▒▒ 63%\r".encode("utf-8")
self.assertEqual(format_install_output(raw), ["安装进度: 63%"])
def test_keeps_readable_winget_text(self):
raw = "已找到 Eclipse Temurin JDK [EclipseAdoptium.Temurin.8.JDK]\n".encode("utf-8")
self.assertEqual(format_install_output(raw), ["已找到 Eclipse Temurin JDK [EclipseAdoptium.Temurin.8.JDK]"])
def test_explains_missing_maven_winget_package(self):
message = explain_install_failure(
"Maven",
2316632084,
["找不到与输入条件匹配的程序包。"],
)
self.assertIn("winget 当前源找不到 Maven 包", message)
self.assertIn("手动下载 Apache Maven", message)
self.assertIn("mvn.cmd", message)
if __name__ == "__main__":
unittest.main()