summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorR David Murray <rdmurray@bitdance.com>2014-04-13 22:07:39 -0400
committerR David Murray <rdmurray@bitdance.com>2014-04-13 22:07:39 -0400
commitd5aa487cceac54fdf2b5c073157b899b3c8c9c94 (patch)
treee9532a4bb5bd51eeefd53dc818b8b448cd411a44
parente544f9a27eec202d4a959dd2a255d8ce05aee663 (diff)
downloadcpython-git-d5aa487cceac54fdf2b5c073157b899b3c8c9c94.tar.gz
#21169: fix getpass to use replace error handler on UnicodeEncodeError.
If the input stream encoding couldn't encode one or more of the non-ascii characters in the prompt, it would fail, throwing a UnicodeEncodeError. Now if that happens we re-encoding using the 'replace' error handler. Patch by Kushal Das.
-rw-r--r--Lib/getpass.py7
-rw-r--r--Lib/test/test_getpass.py10
-rw-r--r--Misc/NEWS4
3 files changed, 19 insertions, 2 deletions
diff --git a/Lib/getpass.py b/Lib/getpass.py
index 53c38b8897..2740363488 100644
--- a/Lib/getpass.py
+++ b/Lib/getpass.py
@@ -135,7 +135,12 @@ def _raw_input(prompt="", stream=None, input=None):
input = sys.stdin
prompt = str(prompt)
if prompt:
- stream.write(prompt)
+ try:
+ stream.write(prompt)
+ except UnicodeEncodeError:
+ prompt = prompt.encode(stream.encoding, 'replace')
+ prompt = prompt.decode(stream.encoding)
+ stream.write(prompt)
stream.flush()
# NOTE: The Python C API calls flockfile() (and unlock) during readline.
line = input.readline()
diff --git a/Lib/test/test_getpass.py b/Lib/test/test_getpass.py
index 1731bd44a6..3452e46213 100644
--- a/Lib/test/test_getpass.py
+++ b/Lib/test/test_getpass.py
@@ -1,7 +1,7 @@
import getpass
import os
import unittest
-from io import BytesIO, StringIO
+from io import BytesIO, StringIO, TextIOWrapper
from unittest import mock
from test import support
@@ -69,6 +69,14 @@ class GetpassRawinputTest(unittest.TestCase):
getpass._raw_input(stream=StringIO())
mock_input.readline.assert_called_once_with()
+ @mock.patch('sys.stdin')
+ def test_uses_stdin_as_different_locale(self, mock_input):
+ stream = TextIOWrapper(BytesIO(), encoding="ascii")
+ mock_input.readline.return_value = "Hasło: "
+ getpass._raw_input(prompt="Hasło: ",stream=stream)
+ mock_input.readline.assert_called_once_with()
+
+
def test_raises_on_empty_input(self):
input = StringIO('')
self.assertRaises(EOFError, getpass._raw_input, input=input)
diff --git a/Misc/NEWS b/Misc/NEWS
index cb20934634..74c5e50cdd 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -27,6 +27,10 @@ Core and Builtins
Library
-------
+- Issue #21169: getpass now handles non-ascii characters that the
+ input stream encoding cannot encode by re-encoding using the
+ replace error handler.
+
- Issue #21171: Fixed undocumented filter API of the rot13 codec.
Patch by Berker Peksag.