Update to v0.1.3
Add `safe_download` option to `download_file`.
The function `save_version_manifest` will save to temp location and then replace path to the destination.
Add `check_core_file_exists_and_verify` and `validate_version_manifest` to `version_info.py`.
Add legacy assets check process code to assets.py (missing in the old version)

Launcher
Update to 0.0.9a0
All launching processes now will check core file hash before game started.
The legacy assets will be checked and redownloaded (if corrupted or missing)
Remove launched profile from `launching_profiles` record and cleanup.
Add online mode launching to TestPage.
Add some tests.
This commit is contained in:
wei committed 2026-10-22 21:28:29 +08:00
1 parent b7af7e3469
commit 77c4be7dcf
16 files changed
+1090 -238

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
import datetime
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from core_lib.common.exception import ArgumentValueError, AuthenticationException
from core_lib.game import authentication
from core_lib.game.account import Account, convert_account_data_to_object, create_account, get_account_sample
from core_lib.game.argument import ArgumentMappings, generate_launch_command, replace_placeholders
from manager import account as account_module
from manager.account import AccountDetail, AccountManager, TokenRefreshWorker
XUID = "2535400000000000"
def claims(xuid=XUID, user_hash="user-hash"):
return {"DisplayClaims": {"xui": [{"uhs": user_hash, "xid": xuid}]}}
def test_xuid_lookup_reuses_existing_claims(monkeypatch):
request = Mock()
monkeypatch.setattr(authentication, "get_xsts_token", request)
assert authentication.get_xbox_xuid("xbox-token", "user-hash", claims()) == XUID
request.assert_not_called()
def test_xuid_lookup_uses_separate_xbox_relying_party(monkeypatch):
request = Mock(return_value=("xbox-service-token", claims()))
monkeypatch.setattr(authentication, "get_xsts_token", request)
assert authentication.get_xbox_xuid("xbox-token", "user-hash", {}) == XUID
request.assert_called_once_with("xbox-token", relying_party="https://xboxlive.com")
def test_optional_xuid_lookup_failure_does_not_fail_login(monkeypatch):
monkeypatch.setattr(authentication, "get_xsts_token", Mock(side_effect=AuthenticationException("unavailable")))
assert authentication.get_xbox_xuid("xbox-token", "user-hash", {}) is None
@pytest.mark.parametrize("data", [{}, {"DisplayClaims": None}, claims(user_hash="other-user"),
claims(xuid="not-a-number"), claims(xuid="9" * 30)])
def test_invalid_or_other_user_claims_are_not_used(data):
assert authentication.extract_xuid(data, "user-hash") is None
@pytest.mark.parametrize("xuid", [None, XUID])
def test_account_xuid_round_trip_and_launch_mapping(xuid):
now = datetime.datetime.now(datetime.timezone.utc)
accounts = get_account_sample()
create_account(Account("id", "player", "token", "refresh", now, now, xuid=xuid), accounts)
restored = convert_account_data_to_object(accounts, "id")
assert restored.xuid == xuid
detail = AccountDetail(
display_name="player", id="id", username="player", minecraft_uuid="uuid",
minecraft_name="player", avatar="", account_type="msa", access_token="token",
refresh_token="refresh", access_token_expires_at=now, refresh_token_expires_at=now,
user_properties=[], xuid=restored.xuid,
)
manager = SimpleNamespace(get_current_account_id=lambda: "id", get_account=lambda _: detail,
settings_use_system_keyring=False)
launch = AccountManager.get_launch_account(manager)
maps = ArgumentMappings(auth_xuid=launch.xuid, natives_directory="natives", classpath="client.jar")
command = generate_launch_command(maps, "Main", "java", {"game": ["--xuid", "${auth_xuid}"]})
assert command[-1] == (xuid or "${auth_xuid}")
if xuid is None:
with pytest.raises(ArgumentValueError):
generate_launch_command(maps, "Main", "java", {"game": ["${auth_xuid}"]}, strict_placeholders=True)
def test_old_account_without_xuid_still_loads():
now = datetime.datetime.now(datetime.timezone.utc)
accounts = get_account_sample()
raw, _ = create_account(Account("id", "player", "token", "refresh", now, now), accounts)
raw.pop("xuid")
assert convert_account_data_to_object(accounts, "id").xuid is None
def test_refresh_retains_minecraft_token_audience_and_emits_xuid(monkeypatch):
monkeypatch.setattr(account_module, "refresh_microsoft_token", lambda *_: ("microsoft", "refresh", {}))
monkeypatch.setattr(account_module, "get_xbox_token_and_user_hash", lambda *_: ("xbox", "user-hash", {}))
monkeypatch.setattr(account_module, "get_xsts_token", lambda *_: ("minecraft-xsts", claims()))
monkeypatch.setattr(account_module, "get_xbox_xuid", lambda *_: XUID)
minecraft_login = Mock(return_value=("minecraft-token", {}))
monkeypatch.setattr(account_module, "get_minecraft_access_token", minecraft_login)
result, errors = [], []
worker = TokenRefreshWorker("id", "refresh", "client")
worker.succeeded.connect(lambda account_id, data: result.append(data))
worker.failed.connect(lambda *args: errors.append(args))
worker.run()
assert not errors
assert result[0]["xuid"] == XUID
minecraft_login.assert_called_once_with("user-hash", "minecraft-xsts")
def test_placeholder_replacement_defaults_to_tolerant_mode():
assert replace_placeholders("${missing}/${unset}", {"unset": None}) == "${missing}/${unset}"
with pytest.raises(ArgumentValueError):
replace_placeholders("${missing}", {}, strict=True)
+85
View File
@@ -0,0 +1,85 @@
import hashlib
import json
import pytest
from core_lib.game import asset
@pytest.fixture
def legacy_assets(tmp_path, monkeypatch, request):
kind = request.param
assets_dir = tmp_path / "assets"
content = b"legacy asset payload"
digest = hashlib.sha1(content).hexdigest()
source = assets_dir / "objects" / digest[:2] / digest
source.parent.mkdir(parents=True)
source.write_bytes(content)
destination = (
assets_dir / "virtual" / "fixture" / "sound.ogg"
if kind == "virtual" else tmp_path / "resources" / "sound.ogg"
)
index_data = {kind: True, "objects": {"sound.ogg": {"hash": digest, "size": len(content)}}}
index_bytes = json.dumps(index_data).encode("utf-8")
index = assets_dir / "indexes" / "fixture.json"
index.parent.mkdir(parents=True)
index.write_bytes(index_bytes)
manifest = {"assetIndex": {"id": "fixture", "sha1": hashlib.sha1(index_bytes).hexdigest()}}
monkeypatch.setattr(asset, "find_useful_part_in_specific_version_manifest",
lambda value: (None, value["assetIndex"], None, None, None, None, None))
def deny_network(*args, **kwargs):
pytest.fail("Local legacy asset repair must not access the network")
monkeypatch.setattr(asset.requests, "get", deny_network)
return manifest, assets_dir, tmp_path, source, destination, content
@pytest.mark.parametrize("legacy_assets", ["virtual", "map_to_resources"], indirect=True)
def test_complete_legacy_assets_pass_without_network(legacy_assets):
manifest, assets_dir, root, source, destination, content = legacy_assets
destination.parent.mkdir(parents=True)
destination.write_bytes(content)
assert asset.check_assets_exist(manifest, assets_dir, root)
assert asset.download_assets(manifest, assets_dir, root) == []
@pytest.mark.parametrize("legacy_assets", ["virtual", "map_to_resources"], indirect=True)
@pytest.mark.parametrize("damaged", [False, True])
def test_legacy_copy_repaired_from_objects_without_network(legacy_assets, damaged):
manifest, assets_dir, root, source, destination, content = legacy_assets
if damaged:
destination.parent.mkdir(parents=True)
# Same size, different content: the default check must verify SHA-1.
destination.write_bytes(b"x" * len(content))
assert not asset.check_assets_exist(manifest, assets_dir, root)
assert asset.download_assets(manifest, assets_dir, root) == []
assert destination.read_bytes() == content
assert asset.check_assets_exist(manifest, assets_dir, root)
@pytest.mark.parametrize("legacy_assets", ["virtual", "map_to_resources"], indirect=True)
def test_missing_object_is_still_reported(legacy_assets):
manifest, assets_dir, root, source, destination, content = legacy_assets
destination.parent.mkdir(parents=True)
destination.write_bytes(content)
source.unlink()
assert not asset.check_assets_exist(manifest, assets_dir, root)
@pytest.mark.parametrize("legacy_assets", ["virtual", "map_to_resources"], indirect=True)
def test_corrupt_cached_index_is_not_trusted(legacy_assets, monkeypatch):
manifest, assets_dir, root, source, destination, content = legacy_assets
index = assets_dir / "indexes" / "fixture.json"
original = json.loads(index.read_text(encoding="utf-8"))
index.write_text("{}", encoding="utf-8")
fetched = []
def fetch(version, path):
fetched.append(path)
return original
monkeypatch.setattr(asset, "fetch_and_save_asset_manifest", fetch)
assert asset.download_assets(manifest, assets_dir, root) == []
assert fetched == [index]
assert destination.read_bytes() == content
+153
View File
@@ -0,0 +1,153 @@
import hashlib
import json
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from core_lib.game import version_info
from core_lib.common.exception import VersionManifestSaveException
from manager.game import ManifestManager
from pages.test import TestPage as LauncherTestPage
@pytest.fixture
def cache(tmp_path):
app = SimpleNamespace(work_dir=tmp_path, widget_manager=MagicMock(), logger=MagicMock())
return ManifestManager(app)
def write_cache(cache, data, version=None):
path = cache.switch_between_specific_path(version)
path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(data).encode("utf-8")
path.write_bytes(payload)
return path, payload
def reply(cache, answer):
def respond(request):
request.result_queue.put(answer)
request.wait_event.set()
cache.widget_mgr.signal.askyesno.emit.side_effect = respond
@pytest.mark.parametrize("answer", [True, False])
def test_stale_root_requires_consent_and_only_one_final_notice(cache, monkeypatch, answer):
data = {"versions": []}
write_cache(cache, data)
fetch = MagicMock(side_effect=OSError("offline"))
monkeypatch.setattr("manager.game.fetch_and_save_version_manifest", fetch)
reply(cache, answer)
assert cache.get_cached_version_manifest(max_age=-1) == (data if answer else None)
assert fetch.call_count == 3
assert cache.use_expired_manifest is answer
cache.widget_mgr.signal.askyesno.emit.assert_called_once()
cache.widget_mgr.signal.show_error_message.emit.assert_not_called()
assert cache.widget_mgr.signal.show_warning_message.emit.call_count == int(answer)
if answer:
assert cache.get_cached_version_manifest(max_age=-1) == data
assert fetch.call_count == 3
assert not ManifestManager(cache.app).use_expired_manifest
def test_timeout_does_not_enable_flag(cache, monkeypatch):
write_cache(cache, {"versions": []})
monkeypatch.setattr(cache, "_cache_version_manifest", lambda *args, **kwargs: (False, None))
monkeypatch.setattr("manager.game.AskForRequest.wait", lambda *args: False)
assert cache.get_cached_version_manifest(max_age=-1) is None
assert not cache.use_expired_manifest
@pytest.mark.parametrize("payload", [None, b"{broken", b"[]", b"{}", b'{"versions":[{"id":"x"}]}'])
def test_unusable_root_never_asks_or_enables_flag(cache, monkeypatch, payload):
if payload is not None:
cache.version_manifest_path.parent.mkdir(parents=True)
cache.version_manifest_path.write_bytes(payload)
fetch = MagicMock(return_value=(False, None))
monkeypatch.setattr(cache, "_cache_version_manifest", fetch)
assert cache.get_cached_version_manifest(max_age=-1) is None
assert fetch.call_count == 3
assert not cache.use_expired_manifest
cache.widget_mgr.signal.askyesno.emit.assert_not_called()
cache.widget_mgr.signal.show_error_message.emit.assert_called_once()
@pytest.mark.parametrize("tampered", [False, True])
def test_specific_version_hash_is_checked_even_when_flag_enabled(cache, monkeypatch, tampered):
data = {"id": "fixture", "mainClass": "Main"}
path, payload = write_cache(cache, data, "fixture")
write_cache(cache, {"versions": [{"id": "fixture", "url": "https://example.invalid",
"sha1": hashlib.sha1(payload).hexdigest()}]})
if tampered:
path.write_text(json.dumps({**data, "mainClass": "Wrong"}), encoding="utf-8")
cache.use_expired_manifest = True
fetch = MagicMock(return_value=(False, None))
monkeypatch.setattr(cache, "_cache_version_manifest", fetch)
assert cache.get_cached_version_manifest("fixture", max_age=-1) == (None if tampered else data)
assert fetch.call_count == (3 if tampered else 0)
cache.widget_mgr.signal.askyesno.emit.assert_not_called()
def test_custom_manifest_shares_fallback_and_session_flag(cache):
data = {"id": "loader", "inheritsFrom": "vanilla"}
write_cache(cache, data, "loader")
fetch = MagicMock(side_effect=OSError("offline"))
reply(cache, True)
assert cache.get_cached_custom_version_manifest("loader", fetch, max_age=-1) == data
assert fetch.call_count == 3
assert cache.get_cached_custom_version_manifest("loader", fetch, max_age=-1) == data
assert fetch.call_count == 3
@pytest.mark.parametrize("payload,sha1", [(b"{broken", None), (b'{"id":"fixture"}', "0" * 40)])
def test_failed_save_preserves_original_and_cleans_temporary_files(tmp_path, payload, sha1):
path = tmp_path / "manifest.json"
path.write_bytes(b"previous content")
with pytest.raises(VersionManifestSaveException):
version_info.save_version_manifest(payload, path, sha1)
assert path.read_bytes() == b"previous content"
assert list(tmp_path.iterdir()) == [path]
def test_failed_download_verification_keeps_valid_specific_cache(cache, monkeypatch):
data = {"id": "fixture", "mainClass": "Main"}
path, payload = write_cache(cache, data, "fixture")
root = {"versions": [{"id": "fixture", "url": "https://example.invalid",
"sha1": hashlib.sha1(payload).hexdigest()}]}
write_cache(cache, root)
fetched = MagicMock(return_value=(b'{"id":"fixture","mainClass":"Wrong"}', hashlib.sha1(payload).hexdigest()))
monkeypatch.setattr(version_info, "fetch_specific_version_manifest", fetched)
reply(cache, True)
assert cache.get_cached_version_manifest("fixture", max_age=-1) == data
assert fetched.call_count == 3
assert path.read_bytes() == payload
assert not list(path.parent.glob("*.tmp"))
def test_structurally_invalid_refresh_does_not_replace_cache(tmp_path, monkeypatch):
path = tmp_path / "manifest.json"
path.write_bytes(b"previous content")
monkeypatch.setattr(version_info, "fetch_specific_version_manifest", lambda *args: (b"{}", None))
with pytest.raises(ValueError):
version_info.fetch_and_save_version_manifest(path, "fixture", {"versions": []})
assert path.read_bytes() == b"previous content"
def test_successful_save_preserves_downloaded_bytes(tmp_path):
payload = b'{ "id": "fixture", "mainClass": "Main" }'
path = tmp_path / "manifest.json"
assert version_info.save_version_manifest(payload, path, hashlib.sha1(payload).hexdigest())["id"] == "fixture"
assert path.read_bytes() == payload
assert list(tmp_path.iterdir()) == [path]
def test_test_page_fetch_runs_in_worker(monkeypatch):
page = SimpleNamespace(button=MagicMock(), output=MagicMock(), get_selected_version=lambda: "fixture",
_fetch_version_data=MagicMock())
worker = MagicMock()
monkeypatch.setattr("pages.test.threading.Thread", worker)
LauncherTestPage.run_test(page)
worker.assert_called_once_with(target=page._fetch_version_data, args=("fixture",), daemon=True)
worker.return_value.start.assert_called_once()
page._fetch_version_data.assert_not_called()
+85
View File
@@ -0,0 +1,85 @@
import zipfile
import pytest
from core_lib.game import argument, library_core
from core_lib.game.argument import ArgumentMappings, generate_launch_command
@pytest.fixture(autouse=True)
def windows_platform(monkeypatch):
for module in (argument, library_core):
monkeypatch.setattr(module, "get_natives_platform_info", lambda: ("windows", "windows", "x86_64"))
monkeypatch.setattr(module, "get_platform_info", lambda: ("windows", "amd64", "10.0.26100"))
@pytest.mark.parametrize("path_argument, subdirectory", [
(None, ""),
("-Djava.library.path=${natives_directory}", ""),
("-Djava.library.path=${natives_directory}/java", "java"),
({"value": ["-Djava.library.path=${natives_directory}/java"]}, "java"),
({"rules": [{"action": "allow", "os": {"name": "osx"}}],
"value": "-Djava.library.path=${natives_directory}/java"}, ""),
])
def test_download_check_and_command_share_native_directory(tmp_path, monkeypatch, path_argument, subdirectory):
libraries_dir = tmp_path / "libraries"
natives_root = tmp_path / "natives"
archive = libraries_dir / "native.jar"
libraries_dir.mkdir()
with zipfile.ZipFile(archive, "w") as jar:
jar.writestr("windows/example.dll", b"native fixture")
jar.writestr("META-INF/MANIFEST.MF", "excluded")
manifest = {
"assetIndex": {"id": "fixture"},
"downloads": {"client": {}},
"mainClass": "example.Main",
"arguments": {"jvm": [] if path_argument is None else [path_argument], "game": ["--demo"]},
"libraries": [{
"name": "example:native:1:natives-windows",
"downloads": {"artifact": {"path": "native.jar"}},
}],
}
# Downloads are stubbed; native selection, extraction and checking use real code.
monkeypatch.setattr(library_core, "collect_library_artifacts", lambda _: [])
monkeypatch.setattr(library_core, "download_libraries", lambda *args, **kwargs: ([], []))
assert not library_core.check_natives_exists(manifest, libraries_dir, natives_root)
library_core.download_full_libraries(manifest, libraries_dir, natives_root)
extract_dir = natives_root / subdirectory
native_file = extract_dir / "example.dll"
assert native_file.read_bytes() == b"native fixture"
assert not (extract_dir / "META-INF").exists()
assert not (natives_root / "java" / "java").exists()
assert library_core.check_full_libraries_exists(manifest, libraries_dir, natives_root)
command = generate_launch_command(
ArgumentMappings(natives_directory=natives_root.as_posix(), classpath="client.jar"),
"example.Main", "java", manifest["arguments"],
)
assert f"-Djava.library.path={extract_dir.as_posix()}" in command
assert command[-2:] == ["example.Main", "--demo"]
native_file.unlink()
assert not library_core.check_natives_exists(manifest, libraries_dir, natives_root)
def test_feature_rules_and_last_applicable_property(tmp_path):
manifest = {"arguments": {"jvm": [
"-Djava.library.path=${natives_directory}",
{"rules": [{"action": "allow", "features": {"new_layout": True}}],
"value": "-Djava.library.path=${natives_directory}/java"},
]}}
locate = library_core.locate_natives_extract_dir_by_manifest
assert locate(manifest, tmp_path) == tmp_path
assert locate(manifest, tmp_path, features={"new_layout": True}) == tmp_path / "java"
assert locate({"minecraftArguments": "--demo"}, tmp_path) == tmp_path
@pytest.mark.parametrize("suffix", ["/../outside", "//absolute", "/C:/outside", "/java;other", "other"])
def test_unsupported_native_layout_is_rejected(tmp_path, suffix):
with pytest.raises(ValueError):
library_core.locate_natives_extract_dir(
["-Djava.library.path=${natives_directory}" + suffix], tmp_path,
)
+3 -3
View File
@@ -164,8 +164,8 @@ def test_account_client_id_is_a_valid_uuid() -> None:
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
updated = manager.set("account", {"custom_client_id": custom_id})
assert str(updated.custom_client_id) == custom_id
with pytest.raises(ValidationError):
manager.set("account", {"client_id": "not-a-client-id"})
manager.set("account", {"custom_client_id": "not-a-client-id"})
+181
View File
@@ -0,0 +1,181 @@
import logging
from pathlib import Path
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QTimer, QEvent, QPointF
from PySide6.QtGui import QPalette, QEnterEvent
from PySide6.QtWidgets import QApplication, QWidget, QDialog, QMessageBox, QPushButton
from app import Launcher
from core_lib.qt import messagebox
from pages.launch_profile import ProfileListItem
from pages.manage_profile import ManageProfileItem
class StylesheetApp:
locate_styles_path = Launcher.locate_styles_path
apply_qss = Launcher.apply_qss
apply_theme = Launcher.apply_theme
_read_theme_manifest = staticmethod(Launcher._read_theme_manifest)
_read_palette = staticmethod(Launcher._read_palette)
_palette_from_colors = staticmethod(Launcher._palette_from_colors)
def __init__(self, root, qt_app):
self.qt_app = qt_app
self.styles_path = root / "styles"
self.styles_path.mkdir()
self.theme_dir = root / "custom"
(self.theme_dir / "styles").mkdir(parents=True)
self.settings_manager = SimpleNamespace(
get=lambda *_: SimpleNamespace(theme="custom")
)
self._system_palette = QPalette(qt_app.palette())
self.logger = logging.getLogger(__name__)
self.setPalette = qt_app.setPalette
self.setStyleSheet = qt_app.setStyleSheet
self.allWidgets = qt_app.allWidgets
def _theme_packages(self):
return {"custom": self.theme_dir}
@pytest.fixture
def style_app(tmp_path):
qt_app = QApplication.instance() or QApplication([])
palette = QPalette(qt_app.palette())
stylesheet = qt_app.styleSheet()
yield StylesheetApp(tmp_path, qt_app)
qt_app.setStyleSheet(stylesheet)
qt_app.setPalette(palette)
def test_theme_stylesheet_override_and_default_fallback(style_app):
default = style_app.styles_path / "main.qss"
default.write_text("QWidget { color: red; }", encoding="utf-8")
override = style_app.theme_dir / "styles" / "main.qss"
assert style_app.locate_styles_path(Path("main.qss")) == default
override.mkdir() # A directory is not a usable stylesheet.
assert style_app.locate_styles_path(Path("main.qss")) == default
override.rmdir()
override.write_text("QWidget { color: blue; }", encoding="utf-8")
assert style_app.locate_styles_path(Path("main.qss")) == override
def test_switching_theme_reloads_stylesheets(style_app):
default_qss = "/* 預設樣式 */ QWidget { color: red; }"
default = style_app.styles_path / "main.qss"
default.write_text(default_qss, encoding="utf-8")
override = style_app.theme_dir / "styles" / "main.qss"
override.write_text("QWidget { color: blue; }", encoding="utf-8")
widget = QWidget()
style_app.apply_qss(Path("main.qss"), widget.setStyleSheet)
assert widget.styleSheet() == override.read_text(encoding="utf-8")
style_app.apply_theme("system")
assert widget.styleSheet() == default_qss
assert style_app.locate_styles_path(Path("main.qss")) == default
widget.close()
def test_invalid_theme_falls_back_to_default_styles(style_app):
default = style_app.styles_path / "main.qss"
default.write_text("QWidget { color: red; }", encoding="utf-8")
style_app.apply_theme("custom") # Missing palette and manifest.
assert style_app._active_theme == "system"
assert style_app.locate_styles_path(Path("main.qss")) == default
@pytest.mark.parametrize("theme, background", [("aqua", "#f1f3f7"), ("windows-9x", "#c0c0c0"), ("bliss", "#ece9d8")])
def test_message_boxes_follow_application_theme(style_app, theme, background):
style_app.theme_dir = Path(__file__).resolve().parents[1] / "resources/themes" / theme
style_app.apply_theme("custom")
parent = QWidget()
boxes = [messagebox.create_messagebox(owner, "Theme", "Message")
for owner in (None, parent)]
for box in boxes:
box.ensurePolished()
assert box.testOption(QMessageBox.Option.DontUseNativeDialog)
assert box.palette().color(QPalette.ColorRole.Window).name() == background
button = box.button(QMessageBox.StandardButton.Ok)
button.ensurePolished()
assert (button.palette().brush(QPalette.ColorRole.Button).gradient() is not None) == (theme in {"aqua", "bliss"})
(style_app.styles_path / "main.qss").write_text("", encoding="utf-8")
style_app.apply_theme("system")
assert style_app.qt_app.styleSheet() == ""
for box in boxes:
box.close()
def test_static_question_inherits_aqua(style_app):
style_app.theme_dir = Path(__file__).resolve().parents[1] / "resources/themes/aqua"
style_app.apply_theme("custom")
colors = []
def accept_question():
box = style_app.qt_app.activeModalWidget()
colors.append(box.palette().color(QPalette.ColorRole.Window).name())
box.button(QMessageBox.StandardButton.Yes).click()
QTimer.singleShot(0, accept_question)
result = QMessageBox.question(None, "Confirm", "Continue?")
assert result == QMessageBox.StandardButton.Yes
assert colors == ["#f1f3f7"]
@pytest.mark.parametrize("question", [False, True])
def test_detailed_dialogs_inherit_aqua(style_app, monkeypatch, question):
style_app.theme_dir = Path(__file__).resolve().parents[1] / "resources/themes/aqua"
style_app.apply_theme("custom")
checked = []
def inspect_dialog(dialog):
dialog.ensurePolished()
buttons = dialog.findChildren(QPushButton)
assert buttons
for button in buttons:
button.ensurePolished()
assert button.palette().brush(QPalette.ColorRole.Button).gradient() is not None
checked.append(True)
return QDialog.DialogCode.Accepted
monkeypatch.setattr(QDialog, "exec", inspect_dialog)
if question:
assert messagebox.ask_yes_no_with_plain_text(None, "Confirm", "Message", "Details")
else:
messagebox.error_with_plain_text(None, "Error", "Message", "Details")
assert checked == [True]
@pytest.mark.parametrize("theme, normal_color", [("aqua", "#626d7e"), ("windows-9x", "#404040"), ("bliss", "#555d69")])
@pytest.mark.parametrize("managed", [False, True])
def test_profile_label_colors_follow_button_state(style_app, theme, normal_color, managed):
root = Path(__file__).resolve().parents[1]
style_app.theme_dir = root / "resources/themes" / theme
style_app.apply_theme("custom")
style_app.icon_dir = root / "resources/icons"
profile = SimpleNamespace(icon=str(style_app.icon_dir / "profile_default.png"),
display_name="Example", version_id="1.21")
container = QWidget()
filename = "manage_profile.qss" if managed else "profile.qss"
style_app.apply_qss(Path(filename), container.setStyleSheet)
row = (ManageProfileItem(style_app, profile, container) if managed
else ProfileListItem(profile, container))
label = row.findChild(QWidget, "itemVersion")
label.ensurePolished()
def color():
return label.palette().color(QPalette.ColorRole.WindowText).name()
assert color() == normal_color
if managed:
row.setChecked(True)
else:
point = QPointF(4, 4)
QApplication.sendEvent(row, QEnterEvent(point, point, point))
assert color() == "#ffffff"
if managed:
row.setChecked(False)
else:
QApplication.sendEvent(row, QEvent(QEvent.Type.Leave))
assert color() == normal_color
container.close()