import hashlib import io import tempfile import unittest import zipfile import ctypes from pathlib import Path from subprocess import CompletedProcess from unittest.mock import patch import deploy_tool.installer as installer_module from deploy_tool.installer import ( MAVEN_ARCHIVE_NAME, MYSQL_VERSION, MYSQL_ROOT_PASSWORD, MYSQL_INSTALLER_SHA256, MYSQL_INSTALLER_URL, build_mysql_installer_command, build_windows_command_parameters, configure_mysql_weak_password_policy, default_mysql_install_log_path, TOMCAT_VERSION, install_maven, install_mysql, install_tomcat, build_install_command, explain_install_failure, format_install_output, recommend_jdk_version, ) 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( """ 1.8 1.8 spring-boot-starter-web """, 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( """ org.springframework.boot spring-boot-starter-parent 3.2.5 """, 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", ], ) 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_builds_unattended_mysql_msi_install_command(self): command = build_mysql_installer_command(Path("mysql-installer.msi"), Path("mysql-install.log")) self.assertEqual(command[0:3], ["msiexec.exe", "/i", "mysql-installer.msi"]) self.assertIn("/passive", command) self.assertNotIn("/qn", command) self.assertIn("/L*V", command) self.assertIn("mysql-install.log", command) self.assertEqual(MYSQL_VERSION, "8.0.43") self.assertIn("root_passwd=123456", command[-1]) self.assertIn("open_win_firewall=false", command[-1]) self.assertEqual(MYSQL_INSTALLER_SHA256, "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80") self.assertIn("downloads.mysql.com/archives/", MYSQL_INSTALLER_URL) def test_formats_mysql_consoleargs_as_an_msi_property_value(self): command = build_mysql_installer_command( Path(r"C:\Temp Folder\mysql-installer.msi"), Path(r"C:\Log Folder\mysql-install.log"), ) parameters = build_windows_command_parameters(command) self.assertIn('/i "C:\\Temp Folder\\mysql-installer.msi"', parameters) self.assertIn('/L*V "C:\\Log Folder\\mysql-install.log"', parameters) self.assertIn('CONSOLEARGS="install server;8.0.43;x64:*:', parameters) self.assertIn('root_passwd=123456 --silent --auto-handle-prereqs"', parameters) self.assertNotIn('"CONSOLEARGS=', parameters) 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) self.assertTrue(Path(command[2]).exists()) return 0 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.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, ) self.assertEqual(executable, Path("mysql.exe")) self.assertEqual(commands[0][0], "msiexec.exe") self.assertIn("/passive", commands[0]) self.assertIn(str(install_log), commands[0]) self.assertTrue(any("校验通过" in message for message in messages)) self.assertTrue(any("进度窗口" in message for message in messages)) self.assertTrue(any(str(install_log) in message for message in messages)) configure.assert_called_once() 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() self.assertEqual( log_path, Path(r"C:\Users\tester\AppData\Local") / "AutoDeploy" / "logs" / "mysql-install.log", ) 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_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") 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()