fix(update): harden reentry state and add runtime regression test
This commit is contained in:
31
main.py
31
main.py
@@ -464,6 +464,7 @@ class VkChatManager(QMainWindow):
|
||||
|
||||
def check_for_updates(self, silent_no_updates=False):
|
||||
if self._update_in_progress:
|
||||
self.status_label.setText("Статус: проверка обновлений уже выполняется...")
|
||||
return
|
||||
|
||||
self._update_check_silent = silent_no_updates
|
||||
@@ -492,8 +493,6 @@ class VkChatManager(QMainWindow):
|
||||
self.update_thread.start()
|
||||
|
||||
def _on_update_check_finished(self, result):
|
||||
self._set_update_action_state(False)
|
||||
|
||||
if result.get("has_update"):
|
||||
latest_version = result.get("latest_version") or result.get("latest_tag") or "unknown"
|
||||
self.status_label.setText(f"Статус: доступно обновление {latest_version}")
|
||||
@@ -552,7 +551,6 @@ class VkChatManager(QMainWindow):
|
||||
QMessageBox.information(self, "Обновления", f"Установлена актуальная версия в канале {channel_label}.")
|
||||
|
||||
def _on_update_check_failed(self, error_text):
|
||||
self._set_update_action_state(False)
|
||||
self._log_event("update_check_failed", error_text, level="WARN")
|
||||
if not self.update_repository_url:
|
||||
self.status_label.setText("Статус: обновления не настроены (URL репозитория не задан).")
|
||||
@@ -570,6 +568,7 @@ class VkChatManager(QMainWindow):
|
||||
QMessageBox.warning(self, "Проверка обновлений", error_text)
|
||||
|
||||
def _on_update_thread_finished(self):
|
||||
self._set_update_action_state(False)
|
||||
self._update_in_progress = False
|
||||
self.update_checker = None
|
||||
self.update_thread = None
|
||||
@@ -768,8 +767,8 @@ class VkChatManager(QMainWindow):
|
||||
timestamp = QDateTime.currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
|
||||
with open(LOG_FILE, "a", encoding="utf-8") as f:
|
||||
f.write(f"[{timestamp}] [{level}] {context}: {message}\n")
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
sys.stderr.write(f"[WARN] log_write_failed: {exc}\n")
|
||||
|
||||
def _log_error(self, context, exc):
|
||||
self._log("ERROR", context, self._format_vk_error(exc))
|
||||
@@ -786,8 +785,8 @@ class VkChatManager(QMainWindow):
|
||||
if os.path.exists(LOG_BACKUP_FILE):
|
||||
os.remove(LOG_BACKUP_FILE)
|
||||
os.replace(LOG_FILE, LOG_BACKUP_FILE)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
sys.stderr.write(f"[WARN] log_rotate_failed: {exc}\n")
|
||||
|
||||
def _format_vk_error(self, exc):
|
||||
error = getattr(exc, "error", None)
|
||||
@@ -899,8 +898,8 @@ class VkChatManager(QMainWindow):
|
||||
try:
|
||||
if output_path and os.path.exists(output_path):
|
||||
os.remove(output_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
self._log_event("auth_result_cleanup", f"Не удалось удалить файл результата авторизации: {exc}", level="WARN")
|
||||
|
||||
def _on_auth_process_finished(self, exit_code, _exit_status):
|
||||
output_path = self.auth_output_path
|
||||
@@ -937,8 +936,8 @@ class VkChatManager(QMainWindow):
|
||||
try:
|
||||
if os.path.exists(output_path):
|
||||
os.remove(output_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
self._log_event("auth_result_cleanup", f"Не удалось удалить файл результата авторизации: {exc}", level="WARN")
|
||||
else:
|
||||
self._log_event("auth_result", "Файл результата авторизации не найден.", level="WARN")
|
||||
|
||||
@@ -970,8 +969,8 @@ class VkChatManager(QMainWindow):
|
||||
try:
|
||||
if os.path.exists(output_path):
|
||||
os.remove(output_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
self._log_event("auth_result_cleanup", f"Не удалось удалить старый файл результата авторизации: {exc}", level="WARN")
|
||||
|
||||
program, args = self._build_auth_command(auth_url, output_path)
|
||||
self.auth_output_path = output_path
|
||||
@@ -1124,7 +1123,8 @@ class VkChatManager(QMainWindow):
|
||||
try:
|
||||
user = self.vk.users.get(user_ids=user_id)[0]
|
||||
return f"{user.get('first_name', '')} {user.get('last_name', '')}"
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
self._log_event("get_user_info", f"Не удалось получить имя пользователя {user_id}: {exc}", level="WARN")
|
||||
return f"Пользователь {user_id}"
|
||||
|
||||
def _get_selected_chats(self):
|
||||
@@ -1408,7 +1408,8 @@ if __name__ == "__main__":
|
||||
idx = sys.argv.index("--auth")
|
||||
auth_url = sys.argv[idx + 1]
|
||||
output_path = sys.argv[idx + 2]
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
sys.stderr.write(f"[ERROR] auth_cli_args_invalid: {exc}\n")
|
||||
sys.exit(1)
|
||||
auth_webview.main_auth(auth_url, output_path)
|
||||
sys.exit(0)
|
||||
|
||||
97
tests/test_update_reentry_runtime.py
Normal file
97
tests/test_update_reentry_runtime.py
Normal file
@@ -0,0 +1,97 @@
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
|
||||
class _DummySignal:
|
||||
def __init__(self):
|
||||
self._callbacks = []
|
||||
|
||||
def connect(self, callback):
|
||||
if callback is not None:
|
||||
self._callbacks.append(callback)
|
||||
|
||||
def emit(self, *args, **kwargs):
|
||||
for callback in list(self._callbacks):
|
||||
callback(*args, **kwargs)
|
||||
|
||||
|
||||
class _DummyThread:
|
||||
created = 0
|
||||
|
||||
def __init__(self, _parent=None):
|
||||
type(self).created += 1
|
||||
self.started = _DummySignal()
|
||||
self.finished = _DummySignal()
|
||||
|
||||
def start(self):
|
||||
self.started.emit()
|
||||
|
||||
def quit(self):
|
||||
self.finished.emit()
|
||||
|
||||
def deleteLater(self):
|
||||
return None
|
||||
|
||||
|
||||
class _DummyChecker:
|
||||
created = 0
|
||||
|
||||
def __init__(self, *_args, **_kwargs):
|
||||
type(self).created += 1
|
||||
self.check_finished = _DummySignal()
|
||||
self.check_failed = _DummySignal()
|
||||
|
||||
def moveToThread(self, _thread):
|
||||
return None
|
||||
|
||||
def run(self):
|
||||
return None
|
||||
|
||||
def deleteLater(self):
|
||||
return None
|
||||
|
||||
|
||||
class UpdateReentryRuntimeTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
try:
|
||||
import main # noqa: PLC0415
|
||||
except Exception as exc:
|
||||
raise unittest.SkipTest(f"main import unavailable: {exc}") from exc
|
||||
cls.main = main
|
||||
|
||||
def test_repeated_update_check_is_ignored_until_thread_finishes(self):
|
||||
_DummyChecker.created = 0
|
||||
_DummyThread.created = 0
|
||||
manager = self.main.VkChatManager.__new__(self.main.VkChatManager)
|
||||
manager._update_in_progress = False
|
||||
manager._update_check_silent = False
|
||||
manager.update_channel = "stable"
|
||||
manager.update_repository_url = "https://example.com/org/repo"
|
||||
manager.update_checker = None
|
||||
manager.update_thread = None
|
||||
manager.status_label = SimpleNamespace(setText=lambda *_args, **_kwargs: None)
|
||||
manager._log_event = lambda *_args, **_kwargs: None
|
||||
manager._set_update_action_state = lambda *_args, **_kwargs: None
|
||||
|
||||
with mock.patch.object(self.main, "UpdateChecker", _DummyChecker), mock.patch.object(self.main, "QThread", _DummyThread):
|
||||
self.main.VkChatManager.check_for_updates(manager, silent_no_updates=True)
|
||||
self.assertTrue(manager._update_in_progress)
|
||||
self.assertEqual(_DummyChecker.created, 1)
|
||||
self.assertEqual(_DummyThread.created, 1)
|
||||
first_thread = manager.update_thread
|
||||
|
||||
self.main.VkChatManager.check_for_updates(manager, silent_no_updates=True)
|
||||
self.assertEqual(_DummyChecker.created, 1)
|
||||
self.assertEqual(_DummyThread.created, 1)
|
||||
self.assertIs(manager.update_thread, first_thread)
|
||||
|
||||
manager.update_checker.check_finished.emit({"has_update": False, "current_version": self.main.APP_VERSION})
|
||||
self.assertFalse(manager._update_in_progress)
|
||||
self.assertIsNone(manager.update_checker)
|
||||
self.assertIsNone(manager.update_thread)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user