From dd8263a6e82dfcbc4bd5891402418f52396a2745 Mon Sep 17 00:00:00 2001 From: Vassilii Khachaturov Date: Thu, 12 Sep 2013 17:51:31 +0000 Subject: [PATCH] 7061: Wrap User...._progress in a context manager ensure end_progress is called when exception is raised svn: r23092 --- gramps/cli/test/user_test.py | 16 ++++++++++++---- gramps/gen/user.py | 8 ++++++-- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/gramps/cli/test/user_test.py b/gramps/cli/test/user_test.py index 050c5335c..6157c176e 100644 --- a/gramps/cli/test/user_test.py +++ b/gramps/cli/test/user_test.py @@ -32,9 +32,9 @@ import sys try: if sys.version_info < (3,3): - from mock import Mock, NonCallableMock + from mock import Mock, patch else: - from unittest.mock import Mock, NonCallableMock + from unittest.mock import Mock, patch MOCKING = True @@ -159,6 +159,8 @@ class TestUser_progress(unittest.TestCase): def setUp(self): self.user = user.User() self.user._fileout = Mock(spec=sys.stderr) + + def test_can_step_using_with(self): # Collect baseline output from the old-style interface (begin/step/end) self._progress_begin_step_end() self.expected_output = list(self.user._fileout.method_calls) @@ -167,16 +169,22 @@ class TestUser_progress(unittest.TestCase): len(self.user._fileout.method_calls) == 0, list(self.user._fileout.method_calls)) - def test(self): with self.user.progress("Foo", "Bar", 0) as step: for i in range(10): step() - def tearDown(self): # Output using `with' differs from one with `progress_...' self.assertEqual(self.expected_output, list(self.user._fileout.method_calls)) + def test_ends_progress_upon_exception_in_with(self): + with patch('gramps.cli.user.User.end_progress') as MockEP: + try: + with self.user.progress("Foo", "Bar", 0) as step: + raise Exception() + except Exception: + pass + self.assertTrue(MockEP.called) if __name__ == "__main__": unittest.main() diff --git a/gramps/gen/user.py b/gramps/gen/user.py index 1007c210c..75e7b1fd8 100644 --- a/gramps/gen/user.py +++ b/gramps/gen/user.py @@ -89,8 +89,12 @@ class User(): @contextmanager def progress(self, *args, **kwargs): self.begin_progress(*args, **kwargs) - yield self.step_progress - self.end_progress() + try: + yield self.step_progress + except: + raise + finally: + self.end_progress() def prompt(self, title, message, accept_label, reject_label): """