From 6fa01e14a0295914eb7dc931eebbdaceb185d272 Mon Sep 17 00:00:00 2001 From: Tiago Nobrega Date: Fri, 8 Nov 2024 16:17:03 -0300 Subject: [PATCH] fix: only greet once when setting the same mode (#301) With this fix, ``Emitter.set_mode(mode)`` becomes a no-op if the emitter is already at that ``mode``. This scenario can happen, for example, if the Emitter is initialized with a mode and then the Dispatcher sets the same mode during command-line handling. --- craft_cli/messages.py | 3 +++ docs/changelog.rst | 6 ++++++ tests/unit/test_messages_emitter.py | 27 +++++++++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/craft_cli/messages.py b/craft_cli/messages.py index bff596e..7a6d1b5 100644 --- a/craft_cli/messages.py +++ b/craft_cli/messages.py @@ -510,6 +510,9 @@ def get_mode(self) -> EmitterMode: @_active_guard() def set_mode(self, mode: EmitterMode) -> None: """Set the mode of the emitter.""" + if mode == self._mode: + return + self._mode = mode self._log_handler.mode = mode diff --git a/docs/changelog.rst b/docs/changelog.rst index 98de553..b1b99dc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -7,6 +7,12 @@ Changelog See the `Releases page`_ on GitHub for a complete list of commits that are included in each version. +2.10.1 (2024-Nov-11) +-------------------- + +- Fix an issue where setting an ``Emitter`` to the same mode multiple times + resulted in multiple greetings. + 2.10.0 (2024-Oct-31) -------------------- - Support adding a link to documentation in help messages. diff --git a/tests/unit/test_messages_emitter.py b/tests/unit/test_messages_emitter.py index e436062..b831e2d 100644 --- a/tests/unit/test_messages_emitter.py +++ b/tests/unit/test_messages_emitter.py @@ -18,6 +18,7 @@ import logging import sys +from unittest import mock from unittest.mock import call, patch import pytest @@ -298,6 +299,32 @@ def test_set_mode_developer_modes(get_initiated_emitter, mode): assert handler.mode == mode +@pytest.mark.parametrize( + "mode", + [ + EmitterMode.VERBOSE, + EmitterMode.DEBUG, + EmitterMode.TRACE, + ], +) +def test_set_mode_repeated(get_initiated_emitter, mode): + """Repeatedly setting the same mode should not emit multiple greetings.""" + greeting = "greeting" + emitter = get_initiated_emitter(EmitterMode.QUIET, greeting=greeting) + + emitter.set_mode(mode) + emitter.set_mode(mode) + + log_locat = f"Logging execution to {emitter._log_filepath!r}" + extra_print_args = {"use_timestamp": mock.ANY, "avoid_logging": True, "end_line": True} + + # Only a single printing of the greeting and the logpath + assert emitter.printer_calls == [ + call().show(sys.stderr, greeting, **extra_print_args), + call().show(sys.stderr, log_locat, **extra_print_args), + ] + + # -- tests for emitting messages of all kind