Skip to content

Commit 91099e2

Browse files
authored
bpo-39359: [zipfile] add missing "pwd: expected bytes, got str" exception (GH-18031)
1 parent 86b833b commit 91099e2

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

Lib/test/test_zipfile.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2190,10 +2190,23 @@ def test_good_password(self):
21902190
self.assertEqual(self.zip2.read("zero"), self.plain2)
21912191

21922192
def test_unicode_password(self):
2193-
self.assertRaises(TypeError, self.zip.setpassword, "unicode")
2194-
self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
2195-
self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
2196-
self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
2193+
expected_msg = "pwd: expected bytes, got str"
2194+
2195+
with self.assertRaisesRegex(TypeError, expected_msg):
2196+
self.zip.setpassword("unicode")
2197+
2198+
with self.assertRaisesRegex(TypeError, expected_msg):
2199+
self.zip.read("test.txt", "python")
2200+
2201+
with self.assertRaisesRegex(TypeError, expected_msg):
2202+
self.zip.open("test.txt", pwd="python")
2203+
2204+
with self.assertRaisesRegex(TypeError, expected_msg):
2205+
self.zip.extract("test.txt", pwd="python")
2206+
2207+
with self.assertRaisesRegex(TypeError, expected_msg):
2208+
self.zip.pwd = "python"
2209+
self.zip.open("test.txt")
21972210

21982211
def test_seek_tell(self):
21992212
self.zip.setpassword(b"python")

Lib/zipfile.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1508,8 +1508,6 @@ def open(self, name, mode="r", pwd=None, *, force_zip64=False):
15081508
"""
15091509
if mode not in {"r", "w"}:
15101510
raise ValueError('open() requires mode "r" or "w"')
1511-
if pwd and not isinstance(pwd, bytes):
1512-
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
15131511
if pwd and (mode == "w"):
15141512
raise ValueError("pwd is only supported for reading files")
15151513
if not self.fp:
@@ -1577,6 +1575,8 @@ def open(self, name, mode="r", pwd=None, *, force_zip64=False):
15771575
if is_encrypted:
15781576
if not pwd:
15791577
pwd = self.pwd
1578+
if pwd and not isinstance(pwd, bytes):
1579+
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
15801580
if not pwd:
15811581
raise RuntimeError("File %r is encrypted, password "
15821582
"required for extraction" % name)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add one missing check that the password is a bytes object for an encrypted zipfile.

0 commit comments

Comments
 (0)