mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
issue27186: add open/io.open; patch by Jelle Zijlstra
This commit is contained in:
parent
228c636908
commit
d62548afed
4 changed files with 65 additions and 21 deletions
|
@ -161,6 +161,8 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None,
|
|||
opened in a text mode, and for bytes a BytesIO can be used like a file
|
||||
opened in a binary mode.
|
||||
"""
|
||||
if not isinstance(file, int):
|
||||
file = os.fspath(file)
|
||||
if not isinstance(file, (str, bytes, int)):
|
||||
raise TypeError("invalid file: %r" % file)
|
||||
if not isinstance(mode, str):
|
||||
|
|
|
@ -844,6 +844,32 @@ class IOTest(unittest.TestCase):
|
|||
self.assertEqual(getattr(stream, method)(buffer), 5)
|
||||
self.assertEqual(bytes(buffer), b"12345")
|
||||
|
||||
def test_fspath_support(self):
|
||||
class PathLike:
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
|
||||
def __fspath__(self):
|
||||
return self.path
|
||||
|
||||
def check_path_succeeds(path):
|
||||
with self.open(path, "w") as f:
|
||||
f.write("egg\n")
|
||||
|
||||
with self.open(path, "r") as f:
|
||||
self.assertEqual(f.read(), "egg\n")
|
||||
|
||||
check_path_succeeds(PathLike(support.TESTFN))
|
||||
check_path_succeeds(PathLike(support.TESTFN.encode('utf-8')))
|
||||
|
||||
bad_path = PathLike(TypeError)
|
||||
with self.assertRaisesRegex(TypeError, 'invalid file'):
|
||||
self.open(bad_path, 'w')
|
||||
|
||||
# ensure that refcounting is correct with some error conditions
|
||||
with self.assertRaisesRegex(ValueError, 'read/write/append mode'):
|
||||
self.open(PathLike(support.TESTFN), 'rwxa')
|
||||
|
||||
|
||||
class CIOTest(IOTest):
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue