]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-128520: pathlib ABCs: validate `magic_open()` arguments (#131617)
authorBarney Gale <barney.gale@gmail.com>
Mon, 24 Mar 2025 15:13:18 +0000 (15:13 +0000)
committerGitHub <noreply@github.com>
Mon, 24 Mar 2025 15:13:18 +0000 (15:13 +0000)
When `pathlib._os.magic_open()` is called to open a path in binary mode,
raise `ValueError` if any of the *encoding*, *errors* or *newline*
arguments are given. This matches the `open()` built-in.

Lib/pathlib/_os.py
Lib/test/test_pathlib/test_read.py
Lib/test/test_pathlib/test_write.py

index ee8657f427efbd5125883fc6bbd89d6a7be4b164..e3751bbcb62377c719ac30b52112ebee23075d49 100644 (file)
@@ -186,6 +186,12 @@ def magic_open(path, mode='r', buffering=-1, encoding=None, errors=None,
             pass
         else:
             return attr(path, buffering, encoding, errors, newline)
+    elif encoding is not None:
+        raise ValueError("binary mode doesn't take an encoding argument")
+    elif errors is not None:
+        raise ValueError("binary mode doesn't take an errors argument")
+    elif newline is not None:
+        raise ValueError("binary mode doesn't take a newline argument")
 
     try:
         attr = getattr(cls, f'__open_{mode}b__')
index 1a14649fafee801edb03daf6168b13fa8d5cd27a..753ae5d760aceb21dd4a36d3761977c98dcfac15 100644 (file)
@@ -39,6 +39,9 @@ class ReadTestBase:
         p = self.root / 'fileA'
         with magic_open(p, 'rb') as f:
             self.assertEqual(f.read(), b'this is file A\n')
+        self.assertRaises(ValueError, magic_open, p, 'rb', encoding='utf8')
+        self.assertRaises(ValueError, magic_open, p, 'rb', errors='strict')
+        self.assertRaises(ValueError, magic_open, p, 'rb', newline='')
 
     def test_read_bytes(self):
         p = self.root / 'fileA'
index 040af7be152fc2577198fc98bf4bc20a640d48e0..d302e0a9caa8896bfc35a0a3b9483c5263d7f9a6 100644 (file)
@@ -41,6 +41,9 @@ class WriteTestBase:
             #self.assertIsInstance(f, io.BufferedWriter)
             f.write(b'this is file A\n')
         self.assertEqual(self.ground.readbytes(p), b'this is file A\n')
+        self.assertRaises(ValueError, magic_open, p, 'wb', encoding='utf8')
+        self.assertRaises(ValueError, magic_open, p, 'wb', errors='strict')
+        self.assertRaises(ValueError, magic_open, p, 'wb', newline='')
 
     def test_write_bytes(self):
         p = self.root / 'fileA'