Fix an issue that causes create symlink failed when installing java on unix-like platforms.

This commit is contained in:
wei committed 2026-10-18 21:42:54 +08:00
1 parent 8bde4ef753
commit 1754b01230
15 files changed
+600 -77

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
import json
from pathlib import Path
from string import Formatter
from core_lib.i18n import TranslationManager
def test_empty_catalog_uses_english_source_strings(tmp_path):
(tmp_path / "zh-TW.json").write_text("{}", encoding="utf-8")
translations = TranslationManager(tmp_path, "zh-TW")
assert translations.language == "zh-TW"
assert translations.translate("Settings") == "Settings"
assert translations.translate("Version: {version}", version="1.0") == "Version: 1.0"
def test_catalog_translation_and_unknown_language_fallback(tmp_path):
(tmp_path / "zh-TW.json").write_text(
json.dumps({"Settings": "設定"}), encoding="utf-8"
)
translations = TranslationManager(tmp_path, "zh-TW")
assert translations.translate("Settings") == "設定"
translations.set_language("unsupported")
assert translations.language == "en"
assert translations.translate("Settings") == "Settings"
def test_bundled_catalogs_have_matching_english_entries():
catalog_dir = Path(__file__).parents[1] / "resources" / "translations"
english = json.loads((catalog_dir / "en.json").read_text(encoding="utf-8"))
traditional_chinese = json.loads(
(catalog_dir / "zh-TW.json").read_text(encoding="utf-8")
)
assert english
assert set(traditional_chinese) == set(english)
assert traditional_chinese["Settings"] == "設定"
untranslated_names = {"English", "Fabric"}
assert {
key
for key, value in traditional_chinese.items()
if key == value
} == untranslated_names
formatter = Formatter()
for key, translated in traditional_chinese.items():
source_fields = {
field for _, field, _, _ in formatter.parse(key) if field is not None
}
translated_fields = {
field
for _, field, _, _ in formatter.parse(translated)
if field is not None
}
assert translated_fields == source_fields, key
+15
View File
@@ -0,0 +1,15 @@
from manager.game import JavaManager
def test_runtime_major_version_from_modern_version():
assert JavaManager._runtime_major_version("21.0.8") == 21
def test_runtime_major_version_from_legacy_version():
assert JavaManager._runtime_major_version("1.8.0_51") == 8
assert JavaManager._runtime_major_version("8u51") == 8
def test_runtime_major_version_rejects_unknown_value():
assert JavaManager._runtime_major_version(None) is None
assert JavaManager._runtime_major_version("unknown") is None
@@ -0,0 +1,30 @@
import logging
import sys
import tempfile
from pathlib import Path
from core_lib.common.exception import JavaRuntimeException
from core_lib.runtime.mojang import download_java_runtimes, get_support_runtime_manifest
def test_mac_os_runtime_install(tmp_path):
destination = tmp_path / "java-runtime-epsilon"
logger = logging.getLogger("Launcher.CoreLib")
logger.setLevel(logging.DEBUG)
print("Installing runtime...")
component = "java-runtime-epsilon"
download_java_runtimes(
component,
destination
)
executable_name = "java"
candidates = sorted(destination.rglob(executable_name))
print(f"{candidates=}")
assert any(path.is_file() for path in candidates), (
f"Installed runtime has no {executable_name}: {destination}"
)
+55
View File
@@ -0,0 +1,55 @@
from datetime import datetime, timezone
from manager.profile import ProfileSummary, sort_profile_summaries
def profile(
profile_id: str,
name: str,
last_used: datetime | None = None,
) -> ProfileSummary:
return ProfileSummary(
display_name=name,
id=profile_id,
name=name,
version_id="1.21.9",
version_type="release",
icon="",
last_used=last_used,
)
def test_sort_profiles_by_name() -> None:
profiles = [profile("z", "Zulu"), profile("a", "alpha"), profile("b", "Beta")]
ordered = sort_profile_summaries(profiles, "ByName")
assert [item.id for item in ordered] == ["a", "b", "z"]
def test_sort_profiles_by_last_played() -> None:
profiles = [
profile("old", "Old", datetime(2025, 1, 1, tzinfo=timezone.utc)),
profile("never", "Never"),
profile("new", "New", datetime(2026, 1, 1, tzinfo=timezone.utc)),
]
ordered = sort_profile_summaries(profiles, "ByLastPlayed")
assert [item.id for item in ordered] == ["new", "old", "never"]
def test_last_played_profile_id_is_first_when_timestamp_is_missing() -> None:
profiles = [profile("first", "First"), profile("current", "Current")]
ordered = sort_profile_summaries(profiles, "ByLastPlayed", "current")
assert [item.id for item in ordered] == ["current", "first"]
def test_unknown_sorting_preserves_file_order() -> None:
profiles = [profile("b", "Beta"), profile("a", "Alpha")]
ordered = sort_profile_summaries(profiles, "FutureSortingMode")
assert [item.id for item in ordered] == ["b", "a"]
+171
View File
@@ -0,0 +1,171 @@
from pathlib import Path
from enum import Enum
from typing import Literal
import pytest
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from manager.settings import (
ConfigValidationError,
ModelRegistrationError,
SettingsError,
SettingsManager,
)
from manager.settings_models import AccountSettings
class AppSettings(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
workers: int = Field(ge=1, le=8)
def write_toml(path: Path, content: str) -> Path:
path.write_text(content, encoding="utf-8")
return path
def test_load_registered_model(tmp_path: Path) -> None:
path = write_toml(tmp_path / "settings.toml", '[app]\nname = "demo"\nworkers = 4\n')
manager = SettingsManager(path)
manager.register("app", AppSettings)
manager.load()
settings = manager.get("app", AppSettings)
assert settings.name == "demo"
assert settings.workers == 4
def test_decorator_registration_and_validation(tmp_path: Path) -> None:
manager = SettingsManager()
@manager.model("plugin")
class PluginSettings(BaseModel):
enabled: bool
manager.validate({"plugin": {"enabled": True}})
assert manager.registered_sections == ("plugin",)
def test_invalid_config_reports_section(tmp_path: Path) -> None:
path = write_toml(tmp_path / "settings.toml", '[app]\nname = "demo"\nworkers = 99\n')
manager = SettingsManager(path)
manager.register("app", AppSettings)
with pytest.raises(ConfigValidationError) as error:
manager.load()
assert "app" in error.value.errors
def test_unknown_section_is_rejected(tmp_path: Path) -> None:
path = write_toml(tmp_path / "settings.toml", "[unknown]\nvalue = 1\n")
manager = SettingsManager(path)
with pytest.raises(SettingsError, match="unknown"):
manager.load()
def test_duplicate_registration_is_rejected() -> None:
manager = SettingsManager()
manager.register("app", AppSettings)
with pytest.raises(ModelRegistrationError):
manager.register("app", AppSettings)
def test_literal_choices_are_exposed_and_validated() -> None:
class UiSettings(BaseModel):
theme: Literal["light", "dark", "system"]
manager = SettingsManager()
manager.register("ui", UiSettings)
assert manager.choices("ui", "theme") == ("light", "dark", "system")
with pytest.raises(ConfigValidationError):
manager.validate({"ui": {"theme": "unknown"}})
def test_enum_choices_use_toml_values() -> None:
class LogLevel(str, Enum):
DEBUG = "debug"
INFO = "info"
class LogSettings(BaseModel):
level: LogLevel
manager = SettingsManager()
manager.register("log", LogSettings)
assert manager.choices("log", "level") == ("debug", "info")
manager.validate({"log": {"level": "debug"}})
def test_nested_model_and_nested_choices(tmp_path: Path) -> None:
class WindowSettings(BaseModel):
mode: Literal["windowed", "fullscreen"]
width: int = Field(ge=640)
class UiSettings(BaseModel):
window: WindowSettings
path = write_toml(
tmp_path / "settings.toml",
'[ui.window]\nmode = "fullscreen"\nwidth = 1920\n',
)
manager = SettingsManager(path)
manager.register("ui", UiSettings)
manager.load()
ui = manager.get("ui", UiSettings)
assert ui.window.width == 1920
assert manager.choices("ui", "window.mode") == ("windowed", "fullscreen")
def test_invalid_nested_model_is_rejected() -> None:
class ChildSettings(BaseModel):
count: int = Field(ge=1)
class ParentSettings(BaseModel):
child: ChildSettings
manager = SettingsManager()
manager.register("parent", ParentSettings)
with pytest.raises(ConfigValidationError) as error:
manager.validate({"parent": {"child": {"count": 0}}})
assert error.value.errors["parent"].errors()[0]["loc"] == ("child", "count")
def test_defaults_set_save_and_reload(tmp_path: Path) -> None:
class GeneralSettings(BaseModel):
language: Literal["en", "zh-TW"] = "zh-TW"
path = tmp_path / "data" / "settings.toml"
manager = SettingsManager(path)
manager.register("general", GeneralSettings)
manager.load_defaults()
manager.set("general", {"language": "en"})
assert manager.save() == path
assert 'language = "en"' in path.read_text(encoding="utf-8")
reloaded = SettingsManager(path)
reloaded.register("general", GeneralSettings)
reloaded.load()
assert reloaded.get("general", GeneralSettings).language == "en"
def test_account_client_id_is_a_valid_uuid() -> None:
manager = SettingsManager()
manager.register("account", AccountSettings)
manager.load_defaults()
custom_id = "12345678-1234-5678-9abc-123456789abc"
updated = manager.set("account", {"client_id": custom_id})
assert str(updated.client_id) == custom_id
with pytest.raises(ValidationError):
manager.set("account", {"client_id": "not-a-client-id"})