From ef14f4674476322bc904549d7cd89a85036088da Mon Sep 17 00:00:00 2001 From: Laurent Monin Date: Fri, 24 May 2024 13:06:57 +0200 Subject: [PATCH] IgnoreUpdatesContext: add on_first_enter and matching tests --- picard/util/__init__.py | 5 ++++- test/test_utils.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/picard/util/__init__.py b/picard/util/__init__.py index fc5b75906..d88f34be5 100644 --- a/picard/util/__init__.py +++ b/picard/util/__init__.py @@ -561,15 +561,18 @@ class IgnoreUpdatesContext: updates if it is `False`. """ - def __init__(self, on_exit=None, on_enter=None): + def __init__(self, on_exit=None, on_enter=None, on_first_enter=None): self._entered = 0 self._on_exit = on_exit self._on_enter = on_enter + self._on_first_enter = on_first_enter def __enter__(self): self._entered += 1 if self._on_enter: self._on_enter() + if self._entered == 1 and self._on_first_enter: + self._on_first_enter() def __exit__(self, type, value, tb): self._entered -= 1 diff --git a/test/test_utils.py b/test/test_utils.py index 2504cd3bb..1cbca07a2 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -954,6 +954,21 @@ class IgnoreUpdatesContextTest(PicardTestCase): with context: self.assertEqual(len(on_enter.mock_calls), 2) + def test_run_on_first_enter(self): + on_first_enter = Mock() + context = IgnoreUpdatesContext(on_first_enter=on_first_enter) + with context: + on_first_enter.assert_called() + on_first_enter.assert_called_once_with() + + def test_run_on_first_enter_nested(self): + on_first_enter = Mock() + context = IgnoreUpdatesContext(on_first_enter=on_first_enter) + with context: + on_first_enter.assert_called_once_with() + with context: + on_first_enter.assert_called_once_with() + def test_nested_with(self): context = IgnoreUpdatesContext() with context: