summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorJacob Walls <jacobtylerwalls@gmail.com>2023-11-27 18:05:55 (GMT)
committerGitHub <noreply@github.com>2023-11-27 18:05:55 (GMT)
commit99a73c3465a45fe57cac01a917fc50e0743b5964 (patch)
treebe3c8979398f0e81a6e9d5bccb7b3d715f1cb418 /Lib
parent936c503a442ee062c837e334f237796554c792ff (diff)
downloadcpython-99a73c3465a45fe57cac01a917fc50e0743b5964.zip
cpython-99a73c3465a45fe57cac01a917fc50e0743b5964.tar.gz
cpython-99a73c3465a45fe57cac01a917fc50e0743b5964.tar.bz2
gh-76912: Raise OSError from any failure in getpass.getuser() (#29739)
* bpo-32731: Raise OSError from any failure in getpass.getuser() Previously, if the username was not set in certain environment variables, ImportError escaped on Windows systems, and it was possible for KeyError to escape on other systems if getpwuid() failed.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/getpass.py13
-rw-r--r--Lib/test/test_getpass.py4
2 files changed, 12 insertions, 5 deletions
diff --git a/Lib/getpass.py b/Lib/getpass.py
index 8b42c0a..bd0097c 100644
--- a/Lib/getpass.py
+++ b/Lib/getpass.py
@@ -156,7 +156,11 @@ def getuser():
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
+ Any failure to find a username raises OSError.
+ .. versionchanged:: 3.13
+ Previously, various exceptions beyond just :exc:`OSError`
+ were raised.
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
@@ -164,9 +168,12 @@ def getuser():
if user:
return user
- # If this fails, the exception will "explain" why
- import pwd
- return pwd.getpwuid(os.getuid())[0]
+ try:
+ import pwd
+ return pwd.getpwuid(os.getuid())[0]
+ except (ImportError, KeyError) as e:
+ raise OSError('No username set in the environment') from e
+
# Bind the name getpass to the appropriate function
try:
diff --git a/Lib/test/test_getpass.py b/Lib/test/test_getpass.py
index 98ecec9..80dda2c 100644
--- a/Lib/test/test_getpass.py
+++ b/Lib/test/test_getpass.py
@@ -26,7 +26,7 @@ class GetpassGetuserTest(unittest.TestCase):
environ.get.return_value = None
try:
getpass.getuser()
- except ImportError: # in case there's no pwd module
+ except OSError: # in case there's no pwd module
pass
except KeyError:
# current user has no pwd entry
@@ -47,7 +47,7 @@ class GetpassGetuserTest(unittest.TestCase):
getpass.getuser())
getpw.assert_called_once_with(42)
else:
- self.assertRaises(ImportError, getpass.getuser)
+ self.assertRaises(OSError, getpass.getuser)
class GetpassRawinputTest(unittest.TestCase):