From 138e9a25e322df0b4d9a0fc8bd5660df543ee784 Mon Sep 17 00:00:00 2001 From: Sorin Sbarnea Date: Wed, 18 Jul 2018 10:40:35 +0100 Subject: [PATCH] Avoid UnicodeEncodeError on python 2 Python2 has default encoding as ascii which means that is likely that some print() commands would fails with UnicodeEncodeError. This hack changes default encoding in order to avoid such errors. Change-Id: I4e21e6e32d4bb815693b7d6ce35efb6a5cca2fc2 --- git_review/cmd.py | 11 +++++++++++ git_review/tests/test_unit.py | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/git_review/cmd.py b/git_review/cmd.py index b94e8110..4311b330 100644 --- a/git_review/cmd.py +++ b/git_review/cmd.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import print_function COPYRIGHT = """\ @@ -1700,6 +1701,16 @@ def _main(): def main(): + # workaround for avoiding UnicodeEncodeError on print() with older python + if sys.version_info[0] < 3: + # without reload print would fail even if sys.stdin.encoding + # would report utf-8 + # see: https://stackoverflow.com/a/23847316/99834 + stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr + reload(sys) + sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr + sys.setdefaultencoding(os.environ.get('PYTHONIOENCODING', 'utf-8')) + try: _main() except GitReviewException as e: diff --git a/git_review/tests/test_unit.py b/git_review/tests/test_unit.py index 8104b527..6b6c7e41 100644 --- a/git_review/tests/test_unit.py +++ b/git_review/tests/test_unit.py @@ -104,6 +104,17 @@ class GitReviewConsole(testtools.TestCase, fixtures.TestWithFixtures): self.run_cmd_patcher.stop() super(GitReviewConsole, self).tearDown() + @mock.patch('git_review.cmd.get_version', + side_effect=cmd.GitReviewException(u"simple-toπ㌀c")) + def test_print_exception_with_unicode(self, exists_mock): + + try: + with mock.patch('sys.argv', ['git-review', '--version']): + with self.assertRaisesRegexp(SystemExit, '1'): + cmd.main() + except Exception as e: + self.fail('Exception not expected: %s' % e) + @mock.patch('git_review.cmd.query_reviews') @mock.patch('git_review.cmd.get_remote_url', mock.MagicMock) @mock.patch('git_review.cmd._has_color', False)