from __future__ import annotations import logging from pathlib import Path import pytest from PySide6.QtCore import Qt from PySide6.QtGui import QUndoCommand from PySide6.QtWidgets import QApplication from bedit_gui.controllers.document_controller import DocumentController from bedit_gui.controllers.log_controller import LogController from bedit_gui.controllers.undo_controller import UndoController from bedit_gui.documents import Document from bedit_gui.services.application_logging import get_logger, set_log_level from bedit_gui.views.dialogs.document_dialogs import SaveChangesChoice from bedit_gui.views.main_window import MainWindow class FakeDialogs: def __init__(self, path: Path) -> None: self.path = path def choose_open_path(self, _current_path: Path | None) -> Path: return self.path def choose_save_path(self, _current_path: Path | None) -> Path: return self.path def ask_save_changes(self) -> SaveChangesChoice: return SaveChangesChoice.DISCARD def show_file_error(self, _title: str, error: Exception) -> None: raise AssertionError("unexpected file error") from error @pytest.fixture(scope="module") def qt_app() -> QApplication: return QApplication.instance() or QApplication([]) @pytest.mark.unit def test_log_level_and_qt_log_model(qt_app: QApplication) -> None: window = MainWindow() controller = LogController(window, logging.WARNING) logger = get_logger("tests") logger.info("hidden message") logger.warning("visible message") qt_app.processEvents() assert controller.model.rowCount() == 1 assert "WARNING visible message" in controller.model.data( controller.model.index(0), Qt.ItemDataRole.DisplayRole, ) set_log_level(logging.INFO) logger.info("now visible") qt_app.processEvents() assert controller.model.rowCount() == 2 @pytest.mark.unit def test_document_and_undo_actions_are_logged( qt_app: QApplication, tmp_path: Path, ) -> None: path = tmp_path / "document.json" window = MainWindow() log_controller = LogController(window) document = Document(qt_app) dialogs = FakeDialogs(path) document_controller = DocumentController(document, window, dialogs) undo_controller = UndoController(document, window) document_controller.new_document() document_controller.save_document_as() document_controller.save_document() document_controller.open_document() document.undo_stack.push(QUndoCommand("test change")) undo_controller.undo() undo_controller.redo() qt_app.processEvents() messages = [ log_controller.model.data(log_controller.model.index(row)) for row in range(log_controller.model.rowCount()) ] assert any("Created new document" in message for message in messages) assert any("Opened document:" in message for message in messages) assert any("Saved document:" in message for message in messages) assert any("Saved document as:" in message for message in messages) assert any("Undo: test change" in message for message in messages) assert any("Redo: test change" in message for message in messages)