Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1 | """Unit tests for the io module.""" |
| 2 | |
| 3 | # Tests of io are scattered over the test suite: |
| 4 | # * test_bufio - tests file buffering |
| 5 | # * test_memoryio - tests BytesIO and StringIO |
| 6 | # * test_fileio - tests FileIO |
| 7 | # * test_file - tests the file interface |
| 8 | # * test_io - tests everything else in the io module |
| 9 | # * test_univnewlines - tests universal newline support |
| 10 | # * test_largefile - tests operations on a file greater than 2**32 bytes |
| 11 | # (only enabled with -ulargefile) |
| 12 | |
| 13 | ################################################################################ |
| 14 | # ATTENTION TEST WRITERS!!! |
| 15 | ################################################################################ |
| 16 | # When writing tests for io, it's important to test both the C and Python |
| 17 | # implementations. This is usually done by writing a base test that refers to |
Serhiy Storchaka | d65c949 | 2015-11-02 14:10:23 +0200 | [diff] [blame] | 18 | # the type it is testing as an attribute. Then it provides custom subclasses to |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 19 | # test both implementations. This file has lots of examples. |
| 20 | ################################################################################ |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 21 | |
Victor Stinner | f86a5e8 | 2012-06-05 13:43:22 +0200 | [diff] [blame] | 22 | import abc |
| 23 | import array |
| 24 | import errno |
| 25 | import locale |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 26 | import os |
Victor Stinner | f86a5e8 | 2012-06-05 13:43:22 +0200 | [diff] [blame] | 27 | import pickle |
| 28 | import random |
| 29 | import signal |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 30 | import sys |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 31 | import threading |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 32 | import time |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 33 | import unittest |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 34 | import warnings |
Victor Stinner | f86a5e8 | 2012-06-05 13:43:22 +0200 | [diff] [blame] | 35 | import weakref |
Antoine Pitrou | 131a489 | 2012-10-16 22:57:11 +0200 | [diff] [blame] | 36 | from collections import deque, UserList |
Victor Stinner | f86a5e8 | 2012-06-05 13:43:22 +0200 | [diff] [blame] | 37 | from itertools import cycle, count |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 38 | from test import support |
Berker Peksag | ce64391 | 2015-05-06 06:33:17 +0300 | [diff] [blame] | 39 | from test.support.script_helper import assert_python_ok, run_python_until_end |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 40 | |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 41 | import codecs |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 42 | import io # C implementation of io |
| 43 | import _pyio as pyio # Python implementation of io |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 44 | |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 45 | try: |
| 46 | import ctypes |
| 47 | except ImportError: |
| 48 | def byteslike(*pos, **kw): |
| 49 | return array.array("b", bytes(*pos, **kw)) |
| 50 | else: |
| 51 | def byteslike(*pos, **kw): |
| 52 | """Create a bytes-like object having no string or sequence methods""" |
| 53 | data = bytes(*pos, **kw) |
| 54 | obj = EmptyStruct() |
| 55 | ctypes.resize(obj, len(data)) |
| 56 | memoryview(obj).cast("B")[:] = data |
| 57 | return obj |
| 58 | class EmptyStruct(ctypes.Structure): |
| 59 | pass |
| 60 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 61 | def _default_chunk_size(): |
| 62 | """Get the default TextIOWrapper chunk size""" |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 63 | with open(__file__, "r", encoding="latin-1") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 64 | return f._CHUNK_SIZE |
| 65 | |
| 66 | |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 67 | class MockRawIOWithoutRead: |
| 68 | """A RawIO implementation without read(), so as to exercise the default |
| 69 | RawIO.read() which calls readinto().""" |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 70 | |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 71 | def __init__(self, read_stack=()): |
| 72 | self._read_stack = list(read_stack) |
| 73 | self._write_stack = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 74 | self._reads = 0 |
Antoine Pitrou | 32cfede | 2010-08-11 13:31:33 +0000 | [diff] [blame] | 75 | self._extraneous_reads = 0 |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 76 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 77 | def write(self, b): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 78 | self._write_stack.append(bytes(b)) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 79 | return len(b) |
| 80 | |
| 81 | def writable(self): |
| 82 | return True |
| 83 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 84 | def fileno(self): |
| 85 | return 42 |
| 86 | |
| 87 | def readable(self): |
| 88 | return True |
| 89 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 90 | def seekable(self): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 91 | return True |
| 92 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 93 | def seek(self, pos, whence): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 94 | return 0 # wrong but we gotta return something |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 95 | |
| 96 | def tell(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 97 | return 0 # same comment as above |
| 98 | |
| 99 | def readinto(self, buf): |
| 100 | self._reads += 1 |
| 101 | max_len = len(buf) |
| 102 | try: |
| 103 | data = self._read_stack[0] |
| 104 | except IndexError: |
Antoine Pitrou | 32cfede | 2010-08-11 13:31:33 +0000 | [diff] [blame] | 105 | self._extraneous_reads += 1 |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 106 | return 0 |
| 107 | if data is None: |
| 108 | del self._read_stack[0] |
| 109 | return None |
| 110 | n = len(data) |
| 111 | if len(data) <= max_len: |
| 112 | del self._read_stack[0] |
| 113 | buf[:n] = data |
| 114 | return n |
| 115 | else: |
| 116 | buf[:] = data[:max_len] |
| 117 | self._read_stack[0] = data[max_len:] |
| 118 | return max_len |
| 119 | |
| 120 | def truncate(self, pos=None): |
| 121 | return pos |
| 122 | |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 123 | class CMockRawIOWithoutRead(MockRawIOWithoutRead, io.RawIOBase): |
| 124 | pass |
| 125 | |
| 126 | class PyMockRawIOWithoutRead(MockRawIOWithoutRead, pyio.RawIOBase): |
| 127 | pass |
| 128 | |
| 129 | |
| 130 | class MockRawIO(MockRawIOWithoutRead): |
| 131 | |
| 132 | def read(self, n=None): |
| 133 | self._reads += 1 |
| 134 | try: |
| 135 | return self._read_stack.pop(0) |
| 136 | except: |
| 137 | self._extraneous_reads += 1 |
| 138 | return b"" |
| 139 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 140 | class CMockRawIO(MockRawIO, io.RawIOBase): |
| 141 | pass |
| 142 | |
| 143 | class PyMockRawIO(MockRawIO, pyio.RawIOBase): |
| 144 | pass |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 145 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 146 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 147 | class MisbehavedRawIO(MockRawIO): |
| 148 | def write(self, b): |
| 149 | return super().write(b) * 2 |
| 150 | |
| 151 | def read(self, n=None): |
| 152 | return super().read(n) * 2 |
| 153 | |
| 154 | def seek(self, pos, whence): |
| 155 | return -123 |
| 156 | |
| 157 | def tell(self): |
| 158 | return -456 |
| 159 | |
| 160 | def readinto(self, buf): |
| 161 | super().readinto(buf) |
| 162 | return len(buf) * 5 |
| 163 | |
| 164 | class CMisbehavedRawIO(MisbehavedRawIO, io.RawIOBase): |
| 165 | pass |
| 166 | |
| 167 | class PyMisbehavedRawIO(MisbehavedRawIO, pyio.RawIOBase): |
| 168 | pass |
| 169 | |
| 170 | |
benfogle | 9703f09 | 2017-11-10 16:03:40 -0500 | [diff] [blame] | 171 | class SlowFlushRawIO(MockRawIO): |
| 172 | def __init__(self): |
| 173 | super().__init__() |
| 174 | self.in_flush = threading.Event() |
| 175 | |
| 176 | def flush(self): |
| 177 | self.in_flush.set() |
| 178 | time.sleep(0.25) |
| 179 | |
| 180 | class CSlowFlushRawIO(SlowFlushRawIO, io.RawIOBase): |
| 181 | pass |
| 182 | |
| 183 | class PySlowFlushRawIO(SlowFlushRawIO, pyio.RawIOBase): |
| 184 | pass |
| 185 | |
| 186 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 187 | class CloseFailureIO(MockRawIO): |
| 188 | closed = 0 |
| 189 | |
| 190 | def close(self): |
| 191 | if not self.closed: |
| 192 | self.closed = 1 |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 193 | raise OSError |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 194 | |
| 195 | class CCloseFailureIO(CloseFailureIO, io.RawIOBase): |
| 196 | pass |
| 197 | |
| 198 | class PyCloseFailureIO(CloseFailureIO, pyio.RawIOBase): |
| 199 | pass |
| 200 | |
| 201 | |
| 202 | class MockFileIO: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 203 | |
| 204 | def __init__(self, data): |
| 205 | self.read_history = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 206 | super().__init__(data) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 207 | |
| 208 | def read(self, n=None): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 209 | res = super().read(n) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 210 | self.read_history.append(None if res is None else len(res)) |
| 211 | return res |
| 212 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 213 | def readinto(self, b): |
| 214 | res = super().readinto(b) |
| 215 | self.read_history.append(res) |
| 216 | return res |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 217 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 218 | class CMockFileIO(MockFileIO, io.BytesIO): |
| 219 | pass |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 220 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 221 | class PyMockFileIO(MockFileIO, pyio.BytesIO): |
| 222 | pass |
| 223 | |
| 224 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 225 | class MockUnseekableIO: |
| 226 | def seekable(self): |
| 227 | return False |
| 228 | |
| 229 | def seek(self, *args): |
| 230 | raise self.UnsupportedOperation("not seekable") |
| 231 | |
| 232 | def tell(self, *args): |
| 233 | raise self.UnsupportedOperation("not seekable") |
| 234 | |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 235 | def truncate(self, *args): |
| 236 | raise self.UnsupportedOperation("not seekable") |
| 237 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 238 | class CMockUnseekableIO(MockUnseekableIO, io.BytesIO): |
| 239 | UnsupportedOperation = io.UnsupportedOperation |
| 240 | |
| 241 | class PyMockUnseekableIO(MockUnseekableIO, pyio.BytesIO): |
| 242 | UnsupportedOperation = pyio.UnsupportedOperation |
| 243 | |
| 244 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 245 | class MockNonBlockWriterIO: |
| 246 | |
| 247 | def __init__(self): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 248 | self._write_stack = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 249 | self._blocker_char = None |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 250 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 251 | def pop_written(self): |
| 252 | s = b"".join(self._write_stack) |
| 253 | self._write_stack[:] = [] |
| 254 | return s |
| 255 | |
| 256 | def block_on(self, char): |
| 257 | """Block when a given char is encountered.""" |
| 258 | self._blocker_char = char |
| 259 | |
| 260 | def readable(self): |
| 261 | return True |
| 262 | |
| 263 | def seekable(self): |
| 264 | return True |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 265 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 266 | def writable(self): |
| 267 | return True |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 268 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 269 | def write(self, b): |
| 270 | b = bytes(b) |
| 271 | n = -1 |
| 272 | if self._blocker_char: |
| 273 | try: |
| 274 | n = b.index(self._blocker_char) |
| 275 | except ValueError: |
| 276 | pass |
| 277 | else: |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 278 | if n > 0: |
| 279 | # write data up to the first blocker |
| 280 | self._write_stack.append(b[:n]) |
| 281 | return n |
| 282 | else: |
| 283 | # cancel blocker and indicate would block |
| 284 | self._blocker_char = None |
| 285 | return None |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 286 | self._write_stack.append(b) |
| 287 | return len(b) |
| 288 | |
| 289 | class CMockNonBlockWriterIO(MockNonBlockWriterIO, io.RawIOBase): |
| 290 | BlockingIOError = io.BlockingIOError |
| 291 | |
| 292 | class PyMockNonBlockWriterIO(MockNonBlockWriterIO, pyio.RawIOBase): |
| 293 | BlockingIOError = pyio.BlockingIOError |
| 294 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 295 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 296 | class IOTest(unittest.TestCase): |
| 297 | |
Neal Norwitz | e7789b1 | 2008-03-24 06:18:09 +0000 | [diff] [blame] | 298 | def setUp(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 299 | support.unlink(support.TESTFN) |
Neal Norwitz | e7789b1 | 2008-03-24 06:18:09 +0000 | [diff] [blame] | 300 | |
Guido van Rossum | 4d0f5a4 | 2007-03-07 22:59:39 +0000 | [diff] [blame] | 301 | def tearDown(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 302 | support.unlink(support.TESTFN) |
Guido van Rossum | 4d0f5a4 | 2007-03-07 22:59:39 +0000 | [diff] [blame] | 303 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 304 | def write_ops(self, f): |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 305 | self.assertEqual(f.write(b"blah."), 5) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 306 | f.truncate(0) |
| 307 | self.assertEqual(f.tell(), 5) |
| 308 | f.seek(0) |
| 309 | |
| 310 | self.assertEqual(f.write(b"blah."), 5) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 311 | self.assertEqual(f.seek(0), 0) |
| 312 | self.assertEqual(f.write(b"Hello."), 6) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 313 | self.assertEqual(f.tell(), 6) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 314 | self.assertEqual(f.seek(-1, 1), 5) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 315 | self.assertEqual(f.tell(), 5) |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 316 | buffer = bytearray(b" world\n\n\n") |
| 317 | self.assertEqual(f.write(buffer), 9) |
| 318 | buffer[:] = b"*" * 9 # Overwrite our copy of the data |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 319 | self.assertEqual(f.seek(0), 0) |
Guido van Rossum | 2b08b38 | 2007-05-08 20:18:39 +0000 | [diff] [blame] | 320 | self.assertEqual(f.write(b"h"), 1) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 321 | self.assertEqual(f.seek(-1, 2), 13) |
| 322 | self.assertEqual(f.tell(), 13) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 323 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 324 | self.assertEqual(f.truncate(12), 12) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 325 | self.assertEqual(f.tell(), 13) |
Christian Heimes | 8e42a0a | 2007-11-08 18:04:45 +0000 | [diff] [blame] | 326 | self.assertRaises(TypeError, f.seek, 0.0) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 327 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 328 | def read_ops(self, f, buffered=False): |
| 329 | data = f.read(5) |
| 330 | self.assertEqual(data, b"hello") |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 331 | data = byteslike(data) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 332 | self.assertEqual(f.readinto(data), 5) |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 333 | self.assertEqual(bytes(data), b" worl") |
| 334 | data = bytearray(5) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 335 | self.assertEqual(f.readinto(data), 2) |
| 336 | self.assertEqual(len(data), 5) |
| 337 | self.assertEqual(data[:2], b"d\n") |
| 338 | self.assertEqual(f.seek(0), 0) |
| 339 | self.assertEqual(f.read(20), b"hello world\n") |
| 340 | self.assertEqual(f.read(1), b"") |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 341 | self.assertEqual(f.readinto(byteslike(b"x")), 0) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 342 | self.assertEqual(f.seek(-6, 2), 6) |
| 343 | self.assertEqual(f.read(5), b"world") |
| 344 | self.assertEqual(f.read(0), b"") |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 345 | self.assertEqual(f.readinto(byteslike()), 0) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 346 | self.assertEqual(f.seek(-6, 1), 5) |
| 347 | self.assertEqual(f.read(5), b" worl") |
| 348 | self.assertEqual(f.tell(), 10) |
Christian Heimes | 8e42a0a | 2007-11-08 18:04:45 +0000 | [diff] [blame] | 349 | self.assertRaises(TypeError, f.seek, 0.0) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 350 | if buffered: |
| 351 | f.seek(0) |
| 352 | self.assertEqual(f.read(), b"hello world\n") |
| 353 | f.seek(6) |
| 354 | self.assertEqual(f.read(), b"world\n") |
| 355 | self.assertEqual(f.read(), b"") |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 356 | f.seek(0) |
| 357 | data = byteslike(5) |
| 358 | self.assertEqual(f.readinto1(data), 5) |
| 359 | self.assertEqual(bytes(data), b"hello") |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 360 | |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 361 | LARGE = 2**31 |
| 362 | |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 363 | def large_file_ops(self, f): |
| 364 | assert f.readable() |
| 365 | assert f.writable() |
Xavier de Gaye | 877f036 | 2016-11-17 09:20:28 +0100 | [diff] [blame] | 366 | try: |
| 367 | self.assertEqual(f.seek(self.LARGE), self.LARGE) |
| 368 | except (OverflowError, ValueError): |
| 369 | self.skipTest("no largefile support") |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 370 | self.assertEqual(f.tell(), self.LARGE) |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 371 | self.assertEqual(f.write(b"xxx"), 3) |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 372 | self.assertEqual(f.tell(), self.LARGE + 3) |
| 373 | self.assertEqual(f.seek(-1, 1), self.LARGE + 2) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 374 | self.assertEqual(f.truncate(), self.LARGE + 2) |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 375 | self.assertEqual(f.tell(), self.LARGE + 2) |
| 376 | self.assertEqual(f.seek(0, 2), self.LARGE + 2) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 377 | self.assertEqual(f.truncate(self.LARGE + 1), self.LARGE + 1) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 378 | self.assertEqual(f.tell(), self.LARGE + 2) |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 379 | self.assertEqual(f.seek(0, 2), self.LARGE + 1) |
| 380 | self.assertEqual(f.seek(-1, 2), self.LARGE) |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 381 | self.assertEqual(f.read(2), b"x") |
| 382 | |
Benjamin Peterson | 81971ea | 2009-05-14 22:01:31 +0000 | [diff] [blame] | 383 | def test_invalid_operations(self): |
| 384 | # Try writing on a file opened in read mode and vice-versa. |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 385 | exc = self.UnsupportedOperation |
Benjamin Peterson | 81971ea | 2009-05-14 22:01:31 +0000 | [diff] [blame] | 386 | for mode in ("w", "wb"): |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 387 | with self.open(support.TESTFN, mode) as fp: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 388 | self.assertRaises(exc, fp.read) |
| 389 | self.assertRaises(exc, fp.readline) |
| 390 | with self.open(support.TESTFN, "wb", buffering=0) as fp: |
| 391 | self.assertRaises(exc, fp.read) |
| 392 | self.assertRaises(exc, fp.readline) |
| 393 | with self.open(support.TESTFN, "rb", buffering=0) as fp: |
| 394 | self.assertRaises(exc, fp.write, b"blah") |
| 395 | self.assertRaises(exc, fp.writelines, [b"blah\n"]) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 396 | with self.open(support.TESTFN, "rb") as fp: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 397 | self.assertRaises(exc, fp.write, b"blah") |
| 398 | self.assertRaises(exc, fp.writelines, [b"blah\n"]) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 399 | with self.open(support.TESTFN, "r") as fp: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 400 | self.assertRaises(exc, fp.write, "blah") |
| 401 | self.assertRaises(exc, fp.writelines, ["blah\n"]) |
| 402 | # Non-zero seeking from current or end pos |
| 403 | self.assertRaises(exc, fp.seek, 1, self.SEEK_CUR) |
| 404 | self.assertRaises(exc, fp.seek, -1, self.SEEK_END) |
Benjamin Peterson | 81971ea | 2009-05-14 22:01:31 +0000 | [diff] [blame] | 405 | |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 406 | def test_optional_abilities(self): |
| 407 | # Test for OSError when optional APIs are not supported |
| 408 | # The purpose of this test is to try fileno(), reading, writing and |
| 409 | # seeking operations with various objects that indicate they do not |
| 410 | # support these operations. |
| 411 | |
| 412 | def pipe_reader(): |
| 413 | [r, w] = os.pipe() |
| 414 | os.close(w) # So that read() is harmless |
| 415 | return self.FileIO(r, "r") |
| 416 | |
| 417 | def pipe_writer(): |
| 418 | [r, w] = os.pipe() |
| 419 | self.addCleanup(os.close, r) |
| 420 | # Guarantee that we can write into the pipe without blocking |
| 421 | thread = threading.Thread(target=os.read, args=(r, 100)) |
| 422 | thread.start() |
| 423 | self.addCleanup(thread.join) |
| 424 | return self.FileIO(w, "w") |
| 425 | |
| 426 | def buffered_reader(): |
| 427 | return self.BufferedReader(self.MockUnseekableIO()) |
| 428 | |
| 429 | def buffered_writer(): |
| 430 | return self.BufferedWriter(self.MockUnseekableIO()) |
| 431 | |
| 432 | def buffered_random(): |
| 433 | return self.BufferedRandom(self.BytesIO()) |
| 434 | |
| 435 | def buffered_rw_pair(): |
| 436 | return self.BufferedRWPair(self.MockUnseekableIO(), |
| 437 | self.MockUnseekableIO()) |
| 438 | |
| 439 | def text_reader(): |
| 440 | class UnseekableReader(self.MockUnseekableIO): |
| 441 | writable = self.BufferedIOBase.writable |
| 442 | write = self.BufferedIOBase.write |
| 443 | return self.TextIOWrapper(UnseekableReader(), "ascii") |
| 444 | |
| 445 | def text_writer(): |
| 446 | class UnseekableWriter(self.MockUnseekableIO): |
| 447 | readable = self.BufferedIOBase.readable |
| 448 | read = self.BufferedIOBase.read |
| 449 | return self.TextIOWrapper(UnseekableWriter(), "ascii") |
| 450 | |
| 451 | tests = ( |
| 452 | (pipe_reader, "fr"), (pipe_writer, "fw"), |
| 453 | (buffered_reader, "r"), (buffered_writer, "w"), |
| 454 | (buffered_random, "rws"), (buffered_rw_pair, "rw"), |
| 455 | (text_reader, "r"), (text_writer, "w"), |
| 456 | (self.BytesIO, "rws"), (self.StringIO, "rws"), |
| 457 | ) |
| 458 | for [test, abilities] in tests: |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 459 | with self.subTest(test), test() as obj: |
| 460 | readable = "r" in abilities |
| 461 | self.assertEqual(obj.readable(), readable) |
| 462 | writable = "w" in abilities |
| 463 | self.assertEqual(obj.writable(), writable) |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 464 | |
| 465 | if isinstance(obj, self.TextIOBase): |
| 466 | data = "3" |
| 467 | elif isinstance(obj, (self.BufferedIOBase, self.RawIOBase)): |
| 468 | data = b"3" |
| 469 | else: |
| 470 | self.fail("Unknown base class") |
| 471 | |
| 472 | if "f" in abilities: |
| 473 | obj.fileno() |
| 474 | else: |
| 475 | self.assertRaises(OSError, obj.fileno) |
| 476 | |
| 477 | if readable: |
| 478 | obj.read(1) |
| 479 | obj.read() |
| 480 | else: |
| 481 | self.assertRaises(OSError, obj.read, 1) |
| 482 | self.assertRaises(OSError, obj.read) |
| 483 | |
| 484 | if writable: |
| 485 | obj.write(data) |
| 486 | else: |
| 487 | self.assertRaises(OSError, obj.write, data) |
| 488 | |
Martin Panter | 3ee147f | 2016-03-31 21:05:31 +0000 | [diff] [blame] | 489 | if sys.platform.startswith("win") and test in ( |
Martin Panter | 0950e6a | 2016-03-31 10:31:30 +0000 | [diff] [blame] | 490 | pipe_reader, pipe_writer): |
| 491 | # Pipes seem to appear as seekable on Windows |
| 492 | continue |
| 493 | seekable = "s" in abilities |
| 494 | self.assertEqual(obj.seekable(), seekable) |
| 495 | |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 496 | if seekable: |
| 497 | obj.tell() |
| 498 | obj.seek(0) |
| 499 | else: |
| 500 | self.assertRaises(OSError, obj.tell) |
| 501 | self.assertRaises(OSError, obj.seek, 0) |
| 502 | |
| 503 | if writable and seekable: |
| 504 | obj.truncate() |
| 505 | obj.truncate(0) |
| 506 | else: |
| 507 | self.assertRaises(OSError, obj.truncate) |
| 508 | self.assertRaises(OSError, obj.truncate, 0) |
| 509 | |
Antoine Pitrou | 1334884 | 2012-01-29 18:36:34 +0100 | [diff] [blame] | 510 | def test_open_handles_NUL_chars(self): |
| 511 | fn_with_NUL = 'foo\0bar' |
Serhiy Storchaka | d8a1447 | 2014-09-06 20:07:17 +0300 | [diff] [blame] | 512 | self.assertRaises(ValueError, self.open, fn_with_NUL, 'w') |
Victor Stinner | 47b4557 | 2016-03-25 09:07:07 +0100 | [diff] [blame] | 513 | |
| 514 | bytes_fn = bytes(fn_with_NUL, 'ascii') |
| 515 | with warnings.catch_warnings(): |
| 516 | warnings.simplefilter("ignore", DeprecationWarning) |
| 517 | self.assertRaises(ValueError, self.open, bytes_fn, 'w') |
Antoine Pitrou | 1334884 | 2012-01-29 18:36:34 +0100 | [diff] [blame] | 518 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 519 | def test_raw_file_io(self): |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 520 | with self.open(support.TESTFN, "wb", buffering=0) as f: |
| 521 | self.assertEqual(f.readable(), False) |
| 522 | self.assertEqual(f.writable(), True) |
| 523 | self.assertEqual(f.seekable(), True) |
| 524 | self.write_ops(f) |
| 525 | with self.open(support.TESTFN, "rb", buffering=0) as f: |
| 526 | self.assertEqual(f.readable(), True) |
| 527 | self.assertEqual(f.writable(), False) |
| 528 | self.assertEqual(f.seekable(), True) |
| 529 | self.read_ops(f) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 530 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 531 | def test_buffered_file_io(self): |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 532 | with self.open(support.TESTFN, "wb") as f: |
| 533 | self.assertEqual(f.readable(), False) |
| 534 | self.assertEqual(f.writable(), True) |
| 535 | self.assertEqual(f.seekable(), True) |
| 536 | self.write_ops(f) |
| 537 | with self.open(support.TESTFN, "rb") as f: |
| 538 | self.assertEqual(f.readable(), True) |
| 539 | self.assertEqual(f.writable(), False) |
| 540 | self.assertEqual(f.seekable(), True) |
| 541 | self.read_ops(f, True) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 542 | |
Guido van Rossum | 48fc58a | 2007-06-07 23:45:37 +0000 | [diff] [blame] | 543 | def test_readline(self): |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 544 | with self.open(support.TESTFN, "wb") as f: |
| 545 | f.write(b"abc\ndef\nxyzzy\nfoo\x00bar\nanother line") |
| 546 | with self.open(support.TESTFN, "rb") as f: |
| 547 | self.assertEqual(f.readline(), b"abc\n") |
| 548 | self.assertEqual(f.readline(10), b"def\n") |
| 549 | self.assertEqual(f.readline(2), b"xy") |
| 550 | self.assertEqual(f.readline(4), b"zzy\n") |
| 551 | self.assertEqual(f.readline(), b"foo\x00bar\n") |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 552 | self.assertEqual(f.readline(None), b"another line") |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 553 | self.assertRaises(TypeError, f.readline, 5.3) |
| 554 | with self.open(support.TESTFN, "r") as f: |
| 555 | self.assertRaises(TypeError, f.readline, 5.3) |
Guido van Rossum | 48fc58a | 2007-06-07 23:45:37 +0000 | [diff] [blame] | 556 | |
Serhiy Storchaka | bf623ae | 2017-04-19 20:03:52 +0300 | [diff] [blame] | 557 | def test_readline_nonsizeable(self): |
| 558 | # Issue #30061 |
| 559 | # Crash when readline() returns an object without __len__ |
| 560 | class R(self.IOBase): |
| 561 | def readline(self): |
| 562 | return None |
| 563 | self.assertRaises((TypeError, StopIteration), next, R()) |
| 564 | |
| 565 | def test_next_nonsizeable(self): |
| 566 | # Issue #30061 |
| 567 | # Crash when __next__() returns an object without __len__ |
| 568 | class R(self.IOBase): |
| 569 | def __next__(self): |
| 570 | return None |
| 571 | self.assertRaises(TypeError, R().readlines, 1) |
| 572 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 573 | def test_raw_bytes_io(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 574 | f = self.BytesIO() |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 575 | self.write_ops(f) |
| 576 | data = f.getvalue() |
| 577 | self.assertEqual(data, b"hello world\n") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 578 | f = self.BytesIO(data) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 579 | self.read_ops(f, True) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 580 | |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 581 | def test_large_file_ops(self): |
Mike | 53f7a7c | 2017-12-14 14:04:53 +0300 | [diff] [blame] | 582 | # On Windows and Mac OSX this test consumes large resources; It takes |
Victor Stinner | 8c663fd | 2017-11-08 14:44:44 -0800 | [diff] [blame] | 583 | # a long time to build the >2 GiB file and takes >2 GiB of disk space |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 584 | # therefore the resource must be enabled to run this test. |
| 585 | if sys.platform[:3] == 'win' or sys.platform == 'darwin': |
Zachary Ware | 9fe6d86 | 2013-12-08 00:20:35 -0600 | [diff] [blame] | 586 | support.requires( |
| 587 | 'largefile', |
| 588 | 'test requires %s bytes and a long time to run' % self.LARGE) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 589 | with self.open(support.TESTFN, "w+b", 0) as f: |
| 590 | self.large_file_ops(f) |
| 591 | with self.open(support.TESTFN, "w+b") as f: |
| 592 | self.large_file_ops(f) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 593 | |
| 594 | def test_with_open(self): |
| 595 | for bufsize in (0, 1, 100): |
| 596 | f = None |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 597 | with self.open(support.TESTFN, "wb", bufsize) as f: |
Guido van Rossum | 1f2ca56 | 2007-08-27 20:44:15 +0000 | [diff] [blame] | 598 | f.write(b"xxx") |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 599 | self.assertEqual(f.closed, True) |
| 600 | f = None |
| 601 | try: |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 602 | with self.open(support.TESTFN, "wb", bufsize) as f: |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 603 | 1/0 |
| 604 | except ZeroDivisionError: |
| 605 | self.assertEqual(f.closed, True) |
| 606 | else: |
| 607 | self.fail("1/0 didn't raise an exception") |
| 608 | |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 609 | # issue 5008 |
| 610 | def test_append_mode_tell(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 611 | with self.open(support.TESTFN, "wb") as f: |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 612 | f.write(b"xxx") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 613 | with self.open(support.TESTFN, "ab", buffering=0) as f: |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 614 | self.assertEqual(f.tell(), 3) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 615 | with self.open(support.TESTFN, "ab") as f: |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 616 | self.assertEqual(f.tell(), 3) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 617 | with self.open(support.TESTFN, "a") as f: |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 618 | self.assertGreater(f.tell(), 0) |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 619 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 620 | def test_destructor(self): |
| 621 | record = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 622 | class MyFileIO(self.FileIO): |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 623 | def __del__(self): |
| 624 | record.append(1) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 625 | try: |
| 626 | f = super().__del__ |
| 627 | except AttributeError: |
| 628 | pass |
| 629 | else: |
| 630 | f() |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 631 | def close(self): |
| 632 | record.append(2) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 633 | super().close() |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 634 | def flush(self): |
| 635 | record.append(3) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 636 | super().flush() |
Brett Cannon | 5a9e91b | 2010-10-29 23:53:03 +0000 | [diff] [blame] | 637 | with support.check_warnings(('', ResourceWarning)): |
| 638 | f = MyFileIO(support.TESTFN, "wb") |
| 639 | f.write(b"xxx") |
| 640 | del f |
| 641 | support.gc_collect() |
| 642 | self.assertEqual(record, [1, 2, 3]) |
| 643 | with self.open(support.TESTFN, "rb") as f: |
| 644 | self.assertEqual(f.read(), b"xxx") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 645 | |
| 646 | def _check_base_destructor(self, base): |
| 647 | record = [] |
| 648 | class MyIO(base): |
| 649 | def __init__(self): |
| 650 | # This exercises the availability of attributes on object |
| 651 | # destruction. |
| 652 | # (in the C version, close() is called by the tp_dealloc |
| 653 | # function, not by __del__) |
| 654 | self.on_del = 1 |
| 655 | self.on_close = 2 |
| 656 | self.on_flush = 3 |
| 657 | def __del__(self): |
| 658 | record.append(self.on_del) |
| 659 | try: |
| 660 | f = super().__del__ |
| 661 | except AttributeError: |
| 662 | pass |
| 663 | else: |
| 664 | f() |
| 665 | def close(self): |
| 666 | record.append(self.on_close) |
| 667 | super().close() |
| 668 | def flush(self): |
| 669 | record.append(self.on_flush) |
| 670 | super().flush() |
| 671 | f = MyIO() |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 672 | del f |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 673 | support.gc_collect() |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 674 | self.assertEqual(record, [1, 2, 3]) |
| 675 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 676 | def test_IOBase_destructor(self): |
| 677 | self._check_base_destructor(self.IOBase) |
| 678 | |
| 679 | def test_RawIOBase_destructor(self): |
| 680 | self._check_base_destructor(self.RawIOBase) |
| 681 | |
| 682 | def test_BufferedIOBase_destructor(self): |
| 683 | self._check_base_destructor(self.BufferedIOBase) |
| 684 | |
| 685 | def test_TextIOBase_destructor(self): |
| 686 | self._check_base_destructor(self.TextIOBase) |
| 687 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 688 | def test_close_flushes(self): |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 689 | with self.open(support.TESTFN, "wb") as f: |
| 690 | f.write(b"xxx") |
| 691 | with self.open(support.TESTFN, "rb") as f: |
| 692 | self.assertEqual(f.read(), b"xxx") |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 693 | |
Guido van Rossum | d410395 | 2007-04-12 05:44:49 +0000 | [diff] [blame] | 694 | def test_array_writes(self): |
| 695 | a = array.array('i', range(10)) |
Antoine Pitrou | 1ce3eb5 | 2010-09-01 20:29:34 +0000 | [diff] [blame] | 696 | n = len(a.tobytes()) |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 697 | def check(f): |
| 698 | with f: |
| 699 | self.assertEqual(f.write(a), n) |
| 700 | f.writelines((a,)) |
| 701 | check(self.BytesIO()) |
| 702 | check(self.FileIO(support.TESTFN, "w")) |
| 703 | check(self.BufferedWriter(self.MockRawIO())) |
| 704 | check(self.BufferedRandom(self.MockRawIO())) |
| 705 | check(self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())) |
Guido van Rossum | d410395 | 2007-04-12 05:44:49 +0000 | [diff] [blame] | 706 | |
Guido van Rossum | 2dced8b | 2007-10-30 17:27:30 +0000 | [diff] [blame] | 707 | def test_closefd(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 708 | self.assertRaises(ValueError, self.open, support.TESTFN, 'w', |
Guido van Rossum | 2dced8b | 2007-10-30 17:27:30 +0000 | [diff] [blame] | 709 | closefd=False) |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 710 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 711 | def test_read_closed(self): |
| 712 | with self.open(support.TESTFN, "w") as f: |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 713 | f.write("egg\n") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 714 | with self.open(support.TESTFN, "r") as f: |
| 715 | file = self.open(f.fileno(), "r", closefd=False) |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 716 | self.assertEqual(file.read(), "egg\n") |
| 717 | file.seek(0) |
| 718 | file.close() |
| 719 | self.assertRaises(ValueError, file.read) |
| 720 | |
| 721 | def test_no_closefd_with_filename(self): |
| 722 | # can't use closefd in combination with a file name |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 723 | self.assertRaises(ValueError, self.open, support.TESTFN, "r", closefd=False) |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 724 | |
| 725 | def test_closefd_attr(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 726 | with self.open(support.TESTFN, "wb") as f: |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 727 | f.write(b"egg\n") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 728 | with self.open(support.TESTFN, "r") as f: |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 729 | self.assertEqual(f.buffer.raw.closefd, True) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 730 | file = self.open(f.fileno(), "r", closefd=False) |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 731 | self.assertEqual(file.buffer.raw.closefd, False) |
| 732 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 733 | def test_garbage_collection(self): |
| 734 | # FileIO objects are collected, and collecting them flushes |
| 735 | # all data to disk. |
Benjamin Peterson | ebe5d8a | 2010-10-31 01:30:11 +0000 | [diff] [blame] | 736 | with support.check_warnings(('', ResourceWarning)): |
| 737 | f = self.FileIO(support.TESTFN, "wb") |
| 738 | f.write(b"abcxxx") |
| 739 | f.f = f |
| 740 | wr = weakref.ref(f) |
| 741 | del f |
| 742 | support.gc_collect() |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 743 | self.assertIsNone(wr(), wr) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 744 | with self.open(support.TESTFN, "rb") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 745 | self.assertEqual(f.read(), b"abcxxx") |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 746 | |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 747 | def test_unbounded_file(self): |
| 748 | # Issue #1174606: reading from an unbounded stream such as /dev/zero. |
| 749 | zero = "/dev/zero" |
| 750 | if not os.path.exists(zero): |
Antoine Pitrou | c50cb8e | 2009-04-19 00:10:36 +0000 | [diff] [blame] | 751 | self.skipTest("{0} does not exist".format(zero)) |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 752 | if sys.maxsize > 0x7FFFFFFF: |
Antoine Pitrou | c50cb8e | 2009-04-19 00:10:36 +0000 | [diff] [blame] | 753 | self.skipTest("test can only run in a 32-bit address space") |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 754 | if support.real_max_memuse < support._2G: |
Victor Stinner | 8c663fd | 2017-11-08 14:44:44 -0800 | [diff] [blame] | 755 | self.skipTest("test requires at least 2 GiB of memory") |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 756 | with self.open(zero, "rb", buffering=0) as f: |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 757 | self.assertRaises(OverflowError, f.read) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 758 | with self.open(zero, "rb") as f: |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 759 | self.assertRaises(OverflowError, f.read) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 760 | with self.open(zero, "r") as f: |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 761 | self.assertRaises(OverflowError, f.read) |
| 762 | |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 763 | def check_flush_error_on_close(self, *args, **kwargs): |
| 764 | # Test that the file is closed despite failed flush |
| 765 | # and that flush() is called before file closed. |
| 766 | f = self.open(*args, **kwargs) |
| 767 | closed = [] |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 768 | def bad_flush(): |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 769 | closed[:] = [f.closed] |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 770 | raise OSError() |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 771 | f.flush = bad_flush |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 772 | self.assertRaises(OSError, f.close) # exception not swallowed |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 773 | self.assertTrue(f.closed) |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 774 | self.assertTrue(closed) # flush() called |
| 775 | self.assertFalse(closed[0]) # flush() called before file closed |
Serhiy Storchaka | c26a1a4 | 2015-02-23 00:28:38 +0200 | [diff] [blame] | 776 | f.flush = lambda: None # break reference loop |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 777 | |
| 778 | def test_flush_error_on_close(self): |
| 779 | # raw file |
| 780 | # Issue #5700: io.FileIO calls flush() after file closed |
| 781 | self.check_flush_error_on_close(support.TESTFN, 'wb', buffering=0) |
| 782 | fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) |
| 783 | self.check_flush_error_on_close(fd, 'wb', buffering=0) |
| 784 | fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) |
| 785 | self.check_flush_error_on_close(fd, 'wb', buffering=0, closefd=False) |
| 786 | os.close(fd) |
| 787 | # buffered io |
| 788 | self.check_flush_error_on_close(support.TESTFN, 'wb') |
| 789 | fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) |
| 790 | self.check_flush_error_on_close(fd, 'wb') |
| 791 | fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) |
| 792 | self.check_flush_error_on_close(fd, 'wb', closefd=False) |
| 793 | os.close(fd) |
| 794 | # text io |
| 795 | self.check_flush_error_on_close(support.TESTFN, 'w') |
| 796 | fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) |
| 797 | self.check_flush_error_on_close(fd, 'w') |
| 798 | fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) |
| 799 | self.check_flush_error_on_close(fd, 'w', closefd=False) |
| 800 | os.close(fd) |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 801 | |
| 802 | def test_multi_close(self): |
| 803 | f = self.open(support.TESTFN, "wb", buffering=0) |
| 804 | f.close() |
| 805 | f.close() |
| 806 | f.close() |
| 807 | self.assertRaises(ValueError, f.flush) |
| 808 | |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 809 | def test_RawIOBase_read(self): |
Sanyam Khurana | 1b74f9b | 2017-12-11 19:12:09 +0530 | [diff] [blame] | 810 | # Exercise the default limited RawIOBase.read(n) implementation (which |
| 811 | # calls readinto() internally). |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 812 | rawio = self.MockRawIOWithoutRead((b"abc", b"d", None, b"efg", None)) |
| 813 | self.assertEqual(rawio.read(2), b"ab") |
| 814 | self.assertEqual(rawio.read(2), b"c") |
| 815 | self.assertEqual(rawio.read(2), b"d") |
| 816 | self.assertEqual(rawio.read(2), None) |
| 817 | self.assertEqual(rawio.read(2), b"ef") |
| 818 | self.assertEqual(rawio.read(2), b"g") |
| 819 | self.assertEqual(rawio.read(2), None) |
| 820 | self.assertEqual(rawio.read(2), b"") |
| 821 | |
Benjamin Peterson | f6f3a35 | 2011-09-03 09:26:20 -0400 | [diff] [blame] | 822 | def test_types_have_dict(self): |
| 823 | test = ( |
| 824 | self.IOBase(), |
| 825 | self.RawIOBase(), |
| 826 | self.TextIOBase(), |
| 827 | self.StringIO(), |
| 828 | self.BytesIO() |
| 829 | ) |
| 830 | for obj in test: |
| 831 | self.assertTrue(hasattr(obj, "__dict__")) |
| 832 | |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 833 | def test_opener(self): |
| 834 | with self.open(support.TESTFN, "w") as f: |
| 835 | f.write("egg\n") |
| 836 | fd = os.open(support.TESTFN, os.O_RDONLY) |
| 837 | def opener(path, flags): |
| 838 | return fd |
| 839 | with self.open("non-existent", "r", opener=opener) as f: |
| 840 | self.assertEqual(f.read(), "egg\n") |
| 841 | |
Barry Warsaw | 480e285 | 2016-06-08 17:47:26 -0400 | [diff] [blame] | 842 | def test_bad_opener_negative_1(self): |
| 843 | # Issue #27066. |
| 844 | def badopener(fname, flags): |
| 845 | return -1 |
| 846 | with self.assertRaises(ValueError) as cm: |
| 847 | open('non-existent', 'r', opener=badopener) |
| 848 | self.assertEqual(str(cm.exception), 'opener returned -1') |
| 849 | |
| 850 | def test_bad_opener_other_negative(self): |
| 851 | # Issue #27066. |
| 852 | def badopener(fname, flags): |
| 853 | return -2 |
| 854 | with self.assertRaises(ValueError) as cm: |
| 855 | open('non-existent', 'r', opener=badopener) |
| 856 | self.assertEqual(str(cm.exception), 'opener returned -2') |
| 857 | |
Hynek Schlawack | 2cc7156 | 2012-05-25 10:05:53 +0200 | [diff] [blame] | 858 | def test_fileio_closefd(self): |
| 859 | # Issue #4841 |
| 860 | with self.open(__file__, 'rb') as f1, \ |
| 861 | self.open(__file__, 'rb') as f2: |
| 862 | fileio = self.FileIO(f1.fileno(), closefd=False) |
| 863 | # .__init__() must not close f1 |
| 864 | fileio.__init__(f2.fileno(), closefd=False) |
| 865 | f1.readline() |
| 866 | # .close() must not close f2 |
| 867 | fileio.close() |
| 868 | f2.readline() |
| 869 | |
Serhiy Storchaka | f10063e | 2014-06-09 13:32:34 +0300 | [diff] [blame] | 870 | def test_nonbuffered_textio(self): |
Serhiy Storchaka | 94a619d | 2016-02-11 13:11:44 +0200 | [diff] [blame] | 871 | with support.check_no_resource_warning(self): |
Serhiy Storchaka | f10063e | 2014-06-09 13:32:34 +0300 | [diff] [blame] | 872 | with self.assertRaises(ValueError): |
| 873 | self.open(support.TESTFN, 'w', buffering=0) |
Serhiy Storchaka | f10063e | 2014-06-09 13:32:34 +0300 | [diff] [blame] | 874 | |
| 875 | def test_invalid_newline(self): |
Serhiy Storchaka | 94a619d | 2016-02-11 13:11:44 +0200 | [diff] [blame] | 876 | with support.check_no_resource_warning(self): |
Serhiy Storchaka | f10063e | 2014-06-09 13:32:34 +0300 | [diff] [blame] | 877 | with self.assertRaises(ValueError): |
| 878 | self.open(support.TESTFN, 'w', newline='invalid') |
Serhiy Storchaka | f10063e | 2014-06-09 13:32:34 +0300 | [diff] [blame] | 879 | |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 880 | def test_buffered_readinto_mixin(self): |
| 881 | # Test the implementation provided by BufferedIOBase |
| 882 | class Stream(self.BufferedIOBase): |
| 883 | def read(self, size): |
| 884 | return b"12345" |
| 885 | read1 = read |
| 886 | stream = Stream() |
| 887 | for method in ("readinto", "readinto1"): |
| 888 | with self.subTest(method): |
| 889 | buffer = byteslike(5) |
| 890 | self.assertEqual(getattr(stream, method)(buffer), 5) |
| 891 | self.assertEqual(bytes(buffer), b"12345") |
| 892 | |
Ethan Furman | d62548a | 2016-06-04 14:38:43 -0700 | [diff] [blame] | 893 | def test_fspath_support(self): |
| 894 | class PathLike: |
| 895 | def __init__(self, path): |
| 896 | self.path = path |
| 897 | |
| 898 | def __fspath__(self): |
| 899 | return self.path |
| 900 | |
| 901 | def check_path_succeeds(path): |
| 902 | with self.open(path, "w") as f: |
| 903 | f.write("egg\n") |
| 904 | |
| 905 | with self.open(path, "r") as f: |
| 906 | self.assertEqual(f.read(), "egg\n") |
| 907 | |
| 908 | check_path_succeeds(PathLike(support.TESTFN)) |
| 909 | check_path_succeeds(PathLike(support.TESTFN.encode('utf-8'))) |
| 910 | |
| 911 | bad_path = PathLike(TypeError) |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 912 | with self.assertRaises(TypeError): |
Ethan Furman | d62548a | 2016-06-04 14:38:43 -0700 | [diff] [blame] | 913 | self.open(bad_path, 'w') |
| 914 | |
| 915 | # ensure that refcounting is correct with some error conditions |
| 916 | with self.assertRaisesRegex(ValueError, 'read/write/append mode'): |
| 917 | self.open(PathLike(support.TESTFN), 'rwxa') |
| 918 | |
Sanyam Khurana | 1b74f9b | 2017-12-11 19:12:09 +0530 | [diff] [blame] | 919 | def test_RawIOBase_readall(self): |
| 920 | # Exercise the default unlimited RawIOBase.read() and readall() |
| 921 | # implementations. |
| 922 | rawio = self.MockRawIOWithoutRead((b"abc", b"d", b"efg")) |
| 923 | self.assertEqual(rawio.read(), b"abcdefg") |
| 924 | rawio = self.MockRawIOWithoutRead((b"abc", b"d", b"efg")) |
| 925 | self.assertEqual(rawio.readall(), b"abcdefg") |
| 926 | |
| 927 | def test_BufferedIOBase_readinto(self): |
| 928 | # Exercise the default BufferedIOBase.readinto() and readinto1() |
| 929 | # implementations (which call read() or read1() internally). |
| 930 | class Reader(self.BufferedIOBase): |
| 931 | def __init__(self, avail): |
| 932 | self.avail = avail |
| 933 | def read(self, size): |
| 934 | result = self.avail[:size] |
| 935 | self.avail = self.avail[size:] |
| 936 | return result |
| 937 | def read1(self, size): |
| 938 | """Returns no more than 5 bytes at once""" |
| 939 | return self.read(min(size, 5)) |
| 940 | tests = ( |
| 941 | # (test method, total data available, read buffer size, expected |
| 942 | # read size) |
| 943 | ("readinto", 10, 5, 5), |
| 944 | ("readinto", 10, 6, 6), # More than read1() can return |
| 945 | ("readinto", 5, 6, 5), # Buffer larger than total available |
| 946 | ("readinto", 6, 7, 6), |
| 947 | ("readinto", 10, 0, 0), # Empty buffer |
| 948 | ("readinto1", 10, 5, 5), # Result limited to single read1() call |
| 949 | ("readinto1", 10, 6, 5), # Buffer larger than read1() can return |
| 950 | ("readinto1", 5, 6, 5), # Buffer larger than total available |
| 951 | ("readinto1", 6, 7, 5), |
| 952 | ("readinto1", 10, 0, 0), # Empty buffer |
| 953 | ) |
| 954 | UNUSED_BYTE = 0x81 |
| 955 | for test in tests: |
| 956 | with self.subTest(test): |
| 957 | method, avail, request, result = test |
| 958 | reader = Reader(bytes(range(avail))) |
| 959 | buffer = bytearray((UNUSED_BYTE,) * request) |
| 960 | method = getattr(reader, method) |
| 961 | self.assertEqual(method(buffer), result) |
| 962 | self.assertEqual(len(buffer), request) |
| 963 | self.assertSequenceEqual(buffer[:result], range(result)) |
| 964 | unused = (UNUSED_BYTE,) * (request - result) |
| 965 | self.assertSequenceEqual(buffer[result:], unused) |
| 966 | self.assertEqual(len(reader.avail), avail - result) |
| 967 | |
Hynek Schlawack | 2cc7156 | 2012-05-25 10:05:53 +0200 | [diff] [blame] | 968 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 969 | class CIOTest(IOTest): |
Antoine Pitrou | 84f1b17 | 2011-07-12 21:57:15 +0200 | [diff] [blame] | 970 | |
| 971 | def test_IOBase_finalize(self): |
| 972 | # Issue #12149: segmentation fault on _PyIOBase_finalize when both a |
| 973 | # class which inherits IOBase and an object of this class are caught |
| 974 | # in a reference cycle and close() is already in the method cache. |
| 975 | class MyIO(self.IOBase): |
| 976 | def close(self): |
| 977 | pass |
| 978 | |
| 979 | # create an instance to populate the method cache |
| 980 | MyIO() |
| 981 | obj = MyIO() |
| 982 | obj.obj = obj |
| 983 | wr = weakref.ref(obj) |
| 984 | del MyIO |
| 985 | del obj |
| 986 | support.gc_collect() |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 987 | self.assertIsNone(wr(), wr) |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 988 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 989 | class PyIOTest(IOTest): |
| 990 | pass |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 991 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 992 | |
Gregory P. Smith | 1bef907 | 2015-04-14 13:24:34 -0700 | [diff] [blame] | 993 | @support.cpython_only |
| 994 | class APIMismatchTest(unittest.TestCase): |
Gregory P. Smith | 054b065 | 2015-04-14 12:58:05 -0700 | [diff] [blame] | 995 | |
Gregory P. Smith | 054b065 | 2015-04-14 12:58:05 -0700 | [diff] [blame] | 996 | def test_RawIOBase_io_in_pyio_match(self): |
| 997 | """Test that pyio RawIOBase class has all c RawIOBase methods""" |
Antoine Pitrou | 45d6156 | 2015-05-20 21:50:59 +0200 | [diff] [blame] | 998 | mismatch = support.detect_api_mismatch(pyio.RawIOBase, io.RawIOBase, |
| 999 | ignore=('__weakref__',)) |
Gregory P. Smith | 054b065 | 2015-04-14 12:58:05 -0700 | [diff] [blame] | 1000 | self.assertEqual(mismatch, set(), msg='Python RawIOBase does not have all C RawIOBase methods') |
| 1001 | |
| 1002 | def test_RawIOBase_pyio_in_io_match(self): |
| 1003 | """Test that c RawIOBase class has all pyio RawIOBase methods""" |
| 1004 | mismatch = support.detect_api_mismatch(io.RawIOBase, pyio.RawIOBase) |
| 1005 | self.assertEqual(mismatch, set(), msg='C RawIOBase does not have all Python RawIOBase methods') |
| 1006 | |
| 1007 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1008 | class CommonBufferedTests: |
| 1009 | # Tests common to BufferedReader, BufferedWriter and BufferedRandom |
| 1010 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 1011 | def test_detach(self): |
| 1012 | raw = self.MockRawIO() |
| 1013 | buf = self.tp(raw) |
| 1014 | self.assertIs(buf.detach(), raw) |
| 1015 | self.assertRaises(ValueError, buf.detach) |
| 1016 | |
Benjamin Peterson | 10e76b6 | 2014-12-21 20:51:50 -0600 | [diff] [blame] | 1017 | repr(buf) # Should still work |
| 1018 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1019 | def test_fileno(self): |
| 1020 | rawio = self.MockRawIO() |
| 1021 | bufio = self.tp(rawio) |
| 1022 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1023 | self.assertEqual(42, bufio.fileno()) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1024 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1025 | def test_invalid_args(self): |
| 1026 | rawio = self.MockRawIO() |
| 1027 | bufio = self.tp(rawio) |
| 1028 | # Invalid whence |
| 1029 | self.assertRaises(ValueError, bufio.seek, 0, -1) |
Jesus Cea | 9436361 | 2012-06-22 18:32:07 +0200 | [diff] [blame] | 1030 | self.assertRaises(ValueError, bufio.seek, 0, 9) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1031 | |
| 1032 | def test_override_destructor(self): |
| 1033 | tp = self.tp |
| 1034 | record = [] |
| 1035 | class MyBufferedIO(tp): |
| 1036 | def __del__(self): |
| 1037 | record.append(1) |
| 1038 | try: |
| 1039 | f = super().__del__ |
| 1040 | except AttributeError: |
| 1041 | pass |
| 1042 | else: |
| 1043 | f() |
| 1044 | def close(self): |
| 1045 | record.append(2) |
| 1046 | super().close() |
| 1047 | def flush(self): |
| 1048 | record.append(3) |
| 1049 | super().flush() |
| 1050 | rawio = self.MockRawIO() |
| 1051 | bufio = MyBufferedIO(rawio) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1052 | del bufio |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 1053 | support.gc_collect() |
Martin Panter | 754aab2 | 2016-03-31 07:21:56 +0000 | [diff] [blame] | 1054 | self.assertEqual(record, [1, 2, 3]) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1055 | |
| 1056 | def test_context_manager(self): |
| 1057 | # Test usability as a context manager |
| 1058 | rawio = self.MockRawIO() |
| 1059 | bufio = self.tp(rawio) |
| 1060 | def _with(): |
| 1061 | with bufio: |
| 1062 | pass |
| 1063 | _with() |
| 1064 | # bufio should now be closed, and using it a second time should raise |
| 1065 | # a ValueError. |
| 1066 | self.assertRaises(ValueError, _with) |
| 1067 | |
| 1068 | def test_error_through_destructor(self): |
| 1069 | # Test that the exception state is not modified by a destructor, |
| 1070 | # even if close() fails. |
| 1071 | rawio = self.CloseFailureIO() |
| 1072 | def f(): |
| 1073 | self.tp(rawio).xyzzy |
| 1074 | with support.captured_output("stderr") as s: |
| 1075 | self.assertRaises(AttributeError, f) |
| 1076 | s = s.getvalue().strip() |
| 1077 | if s: |
| 1078 | # The destructor *may* have printed an unraisable error, check it |
| 1079 | self.assertEqual(len(s.splitlines()), 1) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1080 | self.assertTrue(s.startswith("Exception OSError: "), s) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1081 | self.assertTrue(s.endswith(" ignored"), s) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1082 | |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 1083 | def test_repr(self): |
| 1084 | raw = self.MockRawIO() |
| 1085 | b = self.tp(raw) |
Serhiy Storchaka | 521e586 | 2014-07-22 15:00:37 +0300 | [diff] [blame] | 1086 | clsname = "%s.%s" % (self.tp.__module__, self.tp.__qualname__) |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 1087 | self.assertEqual(repr(b), "<%s>" % clsname) |
| 1088 | raw.name = "dummy" |
| 1089 | self.assertEqual(repr(b), "<%s name='dummy'>" % clsname) |
| 1090 | raw.name = b"dummy" |
| 1091 | self.assertEqual(repr(b), "<%s name=b'dummy'>" % clsname) |
| 1092 | |
Serhiy Storchaka | a5af6e1 | 2017-03-19 19:25:29 +0200 | [diff] [blame] | 1093 | def test_recursive_repr(self): |
| 1094 | # Issue #25455 |
| 1095 | raw = self.MockRawIO() |
| 1096 | b = self.tp(raw) |
| 1097 | with support.swap_attr(raw, 'name', b): |
| 1098 | try: |
| 1099 | repr(b) # Should not crash |
| 1100 | except RuntimeError: |
| 1101 | pass |
| 1102 | |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 1103 | def test_flush_error_on_close(self): |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 1104 | # Test that buffered file is closed despite failed flush |
| 1105 | # and that flush() is called before file closed. |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 1106 | raw = self.MockRawIO() |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 1107 | closed = [] |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 1108 | def bad_flush(): |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 1109 | closed[:] = [b.closed, raw.closed] |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1110 | raise OSError() |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 1111 | raw.flush = bad_flush |
| 1112 | b = self.tp(raw) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1113 | self.assertRaises(OSError, b.close) # exception not swallowed |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1114 | self.assertTrue(b.closed) |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 1115 | self.assertTrue(raw.closed) |
| 1116 | self.assertTrue(closed) # flush() called |
| 1117 | self.assertFalse(closed[0]) # flush() called before file closed |
| 1118 | self.assertFalse(closed[1]) |
Serhiy Storchaka | c26a1a4 | 2015-02-23 00:28:38 +0200 | [diff] [blame] | 1119 | raw.flush = lambda: None # break reference loop |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1120 | |
| 1121 | def test_close_error_on_close(self): |
| 1122 | raw = self.MockRawIO() |
| 1123 | def bad_flush(): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1124 | raise OSError('flush') |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1125 | def bad_close(): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1126 | raise OSError('close') |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1127 | raw.close = bad_close |
| 1128 | b = self.tp(raw) |
| 1129 | b.flush = bad_flush |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1130 | with self.assertRaises(OSError) as err: # exception not swallowed |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1131 | b.close() |
| 1132 | self.assertEqual(err.exception.args, ('close',)) |
Serhiy Storchaka | 8a8f7f9 | 2014-06-09 09:13:04 +0300 | [diff] [blame] | 1133 | self.assertIsInstance(err.exception.__context__, OSError) |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1134 | self.assertEqual(err.exception.__context__.args, ('flush',)) |
| 1135 | self.assertFalse(b.closed) |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 1136 | |
Serhiy Storchaka | 8a8f7f9 | 2014-06-09 09:13:04 +0300 | [diff] [blame] | 1137 | def test_nonnormalized_close_error_on_close(self): |
| 1138 | # Issue #21677 |
| 1139 | raw = self.MockRawIO() |
| 1140 | def bad_flush(): |
| 1141 | raise non_existing_flush |
| 1142 | def bad_close(): |
| 1143 | raise non_existing_close |
| 1144 | raw.close = bad_close |
| 1145 | b = self.tp(raw) |
| 1146 | b.flush = bad_flush |
| 1147 | with self.assertRaises(NameError) as err: # exception not swallowed |
| 1148 | b.close() |
| 1149 | self.assertIn('non_existing_close', str(err.exception)) |
| 1150 | self.assertIsInstance(err.exception.__context__, NameError) |
| 1151 | self.assertIn('non_existing_flush', str(err.exception.__context__)) |
| 1152 | self.assertFalse(b.closed) |
| 1153 | |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 1154 | def test_multi_close(self): |
| 1155 | raw = self.MockRawIO() |
| 1156 | b = self.tp(raw) |
| 1157 | b.close() |
| 1158 | b.close() |
| 1159 | b.close() |
| 1160 | self.assertRaises(ValueError, b.flush) |
| 1161 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 1162 | def test_unseekable(self): |
| 1163 | bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) |
| 1164 | self.assertRaises(self.UnsupportedOperation, bufio.tell) |
| 1165 | self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) |
| 1166 | |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 1167 | def test_readonly_attributes(self): |
| 1168 | raw = self.MockRawIO() |
| 1169 | buf = self.tp(raw) |
| 1170 | x = self.MockRawIO() |
| 1171 | with self.assertRaises(AttributeError): |
| 1172 | buf.raw = x |
| 1173 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1174 | |
Antoine Pitrou | 10f0c50 | 2012-07-29 19:02:46 +0200 | [diff] [blame] | 1175 | class SizeofTest: |
| 1176 | |
| 1177 | @support.cpython_only |
| 1178 | def test_sizeof(self): |
| 1179 | bufsize1 = 4096 |
| 1180 | bufsize2 = 8192 |
| 1181 | rawio = self.MockRawIO() |
| 1182 | bufio = self.tp(rawio, buffer_size=bufsize1) |
| 1183 | size = sys.getsizeof(bufio) - bufsize1 |
| 1184 | rawio = self.MockRawIO() |
| 1185 | bufio = self.tp(rawio, buffer_size=bufsize2) |
| 1186 | self.assertEqual(sys.getsizeof(bufio), size + bufsize2) |
| 1187 | |
Jesus Cea | dc46945 | 2012-10-04 12:37:56 +0200 | [diff] [blame] | 1188 | @support.cpython_only |
| 1189 | def test_buffer_freeing(self) : |
| 1190 | bufsize = 4096 |
| 1191 | rawio = self.MockRawIO() |
| 1192 | bufio = self.tp(rawio, buffer_size=bufsize) |
| 1193 | size = sys.getsizeof(bufio) - bufsize |
| 1194 | bufio.close() |
| 1195 | self.assertEqual(sys.getsizeof(bufio), size) |
Antoine Pitrou | 10f0c50 | 2012-07-29 19:02:46 +0200 | [diff] [blame] | 1196 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1197 | class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): |
| 1198 | read_mode = "rb" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1199 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1200 | def test_constructor(self): |
| 1201 | rawio = self.MockRawIO([b"abc"]) |
| 1202 | bufio = self.tp(rawio) |
| 1203 | bufio.__init__(rawio) |
| 1204 | bufio.__init__(rawio, buffer_size=1024) |
| 1205 | bufio.__init__(rawio, buffer_size=16) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1206 | self.assertEqual(b"abc", bufio.read()) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1207 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) |
| 1208 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) |
| 1209 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) |
| 1210 | rawio = self.MockRawIO([b"abc"]) |
| 1211 | bufio.__init__(rawio) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1212 | self.assertEqual(b"abc", bufio.read()) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1213 | |
Serhiy Storchaka | 61e2493 | 2014-02-12 10:52:35 +0200 | [diff] [blame] | 1214 | def test_uninitialized(self): |
| 1215 | bufio = self.tp.__new__(self.tp) |
| 1216 | del bufio |
| 1217 | bufio = self.tp.__new__(self.tp) |
| 1218 | self.assertRaisesRegex((ValueError, AttributeError), |
| 1219 | 'uninitialized|has no attribute', |
| 1220 | bufio.read, 0) |
| 1221 | bufio.__init__(self.MockRawIO()) |
| 1222 | self.assertEqual(bufio.read(0), b'') |
| 1223 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1224 | def test_read(self): |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 1225 | for arg in (None, 7): |
| 1226 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 1227 | bufio = self.tp(rawio) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1228 | self.assertEqual(b"abcdefg", bufio.read(arg)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1229 | # Invalid args |
| 1230 | self.assertRaises(ValueError, bufio.read, -2) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1231 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1232 | def test_read1(self): |
| 1233 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 1234 | bufio = self.tp(rawio) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1235 | self.assertEqual(b"a", bufio.read(1)) |
| 1236 | self.assertEqual(b"b", bufio.read1(1)) |
| 1237 | self.assertEqual(rawio._reads, 1) |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 1238 | self.assertEqual(b"", bufio.read1(0)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1239 | self.assertEqual(b"c", bufio.read1(100)) |
| 1240 | self.assertEqual(rawio._reads, 1) |
| 1241 | self.assertEqual(b"d", bufio.read1(100)) |
| 1242 | self.assertEqual(rawio._reads, 2) |
| 1243 | self.assertEqual(b"efg", bufio.read1(100)) |
| 1244 | self.assertEqual(rawio._reads, 3) |
| 1245 | self.assertEqual(b"", bufio.read1(100)) |
| 1246 | self.assertEqual(rawio._reads, 4) |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 1247 | |
| 1248 | def test_read1_arbitrary(self): |
| 1249 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 1250 | bufio = self.tp(rawio) |
| 1251 | self.assertEqual(b"a", bufio.read(1)) |
| 1252 | self.assertEqual(b"bc", bufio.read1()) |
| 1253 | self.assertEqual(b"d", bufio.read1()) |
| 1254 | self.assertEqual(b"efg", bufio.read1(-1)) |
| 1255 | self.assertEqual(rawio._reads, 3) |
| 1256 | self.assertEqual(b"", bufio.read1()) |
| 1257 | self.assertEqual(rawio._reads, 4) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1258 | |
| 1259 | def test_readinto(self): |
| 1260 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 1261 | bufio = self.tp(rawio) |
| 1262 | b = bytearray(2) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1263 | self.assertEqual(bufio.readinto(b), 2) |
| 1264 | self.assertEqual(b, b"ab") |
| 1265 | self.assertEqual(bufio.readinto(b), 2) |
| 1266 | self.assertEqual(b, b"cd") |
| 1267 | self.assertEqual(bufio.readinto(b), 2) |
| 1268 | self.assertEqual(b, b"ef") |
| 1269 | self.assertEqual(bufio.readinto(b), 1) |
| 1270 | self.assertEqual(b, b"gf") |
| 1271 | self.assertEqual(bufio.readinto(b), 0) |
| 1272 | self.assertEqual(b, b"gf") |
Antoine Pitrou | 3486a98 | 2011-05-12 01:57:53 +0200 | [diff] [blame] | 1273 | rawio = self.MockRawIO((b"abc", None)) |
| 1274 | bufio = self.tp(rawio) |
| 1275 | self.assertEqual(bufio.readinto(b), 2) |
| 1276 | self.assertEqual(b, b"ab") |
| 1277 | self.assertEqual(bufio.readinto(b), 1) |
| 1278 | self.assertEqual(b, b"cb") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1279 | |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 1280 | def test_readinto1(self): |
| 1281 | buffer_size = 10 |
| 1282 | rawio = self.MockRawIO((b"abc", b"de", b"fgh", b"jkl")) |
| 1283 | bufio = self.tp(rawio, buffer_size=buffer_size) |
| 1284 | b = bytearray(2) |
| 1285 | self.assertEqual(bufio.peek(3), b'abc') |
| 1286 | self.assertEqual(rawio._reads, 1) |
| 1287 | self.assertEqual(bufio.readinto1(b), 2) |
| 1288 | self.assertEqual(b, b"ab") |
| 1289 | self.assertEqual(rawio._reads, 1) |
| 1290 | self.assertEqual(bufio.readinto1(b), 1) |
| 1291 | self.assertEqual(b[:1], b"c") |
| 1292 | self.assertEqual(rawio._reads, 1) |
| 1293 | self.assertEqual(bufio.readinto1(b), 2) |
| 1294 | self.assertEqual(b, b"de") |
| 1295 | self.assertEqual(rawio._reads, 2) |
| 1296 | b = bytearray(2*buffer_size) |
| 1297 | self.assertEqual(bufio.peek(3), b'fgh') |
| 1298 | self.assertEqual(rawio._reads, 3) |
| 1299 | self.assertEqual(bufio.readinto1(b), 6) |
| 1300 | self.assertEqual(b[:6], b"fghjkl") |
| 1301 | self.assertEqual(rawio._reads, 4) |
| 1302 | |
| 1303 | def test_readinto_array(self): |
| 1304 | buffer_size = 60 |
| 1305 | data = b"a" * 26 |
| 1306 | rawio = self.MockRawIO((data,)) |
| 1307 | bufio = self.tp(rawio, buffer_size=buffer_size) |
| 1308 | |
| 1309 | # Create an array with element size > 1 byte |
| 1310 | b = array.array('i', b'x' * 32) |
| 1311 | assert len(b) != 16 |
| 1312 | |
| 1313 | # Read into it. We should get as many *bytes* as we can fit into b |
| 1314 | # (which is more than the number of elements) |
| 1315 | n = bufio.readinto(b) |
| 1316 | self.assertGreater(n, len(b)) |
| 1317 | |
| 1318 | # Check that old contents of b are preserved |
| 1319 | bm = memoryview(b).cast('B') |
| 1320 | self.assertLess(n, len(bm)) |
| 1321 | self.assertEqual(bm[:n], data[:n]) |
| 1322 | self.assertEqual(bm[n:], b'x' * (len(bm[n:]))) |
| 1323 | |
| 1324 | def test_readinto1_array(self): |
| 1325 | buffer_size = 60 |
| 1326 | data = b"a" * 26 |
| 1327 | rawio = self.MockRawIO((data,)) |
| 1328 | bufio = self.tp(rawio, buffer_size=buffer_size) |
| 1329 | |
| 1330 | # Create an array with element size > 1 byte |
| 1331 | b = array.array('i', b'x' * 32) |
| 1332 | assert len(b) != 16 |
| 1333 | |
| 1334 | # Read into it. We should get as many *bytes* as we can fit into b |
| 1335 | # (which is more than the number of elements) |
| 1336 | n = bufio.readinto1(b) |
| 1337 | self.assertGreater(n, len(b)) |
| 1338 | |
| 1339 | # Check that old contents of b are preserved |
| 1340 | bm = memoryview(b).cast('B') |
| 1341 | self.assertLess(n, len(bm)) |
| 1342 | self.assertEqual(bm[:n], data[:n]) |
| 1343 | self.assertEqual(bm[n:], b'x' * (len(bm[n:]))) |
| 1344 | |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 1345 | def test_readlines(self): |
| 1346 | def bufio(): |
| 1347 | rawio = self.MockRawIO((b"abc\n", b"d\n", b"ef")) |
| 1348 | return self.tp(rawio) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1349 | self.assertEqual(bufio().readlines(), [b"abc\n", b"d\n", b"ef"]) |
| 1350 | self.assertEqual(bufio().readlines(5), [b"abc\n", b"d\n"]) |
| 1351 | self.assertEqual(bufio().readlines(None), [b"abc\n", b"d\n", b"ef"]) |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 1352 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1353 | def test_buffering(self): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1354 | data = b"abcdefghi" |
| 1355 | dlen = len(data) |
| 1356 | |
| 1357 | tests = [ |
| 1358 | [ 100, [ 3, 1, 4, 8 ], [ dlen, 0 ] ], |
| 1359 | [ 100, [ 3, 3, 3], [ dlen ] ], |
| 1360 | [ 4, [ 1, 2, 4, 2 ], [ 4, 4, 1 ] ], |
| 1361 | ] |
| 1362 | |
| 1363 | for bufsize, buf_read_sizes, raw_read_sizes in tests: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1364 | rawio = self.MockFileIO(data) |
| 1365 | bufio = self.tp(rawio, buffer_size=bufsize) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1366 | pos = 0 |
| 1367 | for nbytes in buf_read_sizes: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1368 | self.assertEqual(bufio.read(nbytes), data[pos:pos+nbytes]) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1369 | pos += nbytes |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1370 | # this is mildly implementation-dependent |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1371 | self.assertEqual(rawio.read_history, raw_read_sizes) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1372 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1373 | def test_read_non_blocking(self): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1374 | # Inject some None's in there to simulate EWOULDBLOCK |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1375 | rawio = self.MockRawIO((b"abc", b"d", None, b"efg", None, None, None)) |
| 1376 | bufio = self.tp(rawio) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1377 | self.assertEqual(b"abcd", bufio.read(6)) |
| 1378 | self.assertEqual(b"e", bufio.read(1)) |
| 1379 | self.assertEqual(b"fg", bufio.read()) |
| 1380 | self.assertEqual(b"", bufio.peek(1)) |
Victor Stinner | a80987f | 2011-05-25 22:47:16 +0200 | [diff] [blame] | 1381 | self.assertIsNone(bufio.read()) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1382 | self.assertEqual(b"", bufio.read()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1383 | |
Victor Stinner | a80987f | 2011-05-25 22:47:16 +0200 | [diff] [blame] | 1384 | rawio = self.MockRawIO((b"a", None, None)) |
| 1385 | self.assertEqual(b"a", rawio.readall()) |
| 1386 | self.assertIsNone(rawio.readall()) |
| 1387 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1388 | def test_read_past_eof(self): |
| 1389 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 1390 | bufio = self.tp(rawio) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1391 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1392 | self.assertEqual(b"abcdefg", bufio.read(9000)) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1393 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1394 | def test_read_all(self): |
| 1395 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 1396 | bufio = self.tp(rawio) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1397 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1398 | self.assertEqual(b"abcdefg", bufio.read()) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1399 | |
Antoine Pitrou | 5bc4fa7 | 2010-10-14 15:34:31 +0000 | [diff] [blame] | 1400 | @support.requires_resource('cpu') |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1401 | def test_threads(self): |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1402 | try: |
| 1403 | # Write out many bytes with exactly the same number of 0's, |
| 1404 | # 1's... 255's. This will help us check that concurrent reading |
| 1405 | # doesn't duplicate or forget contents. |
| 1406 | N = 1000 |
| 1407 | l = list(range(256)) * N |
| 1408 | random.shuffle(l) |
| 1409 | s = bytes(bytearray(l)) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1410 | with self.open(support.TESTFN, "wb") as f: |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1411 | f.write(s) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1412 | with self.open(support.TESTFN, self.read_mode, buffering=0) as raw: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1413 | bufio = self.tp(raw, 8) |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1414 | errors = [] |
| 1415 | results = [] |
| 1416 | def f(): |
| 1417 | try: |
| 1418 | # Intra-buffer read then buffer-flushing read |
| 1419 | for n in cycle([1, 19]): |
| 1420 | s = bufio.read(n) |
| 1421 | if not s: |
| 1422 | break |
| 1423 | # list.append() is atomic |
| 1424 | results.append(s) |
| 1425 | except Exception as e: |
| 1426 | errors.append(e) |
| 1427 | raise |
| 1428 | threads = [threading.Thread(target=f) for x in range(20)] |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 1429 | with support.start_threads(threads): |
| 1430 | time.sleep(0.02) # yield |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1431 | self.assertFalse(errors, |
| 1432 | "the following exceptions were caught: %r" % errors) |
| 1433 | s = b''.join(results) |
| 1434 | for i in range(256): |
| 1435 | c = bytes(bytearray([i])) |
| 1436 | self.assertEqual(s.count(c), N) |
| 1437 | finally: |
| 1438 | support.unlink(support.TESTFN) |
| 1439 | |
Antoine Pitrou | 1e44fec | 2011-10-04 12:26:20 +0200 | [diff] [blame] | 1440 | def test_unseekable(self): |
| 1441 | bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) |
| 1442 | self.assertRaises(self.UnsupportedOperation, bufio.tell) |
| 1443 | self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) |
| 1444 | bufio.read(1) |
| 1445 | self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) |
| 1446 | self.assertRaises(self.UnsupportedOperation, bufio.tell) |
| 1447 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1448 | def test_misbehaved_io(self): |
| 1449 | rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) |
| 1450 | bufio = self.tp(rawio) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1451 | self.assertRaises(OSError, bufio.seek, 0) |
| 1452 | self.assertRaises(OSError, bufio.tell) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1453 | |
Antoine Pitrou | 32cfede | 2010-08-11 13:31:33 +0000 | [diff] [blame] | 1454 | def test_no_extraneous_read(self): |
| 1455 | # Issue #9550; when the raw IO object has satisfied the read request, |
| 1456 | # we should not issue any additional reads, otherwise it may block |
| 1457 | # (e.g. socket). |
| 1458 | bufsize = 16 |
| 1459 | for n in (2, bufsize - 1, bufsize, bufsize + 1, bufsize * 2): |
| 1460 | rawio = self.MockRawIO([b"x" * n]) |
| 1461 | bufio = self.tp(rawio, bufsize) |
| 1462 | self.assertEqual(bufio.read(n), b"x" * n) |
| 1463 | # Simple case: one raw read is enough to satisfy the request. |
| 1464 | self.assertEqual(rawio._extraneous_reads, 0, |
| 1465 | "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) |
| 1466 | # A more complex case where two raw reads are needed to satisfy |
| 1467 | # the request. |
| 1468 | rawio = self.MockRawIO([b"x" * (n - 1), b"x"]) |
| 1469 | bufio = self.tp(rawio, bufsize) |
| 1470 | self.assertEqual(bufio.read(n), b"x" * n) |
| 1471 | self.assertEqual(rawio._extraneous_reads, 0, |
| 1472 | "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) |
| 1473 | |
Berker Peksag | d10d6ae | 2015-05-12 17:01:05 +0300 | [diff] [blame] | 1474 | def test_read_on_closed(self): |
| 1475 | # Issue #23796 |
| 1476 | b = io.BufferedReader(io.BytesIO(b"12")) |
| 1477 | b.read(1) |
| 1478 | b.close() |
| 1479 | self.assertRaises(ValueError, b.peek) |
| 1480 | self.assertRaises(ValueError, b.read1, 1) |
| 1481 | |
Antoine Pitrou | 32cfede | 2010-08-11 13:31:33 +0000 | [diff] [blame] | 1482 | |
Antoine Pitrou | 10f0c50 | 2012-07-29 19:02:46 +0200 | [diff] [blame] | 1483 | class CBufferedReaderTest(BufferedReaderTest, SizeofTest): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1484 | tp = io.BufferedReader |
| 1485 | |
| 1486 | def test_constructor(self): |
| 1487 | BufferedReaderTest.test_constructor(self) |
| 1488 | # The allocation can succeed on 32-bit builds, e.g. with more |
Victor Stinner | 8c663fd | 2017-11-08 14:44:44 -0800 | [diff] [blame] | 1489 | # than 2 GiB RAM and a 64-bit kernel. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1490 | if sys.maxsize > 0x7FFFFFFF: |
| 1491 | rawio = self.MockRawIO() |
| 1492 | bufio = self.tp(rawio) |
| 1493 | self.assertRaises((OverflowError, MemoryError, ValueError), |
| 1494 | bufio.__init__, rawio, sys.maxsize) |
| 1495 | |
| 1496 | def test_initialization(self): |
| 1497 | rawio = self.MockRawIO([b"abc"]) |
| 1498 | bufio = self.tp(rawio) |
| 1499 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) |
| 1500 | self.assertRaises(ValueError, bufio.read) |
| 1501 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) |
| 1502 | self.assertRaises(ValueError, bufio.read) |
| 1503 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) |
| 1504 | self.assertRaises(ValueError, bufio.read) |
| 1505 | |
| 1506 | def test_misbehaved_io_read(self): |
| 1507 | rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) |
| 1508 | bufio = self.tp(rawio) |
| 1509 | # _pyio.BufferedReader seems to implement reading different, so that |
| 1510 | # checking this is not so easy. |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1511 | self.assertRaises(OSError, bufio.read, 10) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1512 | |
| 1513 | def test_garbage_collection(self): |
| 1514 | # C BufferedReader objects are collected. |
| 1515 | # The Python version has __del__, so it ends into gc.garbage instead |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 1516 | with support.check_warnings(('', ResourceWarning)): |
| 1517 | rawio = self.FileIO(support.TESTFN, "w+b") |
| 1518 | f = self.tp(rawio) |
| 1519 | f.f = f |
| 1520 | wr = weakref.ref(f) |
| 1521 | del f |
| 1522 | support.gc_collect() |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 1523 | self.assertIsNone(wr(), wr) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1524 | |
R David Murray | 67bfe80 | 2013-02-23 21:51:05 -0500 | [diff] [blame] | 1525 | def test_args_error(self): |
| 1526 | # Issue #17275 |
| 1527 | with self.assertRaisesRegex(TypeError, "BufferedReader"): |
| 1528 | self.tp(io.BytesIO(), 1024, 1024, 1024) |
| 1529 | |
| 1530 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1531 | class PyBufferedReaderTest(BufferedReaderTest): |
| 1532 | tp = pyio.BufferedReader |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1533 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 1534 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1535 | class BufferedWriterTest(unittest.TestCase, CommonBufferedTests): |
| 1536 | write_mode = "wb" |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 1537 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1538 | def test_constructor(self): |
| 1539 | rawio = self.MockRawIO() |
| 1540 | bufio = self.tp(rawio) |
| 1541 | bufio.__init__(rawio) |
| 1542 | bufio.__init__(rawio, buffer_size=1024) |
| 1543 | bufio.__init__(rawio, buffer_size=16) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1544 | self.assertEqual(3, bufio.write(b"abc")) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1545 | bufio.flush() |
| 1546 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) |
| 1547 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) |
| 1548 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) |
| 1549 | bufio.__init__(rawio) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1550 | self.assertEqual(3, bufio.write(b"ghi")) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1551 | bufio.flush() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1552 | self.assertEqual(b"".join(rawio._write_stack), b"abcghi") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1553 | |
Serhiy Storchaka | 61e2493 | 2014-02-12 10:52:35 +0200 | [diff] [blame] | 1554 | def test_uninitialized(self): |
| 1555 | bufio = self.tp.__new__(self.tp) |
| 1556 | del bufio |
| 1557 | bufio = self.tp.__new__(self.tp) |
| 1558 | self.assertRaisesRegex((ValueError, AttributeError), |
| 1559 | 'uninitialized|has no attribute', |
| 1560 | bufio.write, b'') |
| 1561 | bufio.__init__(self.MockRawIO()) |
| 1562 | self.assertEqual(bufio.write(b''), 0) |
| 1563 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 1564 | def test_detach_flush(self): |
| 1565 | raw = self.MockRawIO() |
| 1566 | buf = self.tp(raw) |
| 1567 | buf.write(b"howdy!") |
| 1568 | self.assertFalse(raw._write_stack) |
| 1569 | buf.detach() |
| 1570 | self.assertEqual(raw._write_stack, [b"howdy!"]) |
| 1571 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1572 | def test_write(self): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1573 | # Write to the buffered IO but don't overflow the buffer. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1574 | writer = self.MockRawIO() |
| 1575 | bufio = self.tp(writer, 8) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1576 | bufio.write(b"abc") |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1577 | self.assertFalse(writer._write_stack) |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 1578 | buffer = bytearray(b"def") |
| 1579 | bufio.write(buffer) |
| 1580 | buffer[:] = b"***" # Overwrite our copy of the data |
| 1581 | bufio.flush() |
| 1582 | self.assertEqual(b"".join(writer._write_stack), b"abcdef") |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1583 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1584 | def test_write_overflow(self): |
| 1585 | writer = self.MockRawIO() |
| 1586 | bufio = self.tp(writer, 8) |
| 1587 | contents = b"abcdefghijklmnop" |
| 1588 | for n in range(0, len(contents), 3): |
| 1589 | bufio.write(contents[n:n+3]) |
| 1590 | flushed = b"".join(writer._write_stack) |
| 1591 | # At least (total - 8) bytes were implicitly flushed, perhaps more |
| 1592 | # depending on the implementation. |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1593 | self.assertTrue(flushed.startswith(contents[:-8]), flushed) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1594 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1595 | def check_writes(self, intermediate_func): |
| 1596 | # Lots of writes, test the flushed output is as expected. |
| 1597 | contents = bytes(range(256)) * 1000 |
| 1598 | n = 0 |
| 1599 | writer = self.MockRawIO() |
| 1600 | bufio = self.tp(writer, 13) |
| 1601 | # Generator of write sizes: repeat each N 15 times then proceed to N+1 |
| 1602 | def gen_sizes(): |
| 1603 | for size in count(1): |
| 1604 | for i in range(15): |
| 1605 | yield size |
| 1606 | sizes = gen_sizes() |
| 1607 | while n < len(contents): |
| 1608 | size = min(next(sizes), len(contents) - n) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1609 | self.assertEqual(bufio.write(contents[n:n+size]), size) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1610 | intermediate_func(bufio) |
| 1611 | n += size |
| 1612 | bufio.flush() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1613 | self.assertEqual(contents, b"".join(writer._write_stack)) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1614 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1615 | def test_writes(self): |
| 1616 | self.check_writes(lambda bufio: None) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1617 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1618 | def test_writes_and_flushes(self): |
| 1619 | self.check_writes(lambda bufio: bufio.flush()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1620 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1621 | def test_writes_and_seeks(self): |
| 1622 | def _seekabs(bufio): |
| 1623 | pos = bufio.tell() |
| 1624 | bufio.seek(pos + 1, 0) |
| 1625 | bufio.seek(pos - 1, 0) |
| 1626 | bufio.seek(pos, 0) |
| 1627 | self.check_writes(_seekabs) |
| 1628 | def _seekrel(bufio): |
| 1629 | pos = bufio.seek(0, 1) |
| 1630 | bufio.seek(+1, 1) |
| 1631 | bufio.seek(-1, 1) |
| 1632 | bufio.seek(pos, 0) |
| 1633 | self.check_writes(_seekrel) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1634 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1635 | def test_writes_and_truncates(self): |
| 1636 | self.check_writes(lambda bufio: bufio.truncate(bufio.tell())) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1637 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1638 | def test_write_non_blocking(self): |
| 1639 | raw = self.MockNonBlockWriterIO() |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1640 | bufio = self.tp(raw, 8) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1641 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1642 | self.assertEqual(bufio.write(b"abcd"), 4) |
| 1643 | self.assertEqual(bufio.write(b"efghi"), 5) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1644 | # 1 byte will be written, the rest will be buffered |
| 1645 | raw.block_on(b"k") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1646 | self.assertEqual(bufio.write(b"jklmn"), 5) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1647 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1648 | # 8 bytes will be written, 8 will be buffered and the rest will be lost |
| 1649 | raw.block_on(b"0") |
| 1650 | try: |
| 1651 | bufio.write(b"opqrwxyz0123456789") |
| 1652 | except self.BlockingIOError as e: |
| 1653 | written = e.characters_written |
| 1654 | else: |
| 1655 | self.fail("BlockingIOError should have been raised") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1656 | self.assertEqual(written, 16) |
| 1657 | self.assertEqual(raw.pop_written(), |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1658 | b"abcdefghijklmnopqrwxyz") |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1659 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1660 | self.assertEqual(bufio.write(b"ABCDEFGHI"), 9) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1661 | s = raw.pop_written() |
| 1662 | # Previously buffered bytes were flushed |
| 1663 | self.assertTrue(s.startswith(b"01234567A"), s) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1664 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1665 | def test_write_and_rewind(self): |
| 1666 | raw = io.BytesIO() |
| 1667 | bufio = self.tp(raw, 4) |
| 1668 | self.assertEqual(bufio.write(b"abcdef"), 6) |
| 1669 | self.assertEqual(bufio.tell(), 6) |
| 1670 | bufio.seek(0, 0) |
| 1671 | self.assertEqual(bufio.write(b"XY"), 2) |
| 1672 | bufio.seek(6, 0) |
| 1673 | self.assertEqual(raw.getvalue(), b"XYcdef") |
| 1674 | self.assertEqual(bufio.write(b"123456"), 6) |
| 1675 | bufio.flush() |
| 1676 | self.assertEqual(raw.getvalue(), b"XYcdef123456") |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1677 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1678 | def test_flush(self): |
| 1679 | writer = self.MockRawIO() |
| 1680 | bufio = self.tp(writer, 8) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1681 | bufio.write(b"abc") |
| 1682 | bufio.flush() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1683 | self.assertEqual(b"abc", writer._write_stack[0]) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1684 | |
Antoine Pitrou | 131a489 | 2012-10-16 22:57:11 +0200 | [diff] [blame] | 1685 | def test_writelines(self): |
| 1686 | l = [b'ab', b'cd', b'ef'] |
| 1687 | writer = self.MockRawIO() |
| 1688 | bufio = self.tp(writer, 8) |
| 1689 | bufio.writelines(l) |
| 1690 | bufio.flush() |
| 1691 | self.assertEqual(b''.join(writer._write_stack), b'abcdef') |
| 1692 | |
| 1693 | def test_writelines_userlist(self): |
| 1694 | l = UserList([b'ab', b'cd', b'ef']) |
| 1695 | writer = self.MockRawIO() |
| 1696 | bufio = self.tp(writer, 8) |
| 1697 | bufio.writelines(l) |
| 1698 | bufio.flush() |
| 1699 | self.assertEqual(b''.join(writer._write_stack), b'abcdef') |
| 1700 | |
| 1701 | def test_writelines_error(self): |
| 1702 | writer = self.MockRawIO() |
| 1703 | bufio = self.tp(writer, 8) |
| 1704 | self.assertRaises(TypeError, bufio.writelines, [1, 2, 3]) |
| 1705 | self.assertRaises(TypeError, bufio.writelines, None) |
| 1706 | self.assertRaises(TypeError, bufio.writelines, 'abc') |
| 1707 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1708 | def test_destructor(self): |
| 1709 | writer = self.MockRawIO() |
| 1710 | bufio = self.tp(writer, 8) |
| 1711 | bufio.write(b"abc") |
| 1712 | del bufio |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 1713 | support.gc_collect() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1714 | self.assertEqual(b"abc", writer._write_stack[0]) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1715 | |
| 1716 | def test_truncate(self): |
| 1717 | # Truncate implicitly flushes the buffer. |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1718 | with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1719 | bufio = self.tp(raw, 8) |
| 1720 | bufio.write(b"abcdef") |
| 1721 | self.assertEqual(bufio.truncate(3), 3) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 1722 | self.assertEqual(bufio.tell(), 6) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1723 | with self.open(support.TESTFN, "rb", buffering=0) as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1724 | self.assertEqual(f.read(), b"abc") |
| 1725 | |
Nitish Chandra | 059f58c | 2018-01-28 21:30:09 +0530 | [diff] [blame] | 1726 | def test_truncate_after_write(self): |
| 1727 | # Ensure that truncate preserves the file position after |
| 1728 | # writes longer than the buffer size. |
| 1729 | # Issue: https://bugs.python.org/issue32228 |
| 1730 | with self.open(support.TESTFN, "wb") as f: |
| 1731 | # Fill with some buffer |
| 1732 | f.write(b'\x00' * 10000) |
| 1733 | buffer_sizes = [8192, 4096, 200] |
| 1734 | for buffer_size in buffer_sizes: |
| 1735 | with self.open(support.TESTFN, "r+b", buffering=buffer_size) as f: |
| 1736 | f.write(b'\x00' * (buffer_size + 1)) |
| 1737 | # After write write_pos and write_end are set to 0 |
| 1738 | f.read(1) |
| 1739 | # read operation makes sure that pos != raw_pos |
| 1740 | f.truncate() |
| 1741 | self.assertEqual(f.tell(), buffer_size + 2) |
| 1742 | |
Antoine Pitrou | 5bc4fa7 | 2010-10-14 15:34:31 +0000 | [diff] [blame] | 1743 | @support.requires_resource('cpu') |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1744 | def test_threads(self): |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1745 | try: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1746 | # Write out many bytes from many threads and test they were |
| 1747 | # all flushed. |
| 1748 | N = 1000 |
| 1749 | contents = bytes(range(256)) * N |
| 1750 | sizes = cycle([1, 19]) |
| 1751 | n = 0 |
| 1752 | queue = deque() |
| 1753 | while n < len(contents): |
| 1754 | size = next(sizes) |
| 1755 | queue.append(contents[n:n+size]) |
| 1756 | n += size |
| 1757 | del contents |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1758 | # We use a real file object because it allows us to |
| 1759 | # exercise situations where the GIL is released before |
| 1760 | # writing the buffer to the raw streams. This is in addition |
| 1761 | # to concurrency issues due to switching threads in the middle |
| 1762 | # of Python code. |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1763 | with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1764 | bufio = self.tp(raw, 8) |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1765 | errors = [] |
| 1766 | def f(): |
| 1767 | try: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1768 | while True: |
| 1769 | try: |
| 1770 | s = queue.popleft() |
| 1771 | except IndexError: |
| 1772 | return |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1773 | bufio.write(s) |
| 1774 | except Exception as e: |
| 1775 | errors.append(e) |
| 1776 | raise |
| 1777 | threads = [threading.Thread(target=f) for x in range(20)] |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 1778 | with support.start_threads(threads): |
| 1779 | time.sleep(0.02) # yield |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1780 | self.assertFalse(errors, |
| 1781 | "the following exceptions were caught: %r" % errors) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1782 | bufio.close() |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1783 | with self.open(support.TESTFN, "rb") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1784 | s = f.read() |
| 1785 | for i in range(256): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1786 | self.assertEqual(s.count(bytes([i])), N) |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1787 | finally: |
| 1788 | support.unlink(support.TESTFN) |
| 1789 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1790 | def test_misbehaved_io(self): |
| 1791 | rawio = self.MisbehavedRawIO() |
| 1792 | bufio = self.tp(rawio, 5) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1793 | self.assertRaises(OSError, bufio.seek, 0) |
| 1794 | self.assertRaises(OSError, bufio.tell) |
| 1795 | self.assertRaises(OSError, bufio.write, b"abcdef") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1796 | |
Florent Xicluna | 109d573 | 2012-07-07 17:03:22 +0200 | [diff] [blame] | 1797 | def test_max_buffer_size_removal(self): |
| 1798 | with self.assertRaises(TypeError): |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1799 | self.tp(self.MockRawIO(), 8, 12) |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1800 | |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1801 | def test_write_error_on_close(self): |
| 1802 | raw = self.MockRawIO() |
| 1803 | def bad_write(b): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1804 | raise OSError() |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1805 | raw.write = bad_write |
| 1806 | b = self.tp(raw) |
| 1807 | b.write(b'spam') |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1808 | self.assertRaises(OSError, b.close) # exception not swallowed |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 1809 | self.assertTrue(b.closed) |
| 1810 | |
benfogle | 9703f09 | 2017-11-10 16:03:40 -0500 | [diff] [blame] | 1811 | def test_slow_close_from_thread(self): |
| 1812 | # Issue #31976 |
| 1813 | rawio = self.SlowFlushRawIO() |
| 1814 | bufio = self.tp(rawio, 8) |
| 1815 | t = threading.Thread(target=bufio.close) |
| 1816 | t.start() |
| 1817 | rawio.in_flush.wait() |
| 1818 | self.assertRaises(ValueError, bufio.write, b'spam') |
| 1819 | self.assertTrue(bufio.closed) |
| 1820 | t.join() |
| 1821 | |
| 1822 | |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1823 | |
Antoine Pitrou | 10f0c50 | 2012-07-29 19:02:46 +0200 | [diff] [blame] | 1824 | class CBufferedWriterTest(BufferedWriterTest, SizeofTest): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1825 | tp = io.BufferedWriter |
| 1826 | |
| 1827 | def test_constructor(self): |
| 1828 | BufferedWriterTest.test_constructor(self) |
| 1829 | # The allocation can succeed on 32-bit builds, e.g. with more |
Victor Stinner | 8c663fd | 2017-11-08 14:44:44 -0800 | [diff] [blame] | 1830 | # than 2 GiB RAM and a 64-bit kernel. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1831 | if sys.maxsize > 0x7FFFFFFF: |
| 1832 | rawio = self.MockRawIO() |
| 1833 | bufio = self.tp(rawio) |
| 1834 | self.assertRaises((OverflowError, MemoryError, ValueError), |
| 1835 | bufio.__init__, rawio, sys.maxsize) |
| 1836 | |
| 1837 | def test_initialization(self): |
| 1838 | rawio = self.MockRawIO() |
| 1839 | bufio = self.tp(rawio) |
| 1840 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) |
| 1841 | self.assertRaises(ValueError, bufio.write, b"def") |
| 1842 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) |
| 1843 | self.assertRaises(ValueError, bufio.write, b"def") |
| 1844 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) |
| 1845 | self.assertRaises(ValueError, bufio.write, b"def") |
| 1846 | |
| 1847 | def test_garbage_collection(self): |
| 1848 | # C BufferedWriter objects are collected, and collecting them flushes |
| 1849 | # all data to disk. |
| 1850 | # The Python version has __del__, so it ends into gc.garbage instead |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 1851 | with support.check_warnings(('', ResourceWarning)): |
| 1852 | rawio = self.FileIO(support.TESTFN, "w+b") |
| 1853 | f = self.tp(rawio) |
| 1854 | f.write(b"123xxx") |
| 1855 | f.x = f |
| 1856 | wr = weakref.ref(f) |
| 1857 | del f |
| 1858 | support.gc_collect() |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 1859 | self.assertIsNone(wr(), wr) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1860 | with self.open(support.TESTFN, "rb") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1861 | self.assertEqual(f.read(), b"123xxx") |
| 1862 | |
R David Murray | 67bfe80 | 2013-02-23 21:51:05 -0500 | [diff] [blame] | 1863 | def test_args_error(self): |
| 1864 | # Issue #17275 |
| 1865 | with self.assertRaisesRegex(TypeError, "BufferedWriter"): |
| 1866 | self.tp(io.BytesIO(), 1024, 1024, 1024) |
| 1867 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1868 | |
| 1869 | class PyBufferedWriterTest(BufferedWriterTest): |
| 1870 | tp = pyio.BufferedWriter |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 1871 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1872 | class BufferedRWPairTest(unittest.TestCase): |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 1873 | |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1874 | def test_constructor(self): |
| 1875 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 1876 | self.assertFalse(pair.closed) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1877 | |
Serhiy Storchaka | 61e2493 | 2014-02-12 10:52:35 +0200 | [diff] [blame] | 1878 | def test_uninitialized(self): |
| 1879 | pair = self.tp.__new__(self.tp) |
| 1880 | del pair |
| 1881 | pair = self.tp.__new__(self.tp) |
| 1882 | self.assertRaisesRegex((ValueError, AttributeError), |
| 1883 | 'uninitialized|has no attribute', |
| 1884 | pair.read, 0) |
| 1885 | self.assertRaisesRegex((ValueError, AttributeError), |
| 1886 | 'uninitialized|has no attribute', |
| 1887 | pair.write, b'') |
| 1888 | pair.__init__(self.MockRawIO(), self.MockRawIO()) |
| 1889 | self.assertEqual(pair.read(0), b'') |
| 1890 | self.assertEqual(pair.write(b''), 0) |
| 1891 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 1892 | def test_detach(self): |
| 1893 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1894 | self.assertRaises(self.UnsupportedOperation, pair.detach) |
| 1895 | |
Florent Xicluna | 109d573 | 2012-07-07 17:03:22 +0200 | [diff] [blame] | 1896 | def test_constructor_max_buffer_size_removal(self): |
| 1897 | with self.assertRaises(TypeError): |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1898 | self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12) |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1899 | |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1900 | def test_constructor_with_not_readable(self): |
| 1901 | class NotReadable(MockRawIO): |
| 1902 | def readable(self): |
| 1903 | return False |
| 1904 | |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1905 | self.assertRaises(OSError, self.tp, NotReadable(), self.MockRawIO()) |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1906 | |
| 1907 | def test_constructor_with_not_writeable(self): |
| 1908 | class NotWriteable(MockRawIO): |
| 1909 | def writable(self): |
| 1910 | return False |
| 1911 | |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1912 | self.assertRaises(OSError, self.tp, self.MockRawIO(), NotWriteable()) |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1913 | |
| 1914 | def test_read(self): |
| 1915 | pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) |
| 1916 | |
| 1917 | self.assertEqual(pair.read(3), b"abc") |
| 1918 | self.assertEqual(pair.read(1), b"d") |
| 1919 | self.assertEqual(pair.read(), b"ef") |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 1920 | pair = self.tp(self.BytesIO(b"abc"), self.MockRawIO()) |
| 1921 | self.assertEqual(pair.read(None), b"abc") |
| 1922 | |
| 1923 | def test_readlines(self): |
| 1924 | pair = lambda: self.tp(self.BytesIO(b"abc\ndef\nh"), self.MockRawIO()) |
| 1925 | self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) |
| 1926 | self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) |
| 1927 | self.assertEqual(pair().readlines(5), [b"abc\n", b"def\n"]) |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1928 | |
| 1929 | def test_read1(self): |
| 1930 | # .read1() is delegated to the underlying reader object, so this test |
| 1931 | # can be shallow. |
| 1932 | pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) |
| 1933 | |
| 1934 | self.assertEqual(pair.read1(3), b"abc") |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 1935 | self.assertEqual(pair.read1(), b"def") |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1936 | |
| 1937 | def test_readinto(self): |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 1938 | for method in ("readinto", "readinto1"): |
| 1939 | with self.subTest(method): |
| 1940 | pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1941 | |
Serhiy Storchaka | 5f1a518 | 2016-09-11 14:41:02 +0300 | [diff] [blame] | 1942 | data = byteslike(b'\0' * 5) |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 1943 | self.assertEqual(getattr(pair, method)(data), 5) |
| 1944 | self.assertEqual(bytes(data), b"abcde") |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1945 | |
| 1946 | def test_write(self): |
| 1947 | w = self.MockRawIO() |
| 1948 | pair = self.tp(self.MockRawIO(), w) |
| 1949 | |
| 1950 | pair.write(b"abc") |
| 1951 | pair.flush() |
Martin Panter | 6bb91f3 | 2016-05-28 00:41:57 +0000 | [diff] [blame] | 1952 | buffer = bytearray(b"def") |
| 1953 | pair.write(buffer) |
| 1954 | buffer[:] = b"***" # Overwrite our copy of the data |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1955 | pair.flush() |
| 1956 | self.assertEqual(w._write_stack, [b"abc", b"def"]) |
| 1957 | |
| 1958 | def test_peek(self): |
| 1959 | pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) |
| 1960 | |
| 1961 | self.assertTrue(pair.peek(3).startswith(b"abc")) |
| 1962 | self.assertEqual(pair.read(3), b"abc") |
| 1963 | |
| 1964 | def test_readable(self): |
| 1965 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1966 | self.assertTrue(pair.readable()) |
| 1967 | |
| 1968 | def test_writeable(self): |
| 1969 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1970 | self.assertTrue(pair.writable()) |
| 1971 | |
| 1972 | def test_seekable(self): |
| 1973 | # BufferedRWPairs are never seekable, even if their readers and writers |
| 1974 | # are. |
| 1975 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1976 | self.assertFalse(pair.seekable()) |
| 1977 | |
| 1978 | # .flush() is delegated to the underlying writer object and has been |
| 1979 | # tested in the test_write method. |
| 1980 | |
| 1981 | def test_close_and_closed(self): |
| 1982 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1983 | self.assertFalse(pair.closed) |
| 1984 | pair.close() |
| 1985 | self.assertTrue(pair.closed) |
| 1986 | |
Serhiy Storchaka | 7665be6 | 2015-03-24 23:21:57 +0200 | [diff] [blame] | 1987 | def test_reader_close_error_on_close(self): |
| 1988 | def reader_close(): |
| 1989 | reader_non_existing |
| 1990 | reader = self.MockRawIO() |
| 1991 | reader.close = reader_close |
| 1992 | writer = self.MockRawIO() |
| 1993 | pair = self.tp(reader, writer) |
| 1994 | with self.assertRaises(NameError) as err: |
| 1995 | pair.close() |
| 1996 | self.assertIn('reader_non_existing', str(err.exception)) |
| 1997 | self.assertTrue(pair.closed) |
| 1998 | self.assertFalse(reader.closed) |
| 1999 | self.assertTrue(writer.closed) |
| 2000 | |
| 2001 | def test_writer_close_error_on_close(self): |
| 2002 | def writer_close(): |
| 2003 | writer_non_existing |
| 2004 | reader = self.MockRawIO() |
| 2005 | writer = self.MockRawIO() |
| 2006 | writer.close = writer_close |
| 2007 | pair = self.tp(reader, writer) |
| 2008 | with self.assertRaises(NameError) as err: |
| 2009 | pair.close() |
| 2010 | self.assertIn('writer_non_existing', str(err.exception)) |
| 2011 | self.assertFalse(pair.closed) |
| 2012 | self.assertTrue(reader.closed) |
| 2013 | self.assertFalse(writer.closed) |
| 2014 | |
| 2015 | def test_reader_writer_close_error_on_close(self): |
| 2016 | def reader_close(): |
| 2017 | reader_non_existing |
| 2018 | def writer_close(): |
| 2019 | writer_non_existing |
| 2020 | reader = self.MockRawIO() |
| 2021 | reader.close = reader_close |
| 2022 | writer = self.MockRawIO() |
| 2023 | writer.close = writer_close |
| 2024 | pair = self.tp(reader, writer) |
| 2025 | with self.assertRaises(NameError) as err: |
| 2026 | pair.close() |
| 2027 | self.assertIn('reader_non_existing', str(err.exception)) |
| 2028 | self.assertIsInstance(err.exception.__context__, NameError) |
| 2029 | self.assertIn('writer_non_existing', str(err.exception.__context__)) |
| 2030 | self.assertFalse(pair.closed) |
| 2031 | self.assertFalse(reader.closed) |
| 2032 | self.assertFalse(writer.closed) |
| 2033 | |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 2034 | def test_isatty(self): |
| 2035 | class SelectableIsAtty(MockRawIO): |
| 2036 | def __init__(self, isatty): |
| 2037 | MockRawIO.__init__(self) |
| 2038 | self._isatty = isatty |
| 2039 | |
| 2040 | def isatty(self): |
| 2041 | return self._isatty |
| 2042 | |
| 2043 | pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(False)) |
| 2044 | self.assertFalse(pair.isatty()) |
| 2045 | |
| 2046 | pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(False)) |
| 2047 | self.assertTrue(pair.isatty()) |
| 2048 | |
| 2049 | pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(True)) |
| 2050 | self.assertTrue(pair.isatty()) |
| 2051 | |
| 2052 | pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(True)) |
| 2053 | self.assertTrue(pair.isatty()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2054 | |
Benjamin Peterson | bbd0a32 | 2014-09-29 22:46:57 -0400 | [diff] [blame] | 2055 | def test_weakref_clearing(self): |
| 2056 | brw = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 2057 | ref = weakref.ref(brw) |
| 2058 | brw = None |
| 2059 | ref = None # Shouldn't segfault. |
| 2060 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2061 | class CBufferedRWPairTest(BufferedRWPairTest): |
| 2062 | tp = io.BufferedRWPair |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 2063 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2064 | class PyBufferedRWPairTest(BufferedRWPairTest): |
| 2065 | tp = pyio.BufferedRWPair |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 2066 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2067 | |
| 2068 | class BufferedRandomTest(BufferedReaderTest, BufferedWriterTest): |
| 2069 | read_mode = "rb+" |
| 2070 | write_mode = "wb+" |
| 2071 | |
| 2072 | def test_constructor(self): |
| 2073 | BufferedReaderTest.test_constructor(self) |
| 2074 | BufferedWriterTest.test_constructor(self) |
| 2075 | |
Serhiy Storchaka | 61e2493 | 2014-02-12 10:52:35 +0200 | [diff] [blame] | 2076 | def test_uninitialized(self): |
| 2077 | BufferedReaderTest.test_uninitialized(self) |
| 2078 | BufferedWriterTest.test_uninitialized(self) |
| 2079 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2080 | def test_read_and_write(self): |
| 2081 | raw = self.MockRawIO((b"asdf", b"ghjk")) |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 2082 | rw = self.tp(raw, 8) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2083 | |
| 2084 | self.assertEqual(b"as", rw.read(2)) |
| 2085 | rw.write(b"ddd") |
| 2086 | rw.write(b"eee") |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 2087 | self.assertFalse(raw._write_stack) # Buffer writes |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2088 | self.assertEqual(b"ghjk", rw.read()) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2089 | self.assertEqual(b"dddeee", raw._write_stack[0]) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2090 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2091 | def test_seek_and_tell(self): |
| 2092 | raw = self.BytesIO(b"asdfghjkl") |
| 2093 | rw = self.tp(raw) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2094 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2095 | self.assertEqual(b"as", rw.read(2)) |
| 2096 | self.assertEqual(2, rw.tell()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2097 | rw.seek(0, 0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2098 | self.assertEqual(b"asdf", rw.read(4)) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2099 | |
Antoine Pitrou | e05565e | 2011-08-20 14:39:23 +0200 | [diff] [blame] | 2100 | rw.write(b"123f") |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2101 | rw.seek(0, 0) |
Antoine Pitrou | e05565e | 2011-08-20 14:39:23 +0200 | [diff] [blame] | 2102 | self.assertEqual(b"asdf123fl", rw.read()) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2103 | self.assertEqual(9, rw.tell()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2104 | rw.seek(-4, 2) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2105 | self.assertEqual(5, rw.tell()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2106 | rw.seek(2, 1) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2107 | self.assertEqual(7, rw.tell()) |
| 2108 | self.assertEqual(b"fl", rw.read(11)) |
Antoine Pitrou | e05565e | 2011-08-20 14:39:23 +0200 | [diff] [blame] | 2109 | rw.flush() |
| 2110 | self.assertEqual(b"asdf123fl", raw.getvalue()) |
| 2111 | |
Christian Heimes | 8e42a0a | 2007-11-08 18:04:45 +0000 | [diff] [blame] | 2112 | self.assertRaises(TypeError, rw.seek, 0.0) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2113 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2114 | def check_flush_and_read(self, read_func): |
| 2115 | raw = self.BytesIO(b"abcdefghi") |
| 2116 | bufio = self.tp(raw) |
| 2117 | |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2118 | self.assertEqual(b"ab", read_func(bufio, 2)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2119 | bufio.write(b"12") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2120 | self.assertEqual(b"ef", read_func(bufio, 2)) |
| 2121 | self.assertEqual(6, bufio.tell()) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2122 | bufio.flush() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2123 | self.assertEqual(6, bufio.tell()) |
| 2124 | self.assertEqual(b"ghi", read_func(bufio)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2125 | raw.seek(0, 0) |
| 2126 | raw.write(b"XYZ") |
| 2127 | # flush() resets the read buffer |
| 2128 | bufio.flush() |
| 2129 | bufio.seek(0, 0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2130 | self.assertEqual(b"XYZ", read_func(bufio, 3)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2131 | |
| 2132 | def test_flush_and_read(self): |
| 2133 | self.check_flush_and_read(lambda bufio, *args: bufio.read(*args)) |
| 2134 | |
| 2135 | def test_flush_and_readinto(self): |
| 2136 | def _readinto(bufio, n=-1): |
| 2137 | b = bytearray(n if n >= 0 else 9999) |
| 2138 | n = bufio.readinto(b) |
| 2139 | return bytes(b[:n]) |
| 2140 | self.check_flush_and_read(_readinto) |
| 2141 | |
| 2142 | def test_flush_and_peek(self): |
| 2143 | def _peek(bufio, n=-1): |
| 2144 | # This relies on the fact that the buffer can contain the whole |
| 2145 | # raw stream, otherwise peek() can return less. |
| 2146 | b = bufio.peek(n) |
| 2147 | if n != -1: |
| 2148 | b = b[:n] |
| 2149 | bufio.seek(len(b), 1) |
| 2150 | return b |
| 2151 | self.check_flush_and_read(_peek) |
| 2152 | |
| 2153 | def test_flush_and_write(self): |
| 2154 | raw = self.BytesIO(b"abcdefghi") |
| 2155 | bufio = self.tp(raw) |
| 2156 | |
| 2157 | bufio.write(b"123") |
| 2158 | bufio.flush() |
| 2159 | bufio.write(b"45") |
| 2160 | bufio.flush() |
| 2161 | bufio.seek(0, 0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2162 | self.assertEqual(b"12345fghi", raw.getvalue()) |
| 2163 | self.assertEqual(b"12345fghi", bufio.read()) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2164 | |
| 2165 | def test_threads(self): |
| 2166 | BufferedReaderTest.test_threads(self) |
| 2167 | BufferedWriterTest.test_threads(self) |
| 2168 | |
| 2169 | def test_writes_and_peek(self): |
| 2170 | def _peek(bufio): |
| 2171 | bufio.peek(1) |
| 2172 | self.check_writes(_peek) |
| 2173 | def _peek(bufio): |
| 2174 | pos = bufio.tell() |
| 2175 | bufio.seek(-1, 1) |
| 2176 | bufio.peek(1) |
| 2177 | bufio.seek(pos, 0) |
| 2178 | self.check_writes(_peek) |
| 2179 | |
| 2180 | def test_writes_and_reads(self): |
| 2181 | def _read(bufio): |
| 2182 | bufio.seek(-1, 1) |
| 2183 | bufio.read(1) |
| 2184 | self.check_writes(_read) |
| 2185 | |
| 2186 | def test_writes_and_read1s(self): |
| 2187 | def _read1(bufio): |
| 2188 | bufio.seek(-1, 1) |
| 2189 | bufio.read1(1) |
| 2190 | self.check_writes(_read1) |
| 2191 | |
| 2192 | def test_writes_and_readintos(self): |
| 2193 | def _read(bufio): |
| 2194 | bufio.seek(-1, 1) |
| 2195 | bufio.readinto(bytearray(1)) |
| 2196 | self.check_writes(_read) |
| 2197 | |
Antoine Pitrou | a0ceb73 | 2009-08-06 20:29:56 +0000 | [diff] [blame] | 2198 | def test_write_after_readahead(self): |
| 2199 | # Issue #6629: writing after the buffer was filled by readahead should |
| 2200 | # first rewind the raw stream. |
| 2201 | for overwrite_size in [1, 5]: |
| 2202 | raw = self.BytesIO(b"A" * 10) |
| 2203 | bufio = self.tp(raw, 4) |
| 2204 | # Trigger readahead |
| 2205 | self.assertEqual(bufio.read(1), b"A") |
| 2206 | self.assertEqual(bufio.tell(), 1) |
| 2207 | # Overwriting should rewind the raw stream if it needs so |
| 2208 | bufio.write(b"B" * overwrite_size) |
| 2209 | self.assertEqual(bufio.tell(), overwrite_size + 1) |
| 2210 | # If the write size was smaller than the buffer size, flush() and |
| 2211 | # check that rewind happens. |
| 2212 | bufio.flush() |
| 2213 | self.assertEqual(bufio.tell(), overwrite_size + 1) |
| 2214 | s = raw.getvalue() |
| 2215 | self.assertEqual(s, |
| 2216 | b"A" + b"B" * overwrite_size + b"A" * (9 - overwrite_size)) |
| 2217 | |
Antoine Pitrou | 7c40489 | 2011-05-13 00:13:33 +0200 | [diff] [blame] | 2218 | def test_write_rewind_write(self): |
| 2219 | # Various combinations of reading / writing / seeking backwards / writing again |
| 2220 | def mutate(bufio, pos1, pos2): |
| 2221 | assert pos2 >= pos1 |
| 2222 | # Fill the buffer |
| 2223 | bufio.seek(pos1) |
| 2224 | bufio.read(pos2 - pos1) |
| 2225 | bufio.write(b'\x02') |
| 2226 | # This writes earlier than the previous write, but still inside |
| 2227 | # the buffer. |
| 2228 | bufio.seek(pos1) |
| 2229 | bufio.write(b'\x01') |
| 2230 | |
| 2231 | b = b"\x80\x81\x82\x83\x84" |
| 2232 | for i in range(0, len(b)): |
| 2233 | for j in range(i, len(b)): |
| 2234 | raw = self.BytesIO(b) |
| 2235 | bufio = self.tp(raw, 100) |
| 2236 | mutate(bufio, i, j) |
| 2237 | bufio.flush() |
| 2238 | expected = bytearray(b) |
| 2239 | expected[j] = 2 |
| 2240 | expected[i] = 1 |
| 2241 | self.assertEqual(raw.getvalue(), expected, |
| 2242 | "failed result for i=%d, j=%d" % (i, j)) |
| 2243 | |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 2244 | def test_truncate_after_read_or_write(self): |
| 2245 | raw = self.BytesIO(b"A" * 10) |
| 2246 | bufio = self.tp(raw, 100) |
| 2247 | self.assertEqual(bufio.read(2), b"AA") # the read buffer gets filled |
| 2248 | self.assertEqual(bufio.truncate(), 2) |
| 2249 | self.assertEqual(bufio.write(b"BB"), 2) # the write buffer increases |
| 2250 | self.assertEqual(bufio.truncate(), 4) |
| 2251 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2252 | def test_misbehaved_io(self): |
| 2253 | BufferedReaderTest.test_misbehaved_io(self) |
| 2254 | BufferedWriterTest.test_misbehaved_io(self) |
| 2255 | |
Antoine Pitrou | e05565e | 2011-08-20 14:39:23 +0200 | [diff] [blame] | 2256 | def test_interleaved_read_write(self): |
| 2257 | # Test for issue #12213 |
| 2258 | with self.BytesIO(b'abcdefgh') as raw: |
| 2259 | with self.tp(raw, 100) as f: |
| 2260 | f.write(b"1") |
| 2261 | self.assertEqual(f.read(1), b'b') |
| 2262 | f.write(b'2') |
| 2263 | self.assertEqual(f.read1(1), b'd') |
| 2264 | f.write(b'3') |
| 2265 | buf = bytearray(1) |
| 2266 | f.readinto(buf) |
| 2267 | self.assertEqual(buf, b'f') |
| 2268 | f.write(b'4') |
| 2269 | self.assertEqual(f.peek(1), b'h') |
| 2270 | f.flush() |
| 2271 | self.assertEqual(raw.getvalue(), b'1b2d3f4h') |
| 2272 | |
| 2273 | with self.BytesIO(b'abc') as raw: |
| 2274 | with self.tp(raw, 100) as f: |
| 2275 | self.assertEqual(f.read(1), b'a') |
| 2276 | f.write(b"2") |
| 2277 | self.assertEqual(f.read(1), b'c') |
| 2278 | f.flush() |
| 2279 | self.assertEqual(raw.getvalue(), b'a2c') |
| 2280 | |
| 2281 | def test_interleaved_readline_write(self): |
| 2282 | with self.BytesIO(b'ab\ncdef\ng\n') as raw: |
| 2283 | with self.tp(raw) as f: |
| 2284 | f.write(b'1') |
| 2285 | self.assertEqual(f.readline(), b'b\n') |
| 2286 | f.write(b'2') |
| 2287 | self.assertEqual(f.readline(), b'def\n') |
| 2288 | f.write(b'3') |
| 2289 | self.assertEqual(f.readline(), b'\n') |
| 2290 | f.flush() |
| 2291 | self.assertEqual(raw.getvalue(), b'1b\n2def\n3\n') |
| 2292 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 2293 | # You can't construct a BufferedRandom over a non-seekable stream. |
| 2294 | test_unseekable = None |
| 2295 | |
R David Murray | 67bfe80 | 2013-02-23 21:51:05 -0500 | [diff] [blame] | 2296 | |
Antoine Pitrou | 10f0c50 | 2012-07-29 19:02:46 +0200 | [diff] [blame] | 2297 | class CBufferedRandomTest(BufferedRandomTest, SizeofTest): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2298 | tp = io.BufferedRandom |
| 2299 | |
| 2300 | def test_constructor(self): |
| 2301 | BufferedRandomTest.test_constructor(self) |
| 2302 | # The allocation can succeed on 32-bit builds, e.g. with more |
Victor Stinner | 8c663fd | 2017-11-08 14:44:44 -0800 | [diff] [blame] | 2303 | # than 2 GiB RAM and a 64-bit kernel. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2304 | if sys.maxsize > 0x7FFFFFFF: |
| 2305 | rawio = self.MockRawIO() |
| 2306 | bufio = self.tp(rawio) |
| 2307 | self.assertRaises((OverflowError, MemoryError, ValueError), |
| 2308 | bufio.__init__, rawio, sys.maxsize) |
| 2309 | |
| 2310 | def test_garbage_collection(self): |
| 2311 | CBufferedReaderTest.test_garbage_collection(self) |
| 2312 | CBufferedWriterTest.test_garbage_collection(self) |
| 2313 | |
R David Murray | 67bfe80 | 2013-02-23 21:51:05 -0500 | [diff] [blame] | 2314 | def test_args_error(self): |
| 2315 | # Issue #17275 |
| 2316 | with self.assertRaisesRegex(TypeError, "BufferedRandom"): |
| 2317 | self.tp(io.BytesIO(), 1024, 1024, 1024) |
| 2318 | |
| 2319 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2320 | class PyBufferedRandomTest(BufferedRandomTest): |
| 2321 | tp = pyio.BufferedRandom |
| 2322 | |
| 2323 | |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2324 | # To fully exercise seek/tell, the StatefulIncrementalDecoder has these |
| 2325 | # properties: |
| 2326 | # - A single output character can correspond to many bytes of input. |
| 2327 | # - The number of input bytes to complete the character can be |
| 2328 | # undetermined until the last input byte is received. |
| 2329 | # - The number of input bytes can vary depending on previous input. |
| 2330 | # - A single input byte can correspond to many characters of output. |
| 2331 | # - The number of output characters can be undetermined until the |
| 2332 | # last input byte is received. |
| 2333 | # - The number of output characters can vary depending on previous input. |
| 2334 | |
| 2335 | class StatefulIncrementalDecoder(codecs.IncrementalDecoder): |
| 2336 | """ |
| 2337 | For testing seek/tell behavior with a stateful, buffering decoder. |
| 2338 | |
| 2339 | Input is a sequence of words. Words may be fixed-length (length set |
| 2340 | by input) or variable-length (period-terminated). In variable-length |
| 2341 | mode, extra periods are ignored. Possible words are: |
| 2342 | - 'i' followed by a number sets the input length, I (maximum 99). |
| 2343 | When I is set to 0, words are space-terminated. |
| 2344 | - 'o' followed by a number sets the output length, O (maximum 99). |
| 2345 | - Any other word is converted into a word followed by a period on |
| 2346 | the output. The output word consists of the input word truncated |
| 2347 | or padded out with hyphens to make its length equal to O. If O |
| 2348 | is 0, the word is output verbatim without truncating or padding. |
| 2349 | I and O are initially set to 1. When I changes, any buffered input is |
| 2350 | re-scanned according to the new I. EOF also terminates the last word. |
| 2351 | """ |
| 2352 | |
| 2353 | def __init__(self, errors='strict'): |
Christian Heimes | ab56887 | 2008-03-23 02:11:13 +0000 | [diff] [blame] | 2354 | codecs.IncrementalDecoder.__init__(self, errors) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2355 | self.reset() |
| 2356 | |
| 2357 | def __repr__(self): |
| 2358 | return '<SID %x>' % id(self) |
| 2359 | |
| 2360 | def reset(self): |
| 2361 | self.i = 1 |
| 2362 | self.o = 1 |
| 2363 | self.buffer = bytearray() |
| 2364 | |
| 2365 | def getstate(self): |
| 2366 | i, o = self.i ^ 1, self.o ^ 1 # so that flags = 0 after reset() |
| 2367 | return bytes(self.buffer), i*100 + o |
| 2368 | |
| 2369 | def setstate(self, state): |
| 2370 | buffer, io = state |
| 2371 | self.buffer = bytearray(buffer) |
| 2372 | i, o = divmod(io, 100) |
| 2373 | self.i, self.o = i ^ 1, o ^ 1 |
| 2374 | |
| 2375 | def decode(self, input, final=False): |
| 2376 | output = '' |
| 2377 | for b in input: |
| 2378 | if self.i == 0: # variable-length, terminated with period |
| 2379 | if b == ord('.'): |
| 2380 | if self.buffer: |
| 2381 | output += self.process_word() |
| 2382 | else: |
| 2383 | self.buffer.append(b) |
| 2384 | else: # fixed-length, terminate after self.i bytes |
| 2385 | self.buffer.append(b) |
| 2386 | if len(self.buffer) == self.i: |
| 2387 | output += self.process_word() |
| 2388 | if final and self.buffer: # EOF terminates the last word |
| 2389 | output += self.process_word() |
| 2390 | return output |
| 2391 | |
| 2392 | def process_word(self): |
| 2393 | output = '' |
| 2394 | if self.buffer[0] == ord('i'): |
| 2395 | self.i = min(99, int(self.buffer[1:] or 0)) # set input length |
| 2396 | elif self.buffer[0] == ord('o'): |
| 2397 | self.o = min(99, int(self.buffer[1:] or 0)) # set output length |
| 2398 | else: |
| 2399 | output = self.buffer.decode('ascii') |
| 2400 | if len(output) < self.o: |
| 2401 | output += '-'*self.o # pad out with hyphens |
| 2402 | if self.o: |
| 2403 | output = output[:self.o] # truncate to output length |
| 2404 | output += '.' |
| 2405 | self.buffer = bytearray() |
| 2406 | return output |
| 2407 | |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 2408 | codecEnabled = False |
| 2409 | |
| 2410 | @classmethod |
| 2411 | def lookupTestDecoder(cls, name): |
| 2412 | if cls.codecEnabled and name == 'test_decoder': |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2413 | latin1 = codecs.lookup('latin-1') |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 2414 | return codecs.CodecInfo( |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2415 | name='test_decoder', encode=latin1.encode, decode=None, |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 2416 | incrementalencoder=None, |
| 2417 | streamreader=None, streamwriter=None, |
| 2418 | incrementaldecoder=cls) |
| 2419 | |
| 2420 | # Register the previous decoder for testing. |
| 2421 | # Disabled by default, tests will enable it. |
| 2422 | codecs.register(StatefulIncrementalDecoder.lookupTestDecoder) |
| 2423 | |
| 2424 | |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2425 | class StatefulIncrementalDecoderTest(unittest.TestCase): |
| 2426 | """ |
| 2427 | Make sure the StatefulIncrementalDecoder actually works. |
| 2428 | """ |
| 2429 | |
| 2430 | test_cases = [ |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 2431 | # I=1, O=1 (fixed-length input == fixed-length output) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2432 | (b'abcd', False, 'a.b.c.d.'), |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 2433 | # I=0, O=0 (variable-length input, variable-length output) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2434 | (b'oiabcd', True, 'abcd.'), |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 2435 | # I=0, O=0 (should ignore extra periods) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2436 | (b'oi...abcd...', True, 'abcd.'), |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 2437 | # I=0, O=6 (variable-length input, fixed-length output) |
| 2438 | (b'i.o6.x.xyz.toolongtofit.', False, 'x-----.xyz---.toolon.'), |
| 2439 | # I=2, O=6 (fixed-length input < fixed-length output) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2440 | (b'i.i2.o6xyz', True, 'xy----.z-----.'), |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 2441 | # I=6, O=3 (fixed-length input > fixed-length output) |
| 2442 | (b'i.o3.i6.abcdefghijklmnop', True, 'abc.ghi.mno.'), |
| 2443 | # I=0, then 3; O=29, then 15 (with longer output) |
| 2444 | (b'i.o29.a.b.cde.o15.abcdefghijabcdefghij.i3.a.b.c.d.ei00k.l.m', True, |
| 2445 | 'a----------------------------.' + |
| 2446 | 'b----------------------------.' + |
| 2447 | 'cde--------------------------.' + |
| 2448 | 'abcdefghijabcde.' + |
| 2449 | 'a.b------------.' + |
| 2450 | '.c.------------.' + |
| 2451 | 'd.e------------.' + |
| 2452 | 'k--------------.' + |
| 2453 | 'l--------------.' + |
| 2454 | 'm--------------.') |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2455 | ] |
| 2456 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2457 | def test_decoder(self): |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2458 | # Try a few one-shot test cases. |
| 2459 | for input, eof, output in self.test_cases: |
| 2460 | d = StatefulIncrementalDecoder() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2461 | self.assertEqual(d.decode(input, eof), output) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2462 | |
| 2463 | # Also test an unfinished decode, followed by forcing EOF. |
| 2464 | d = StatefulIncrementalDecoder() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2465 | self.assertEqual(d.decode(b'oiabcd'), '') |
| 2466 | self.assertEqual(d.decode(b'', 1), 'abcd.') |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2467 | |
| 2468 | class TextIOWrapperTest(unittest.TestCase): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2469 | |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2470 | def setUp(self): |
| 2471 | self.testdata = b"AAA\r\nBBB\rCCC\r\nDDD\nEEE\r\n" |
| 2472 | self.normalized = b"AAA\nBBB\nCCC\nDDD\nEEE\n".decode("ascii") |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2473 | support.unlink(support.TESTFN) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2474 | |
Guido van Rossum | d071281 | 2007-04-11 16:32:43 +0000 | [diff] [blame] | 2475 | def tearDown(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2476 | support.unlink(support.TESTFN) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2477 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2478 | def test_constructor(self): |
| 2479 | r = self.BytesIO(b"\xc3\xa9\n\n") |
| 2480 | b = self.BufferedReader(r, 1000) |
| 2481 | t = self.TextIOWrapper(b) |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 2482 | t.__init__(b, encoding="latin-1", newline="\r\n") |
| 2483 | self.assertEqual(t.encoding, "latin-1") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2484 | self.assertEqual(t.line_buffering, False) |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 2485 | t.__init__(b, encoding="utf-8", line_buffering=True) |
| 2486 | self.assertEqual(t.encoding, "utf-8") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2487 | self.assertEqual(t.line_buffering, True) |
| 2488 | self.assertEqual("\xe9\n", t.readline()) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2489 | self.assertRaises(TypeError, t.__init__, b, newline=42) |
| 2490 | self.assertRaises(ValueError, t.__init__, b, newline='xyzzy') |
| 2491 | |
Serhiy Storchaka | f24131f | 2015-04-16 11:19:43 +0300 | [diff] [blame] | 2492 | def test_uninitialized(self): |
| 2493 | t = self.TextIOWrapper.__new__(self.TextIOWrapper) |
| 2494 | del t |
| 2495 | t = self.TextIOWrapper.__new__(self.TextIOWrapper) |
| 2496 | self.assertRaises(Exception, repr, t) |
| 2497 | self.assertRaisesRegex((ValueError, AttributeError), |
| 2498 | 'uninitialized|has no attribute', |
| 2499 | t.read, 0) |
| 2500 | t.__init__(self.MockRawIO()) |
| 2501 | self.assertEqual(t.read(0), '') |
| 2502 | |
Nick Coghlan | a9b1524 | 2014-02-04 22:11:18 +1000 | [diff] [blame] | 2503 | def test_non_text_encoding_codecs_are_rejected(self): |
| 2504 | # Ensure the constructor complains if passed a codec that isn't |
| 2505 | # marked as a text encoding |
| 2506 | # http://bugs.python.org/issue20404 |
| 2507 | r = self.BytesIO() |
| 2508 | b = self.BufferedWriter(r) |
| 2509 | with self.assertRaisesRegex(LookupError, "is not a text encoding"): |
| 2510 | self.TextIOWrapper(b, encoding="hex") |
| 2511 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 2512 | def test_detach(self): |
| 2513 | r = self.BytesIO() |
| 2514 | b = self.BufferedWriter(r) |
| 2515 | t = self.TextIOWrapper(b) |
| 2516 | self.assertIs(t.detach(), b) |
| 2517 | |
| 2518 | t = self.TextIOWrapper(b, encoding="ascii") |
| 2519 | t.write("howdy") |
| 2520 | self.assertFalse(r.getvalue()) |
| 2521 | t.detach() |
| 2522 | self.assertEqual(r.getvalue(), b"howdy") |
| 2523 | self.assertRaises(ValueError, t.detach) |
| 2524 | |
Benjamin Peterson | 10e76b6 | 2014-12-21 20:51:50 -0600 | [diff] [blame] | 2525 | # Operations independent of the detached stream should still work |
| 2526 | repr(t) |
| 2527 | self.assertEqual(t.encoding, "ascii") |
| 2528 | self.assertEqual(t.errors, "strict") |
| 2529 | self.assertFalse(t.line_buffering) |
Antoine Pitrou | 3c2817b | 2017-06-03 12:32:28 +0200 | [diff] [blame] | 2530 | self.assertFalse(t.write_through) |
Benjamin Peterson | 10e76b6 | 2014-12-21 20:51:50 -0600 | [diff] [blame] | 2531 | |
Benjamin Peterson | c4c0eae | 2009-03-09 00:07:03 +0000 | [diff] [blame] | 2532 | def test_repr(self): |
| 2533 | raw = self.BytesIO("hello".encode("utf-8")) |
| 2534 | b = self.BufferedReader(raw) |
| 2535 | t = self.TextIOWrapper(b, encoding="utf-8") |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 2536 | modname = self.TextIOWrapper.__module__ |
| 2537 | self.assertEqual(repr(t), |
| 2538 | "<%s.TextIOWrapper encoding='utf-8'>" % modname) |
| 2539 | raw.name = "dummy" |
| 2540 | self.assertEqual(repr(t), |
| 2541 | "<%s.TextIOWrapper name='dummy' encoding='utf-8'>" % modname) |
Antoine Pitrou | a4815ca | 2011-01-09 20:38:15 +0000 | [diff] [blame] | 2542 | t.mode = "r" |
| 2543 | self.assertEqual(repr(t), |
| 2544 | "<%s.TextIOWrapper name='dummy' mode='r' encoding='utf-8'>" % modname) |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 2545 | raw.name = b"dummy" |
| 2546 | self.assertEqual(repr(t), |
Antoine Pitrou | a4815ca | 2011-01-09 20:38:15 +0000 | [diff] [blame] | 2547 | "<%s.TextIOWrapper name=b'dummy' mode='r' encoding='utf-8'>" % modname) |
Benjamin Peterson | c4c0eae | 2009-03-09 00:07:03 +0000 | [diff] [blame] | 2548 | |
Benjamin Peterson | 10e76b6 | 2014-12-21 20:51:50 -0600 | [diff] [blame] | 2549 | t.buffer.detach() |
| 2550 | repr(t) # Should not raise an exception |
| 2551 | |
Serhiy Storchaka | a5af6e1 | 2017-03-19 19:25:29 +0200 | [diff] [blame] | 2552 | def test_recursive_repr(self): |
| 2553 | # Issue #25455 |
| 2554 | raw = self.BytesIO() |
| 2555 | t = self.TextIOWrapper(raw) |
| 2556 | with support.swap_attr(raw, 'name', t): |
| 2557 | try: |
| 2558 | repr(t) # Should not crash |
| 2559 | except RuntimeError: |
| 2560 | pass |
| 2561 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2562 | def test_line_buffering(self): |
| 2563 | r = self.BytesIO() |
| 2564 | b = self.BufferedWriter(r, 1000) |
| 2565 | t = self.TextIOWrapper(b, newline="\n", line_buffering=True) |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 2566 | t.write("X") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2567 | self.assertEqual(r.getvalue(), b"") # No flush happened |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 2568 | t.write("Y\nZ") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2569 | self.assertEqual(r.getvalue(), b"XY\nZ") # All got flushed |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 2570 | t.write("A\rB") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2571 | self.assertEqual(r.getvalue(), b"XY\nZA\rB") |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 2572 | |
Antoine Pitrou | 3c2817b | 2017-06-03 12:32:28 +0200 | [diff] [blame] | 2573 | def test_reconfigure_line_buffering(self): |
| 2574 | r = self.BytesIO() |
| 2575 | b = self.BufferedWriter(r, 1000) |
| 2576 | t = self.TextIOWrapper(b, newline="\n", line_buffering=False) |
| 2577 | t.write("AB\nC") |
| 2578 | self.assertEqual(r.getvalue(), b"") |
| 2579 | |
| 2580 | t.reconfigure(line_buffering=True) # implicit flush |
| 2581 | self.assertEqual(r.getvalue(), b"AB\nC") |
| 2582 | t.write("DEF\nG") |
| 2583 | self.assertEqual(r.getvalue(), b"AB\nCDEF\nG") |
| 2584 | t.write("H") |
| 2585 | self.assertEqual(r.getvalue(), b"AB\nCDEF\nG") |
| 2586 | t.reconfigure(line_buffering=False) # implicit flush |
| 2587 | self.assertEqual(r.getvalue(), b"AB\nCDEF\nGH") |
| 2588 | t.write("IJ") |
| 2589 | self.assertEqual(r.getvalue(), b"AB\nCDEF\nGH") |
| 2590 | |
| 2591 | # Keeping default value |
| 2592 | t.reconfigure() |
| 2593 | t.reconfigure(line_buffering=None) |
| 2594 | self.assertEqual(t.line_buffering, False) |
| 2595 | t.reconfigure(line_buffering=True) |
| 2596 | t.reconfigure() |
| 2597 | t.reconfigure(line_buffering=None) |
| 2598 | self.assertEqual(t.line_buffering, True) |
| 2599 | |
Victor Stinner | 91106cd | 2017-12-13 12:29:09 +0100 | [diff] [blame] | 2600 | @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled") |
Victor Stinner | f86a5e8 | 2012-06-05 13:43:22 +0200 | [diff] [blame] | 2601 | def test_default_encoding(self): |
| 2602 | old_environ = dict(os.environ) |
| 2603 | try: |
| 2604 | # try to get a user preferred encoding different than the current |
| 2605 | # locale encoding to check that TextIOWrapper() uses the current |
| 2606 | # locale encoding and not the user preferred encoding |
| 2607 | for key in ('LC_ALL', 'LANG', 'LC_CTYPE'): |
| 2608 | if key in os.environ: |
| 2609 | del os.environ[key] |
| 2610 | |
| 2611 | current_locale_encoding = locale.getpreferredencoding(False) |
| 2612 | b = self.BytesIO() |
| 2613 | t = self.TextIOWrapper(b) |
| 2614 | self.assertEqual(t.encoding, current_locale_encoding) |
| 2615 | finally: |
| 2616 | os.environ.clear() |
| 2617 | os.environ.update(old_environ) |
| 2618 | |
Serhiy Storchaka | 5cfc79d | 2014-02-07 10:06:39 +0200 | [diff] [blame] | 2619 | @support.cpython_only |
Victor Stinner | 91106cd | 2017-12-13 12:29:09 +0100 | [diff] [blame] | 2620 | @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled") |
Serhiy Storchaka | 7898043 | 2013-01-15 01:12:17 +0200 | [diff] [blame] | 2621 | def test_device_encoding(self): |
Serhiy Storchaka | 5cfc79d | 2014-02-07 10:06:39 +0200 | [diff] [blame] | 2622 | # Issue 15989 |
| 2623 | import _testcapi |
Serhiy Storchaka | 7898043 | 2013-01-15 01:12:17 +0200 | [diff] [blame] | 2624 | b = self.BytesIO() |
| 2625 | b.fileno = lambda: _testcapi.INT_MAX + 1 |
| 2626 | self.assertRaises(OverflowError, self.TextIOWrapper, b) |
| 2627 | b.fileno = lambda: _testcapi.UINT_MAX + 1 |
| 2628 | self.assertRaises(OverflowError, self.TextIOWrapper, b) |
| 2629 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2630 | def test_encoding(self): |
| 2631 | # Check the encoding attribute is always set, and valid |
| 2632 | b = self.BytesIO() |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 2633 | t = self.TextIOWrapper(b, encoding="utf-8") |
| 2634 | self.assertEqual(t.encoding, "utf-8") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2635 | t = self.TextIOWrapper(b) |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 2636 | self.assertIsNotNone(t.encoding) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2637 | codecs.lookup(t.encoding) |
| 2638 | |
| 2639 | def test_encoding_errors_reading(self): |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2640 | # (1) default |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2641 | b = self.BytesIO(b"abc\n\xff\n") |
| 2642 | t = self.TextIOWrapper(b, encoding="ascii") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2643 | self.assertRaises(UnicodeError, t.read) |
| 2644 | # (2) explicit strict |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2645 | b = self.BytesIO(b"abc\n\xff\n") |
| 2646 | t = self.TextIOWrapper(b, encoding="ascii", errors="strict") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2647 | self.assertRaises(UnicodeError, t.read) |
| 2648 | # (3) ignore |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2649 | b = self.BytesIO(b"abc\n\xff\n") |
| 2650 | t = self.TextIOWrapper(b, encoding="ascii", errors="ignore") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2651 | self.assertEqual(t.read(), "abc\n\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2652 | # (4) replace |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2653 | b = self.BytesIO(b"abc\n\xff\n") |
| 2654 | t = self.TextIOWrapper(b, encoding="ascii", errors="replace") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2655 | self.assertEqual(t.read(), "abc\n\ufffd\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2656 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2657 | def test_encoding_errors_writing(self): |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2658 | # (1) default |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2659 | b = self.BytesIO() |
| 2660 | t = self.TextIOWrapper(b, encoding="ascii") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2661 | self.assertRaises(UnicodeError, t.write, "\xff") |
| 2662 | # (2) explicit strict |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2663 | b = self.BytesIO() |
| 2664 | t = self.TextIOWrapper(b, encoding="ascii", errors="strict") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2665 | self.assertRaises(UnicodeError, t.write, "\xff") |
| 2666 | # (3) ignore |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2667 | b = self.BytesIO() |
| 2668 | t = self.TextIOWrapper(b, encoding="ascii", errors="ignore", |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 2669 | newline="\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2670 | t.write("abc\xffdef\n") |
| 2671 | t.flush() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2672 | self.assertEqual(b.getvalue(), b"abcdef\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2673 | # (4) replace |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2674 | b = self.BytesIO() |
| 2675 | t = self.TextIOWrapper(b, encoding="ascii", errors="replace", |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 2676 | newline="\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2677 | t.write("abc\xffdef\n") |
| 2678 | t.flush() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2679 | self.assertEqual(b.getvalue(), b"abc?def\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 2680 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2681 | def test_newlines(self): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2682 | input_lines = [ "unix\n", "windows\r\n", "os9\r", "last\n", "nonl" ] |
| 2683 | |
| 2684 | tests = [ |
| 2685 | [ None, [ 'unix\n', 'windows\n', 'os9\n', 'last\n', 'nonl' ] ], |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2686 | [ '', input_lines ], |
| 2687 | [ '\n', [ "unix\n", "windows\r\n", "os9\rlast\n", "nonl" ] ], |
| 2688 | [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ], |
| 2689 | [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ], |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2690 | ] |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2691 | encodings = ( |
| 2692 | 'utf-8', 'latin-1', |
| 2693 | 'utf-16', 'utf-16-le', 'utf-16-be', |
| 2694 | 'utf-32', 'utf-32-le', 'utf-32-be', |
| 2695 | ) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2696 | |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2697 | # Try a range of buffer sizes to test the case where \r is the last |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2698 | # character in TextIOWrapper._pending_line. |
| 2699 | for encoding in encodings: |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2700 | # XXX: str.encode() should return bytes |
| 2701 | data = bytes(''.join(input_lines).encode(encoding)) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2702 | for do_reads in (False, True): |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2703 | for bufsize in range(1, 10): |
| 2704 | for newline, exp_lines in tests: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2705 | bufio = self.BufferedReader(self.BytesIO(data), bufsize) |
| 2706 | textio = self.TextIOWrapper(bufio, newline=newline, |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2707 | encoding=encoding) |
| 2708 | if do_reads: |
| 2709 | got_lines = [] |
| 2710 | while True: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 2711 | c2 = textio.read(2) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2712 | if c2 == '': |
| 2713 | break |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2714 | self.assertEqual(len(c2), 2) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 2715 | got_lines.append(c2 + textio.readline()) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2716 | else: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 2717 | got_lines = list(textio) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2718 | |
| 2719 | for got_line, exp_line in zip(got_lines, exp_lines): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2720 | self.assertEqual(got_line, exp_line) |
| 2721 | self.assertEqual(len(got_lines), len(exp_lines)) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 2722 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2723 | def test_newlines_input(self): |
| 2724 | testdata = b"AAA\nBB\x00B\nCCC\rDDD\rEEE\r\nFFF\r\nGGG" |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2725 | normalized = testdata.replace(b"\r\n", b"\n").replace(b"\r", b"\n") |
| 2726 | for newline, expected in [ |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 2727 | (None, normalized.decode("ascii").splitlines(keepends=True)), |
| 2728 | ("", testdata.decode("ascii").splitlines(keepends=True)), |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2729 | ("\n", ["AAA\n", "BB\x00B\n", "CCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), |
| 2730 | ("\r\n", ["AAA\nBB\x00B\nCCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), |
| 2731 | ("\r", ["AAA\nBB\x00B\nCCC\r", "DDD\r", "EEE\r", "\nFFF\r", "\nGGG"]), |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2732 | ]: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2733 | buf = self.BytesIO(testdata) |
| 2734 | txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2735 | self.assertEqual(txt.readlines(), expected) |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2736 | txt.seek(0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2737 | self.assertEqual(txt.read(), "".join(expected)) |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2738 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2739 | def test_newlines_output(self): |
| 2740 | testdict = { |
| 2741 | "": b"AAA\nBBB\nCCC\nX\rY\r\nZ", |
| 2742 | "\n": b"AAA\nBBB\nCCC\nX\rY\r\nZ", |
| 2743 | "\r": b"AAA\rBBB\rCCC\rX\rY\r\rZ", |
| 2744 | "\r\n": b"AAA\r\nBBB\r\nCCC\r\nX\rY\r\r\nZ", |
| 2745 | } |
| 2746 | tests = [(None, testdict[os.linesep])] + sorted(testdict.items()) |
| 2747 | for newline, expected in tests: |
| 2748 | buf = self.BytesIO() |
| 2749 | txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) |
| 2750 | txt.write("AAA\nB") |
| 2751 | txt.write("BB\nCCC\n") |
| 2752 | txt.write("X\rY\r\nZ") |
| 2753 | txt.flush() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2754 | self.assertEqual(buf.closed, False) |
| 2755 | self.assertEqual(buf.getvalue(), expected) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2756 | |
| 2757 | def test_destructor(self): |
| 2758 | l = [] |
| 2759 | base = self.BytesIO |
| 2760 | class MyBytesIO(base): |
| 2761 | def close(self): |
| 2762 | l.append(self.getvalue()) |
| 2763 | base.close(self) |
| 2764 | b = MyBytesIO() |
| 2765 | t = self.TextIOWrapper(b, encoding="ascii") |
| 2766 | t.write("abc") |
| 2767 | del t |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 2768 | support.gc_collect() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2769 | self.assertEqual([b"abc"], l) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2770 | |
| 2771 | def test_override_destructor(self): |
| 2772 | record = [] |
| 2773 | class MyTextIO(self.TextIOWrapper): |
| 2774 | def __del__(self): |
| 2775 | record.append(1) |
| 2776 | try: |
| 2777 | f = super().__del__ |
| 2778 | except AttributeError: |
| 2779 | pass |
| 2780 | else: |
| 2781 | f() |
| 2782 | def close(self): |
| 2783 | record.append(2) |
| 2784 | super().close() |
| 2785 | def flush(self): |
| 2786 | record.append(3) |
| 2787 | super().flush() |
| 2788 | b = self.BytesIO() |
| 2789 | t = MyTextIO(b, encoding="ascii") |
| 2790 | del t |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 2791 | support.gc_collect() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2792 | self.assertEqual(record, [1, 2, 3]) |
| 2793 | |
| 2794 | def test_error_through_destructor(self): |
| 2795 | # Test that the exception state is not modified by a destructor, |
| 2796 | # even if close() fails. |
| 2797 | rawio = self.CloseFailureIO() |
| 2798 | def f(): |
| 2799 | self.TextIOWrapper(rawio).xyzzy |
| 2800 | with support.captured_output("stderr") as s: |
| 2801 | self.assertRaises(AttributeError, f) |
| 2802 | s = s.getvalue().strip() |
| 2803 | if s: |
| 2804 | # The destructor *may* have printed an unraisable error, check it |
| 2805 | self.assertEqual(len(s.splitlines()), 1) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 2806 | self.assertTrue(s.startswith("Exception OSError: "), s) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 2807 | self.assertTrue(s.endswith(" ignored"), s) |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 2808 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2809 | # Systematic tests of the text I/O API |
| 2810 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2811 | def test_basic_io(self): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2812 | for chunksize in (1, 2, 3, 4, 5, 15, 16, 17, 31, 32, 33, 63, 64, 65): |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 2813 | for enc in "ascii", "latin-1", "utf-8" :# , "utf-16-be", "utf-16-le": |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2814 | f = self.open(support.TESTFN, "w+", encoding=enc) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2815 | f._CHUNK_SIZE = chunksize |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2816 | self.assertEqual(f.write("abc"), 3) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2817 | f.close() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2818 | f = self.open(support.TESTFN, "r+", encoding=enc) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2819 | f._CHUNK_SIZE = chunksize |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2820 | self.assertEqual(f.tell(), 0) |
| 2821 | self.assertEqual(f.read(), "abc") |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2822 | cookie = f.tell() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2823 | self.assertEqual(f.seek(0), 0) |
| 2824 | self.assertEqual(f.read(None), "abc") |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 2825 | f.seek(0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2826 | self.assertEqual(f.read(2), "ab") |
| 2827 | self.assertEqual(f.read(1), "c") |
| 2828 | self.assertEqual(f.read(1), "") |
| 2829 | self.assertEqual(f.read(), "") |
| 2830 | self.assertEqual(f.tell(), cookie) |
| 2831 | self.assertEqual(f.seek(0), 0) |
| 2832 | self.assertEqual(f.seek(0, 2), cookie) |
| 2833 | self.assertEqual(f.write("def"), 3) |
| 2834 | self.assertEqual(f.seek(cookie), cookie) |
| 2835 | self.assertEqual(f.read(), "def") |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2836 | if enc.startswith("utf"): |
| 2837 | self.multi_line_test(f, enc) |
| 2838 | f.close() |
| 2839 | |
| 2840 | def multi_line_test(self, f, enc): |
| 2841 | f.seek(0) |
| 2842 | f.truncate() |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 2843 | sample = "s\xff\u0fff\uffff" |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2844 | wlines = [] |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 2845 | for size in (0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 62, 63, 64, 65, 1000): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2846 | chars = [] |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 2847 | for i in range(size): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2848 | chars.append(sample[i % len(sample)]) |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 2849 | line = "".join(chars) + "\n" |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2850 | wlines.append((f.tell(), line)) |
| 2851 | f.write(line) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2852 | f.seek(0) |
| 2853 | rlines = [] |
| 2854 | while True: |
| 2855 | pos = f.tell() |
| 2856 | line = f.readline() |
| 2857 | if not line: |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2858 | break |
| 2859 | rlines.append((pos, line)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2860 | self.assertEqual(rlines, wlines) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2861 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2862 | def test_telling(self): |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 2863 | f = self.open(support.TESTFN, "w+", encoding="utf-8") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 2864 | p0 = f.tell() |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 2865 | f.write("\xff\n") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 2866 | p1 = f.tell() |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 2867 | f.write("\xff\n") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 2868 | p2 = f.tell() |
| 2869 | f.seek(0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2870 | self.assertEqual(f.tell(), p0) |
| 2871 | self.assertEqual(f.readline(), "\xff\n") |
| 2872 | self.assertEqual(f.tell(), p1) |
| 2873 | self.assertEqual(f.readline(), "\xff\n") |
| 2874 | self.assertEqual(f.tell(), p2) |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 2875 | f.seek(0) |
| 2876 | for line in f: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2877 | self.assertEqual(line, "\xff\n") |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 2878 | self.assertRaises(OSError, f.tell) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2879 | self.assertEqual(f.tell(), p2) |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 2880 | f.close() |
| 2881 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2882 | def test_seeking(self): |
| 2883 | chunk_size = _default_chunk_size() |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 2884 | prefix_size = chunk_size - 2 |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 2885 | u_prefix = "a" * prefix_size |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 2886 | prefix = bytes(u_prefix.encode("utf-8")) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2887 | self.assertEqual(len(u_prefix), len(prefix)) |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 2888 | u_suffix = "\u8888\n" |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 2889 | suffix = bytes(u_suffix.encode("utf-8")) |
| 2890 | line = prefix + suffix |
Benjamin Peterson | ebe5d8a | 2010-10-31 01:30:11 +0000 | [diff] [blame] | 2891 | with self.open(support.TESTFN, "wb") as f: |
| 2892 | f.write(line*2) |
| 2893 | with self.open(support.TESTFN, "r", encoding="utf-8") as f: |
| 2894 | s = f.read(prefix_size) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2895 | self.assertEqual(s, str(prefix, "ascii")) |
| 2896 | self.assertEqual(f.tell(), prefix_size) |
| 2897 | self.assertEqual(f.readline(), u_suffix) |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 2898 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2899 | def test_seeking_too(self): |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 2900 | # Regression test for a specific bug |
| 2901 | data = b'\xe0\xbf\xbf\n' |
Benjamin Peterson | ebe5d8a | 2010-10-31 01:30:11 +0000 | [diff] [blame] | 2902 | with self.open(support.TESTFN, "wb") as f: |
| 2903 | f.write(data) |
| 2904 | with self.open(support.TESTFN, "r", encoding="utf-8") as f: |
| 2905 | f._CHUNK_SIZE # Just test that it exists |
| 2906 | f._CHUNK_SIZE = 2 |
| 2907 | f.readline() |
| 2908 | f.tell() |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 2909 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2910 | def test_seek_and_tell(self): |
| 2911 | #Test seek/tell using the StatefulIncrementalDecoder. |
| 2912 | # Make test faster by doing smaller seeks |
| 2913 | CHUNK_SIZE = 128 |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2914 | |
Benjamin Peterson | 5fd871d | 2009-03-05 00:49:53 +0000 | [diff] [blame] | 2915 | def test_seek_and_tell_with_data(data, min_pos=0): |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2916 | """Tell/seek to various points within a data stream and ensure |
| 2917 | that the decoded data returned by read() is consistent.""" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2918 | f = self.open(support.TESTFN, 'wb') |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2919 | f.write(data) |
| 2920 | f.close() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2921 | f = self.open(support.TESTFN, encoding='test_decoder') |
| 2922 | f._CHUNK_SIZE = CHUNK_SIZE |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2923 | decoded = f.read() |
| 2924 | f.close() |
| 2925 | |
Neal Norwitz | e2b0705 | 2008-03-18 19:52:05 +0000 | [diff] [blame] | 2926 | for i in range(min_pos, len(decoded) + 1): # seek positions |
| 2927 | for j in [1, 5, len(decoded) - i]: # read lengths |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2928 | f = self.open(support.TESTFN, encoding='test_decoder') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2929 | self.assertEqual(f.read(i), decoded[:i]) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2930 | cookie = f.tell() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2931 | self.assertEqual(f.read(j), decoded[i:i + j]) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2932 | f.seek(cookie) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2933 | self.assertEqual(f.read(), decoded[i:]) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2934 | f.close() |
| 2935 | |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 2936 | # Enable the test decoder. |
| 2937 | StatefulIncrementalDecoder.codecEnabled = 1 |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2938 | |
| 2939 | # Run the tests. |
| 2940 | try: |
| 2941 | # Try each test case. |
| 2942 | for input, _, _ in StatefulIncrementalDecoderTest.test_cases: |
Benjamin Peterson | 5fd871d | 2009-03-05 00:49:53 +0000 | [diff] [blame] | 2943 | test_seek_and_tell_with_data(input) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2944 | |
| 2945 | # Position each test case so that it crosses a chunk boundary. |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2946 | for input, _, _ in StatefulIncrementalDecoderTest.test_cases: |
| 2947 | offset = CHUNK_SIZE - len(input)//2 |
| 2948 | prefix = b'.'*offset |
| 2949 | # Don't bother seeking into the prefix (takes too long). |
| 2950 | min_pos = offset*2 |
Benjamin Peterson | 5fd871d | 2009-03-05 00:49:53 +0000 | [diff] [blame] | 2951 | test_seek_and_tell_with_data(prefix + input, min_pos) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2952 | |
| 2953 | # Ensure our test decoder won't interfere with subsequent tests. |
| 2954 | finally: |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 2955 | StatefulIncrementalDecoder.codecEnabled = 0 |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2956 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2957 | def test_encoded_writes(self): |
Alexandre Vassalotti | a38f73b | 2008-01-07 18:30:48 +0000 | [diff] [blame] | 2958 | data = "1234567890" |
| 2959 | tests = ("utf-16", |
| 2960 | "utf-16-le", |
| 2961 | "utf-16-be", |
| 2962 | "utf-32", |
| 2963 | "utf-32-le", |
| 2964 | "utf-32-be") |
| 2965 | for encoding in tests: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2966 | buf = self.BytesIO() |
| 2967 | f = self.TextIOWrapper(buf, encoding=encoding) |
Alexandre Vassalotti | a38f73b | 2008-01-07 18:30:48 +0000 | [diff] [blame] | 2968 | # Check if the BOM is written only once (see issue1753). |
| 2969 | f.write(data) |
| 2970 | f.write(data) |
| 2971 | f.seek(0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2972 | self.assertEqual(f.read(), data * 2) |
Benjamin Peterson | 9363a65 | 2009-03-05 00:42:09 +0000 | [diff] [blame] | 2973 | f.seek(0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2974 | self.assertEqual(f.read(), data * 2) |
| 2975 | self.assertEqual(buf.getvalue(), (data * 2).encode(encoding)) |
Alexandre Vassalotti | a38f73b | 2008-01-07 18:30:48 +0000 | [diff] [blame] | 2976 | |
Benjamin Peterson | a1b4901 | 2009-03-31 23:11:32 +0000 | [diff] [blame] | 2977 | def test_unreadable(self): |
| 2978 | class UnReadable(self.BytesIO): |
| 2979 | def readable(self): |
| 2980 | return False |
| 2981 | txt = self.TextIOWrapper(UnReadable()) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 2982 | self.assertRaises(OSError, txt.read) |
Benjamin Peterson | a1b4901 | 2009-03-31 23:11:32 +0000 | [diff] [blame] | 2983 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2984 | def test_read_one_by_one(self): |
| 2985 | txt = self.TextIOWrapper(self.BytesIO(b"AA\r\nBB")) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2986 | reads = "" |
| 2987 | while True: |
| 2988 | c = txt.read(1) |
| 2989 | if not c: |
| 2990 | break |
| 2991 | reads += c |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2992 | self.assertEqual(reads, "AA\nBB") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2993 | |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 2994 | def test_readlines(self): |
| 2995 | txt = self.TextIOWrapper(self.BytesIO(b"AA\nBB\nCC")) |
| 2996 | self.assertEqual(txt.readlines(), ["AA\n", "BB\n", "CC"]) |
| 2997 | txt.seek(0) |
| 2998 | self.assertEqual(txt.readlines(None), ["AA\n", "BB\n", "CC"]) |
| 2999 | txt.seek(0) |
| 3000 | self.assertEqual(txt.readlines(5), ["AA\n", "BB\n"]) |
| 3001 | |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3002 | # read in amounts equal to TextIOWrapper._CHUNK_SIZE which is 128. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3003 | def test_read_by_chunk(self): |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3004 | # make sure "\r\n" straddles 128 char boundary. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3005 | txt = self.TextIOWrapper(self.BytesIO(b"A" * 127 + b"\r\nB")) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3006 | reads = "" |
| 3007 | while True: |
| 3008 | c = txt.read(128) |
| 3009 | if not c: |
| 3010 | break |
| 3011 | reads += c |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3012 | self.assertEqual(reads, "A"*127+"\nB") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3013 | |
Antoine Pitrou | 3ed2cb5 | 2012-10-16 23:02:27 +0200 | [diff] [blame] | 3014 | def test_writelines(self): |
| 3015 | l = ['ab', 'cd', 'ef'] |
| 3016 | buf = self.BytesIO() |
| 3017 | txt = self.TextIOWrapper(buf) |
| 3018 | txt.writelines(l) |
| 3019 | txt.flush() |
| 3020 | self.assertEqual(buf.getvalue(), b'abcdef') |
| 3021 | |
| 3022 | def test_writelines_userlist(self): |
| 3023 | l = UserList(['ab', 'cd', 'ef']) |
| 3024 | buf = self.BytesIO() |
| 3025 | txt = self.TextIOWrapper(buf) |
| 3026 | txt.writelines(l) |
| 3027 | txt.flush() |
| 3028 | self.assertEqual(buf.getvalue(), b'abcdef') |
| 3029 | |
| 3030 | def test_writelines_error(self): |
| 3031 | txt = self.TextIOWrapper(self.BytesIO()) |
| 3032 | self.assertRaises(TypeError, txt.writelines, [1, 2, 3]) |
| 3033 | self.assertRaises(TypeError, txt.writelines, None) |
| 3034 | self.assertRaises(TypeError, txt.writelines, b'abc') |
| 3035 | |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3036 | def test_issue1395_1(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3037 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3038 | |
| 3039 | # read one char at a time |
| 3040 | reads = "" |
| 3041 | while True: |
| 3042 | c = txt.read(1) |
| 3043 | if not c: |
| 3044 | break |
| 3045 | reads += c |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3046 | self.assertEqual(reads, self.normalized) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3047 | |
| 3048 | def test_issue1395_2(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3049 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3050 | txt._CHUNK_SIZE = 4 |
| 3051 | |
| 3052 | reads = "" |
| 3053 | while True: |
| 3054 | c = txt.read(4) |
| 3055 | if not c: |
| 3056 | break |
| 3057 | reads += c |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3058 | self.assertEqual(reads, self.normalized) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3059 | |
| 3060 | def test_issue1395_3(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3061 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3062 | txt._CHUNK_SIZE = 4 |
| 3063 | |
| 3064 | reads = txt.read(4) |
| 3065 | reads += txt.read(4) |
| 3066 | reads += txt.readline() |
| 3067 | reads += txt.readline() |
| 3068 | reads += txt.readline() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3069 | self.assertEqual(reads, self.normalized) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3070 | |
| 3071 | def test_issue1395_4(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3072 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3073 | txt._CHUNK_SIZE = 4 |
| 3074 | |
| 3075 | reads = txt.read(4) |
| 3076 | reads += txt.read() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3077 | self.assertEqual(reads, self.normalized) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3078 | |
| 3079 | def test_issue1395_5(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3080 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3081 | txt._CHUNK_SIZE = 4 |
| 3082 | |
| 3083 | reads = txt.read(4) |
| 3084 | pos = txt.tell() |
| 3085 | txt.seek(0) |
| 3086 | txt.seek(pos) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3087 | self.assertEqual(txt.read(4), "BBB\n") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3088 | |
Ka-Ping Yee | ddaa706 | 2008-03-17 20:35:15 +0000 | [diff] [blame] | 3089 | def test_issue2282(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3090 | buffer = self.BytesIO(self.testdata) |
| 3091 | txt = self.TextIOWrapper(buffer, encoding="ascii") |
Ka-Ping Yee | ddaa706 | 2008-03-17 20:35:15 +0000 | [diff] [blame] | 3092 | |
| 3093 | self.assertEqual(buffer.seekable(), txt.seekable()) |
| 3094 | |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 3095 | def test_append_bom(self): |
| 3096 | # The BOM is not written again when appending to a non-empty file |
| 3097 | filename = support.TESTFN |
| 3098 | for charset in ('utf-8-sig', 'utf-16', 'utf-32'): |
| 3099 | with self.open(filename, 'w', encoding=charset) as f: |
| 3100 | f.write('aaa') |
| 3101 | pos = f.tell() |
| 3102 | with self.open(filename, 'rb') as f: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3103 | self.assertEqual(f.read(), 'aaa'.encode(charset)) |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 3104 | |
| 3105 | with self.open(filename, 'a', encoding=charset) as f: |
| 3106 | f.write('xxx') |
| 3107 | with self.open(filename, 'rb') as f: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3108 | self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 3109 | |
| 3110 | def test_seek_bom(self): |
| 3111 | # Same test, but when seeking manually |
| 3112 | filename = support.TESTFN |
| 3113 | for charset in ('utf-8-sig', 'utf-16', 'utf-32'): |
| 3114 | with self.open(filename, 'w', encoding=charset) as f: |
| 3115 | f.write('aaa') |
| 3116 | pos = f.tell() |
| 3117 | with self.open(filename, 'r+', encoding=charset) as f: |
| 3118 | f.seek(pos) |
| 3119 | f.write('zzz') |
| 3120 | f.seek(0) |
| 3121 | f.write('bbb') |
| 3122 | with self.open(filename, 'rb') as f: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3123 | self.assertEqual(f.read(), 'bbbzzz'.encode(charset)) |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 3124 | |
Antoine Pitrou | 85e3ee7 | 2015-04-13 20:01:21 +0200 | [diff] [blame] | 3125 | def test_seek_append_bom(self): |
| 3126 | # Same test, but first seek to the start and then to the end |
| 3127 | filename = support.TESTFN |
| 3128 | for charset in ('utf-8-sig', 'utf-16', 'utf-32'): |
| 3129 | with self.open(filename, 'w', encoding=charset) as f: |
| 3130 | f.write('aaa') |
| 3131 | with self.open(filename, 'a', encoding=charset) as f: |
| 3132 | f.seek(0) |
| 3133 | f.seek(0, self.SEEK_END) |
| 3134 | f.write('xxx') |
| 3135 | with self.open(filename, 'rb') as f: |
| 3136 | self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) |
| 3137 | |
Benjamin Peterson | 0926ad1 | 2009-06-06 18:02:12 +0000 | [diff] [blame] | 3138 | def test_errors_property(self): |
| 3139 | with self.open(support.TESTFN, "w") as f: |
| 3140 | self.assertEqual(f.errors, "strict") |
| 3141 | with self.open(support.TESTFN, "w", errors="replace") as f: |
| 3142 | self.assertEqual(f.errors, "replace") |
| 3143 | |
Brett Cannon | 31f5929 | 2011-02-21 19:29:56 +0000 | [diff] [blame] | 3144 | @support.no_tracing |
Amaury Forgeot d'Arc | ccd686a | 2009-08-29 23:00:38 +0000 | [diff] [blame] | 3145 | def test_threads_write(self): |
| 3146 | # Issue6750: concurrent writes could duplicate data |
| 3147 | event = threading.Event() |
| 3148 | with self.open(support.TESTFN, "w", buffering=1) as f: |
| 3149 | def run(n): |
| 3150 | text = "Thread%03d\n" % n |
| 3151 | event.wait() |
| 3152 | f.write(text) |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 3153 | threads = [threading.Thread(target=run, args=(x,)) |
Amaury Forgeot d'Arc | ccd686a | 2009-08-29 23:00:38 +0000 | [diff] [blame] | 3154 | for x in range(20)] |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 3155 | with support.start_threads(threads, event.set): |
| 3156 | time.sleep(0.02) |
Amaury Forgeot d'Arc | ccd686a | 2009-08-29 23:00:38 +0000 | [diff] [blame] | 3157 | with self.open(support.TESTFN) as f: |
| 3158 | content = f.read() |
| 3159 | for n in range(20): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3160 | self.assertEqual(content.count("Thread%03d\n" % n), 1) |
Amaury Forgeot d'Arc | ccd686a | 2009-08-29 23:00:38 +0000 | [diff] [blame] | 3161 | |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 3162 | def test_flush_error_on_close(self): |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 3163 | # Test that text file is closed despite failed flush |
| 3164 | # and that flush() is called before file closed. |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 3165 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 3166 | closed = [] |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 3167 | def bad_flush(): |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 3168 | closed[:] = [txt.closed, txt.buffer.closed] |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 3169 | raise OSError() |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 3170 | txt.flush = bad_flush |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 3171 | self.assertRaises(OSError, txt.close) # exception not swallowed |
Benjamin Peterson | 6862361 | 2012-12-20 11:53:11 -0600 | [diff] [blame] | 3172 | self.assertTrue(txt.closed) |
Serhiy Storchaka | a3712a9 | 2015-02-21 00:35:09 +0200 | [diff] [blame] | 3173 | self.assertTrue(txt.buffer.closed) |
| 3174 | self.assertTrue(closed) # flush() called |
| 3175 | self.assertFalse(closed[0]) # flush() called before file closed |
| 3176 | self.assertFalse(closed[1]) |
Serhiy Storchaka | c26a1a4 | 2015-02-23 00:28:38 +0200 | [diff] [blame] | 3177 | txt.flush = lambda: None # break reference loop |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 3178 | |
Serhiy Storchaka | 8a8f7f9 | 2014-06-09 09:13:04 +0300 | [diff] [blame] | 3179 | def test_close_error_on_close(self): |
| 3180 | buffer = self.BytesIO(self.testdata) |
| 3181 | def bad_flush(): |
| 3182 | raise OSError('flush') |
| 3183 | def bad_close(): |
| 3184 | raise OSError('close') |
| 3185 | buffer.close = bad_close |
| 3186 | txt = self.TextIOWrapper(buffer, encoding="ascii") |
| 3187 | txt.flush = bad_flush |
| 3188 | with self.assertRaises(OSError) as err: # exception not swallowed |
| 3189 | txt.close() |
| 3190 | self.assertEqual(err.exception.args, ('close',)) |
| 3191 | self.assertIsInstance(err.exception.__context__, OSError) |
| 3192 | self.assertEqual(err.exception.__context__.args, ('flush',)) |
| 3193 | self.assertFalse(txt.closed) |
| 3194 | |
| 3195 | def test_nonnormalized_close_error_on_close(self): |
| 3196 | # Issue #21677 |
| 3197 | buffer = self.BytesIO(self.testdata) |
| 3198 | def bad_flush(): |
| 3199 | raise non_existing_flush |
| 3200 | def bad_close(): |
| 3201 | raise non_existing_close |
| 3202 | buffer.close = bad_close |
| 3203 | txt = self.TextIOWrapper(buffer, encoding="ascii") |
| 3204 | txt.flush = bad_flush |
| 3205 | with self.assertRaises(NameError) as err: # exception not swallowed |
| 3206 | txt.close() |
| 3207 | self.assertIn('non_existing_close', str(err.exception)) |
| 3208 | self.assertIsInstance(err.exception.__context__, NameError) |
| 3209 | self.assertIn('non_existing_flush', str(err.exception.__context__)) |
| 3210 | self.assertFalse(txt.closed) |
| 3211 | |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 3212 | def test_multi_close(self): |
| 3213 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
| 3214 | txt.close() |
| 3215 | txt.close() |
| 3216 | txt.close() |
| 3217 | self.assertRaises(ValueError, txt.flush) |
| 3218 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 3219 | def test_unseekable(self): |
| 3220 | txt = self.TextIOWrapper(self.MockUnseekableIO(self.testdata)) |
| 3221 | self.assertRaises(self.UnsupportedOperation, txt.tell) |
| 3222 | self.assertRaises(self.UnsupportedOperation, txt.seek, 0) |
| 3223 | |
Antoine Pitrou | 7f8f418 | 2010-12-21 21:20:59 +0000 | [diff] [blame] | 3224 | def test_readonly_attributes(self): |
| 3225 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
| 3226 | buf = self.BytesIO(self.testdata) |
| 3227 | with self.assertRaises(AttributeError): |
| 3228 | txt.buffer = buf |
| 3229 | |
Antoine Pitrou | e96ec68 | 2011-07-23 21:46:35 +0200 | [diff] [blame] | 3230 | def test_rawio(self): |
| 3231 | # Issue #12591: TextIOWrapper must work with raw I/O objects, so |
| 3232 | # that subprocess.Popen() can have the required unbuffered |
| 3233 | # semantics with universal_newlines=True. |
| 3234 | raw = self.MockRawIO([b'abc', b'def', b'ghi\njkl\nopq\n']) |
| 3235 | txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') |
| 3236 | # Reads |
| 3237 | self.assertEqual(txt.read(4), 'abcd') |
| 3238 | self.assertEqual(txt.readline(), 'efghi\n') |
| 3239 | self.assertEqual(list(txt), ['jkl\n', 'opq\n']) |
| 3240 | |
| 3241 | def test_rawio_write_through(self): |
| 3242 | # Issue #12591: with write_through=True, writes don't need a flush |
| 3243 | raw = self.MockRawIO([b'abc', b'def', b'ghi\njkl\nopq\n']) |
| 3244 | txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n', |
| 3245 | write_through=True) |
| 3246 | txt.write('1') |
| 3247 | txt.write('23\n4') |
| 3248 | txt.write('5') |
| 3249 | self.assertEqual(b''.join(raw._write_stack), b'123\n45') |
| 3250 | |
Antoine Pitrou | c644e7c | 2014-05-09 00:24:50 +0200 | [diff] [blame] | 3251 | def test_bufio_write_through(self): |
| 3252 | # Issue #21396: write_through=True doesn't force a flush() |
| 3253 | # on the underlying binary buffered object. |
| 3254 | flush_called, write_called = [], [] |
| 3255 | class BufferedWriter(self.BufferedWriter): |
| 3256 | def flush(self, *args, **kwargs): |
| 3257 | flush_called.append(True) |
| 3258 | return super().flush(*args, **kwargs) |
| 3259 | def write(self, *args, **kwargs): |
| 3260 | write_called.append(True) |
| 3261 | return super().write(*args, **kwargs) |
| 3262 | |
| 3263 | rawio = self.BytesIO() |
| 3264 | data = b"a" |
| 3265 | bufio = BufferedWriter(rawio, len(data)*2) |
| 3266 | textio = self.TextIOWrapper(bufio, encoding='ascii', |
| 3267 | write_through=True) |
| 3268 | # write to the buffered io but don't overflow the buffer |
| 3269 | text = data.decode('ascii') |
| 3270 | textio.write(text) |
| 3271 | |
| 3272 | # buffer.flush is not called with write_through=True |
| 3273 | self.assertFalse(flush_called) |
| 3274 | # buffer.write *is* called with write_through=True |
| 3275 | self.assertTrue(write_called) |
| 3276 | self.assertEqual(rawio.getvalue(), b"") # no flush |
| 3277 | |
| 3278 | write_called = [] # reset |
| 3279 | textio.write(text * 10) # total content is larger than bufio buffer |
| 3280 | self.assertTrue(write_called) |
| 3281 | self.assertEqual(rawio.getvalue(), data * 11) # all flushed |
| 3282 | |
Antoine Pitrou | 3c2817b | 2017-06-03 12:32:28 +0200 | [diff] [blame] | 3283 | def test_reconfigure_write_through(self): |
| 3284 | raw = self.MockRawIO([]) |
| 3285 | t = self.TextIOWrapper(raw, encoding='ascii', newline='\n') |
| 3286 | t.write('1') |
| 3287 | t.reconfigure(write_through=True) # implied flush |
| 3288 | self.assertEqual(t.write_through, True) |
| 3289 | self.assertEqual(b''.join(raw._write_stack), b'1') |
| 3290 | t.write('23') |
| 3291 | self.assertEqual(b''.join(raw._write_stack), b'123') |
| 3292 | t.reconfigure(write_through=False) |
| 3293 | self.assertEqual(t.write_through, False) |
| 3294 | t.write('45') |
| 3295 | t.flush() |
| 3296 | self.assertEqual(b''.join(raw._write_stack), b'12345') |
| 3297 | # Keeping default value |
| 3298 | t.reconfigure() |
| 3299 | t.reconfigure(write_through=None) |
| 3300 | self.assertEqual(t.write_through, False) |
| 3301 | t.reconfigure(write_through=True) |
| 3302 | t.reconfigure() |
| 3303 | t.reconfigure(write_through=None) |
| 3304 | self.assertEqual(t.write_through, True) |
| 3305 | |
Serhiy Storchaka | 94dc673 | 2013-02-03 17:03:31 +0200 | [diff] [blame] | 3306 | def test_read_nonbytes(self): |
| 3307 | # Issue #17106 |
| 3308 | # Crash when underlying read() returns non-bytes |
| 3309 | t = self.TextIOWrapper(self.StringIO('a')) |
| 3310 | self.assertRaises(TypeError, t.read, 1) |
| 3311 | t = self.TextIOWrapper(self.StringIO('a')) |
| 3312 | self.assertRaises(TypeError, t.readline) |
| 3313 | t = self.TextIOWrapper(self.StringIO('a')) |
| 3314 | self.assertRaises(TypeError, t.read) |
| 3315 | |
Oren Milman | a5b4ea1 | 2017-08-25 21:14:54 +0300 | [diff] [blame] | 3316 | def test_illegal_encoder(self): |
| 3317 | # Issue 31271: Calling write() while the return value of encoder's |
| 3318 | # encode() is invalid shouldn't cause an assertion failure. |
| 3319 | rot13 = codecs.lookup("rot13") |
| 3320 | with support.swap_attr(rot13, '_is_text_encoding', True): |
| 3321 | t = io.TextIOWrapper(io.BytesIO(b'foo'), encoding="rot13") |
| 3322 | self.assertRaises(TypeError, t.write, 'bar') |
| 3323 | |
Serhiy Storchaka | 94dc673 | 2013-02-03 17:03:31 +0200 | [diff] [blame] | 3324 | def test_illegal_decoder(self): |
| 3325 | # Issue #17106 |
Nick Coghlan | a9b1524 | 2014-02-04 22:11:18 +1000 | [diff] [blame] | 3326 | # Bypass the early encoding check added in issue 20404 |
| 3327 | def _make_illegal_wrapper(): |
| 3328 | quopri = codecs.lookup("quopri") |
| 3329 | quopri._is_text_encoding = True |
| 3330 | try: |
| 3331 | t = self.TextIOWrapper(self.BytesIO(b'aaaaaa'), |
| 3332 | newline='\n', encoding="quopri") |
| 3333 | finally: |
| 3334 | quopri._is_text_encoding = False |
| 3335 | return t |
Serhiy Storchaka | 94dc673 | 2013-02-03 17:03:31 +0200 | [diff] [blame] | 3336 | # Crash when decoder returns non-string |
Nick Coghlan | a9b1524 | 2014-02-04 22:11:18 +1000 | [diff] [blame] | 3337 | t = _make_illegal_wrapper() |
Serhiy Storchaka | 94dc673 | 2013-02-03 17:03:31 +0200 | [diff] [blame] | 3338 | self.assertRaises(TypeError, t.read, 1) |
Nick Coghlan | a9b1524 | 2014-02-04 22:11:18 +1000 | [diff] [blame] | 3339 | t = _make_illegal_wrapper() |
Serhiy Storchaka | 94dc673 | 2013-02-03 17:03:31 +0200 | [diff] [blame] | 3340 | self.assertRaises(TypeError, t.readline) |
Nick Coghlan | a9b1524 | 2014-02-04 22:11:18 +1000 | [diff] [blame] | 3341 | t = _make_illegal_wrapper() |
Serhiy Storchaka | 94dc673 | 2013-02-03 17:03:31 +0200 | [diff] [blame] | 3342 | self.assertRaises(TypeError, t.read) |
| 3343 | |
Oren Milman | ba7d736 | 2017-08-29 11:58:27 +0300 | [diff] [blame] | 3344 | # Issue 31243: calling read() while the return value of decoder's |
| 3345 | # getstate() is invalid should neither crash the interpreter nor |
| 3346 | # raise a SystemError. |
| 3347 | def _make_very_illegal_wrapper(getstate_ret_val): |
| 3348 | class BadDecoder: |
| 3349 | def getstate(self): |
| 3350 | return getstate_ret_val |
| 3351 | def _get_bad_decoder(dummy): |
| 3352 | return BadDecoder() |
| 3353 | quopri = codecs.lookup("quopri") |
| 3354 | with support.swap_attr(quopri, 'incrementaldecoder', |
| 3355 | _get_bad_decoder): |
| 3356 | return _make_illegal_wrapper() |
| 3357 | t = _make_very_illegal_wrapper(42) |
| 3358 | self.assertRaises(TypeError, t.read, 42) |
| 3359 | t = _make_very_illegal_wrapper(()) |
| 3360 | self.assertRaises(TypeError, t.read, 42) |
| 3361 | t = _make_very_illegal_wrapper((1, 2)) |
| 3362 | self.assertRaises(TypeError, t.read, 42) |
| 3363 | |
Antoine Pitrou | 712cb73 | 2013-12-21 15:51:54 +0100 | [diff] [blame] | 3364 | def _check_create_at_shutdown(self, **kwargs): |
| 3365 | # Issue #20037: creating a TextIOWrapper at shutdown |
| 3366 | # shouldn't crash the interpreter. |
| 3367 | iomod = self.io.__name__ |
| 3368 | code = """if 1: |
| 3369 | import codecs |
| 3370 | import {iomod} as io |
| 3371 | |
| 3372 | # Avoid looking up codecs at shutdown |
| 3373 | codecs.lookup('utf-8') |
| 3374 | |
| 3375 | class C: |
| 3376 | def __init__(self): |
| 3377 | self.buf = io.BytesIO() |
| 3378 | def __del__(self): |
| 3379 | io.TextIOWrapper(self.buf, **{kwargs}) |
| 3380 | print("ok") |
| 3381 | c = C() |
| 3382 | """.format(iomod=iomod, kwargs=kwargs) |
| 3383 | return assert_python_ok("-c", code) |
| 3384 | |
Serhiy Storchaka | a793037 | 2016-07-03 22:27:26 +0300 | [diff] [blame] | 3385 | @support.requires_type_collecting |
Antoine Pitrou | 712cb73 | 2013-12-21 15:51:54 +0100 | [diff] [blame] | 3386 | def test_create_at_shutdown_without_encoding(self): |
| 3387 | rc, out, err = self._check_create_at_shutdown() |
| 3388 | if err: |
| 3389 | # Can error out with a RuntimeError if the module state |
| 3390 | # isn't found. |
Nick Coghlan | a9b1524 | 2014-02-04 22:11:18 +1000 | [diff] [blame] | 3391 | self.assertIn(self.shutdown_error, err.decode()) |
Antoine Pitrou | 712cb73 | 2013-12-21 15:51:54 +0100 | [diff] [blame] | 3392 | else: |
| 3393 | self.assertEqual("ok", out.decode().strip()) |
| 3394 | |
Serhiy Storchaka | a793037 | 2016-07-03 22:27:26 +0300 | [diff] [blame] | 3395 | @support.requires_type_collecting |
Antoine Pitrou | 712cb73 | 2013-12-21 15:51:54 +0100 | [diff] [blame] | 3396 | def test_create_at_shutdown_with_encoding(self): |
| 3397 | rc, out, err = self._check_create_at_shutdown(encoding='utf-8', |
| 3398 | errors='strict') |
| 3399 | self.assertFalse(err) |
| 3400 | self.assertEqual("ok", out.decode().strip()) |
| 3401 | |
Antoine Pitrou | b850389 | 2014-04-29 10:14:02 +0200 | [diff] [blame] | 3402 | def test_read_byteslike(self): |
| 3403 | r = MemviewBytesIO(b'Just some random string\n') |
| 3404 | t = self.TextIOWrapper(r, 'utf-8') |
| 3405 | |
| 3406 | # TextIOwrapper will not read the full string, because |
| 3407 | # we truncate it to a multiple of the native int size |
| 3408 | # so that we can construct a more complex memoryview. |
| 3409 | bytes_val = _to_memoryview(r.getvalue()).tobytes() |
| 3410 | |
| 3411 | self.assertEqual(t.read(200), bytes_val.decode('utf-8')) |
| 3412 | |
Benjamin Peterson | 6c14f23 | 2014-11-12 10:19:46 -0500 | [diff] [blame] | 3413 | def test_issue22849(self): |
| 3414 | class F(object): |
| 3415 | def readable(self): return True |
| 3416 | def writable(self): return True |
| 3417 | def seekable(self): return True |
| 3418 | |
| 3419 | for i in range(10): |
| 3420 | try: |
| 3421 | self.TextIOWrapper(F(), encoding='utf-8') |
| 3422 | except Exception: |
| 3423 | pass |
| 3424 | |
| 3425 | F.tell = lambda x: 0 |
| 3426 | t = self.TextIOWrapper(F(), encoding='utf-8') |
| 3427 | |
INADA Naoki | 507434f | 2017-12-21 09:59:53 +0900 | [diff] [blame] | 3428 | def test_reconfigure_encoding_read(self): |
| 3429 | # latin1 -> utf8 |
| 3430 | # (latin1 can decode utf-8 encoded string) |
| 3431 | data = 'abc\xe9\n'.encode('latin1') + 'd\xe9f\n'.encode('utf8') |
| 3432 | raw = self.BytesIO(data) |
| 3433 | txt = self.TextIOWrapper(raw, encoding='latin1', newline='\n') |
| 3434 | self.assertEqual(txt.readline(), 'abc\xe9\n') |
| 3435 | with self.assertRaises(self.UnsupportedOperation): |
| 3436 | txt.reconfigure(encoding='utf-8') |
| 3437 | with self.assertRaises(self.UnsupportedOperation): |
| 3438 | txt.reconfigure(newline=None) |
| 3439 | |
| 3440 | def test_reconfigure_write_fromascii(self): |
| 3441 | # ascii has a specific encodefunc in the C implementation, |
| 3442 | # but utf-8-sig has not. Make sure that we get rid of the |
| 3443 | # cached encodefunc when we switch encoders. |
| 3444 | raw = self.BytesIO() |
| 3445 | txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') |
| 3446 | txt.write('foo\n') |
| 3447 | txt.reconfigure(encoding='utf-8-sig') |
| 3448 | txt.write('\xe9\n') |
| 3449 | txt.flush() |
| 3450 | self.assertEqual(raw.getvalue(), b'foo\n\xc3\xa9\n') |
| 3451 | |
| 3452 | def test_reconfigure_write(self): |
| 3453 | # latin -> utf8 |
| 3454 | raw = self.BytesIO() |
| 3455 | txt = self.TextIOWrapper(raw, encoding='latin1', newline='\n') |
| 3456 | txt.write('abc\xe9\n') |
| 3457 | txt.reconfigure(encoding='utf-8') |
| 3458 | self.assertEqual(raw.getvalue(), b'abc\xe9\n') |
| 3459 | txt.write('d\xe9f\n') |
| 3460 | txt.flush() |
| 3461 | self.assertEqual(raw.getvalue(), b'abc\xe9\nd\xc3\xa9f\n') |
| 3462 | |
| 3463 | # ascii -> utf-8-sig: ensure that no BOM is written in the middle of |
| 3464 | # the file |
| 3465 | raw = self.BytesIO() |
| 3466 | txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') |
| 3467 | txt.write('abc\n') |
| 3468 | txt.reconfigure(encoding='utf-8-sig') |
| 3469 | txt.write('d\xe9f\n') |
| 3470 | txt.flush() |
| 3471 | self.assertEqual(raw.getvalue(), b'abc\nd\xc3\xa9f\n') |
| 3472 | |
| 3473 | def test_reconfigure_write_non_seekable(self): |
| 3474 | raw = self.BytesIO() |
| 3475 | raw.seekable = lambda: False |
| 3476 | raw.seek = None |
| 3477 | txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') |
| 3478 | txt.write('abc\n') |
| 3479 | txt.reconfigure(encoding='utf-8-sig') |
| 3480 | txt.write('d\xe9f\n') |
| 3481 | txt.flush() |
| 3482 | |
| 3483 | # If the raw stream is not seekable, there'll be a BOM |
| 3484 | self.assertEqual(raw.getvalue(), b'abc\n\xef\xbb\xbfd\xc3\xa9f\n') |
| 3485 | |
| 3486 | def test_reconfigure_defaults(self): |
| 3487 | txt = self.TextIOWrapper(self.BytesIO(), 'ascii', 'replace', '\n') |
| 3488 | txt.reconfigure(encoding=None) |
| 3489 | self.assertEqual(txt.encoding, 'ascii') |
| 3490 | self.assertEqual(txt.errors, 'replace') |
| 3491 | txt.write('LF\n') |
| 3492 | |
| 3493 | txt.reconfigure(newline='\r\n') |
| 3494 | self.assertEqual(txt.encoding, 'ascii') |
| 3495 | self.assertEqual(txt.errors, 'replace') |
| 3496 | |
| 3497 | txt.reconfigure(errors='ignore') |
| 3498 | self.assertEqual(txt.encoding, 'ascii') |
| 3499 | self.assertEqual(txt.errors, 'ignore') |
| 3500 | txt.write('CRLF\n') |
| 3501 | |
| 3502 | txt.reconfigure(encoding='utf-8', newline=None) |
| 3503 | self.assertEqual(txt.errors, 'strict') |
| 3504 | txt.seek(0) |
| 3505 | self.assertEqual(txt.read(), 'LF\nCRLF\n') |
| 3506 | |
| 3507 | self.assertEqual(txt.detach().getvalue(), b'LF\nCRLF\r\n') |
| 3508 | |
| 3509 | def test_reconfigure_newline(self): |
| 3510 | raw = self.BytesIO(b'CR\rEOF') |
| 3511 | txt = self.TextIOWrapper(raw, 'ascii', newline='\n') |
| 3512 | txt.reconfigure(newline=None) |
| 3513 | self.assertEqual(txt.readline(), 'CR\n') |
| 3514 | raw = self.BytesIO(b'CR\rEOF') |
| 3515 | txt = self.TextIOWrapper(raw, 'ascii', newline='\n') |
| 3516 | txt.reconfigure(newline='') |
| 3517 | self.assertEqual(txt.readline(), 'CR\r') |
| 3518 | raw = self.BytesIO(b'CR\rLF\nEOF') |
| 3519 | txt = self.TextIOWrapper(raw, 'ascii', newline='\r') |
| 3520 | txt.reconfigure(newline='\n') |
| 3521 | self.assertEqual(txt.readline(), 'CR\rLF\n') |
| 3522 | raw = self.BytesIO(b'LF\nCR\rEOF') |
| 3523 | txt = self.TextIOWrapper(raw, 'ascii', newline='\n') |
| 3524 | txt.reconfigure(newline='\r') |
| 3525 | self.assertEqual(txt.readline(), 'LF\nCR\r') |
| 3526 | raw = self.BytesIO(b'CR\rCRLF\r\nEOF') |
| 3527 | txt = self.TextIOWrapper(raw, 'ascii', newline='\r') |
| 3528 | txt.reconfigure(newline='\r\n') |
| 3529 | self.assertEqual(txt.readline(), 'CR\rCRLF\r\n') |
| 3530 | |
| 3531 | txt = self.TextIOWrapper(self.BytesIO(), 'ascii', newline='\r') |
| 3532 | txt.reconfigure(newline=None) |
| 3533 | txt.write('linesep\n') |
| 3534 | txt.reconfigure(newline='') |
| 3535 | txt.write('LF\n') |
| 3536 | txt.reconfigure(newline='\n') |
| 3537 | txt.write('LF\n') |
| 3538 | txt.reconfigure(newline='\r') |
| 3539 | txt.write('CR\n') |
| 3540 | txt.reconfigure(newline='\r\n') |
| 3541 | txt.write('CRLF\n') |
| 3542 | expected = 'linesep' + os.linesep + 'LF\nLF\nCR\rCRLF\r\n' |
| 3543 | self.assertEqual(txt.detach().getvalue().decode('ascii'), expected) |
| 3544 | |
Serhiy Storchaka | 94dc673 | 2013-02-03 17:03:31 +0200 | [diff] [blame] | 3545 | |
Antoine Pitrou | b850389 | 2014-04-29 10:14:02 +0200 | [diff] [blame] | 3546 | class MemviewBytesIO(io.BytesIO): |
| 3547 | '''A BytesIO object whose read method returns memoryviews |
| 3548 | rather than bytes''' |
| 3549 | |
| 3550 | def read1(self, len_): |
| 3551 | return _to_memoryview(super().read1(len_)) |
| 3552 | |
| 3553 | def read(self, len_): |
| 3554 | return _to_memoryview(super().read(len_)) |
| 3555 | |
| 3556 | def _to_memoryview(buf): |
| 3557 | '''Convert bytes-object *buf* to a non-trivial memoryview''' |
| 3558 | |
| 3559 | arr = array.array('i') |
| 3560 | idx = len(buf) - len(buf) % arr.itemsize |
| 3561 | arr.frombytes(buf[:idx]) |
| 3562 | return memoryview(arr) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 3563 | |
Benjamin Peterson | 6fd113c | 2014-11-12 10:23:44 -0500 | [diff] [blame] | 3564 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3565 | class CTextIOWrapperTest(TextIOWrapperTest): |
Antoine Pitrou | 712cb73 | 2013-12-21 15:51:54 +0100 | [diff] [blame] | 3566 | io = io |
Steve Dower | fe8f4c9 | 2016-09-07 09:31:52 -0700 | [diff] [blame] | 3567 | shutdown_error = "RuntimeError: could not find io module state" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3568 | |
| 3569 | def test_initialization(self): |
| 3570 | r = self.BytesIO(b"\xc3\xa9\n\n") |
| 3571 | b = self.BufferedReader(r, 1000) |
| 3572 | t = self.TextIOWrapper(b) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3573 | self.assertRaises(ValueError, t.__init__, b, newline='xyzzy') |
| 3574 | self.assertRaises(ValueError, t.read) |
| 3575 | |
Benjamin Peterson | 10e76b6 | 2014-12-21 20:51:50 -0600 | [diff] [blame] | 3576 | t = self.TextIOWrapper.__new__(self.TextIOWrapper) |
| 3577 | self.assertRaises(Exception, repr, t) |
| 3578 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3579 | def test_garbage_collection(self): |
| 3580 | # C TextIOWrapper objects are collected, and collecting them flushes |
| 3581 | # all data to disk. |
| 3582 | # The Python version has __del__, so it ends in gc.garbage instead. |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 3583 | with support.check_warnings(('', ResourceWarning)): |
| 3584 | rawio = io.FileIO(support.TESTFN, "wb") |
| 3585 | b = self.BufferedWriter(rawio) |
| 3586 | t = self.TextIOWrapper(b, encoding="ascii") |
| 3587 | t.write("456def") |
| 3588 | t.x = t |
| 3589 | wr = weakref.ref(t) |
| 3590 | del t |
| 3591 | support.gc_collect() |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 3592 | self.assertIsNone(wr(), wr) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 3593 | with self.open(support.TESTFN, "rb") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3594 | self.assertEqual(f.read(), b"456def") |
| 3595 | |
Charles-François Natali | 42c28cd | 2011-10-05 19:53:43 +0200 | [diff] [blame] | 3596 | def test_rwpair_cleared_before_textio(self): |
| 3597 | # Issue 13070: TextIOWrapper's finalization would crash when called |
| 3598 | # after the reference to the underlying BufferedRWPair's writer got |
| 3599 | # cleared by the GC. |
| 3600 | for i in range(1000): |
| 3601 | b1 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) |
| 3602 | t1 = self.TextIOWrapper(b1, encoding="ascii") |
| 3603 | b2 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) |
| 3604 | t2 = self.TextIOWrapper(b2, encoding="ascii") |
| 3605 | # circular references |
| 3606 | t1.buddy = t2 |
| 3607 | t2.buddy = t1 |
| 3608 | support.gc_collect() |
| 3609 | |
| 3610 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3611 | class PyTextIOWrapperTest(TextIOWrapperTest): |
Antoine Pitrou | 712cb73 | 2013-12-21 15:51:54 +0100 | [diff] [blame] | 3612 | io = pyio |
Steve Dower | 6d5cf8a | 2016-09-09 09:21:01 -0700 | [diff] [blame] | 3613 | shutdown_error = "LookupError: unknown encoding: ascii" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3614 | |
| 3615 | |
| 3616 | class IncrementalNewlineDecoderTest(unittest.TestCase): |
| 3617 | |
| 3618 | def check_newline_decoding_utf8(self, decoder): |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3619 | # UTF-8 specific tests for a newline decoder |
| 3620 | def _check_decode(b, s, **kwargs): |
| 3621 | # We exercise getstate() / setstate() as well as decode() |
| 3622 | state = decoder.getstate() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3623 | self.assertEqual(decoder.decode(b, **kwargs), s) |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3624 | decoder.setstate(state) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3625 | self.assertEqual(decoder.decode(b, **kwargs), s) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3626 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3627 | _check_decode(b'\xe8\xa2\x88', "\u8888") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3628 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3629 | _check_decode(b'\xe8', "") |
| 3630 | _check_decode(b'\xa2', "") |
| 3631 | _check_decode(b'\x88', "\u8888") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3632 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3633 | _check_decode(b'\xe8', "") |
| 3634 | _check_decode(b'\xa2', "") |
| 3635 | _check_decode(b'\x88', "\u8888") |
| 3636 | |
| 3637 | _check_decode(b'\xe8', "") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3638 | self.assertRaises(UnicodeDecodeError, decoder.decode, b'', final=True) |
| 3639 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3640 | decoder.reset() |
| 3641 | _check_decode(b'\n', "\n") |
| 3642 | _check_decode(b'\r', "") |
| 3643 | _check_decode(b'', "\n", final=True) |
| 3644 | _check_decode(b'\r', "\n", final=True) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3645 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3646 | _check_decode(b'\r', "") |
| 3647 | _check_decode(b'a', "\na") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3648 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3649 | _check_decode(b'\r\r\n', "\n\n") |
| 3650 | _check_decode(b'\r', "") |
| 3651 | _check_decode(b'\r', "\n") |
| 3652 | _check_decode(b'\na', "\na") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 3653 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3654 | _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n") |
| 3655 | _check_decode(b'\xe8\xa2\x88', "\u8888") |
| 3656 | _check_decode(b'\n', "\n") |
| 3657 | _check_decode(b'\xe8\xa2\x88\r', "\u8888") |
| 3658 | _check_decode(b'\n', "\n") |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 3659 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3660 | def check_newline_decoding(self, decoder, encoding): |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3661 | result = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3662 | if encoding is not None: |
| 3663 | encoder = codecs.getincrementalencoder(encoding)() |
| 3664 | def _decode_bytewise(s): |
| 3665 | # Decode one byte at a time |
| 3666 | for b in encoder.encode(s): |
| 3667 | result.append(decoder.decode(bytes([b]))) |
| 3668 | else: |
| 3669 | encoder = None |
| 3670 | def _decode_bytewise(s): |
| 3671 | # Decode one char at a time |
| 3672 | for c in s: |
| 3673 | result.append(decoder.decode(c)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3674 | self.assertEqual(decoder.newlines, None) |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3675 | _decode_bytewise("abc\n\r") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3676 | self.assertEqual(decoder.newlines, '\n') |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3677 | _decode_bytewise("\nabc") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3678 | self.assertEqual(decoder.newlines, ('\n', '\r\n')) |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3679 | _decode_bytewise("abc\r") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3680 | self.assertEqual(decoder.newlines, ('\n', '\r\n')) |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3681 | _decode_bytewise("abc") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3682 | self.assertEqual(decoder.newlines, ('\r', '\n', '\r\n')) |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3683 | _decode_bytewise("abc\r") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3684 | self.assertEqual("".join(result), "abc\n\nabcabc\nabcabc") |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3685 | decoder.reset() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3686 | input = "abc" |
| 3687 | if encoder is not None: |
| 3688 | encoder.reset() |
| 3689 | input = encoder.encode(input) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3690 | self.assertEqual(decoder.decode(input), "abc") |
| 3691 | self.assertEqual(decoder.newlines, None) |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3692 | |
| 3693 | def test_newline_decoder(self): |
| 3694 | encodings = ( |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3695 | # None meaning the IncrementalNewlineDecoder takes unicode input |
| 3696 | # rather than bytes input |
| 3697 | None, 'utf-8', 'latin-1', |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3698 | 'utf-16', 'utf-16-le', 'utf-16-be', |
| 3699 | 'utf-32', 'utf-32-le', 'utf-32-be', |
| 3700 | ) |
| 3701 | for enc in encodings: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3702 | decoder = enc and codecs.getincrementaldecoder(enc)() |
| 3703 | decoder = self.IncrementalNewlineDecoder(decoder, translate=True) |
| 3704 | self.check_newline_decoding(decoder, enc) |
Alexandre Vassalotti | 472f07d | 2008-01-06 00:34:32 +0000 | [diff] [blame] | 3705 | decoder = codecs.getincrementaldecoder("utf-8")() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3706 | decoder = self.IncrementalNewlineDecoder(decoder, translate=True) |
| 3707 | self.check_newline_decoding_utf8(decoder) |
Oren Milman | 1d1d3e9 | 2017-08-20 18:35:36 +0300 | [diff] [blame] | 3708 | self.assertRaises(TypeError, decoder.setstate, 42) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3709 | |
Antoine Pitrou | 66913e2 | 2009-03-06 23:40:56 +0000 | [diff] [blame] | 3710 | def test_newline_bytes(self): |
| 3711 | # Issue 5433: Excessive optimization in IncrementalNewlineDecoder |
| 3712 | def _check(dec): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3713 | self.assertEqual(dec.newlines, None) |
| 3714 | self.assertEqual(dec.decode("\u0D00"), "\u0D00") |
| 3715 | self.assertEqual(dec.newlines, None) |
| 3716 | self.assertEqual(dec.decode("\u0A00"), "\u0A00") |
| 3717 | self.assertEqual(dec.newlines, None) |
Antoine Pitrou | 66913e2 | 2009-03-06 23:40:56 +0000 | [diff] [blame] | 3718 | dec = self.IncrementalNewlineDecoder(None, translate=False) |
| 3719 | _check(dec) |
| 3720 | dec = self.IncrementalNewlineDecoder(None, translate=True) |
| 3721 | _check(dec) |
| 3722 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3723 | class CIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): |
| 3724 | pass |
| 3725 | |
| 3726 | class PyIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): |
| 3727 | pass |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 3728 | |
Alexandre Vassalotti | 472f07d | 2008-01-06 00:34:32 +0000 | [diff] [blame] | 3729 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 3730 | # XXX Tests for open() |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 3731 | |
Guido van Rossum | 5abbf75 | 2007-08-27 17:39:33 +0000 | [diff] [blame] | 3732 | class MiscIOTest(unittest.TestCase): |
| 3733 | |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 3734 | def tearDown(self): |
| 3735 | support.unlink(support.TESTFN) |
| 3736 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3737 | def test___all__(self): |
| 3738 | for name in self.io.__all__: |
| 3739 | obj = getattr(self.io, name, None) |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 3740 | self.assertIsNotNone(obj, name) |
Guido van Rossum | 5abbf75 | 2007-08-27 17:39:33 +0000 | [diff] [blame] | 3741 | if name == "open": |
| 3742 | continue |
Benjamin Peterson | 6a52a9c | 2009-04-29 22:00:44 +0000 | [diff] [blame] | 3743 | elif "error" in name.lower() or name == "UnsupportedOperation": |
Benjamin Peterson | bfb9594 | 2009-04-02 01:13:40 +0000 | [diff] [blame] | 3744 | self.assertTrue(issubclass(obj, Exception), name) |
| 3745 | elif not name.startswith("SEEK_"): |
| 3746 | self.assertTrue(issubclass(obj, self.IOBase)) |
Benjamin Peterson | 65676e4 | 2008-11-05 21:42:45 +0000 | [diff] [blame] | 3747 | |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 3748 | def test_attributes(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3749 | f = self.open(support.TESTFN, "wb", buffering=0) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3750 | self.assertEqual(f.mode, "wb") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 3751 | f.close() |
| 3752 | |
Serhiy Storchaka | 2480c2e | 2013-11-24 23:13:26 +0200 | [diff] [blame] | 3753 | with support.check_warnings(('', DeprecationWarning)): |
| 3754 | f = self.open(support.TESTFN, "U") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3755 | self.assertEqual(f.name, support.TESTFN) |
| 3756 | self.assertEqual(f.buffer.name, support.TESTFN) |
| 3757 | self.assertEqual(f.buffer.raw.name, support.TESTFN) |
| 3758 | self.assertEqual(f.mode, "U") |
| 3759 | self.assertEqual(f.buffer.mode, "rb") |
| 3760 | self.assertEqual(f.buffer.raw.mode, "rb") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 3761 | f.close() |
| 3762 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3763 | f = self.open(support.TESTFN, "w+") |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3764 | self.assertEqual(f.mode, "w+") |
| 3765 | self.assertEqual(f.buffer.mode, "rb+") # Does it really matter? |
| 3766 | self.assertEqual(f.buffer.raw.mode, "rb+") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 3767 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3768 | g = self.open(f.fileno(), "wb", closefd=False) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 3769 | self.assertEqual(g.mode, "wb") |
| 3770 | self.assertEqual(g.raw.mode, "wb") |
| 3771 | self.assertEqual(g.name, f.fileno()) |
| 3772 | self.assertEqual(g.raw.name, f.fileno()) |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 3773 | f.close() |
| 3774 | g.close() |
| 3775 | |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 3776 | def test_io_after_close(self): |
| 3777 | for kwargs in [ |
| 3778 | {"mode": "w"}, |
| 3779 | {"mode": "wb"}, |
| 3780 | {"mode": "w", "buffering": 1}, |
| 3781 | {"mode": "w", "buffering": 2}, |
| 3782 | {"mode": "wb", "buffering": 0}, |
| 3783 | {"mode": "r"}, |
| 3784 | {"mode": "rb"}, |
| 3785 | {"mode": "r", "buffering": 1}, |
| 3786 | {"mode": "r", "buffering": 2}, |
| 3787 | {"mode": "rb", "buffering": 0}, |
| 3788 | {"mode": "w+"}, |
| 3789 | {"mode": "w+b"}, |
| 3790 | {"mode": "w+", "buffering": 1}, |
| 3791 | {"mode": "w+", "buffering": 2}, |
| 3792 | {"mode": "w+b", "buffering": 0}, |
| 3793 | ]: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3794 | f = self.open(support.TESTFN, **kwargs) |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 3795 | f.close() |
| 3796 | self.assertRaises(ValueError, f.flush) |
| 3797 | self.assertRaises(ValueError, f.fileno) |
| 3798 | self.assertRaises(ValueError, f.isatty) |
| 3799 | self.assertRaises(ValueError, f.__iter__) |
| 3800 | if hasattr(f, "peek"): |
| 3801 | self.assertRaises(ValueError, f.peek, 1) |
| 3802 | self.assertRaises(ValueError, f.read) |
| 3803 | if hasattr(f, "read1"): |
| 3804 | self.assertRaises(ValueError, f.read1, 1024) |
Martin Panter | ccb2c0e | 2016-10-20 23:48:14 +0000 | [diff] [blame] | 3805 | self.assertRaises(ValueError, f.read1) |
Victor Stinner | b79f28c | 2011-05-25 22:09:03 +0200 | [diff] [blame] | 3806 | if hasattr(f, "readall"): |
| 3807 | self.assertRaises(ValueError, f.readall) |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 3808 | if hasattr(f, "readinto"): |
| 3809 | self.assertRaises(ValueError, f.readinto, bytearray(1024)) |
Benjamin Peterson | a96fea0 | 2014-06-22 14:17:44 -0700 | [diff] [blame] | 3810 | if hasattr(f, "readinto1"): |
| 3811 | self.assertRaises(ValueError, f.readinto1, bytearray(1024)) |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 3812 | self.assertRaises(ValueError, f.readline) |
| 3813 | self.assertRaises(ValueError, f.readlines) |
Xiang Zhang | 026435c | 2017-04-15 12:47:28 +0800 | [diff] [blame] | 3814 | self.assertRaises(ValueError, f.readlines, 1) |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 3815 | self.assertRaises(ValueError, f.seek, 0) |
| 3816 | self.assertRaises(ValueError, f.tell) |
| 3817 | self.assertRaises(ValueError, f.truncate) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3818 | self.assertRaises(ValueError, f.write, |
| 3819 | b"" if "b" in kwargs['mode'] else "") |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 3820 | self.assertRaises(ValueError, f.writelines, []) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3821 | self.assertRaises(ValueError, next, f) |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 3822 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3823 | def test_blockingioerror(self): |
| 3824 | # Various BlockingIOError issues |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3825 | class C(str): |
| 3826 | pass |
| 3827 | c = C("") |
| 3828 | b = self.BlockingIOError(1, c) |
| 3829 | c.b = b |
| 3830 | b.c = c |
| 3831 | wr = weakref.ref(c) |
| 3832 | del c, b |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 3833 | support.gc_collect() |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 3834 | self.assertIsNone(wr(), wr) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3835 | |
| 3836 | def test_abcs(self): |
| 3837 | # Test the visible base classes are ABCs. |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 3838 | self.assertIsInstance(self.IOBase, abc.ABCMeta) |
| 3839 | self.assertIsInstance(self.RawIOBase, abc.ABCMeta) |
| 3840 | self.assertIsInstance(self.BufferedIOBase, abc.ABCMeta) |
| 3841 | self.assertIsInstance(self.TextIOBase, abc.ABCMeta) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3842 | |
| 3843 | def _check_abc_inheritance(self, abcmodule): |
| 3844 | with self.open(support.TESTFN, "wb", buffering=0) as f: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 3845 | self.assertIsInstance(f, abcmodule.IOBase) |
| 3846 | self.assertIsInstance(f, abcmodule.RawIOBase) |
| 3847 | self.assertNotIsInstance(f, abcmodule.BufferedIOBase) |
| 3848 | self.assertNotIsInstance(f, abcmodule.TextIOBase) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3849 | with self.open(support.TESTFN, "wb") as f: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 3850 | self.assertIsInstance(f, abcmodule.IOBase) |
| 3851 | self.assertNotIsInstance(f, abcmodule.RawIOBase) |
| 3852 | self.assertIsInstance(f, abcmodule.BufferedIOBase) |
| 3853 | self.assertNotIsInstance(f, abcmodule.TextIOBase) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3854 | with self.open(support.TESTFN, "w") as f: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 3855 | self.assertIsInstance(f, abcmodule.IOBase) |
| 3856 | self.assertNotIsInstance(f, abcmodule.RawIOBase) |
| 3857 | self.assertNotIsInstance(f, abcmodule.BufferedIOBase) |
| 3858 | self.assertIsInstance(f, abcmodule.TextIOBase) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 3859 | |
| 3860 | def test_abc_inheritance(self): |
| 3861 | # Test implementations inherit from their respective ABCs |
| 3862 | self._check_abc_inheritance(self) |
| 3863 | |
| 3864 | def test_abc_inheritance_official(self): |
| 3865 | # Test implementations inherit from the official ABCs of the |
| 3866 | # baseline "io" module. |
| 3867 | self._check_abc_inheritance(io) |
| 3868 | |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 3869 | def _check_warn_on_dealloc(self, *args, **kwargs): |
| 3870 | f = open(*args, **kwargs) |
| 3871 | r = repr(f) |
| 3872 | with self.assertWarns(ResourceWarning) as cm: |
| 3873 | f = None |
| 3874 | support.gc_collect() |
| 3875 | self.assertIn(r, str(cm.warning.args[0])) |
| 3876 | |
| 3877 | def test_warn_on_dealloc(self): |
| 3878 | self._check_warn_on_dealloc(support.TESTFN, "wb", buffering=0) |
| 3879 | self._check_warn_on_dealloc(support.TESTFN, "wb") |
| 3880 | self._check_warn_on_dealloc(support.TESTFN, "w") |
| 3881 | |
| 3882 | def _check_warn_on_dealloc_fd(self, *args, **kwargs): |
| 3883 | fds = [] |
Benjamin Peterson | 556c735 | 2010-10-31 01:35:43 +0000 | [diff] [blame] | 3884 | def cleanup_fds(): |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 3885 | for fd in fds: |
| 3886 | try: |
| 3887 | os.close(fd) |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 3888 | except OSError as e: |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 3889 | if e.errno != errno.EBADF: |
| 3890 | raise |
Benjamin Peterson | 556c735 | 2010-10-31 01:35:43 +0000 | [diff] [blame] | 3891 | self.addCleanup(cleanup_fds) |
| 3892 | r, w = os.pipe() |
| 3893 | fds += r, w |
| 3894 | self._check_warn_on_dealloc(r, *args, **kwargs) |
| 3895 | # When using closefd=False, there's no warning |
| 3896 | r, w = os.pipe() |
| 3897 | fds += r, w |
Serhiy Storchaka | 94a619d | 2016-02-11 13:11:44 +0200 | [diff] [blame] | 3898 | with support.check_no_resource_warning(self): |
Benjamin Peterson | 556c735 | 2010-10-31 01:35:43 +0000 | [diff] [blame] | 3899 | open(r, *args, closefd=False, **kwargs) |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 3900 | |
| 3901 | def test_warn_on_dealloc_fd(self): |
| 3902 | self._check_warn_on_dealloc_fd("rb", buffering=0) |
| 3903 | self._check_warn_on_dealloc_fd("rb") |
| 3904 | self._check_warn_on_dealloc_fd("r") |
| 3905 | |
| 3906 | |
Antoine Pitrou | 243757e | 2010-11-05 21:15:39 +0000 | [diff] [blame] | 3907 | def test_pickling(self): |
| 3908 | # Pickling file objects is forbidden |
| 3909 | for kwargs in [ |
| 3910 | {"mode": "w"}, |
| 3911 | {"mode": "wb"}, |
| 3912 | {"mode": "wb", "buffering": 0}, |
| 3913 | {"mode": "r"}, |
| 3914 | {"mode": "rb"}, |
| 3915 | {"mode": "rb", "buffering": 0}, |
| 3916 | {"mode": "w+"}, |
| 3917 | {"mode": "w+b"}, |
| 3918 | {"mode": "w+b", "buffering": 0}, |
| 3919 | ]: |
| 3920 | for protocol in range(pickle.HIGHEST_PROTOCOL + 1): |
| 3921 | with self.open(support.TESTFN, **kwargs) as f: |
| 3922 | self.assertRaises(TypeError, pickle.dumps, f, protocol) |
| 3923 | |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 3924 | def test_nonblock_pipe_write_bigbuf(self): |
| 3925 | self._test_nonblock_pipe_write(16*1024) |
| 3926 | |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 3927 | def test_nonblock_pipe_write_smallbuf(self): |
| 3928 | self._test_nonblock_pipe_write(1024) |
| 3929 | |
Victor Stinner | 1db9e7b | 2014-07-29 22:32:47 +0200 | [diff] [blame] | 3930 | @unittest.skipUnless(hasattr(os, 'set_blocking'), |
| 3931 | 'os.set_blocking() required for this test') |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 3932 | def _test_nonblock_pipe_write(self, bufsize): |
| 3933 | sent = [] |
| 3934 | received = [] |
| 3935 | r, w = os.pipe() |
Victor Stinner | 1db9e7b | 2014-07-29 22:32:47 +0200 | [diff] [blame] | 3936 | os.set_blocking(r, False) |
| 3937 | os.set_blocking(w, False) |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 3938 | |
| 3939 | # To exercise all code paths in the C implementation we need |
| 3940 | # to play with buffer sizes. For instance, if we choose a |
| 3941 | # buffer size less than or equal to _PIPE_BUF (4096 on Linux) |
| 3942 | # then we will never get a partial write of the buffer. |
| 3943 | rf = self.open(r, mode='rb', closefd=True, buffering=bufsize) |
| 3944 | wf = self.open(w, mode='wb', closefd=True, buffering=bufsize) |
| 3945 | |
| 3946 | with rf, wf: |
| 3947 | for N in 9999, 73, 7574: |
| 3948 | try: |
| 3949 | i = 0 |
| 3950 | while True: |
| 3951 | msg = bytes([i % 26 + 97]) * N |
| 3952 | sent.append(msg) |
| 3953 | wf.write(msg) |
| 3954 | i += 1 |
| 3955 | |
| 3956 | except self.BlockingIOError as e: |
| 3957 | self.assertEqual(e.args[0], errno.EAGAIN) |
Antoine Pitrou | 7fe601c | 2011-11-21 20:22:01 +0100 | [diff] [blame] | 3958 | self.assertEqual(e.args[2], e.characters_written) |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 3959 | sent[-1] = sent[-1][:e.characters_written] |
| 3960 | received.append(rf.read()) |
| 3961 | msg = b'BLOCKED' |
| 3962 | wf.write(msg) |
| 3963 | sent.append(msg) |
| 3964 | |
| 3965 | while True: |
| 3966 | try: |
| 3967 | wf.flush() |
| 3968 | break |
| 3969 | except self.BlockingIOError as e: |
| 3970 | self.assertEqual(e.args[0], errno.EAGAIN) |
Antoine Pitrou | 7fe601c | 2011-11-21 20:22:01 +0100 | [diff] [blame] | 3971 | self.assertEqual(e.args[2], e.characters_written) |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 3972 | self.assertEqual(e.characters_written, 0) |
| 3973 | received.append(rf.read()) |
| 3974 | |
| 3975 | received += iter(rf.read, None) |
| 3976 | |
| 3977 | sent, received = b''.join(sent), b''.join(received) |
Serhiy Storchaka | 0dcd80a | 2015-08-02 15:17:49 +0300 | [diff] [blame] | 3978 | self.assertEqual(sent, received) |
Antoine Pitrou | 58fcf9f | 2011-11-21 20:16:44 +0100 | [diff] [blame] | 3979 | self.assertTrue(wf.closed) |
| 3980 | self.assertTrue(rf.closed) |
| 3981 | |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 3982 | def test_create_fail(self): |
| 3983 | # 'x' mode fails if file is existing |
| 3984 | with self.open(support.TESTFN, 'w'): |
| 3985 | pass |
| 3986 | self.assertRaises(FileExistsError, self.open, support.TESTFN, 'x') |
| 3987 | |
| 3988 | def test_create_writes(self): |
| 3989 | # 'x' mode opens for writing |
| 3990 | with self.open(support.TESTFN, 'xb') as f: |
| 3991 | f.write(b"spam") |
| 3992 | with self.open(support.TESTFN, 'rb') as f: |
| 3993 | self.assertEqual(b"spam", f.read()) |
| 3994 | |
Christian Heimes | 7b64875 | 2012-09-10 14:48:43 +0200 | [diff] [blame] | 3995 | def test_open_allargs(self): |
| 3996 | # there used to be a buffer overflow in the parser for rawmode |
| 3997 | self.assertRaises(ValueError, self.open, support.TESTFN, 'rwax+') |
| 3998 | |
| 3999 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 4000 | class CMiscIOTest(MiscIOTest): |
| 4001 | io = io |
| 4002 | |
Serhiy Storchaka | 37a79a1 | 2013-05-28 16:24:45 +0300 | [diff] [blame] | 4003 | def test_readinto_buffer_overflow(self): |
| 4004 | # Issue #18025 |
| 4005 | class BadReader(self.io.BufferedIOBase): |
| 4006 | def read(self, n=-1): |
| 4007 | return b'x' * 10**6 |
| 4008 | bufio = BadReader() |
| 4009 | b = bytearray(2) |
| 4010 | self.assertRaises(ValueError, bufio.readinto, b) |
| 4011 | |
Antoine Pitrou | 25f85d4 | 2015-04-13 19:41:47 +0200 | [diff] [blame] | 4012 | def check_daemon_threads_shutdown_deadlock(self, stream_name): |
| 4013 | # Issue #23309: deadlocks at shutdown should be avoided when a |
| 4014 | # daemon thread and the main thread both write to a file. |
| 4015 | code = """if 1: |
| 4016 | import sys |
| 4017 | import time |
| 4018 | import threading |
Victor Stinner | 2a1aed0 | 2017-04-21 17:59:23 +0200 | [diff] [blame] | 4019 | from test.support import SuppressCrashReport |
Antoine Pitrou | 25f85d4 | 2015-04-13 19:41:47 +0200 | [diff] [blame] | 4020 | |
| 4021 | file = sys.{stream_name} |
| 4022 | |
| 4023 | def run(): |
| 4024 | while True: |
| 4025 | file.write('.') |
| 4026 | file.flush() |
| 4027 | |
Victor Stinner | 2a1aed0 | 2017-04-21 17:59:23 +0200 | [diff] [blame] | 4028 | crash = SuppressCrashReport() |
| 4029 | crash.__enter__() |
| 4030 | # don't call __exit__(): the crash occurs at Python shutdown |
| 4031 | |
Antoine Pitrou | 25f85d4 | 2015-04-13 19:41:47 +0200 | [diff] [blame] | 4032 | thread = threading.Thread(target=run) |
| 4033 | thread.daemon = True |
| 4034 | thread.start() |
| 4035 | |
| 4036 | time.sleep(0.5) |
| 4037 | file.write('!') |
| 4038 | file.flush() |
| 4039 | """.format_map(locals()) |
| 4040 | res, _ = run_python_until_end("-c", code) |
| 4041 | err = res.err.decode() |
| 4042 | if res.rc != 0: |
| 4043 | # Failure: should be a fatal error |
| 4044 | self.assertIn("Fatal Python error: could not acquire lock " |
| 4045 | "for <_io.BufferedWriter name='<{stream_name}>'> " |
| 4046 | "at interpreter shutdown, possibly due to " |
| 4047 | "daemon threads".format_map(locals()), |
| 4048 | err) |
| 4049 | else: |
| 4050 | self.assertFalse(err.strip('.!')) |
| 4051 | |
| 4052 | def test_daemon_threads_shutdown_stdout_deadlock(self): |
| 4053 | self.check_daemon_threads_shutdown_deadlock('stdout') |
| 4054 | |
| 4055 | def test_daemon_threads_shutdown_stderr_deadlock(self): |
| 4056 | self.check_daemon_threads_shutdown_deadlock('stderr') |
| 4057 | |
| 4058 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 4059 | class PyMiscIOTest(MiscIOTest): |
| 4060 | io = pyio |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 4061 | |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4062 | |
| 4063 | @unittest.skipIf(os.name == 'nt', 'POSIX signals required for this test.') |
| 4064 | class SignalsTest(unittest.TestCase): |
| 4065 | |
| 4066 | def setUp(self): |
| 4067 | self.oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt) |
| 4068 | |
| 4069 | def tearDown(self): |
| 4070 | signal.signal(signal.SIGALRM, self.oldalrm) |
| 4071 | |
| 4072 | def alarm_interrupt(self, sig, frame): |
| 4073 | 1/0 |
| 4074 | |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4075 | def check_interrupted_write(self, item, bytes, **fdopen_kwargs): |
| 4076 | """Check that a partial write, when it gets interrupted, properly |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4077 | invokes the signal handler, and bubbles up the exception raised |
| 4078 | in the latter.""" |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4079 | read_results = [] |
| 4080 | def _read(): |
Victor Stinner | a929335 | 2011-04-30 15:21:58 +0200 | [diff] [blame] | 4081 | if hasattr(signal, 'pthread_sigmask'): |
| 4082 | signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGALRM]) |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4083 | s = os.read(r, 1) |
| 4084 | read_results.append(s) |
| 4085 | t = threading.Thread(target=_read) |
| 4086 | t.daemon = True |
| 4087 | r, w = os.pipe() |
Benjamin Peterson | d8fc2e1 | 2010-10-31 01:19:53 +0000 | [diff] [blame] | 4088 | fdopen_kwargs["closefd"] = False |
Victor Stinner | 9c182a1 | 2015-03-16 18:03:06 +0100 | [diff] [blame] | 4089 | large_data = item * (support.PIPE_MAX_SIZE // len(item) + 1) |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4090 | try: |
| 4091 | wio = self.io.open(w, **fdopen_kwargs) |
| 4092 | t.start() |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4093 | # Fill the pipe enough that the write will be blocking. |
| 4094 | # It will be interrupted by the timer armed above. Since the |
| 4095 | # other thread has read one byte, the low-level write will |
| 4096 | # return with a successful (partial) result rather than an EINTR. |
| 4097 | # The buffered IO layer must check for pending signal |
| 4098 | # handlers, which in this case will invoke alarm_interrupt(). |
Victor Stinner | 775b2dd | 2013-07-15 19:53:13 +0200 | [diff] [blame] | 4099 | signal.alarm(1) |
| 4100 | try: |
Victor Stinner | 9c182a1 | 2015-03-16 18:03:06 +0100 | [diff] [blame] | 4101 | self.assertRaises(ZeroDivisionError, wio.write, large_data) |
Victor Stinner | 775b2dd | 2013-07-15 19:53:13 +0200 | [diff] [blame] | 4102 | finally: |
| 4103 | signal.alarm(0) |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 4104 | t.join() |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4105 | # We got one byte, get another one and check that it isn't a |
| 4106 | # repeat of the first one. |
| 4107 | read_results.append(os.read(r, 1)) |
| 4108 | self.assertEqual(read_results, [bytes[0:1], bytes[1:2]]) |
| 4109 | finally: |
| 4110 | os.close(w) |
| 4111 | os.close(r) |
| 4112 | # This is deliberate. If we didn't close the file descriptor |
| 4113 | # before closing wio, wio would try to flush its internal |
| 4114 | # buffer, and block again. |
| 4115 | try: |
| 4116 | wio.close() |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 4117 | except OSError as e: |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4118 | if e.errno != errno.EBADF: |
| 4119 | raise |
| 4120 | |
| 4121 | def test_interrupted_write_unbuffered(self): |
| 4122 | self.check_interrupted_write(b"xy", b"xy", mode="wb", buffering=0) |
| 4123 | |
| 4124 | def test_interrupted_write_buffered(self): |
| 4125 | self.check_interrupted_write(b"xy", b"xy", mode="wb") |
| 4126 | |
| 4127 | def test_interrupted_write_text(self): |
| 4128 | self.check_interrupted_write("xy", b"xy", mode="w", encoding="ascii") |
| 4129 | |
Brett Cannon | 31f5929 | 2011-02-21 19:29:56 +0000 | [diff] [blame] | 4130 | @support.no_tracing |
Antoine Pitrou | f3b68b3 | 2010-12-03 18:41:39 +0000 | [diff] [blame] | 4131 | def check_reentrant_write(self, data, **fdopen_kwargs): |
| 4132 | def on_alarm(*args): |
| 4133 | # Will be called reentrantly from the same thread |
| 4134 | wio.write(data) |
| 4135 | 1/0 |
| 4136 | signal.signal(signal.SIGALRM, on_alarm) |
| 4137 | r, w = os.pipe() |
| 4138 | wio = self.io.open(w, **fdopen_kwargs) |
| 4139 | try: |
Gregory P. Smith | b5ba203 | 2012-06-25 01:13:32 -0700 | [diff] [blame] | 4140 | signal.alarm(1) |
Antoine Pitrou | f3b68b3 | 2010-12-03 18:41:39 +0000 | [diff] [blame] | 4141 | # Either the reentrant call to wio.write() fails with RuntimeError, |
| 4142 | # or the signal handler raises ZeroDivisionError. |
| 4143 | with self.assertRaises((ZeroDivisionError, RuntimeError)) as cm: |
| 4144 | while 1: |
| 4145 | for i in range(100): |
| 4146 | wio.write(data) |
| 4147 | wio.flush() |
| 4148 | # Make sure the buffer doesn't fill up and block further writes |
| 4149 | os.read(r, len(data) * 100) |
| 4150 | exc = cm.exception |
| 4151 | if isinstance(exc, RuntimeError): |
| 4152 | self.assertTrue(str(exc).startswith("reentrant call"), str(exc)) |
| 4153 | finally: |
Victor Stinner | 9abee72 | 2017-09-19 09:36:54 -0700 | [diff] [blame] | 4154 | signal.alarm(0) |
Antoine Pitrou | f3b68b3 | 2010-12-03 18:41:39 +0000 | [diff] [blame] | 4155 | wio.close() |
| 4156 | os.close(r) |
| 4157 | |
| 4158 | def test_reentrant_write_buffered(self): |
| 4159 | self.check_reentrant_write(b"xy", mode="wb") |
| 4160 | |
| 4161 | def test_reentrant_write_text(self): |
| 4162 | self.check_reentrant_write("xy", mode="w", encoding="ascii") |
| 4163 | |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4164 | def check_interrupted_read_retry(self, decode, **fdopen_kwargs): |
| 4165 | """Check that a buffered read, when it gets interrupted (either |
| 4166 | returning a partial result or EINTR), properly invokes the signal |
| 4167 | handler and retries if the latter returned successfully.""" |
| 4168 | r, w = os.pipe() |
| 4169 | fdopen_kwargs["closefd"] = False |
| 4170 | def alarm_handler(sig, frame): |
| 4171 | os.write(w, b"bar") |
| 4172 | signal.signal(signal.SIGALRM, alarm_handler) |
| 4173 | try: |
| 4174 | rio = self.io.open(r, **fdopen_kwargs) |
| 4175 | os.write(w, b"foo") |
Gregory P. Smith | b5ba203 | 2012-06-25 01:13:32 -0700 | [diff] [blame] | 4176 | signal.alarm(1) |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4177 | # Expected behaviour: |
| 4178 | # - first raw read() returns partial b"foo" |
| 4179 | # - second raw read() returns EINTR |
| 4180 | # - third raw read() returns b"bar" |
| 4181 | self.assertEqual(decode(rio.read(6)), "foobar") |
| 4182 | finally: |
Victor Stinner | 9abee72 | 2017-09-19 09:36:54 -0700 | [diff] [blame] | 4183 | signal.alarm(0) |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4184 | rio.close() |
| 4185 | os.close(w) |
| 4186 | os.close(r) |
| 4187 | |
Antoine Pitrou | 20db511 | 2011-08-19 20:32:34 +0200 | [diff] [blame] | 4188 | def test_interrupted_read_retry_buffered(self): |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4189 | self.check_interrupted_read_retry(lambda x: x.decode('latin1'), |
| 4190 | mode="rb") |
| 4191 | |
Antoine Pitrou | 20db511 | 2011-08-19 20:32:34 +0200 | [diff] [blame] | 4192 | def test_interrupted_read_retry_text(self): |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4193 | self.check_interrupted_read_retry(lambda x: x, |
| 4194 | mode="r") |
| 4195 | |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4196 | def check_interrupted_write_retry(self, item, **fdopen_kwargs): |
| 4197 | """Check that a buffered write, when it gets interrupted (either |
| 4198 | returning a partial result or EINTR), properly invokes the signal |
| 4199 | handler and retries if the latter returned successfully.""" |
| 4200 | select = support.import_module("select") |
Victor Stinner | 6d3c09f | 2015-03-16 17:57:49 +0100 | [diff] [blame] | 4201 | |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4202 | # A quantity that exceeds the buffer size of an anonymous pipe's |
| 4203 | # write end. |
Antoine Pitrou | e1a1674 | 2013-04-24 23:31:38 +0200 | [diff] [blame] | 4204 | N = support.PIPE_MAX_SIZE |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4205 | r, w = os.pipe() |
| 4206 | fdopen_kwargs["closefd"] = False |
Victor Stinner | 6d3c09f | 2015-03-16 17:57:49 +0100 | [diff] [blame] | 4207 | |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4208 | # We need a separate thread to read from the pipe and allow the |
| 4209 | # write() to finish. This thread is started after the SIGALRM is |
| 4210 | # received (forcing a first EINTR in write()). |
| 4211 | read_results = [] |
| 4212 | write_finished = False |
Serhiy Storchaka | 9db5500 | 2015-03-28 20:38:37 +0200 | [diff] [blame] | 4213 | error = None |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4214 | def _read(): |
Serhiy Storchaka | 9db5500 | 2015-03-28 20:38:37 +0200 | [diff] [blame] | 4215 | try: |
| 4216 | while not write_finished: |
| 4217 | while r in select.select([r], [], [], 1.0)[0]: |
| 4218 | s = os.read(r, 1024) |
| 4219 | read_results.append(s) |
| 4220 | except BaseException as exc: |
| 4221 | nonlocal error |
| 4222 | error = exc |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4223 | t = threading.Thread(target=_read) |
| 4224 | t.daemon = True |
| 4225 | def alarm1(sig, frame): |
| 4226 | signal.signal(signal.SIGALRM, alarm2) |
Gregory P. Smith | b5ba203 | 2012-06-25 01:13:32 -0700 | [diff] [blame] | 4227 | signal.alarm(1) |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4228 | def alarm2(sig, frame): |
| 4229 | t.start() |
Victor Stinner | 6d3c09f | 2015-03-16 17:57:49 +0100 | [diff] [blame] | 4230 | |
| 4231 | large_data = item * N |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4232 | signal.signal(signal.SIGALRM, alarm1) |
| 4233 | try: |
| 4234 | wio = self.io.open(w, **fdopen_kwargs) |
Gregory P. Smith | b5ba203 | 2012-06-25 01:13:32 -0700 | [diff] [blame] | 4235 | signal.alarm(1) |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4236 | # Expected behaviour: |
| 4237 | # - first raw write() is partial (because of the limited pipe buffer |
| 4238 | # and the first alarm) |
| 4239 | # - second raw write() returns EINTR (because of the second alarm) |
| 4240 | # - subsequent write()s are successful (either partial or complete) |
Victor Stinner | 6d3c09f | 2015-03-16 17:57:49 +0100 | [diff] [blame] | 4241 | written = wio.write(large_data) |
| 4242 | self.assertEqual(N, written) |
| 4243 | |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4244 | wio.flush() |
| 4245 | write_finished = True |
| 4246 | t.join() |
Victor Stinner | 6d3c09f | 2015-03-16 17:57:49 +0100 | [diff] [blame] | 4247 | |
Serhiy Storchaka | 9db5500 | 2015-03-28 20:38:37 +0200 | [diff] [blame] | 4248 | self.assertIsNone(error) |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4249 | self.assertEqual(N, sum(len(x) for x in read_results)) |
| 4250 | finally: |
Victor Stinner | 9abee72 | 2017-09-19 09:36:54 -0700 | [diff] [blame] | 4251 | signal.alarm(0) |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4252 | write_finished = True |
| 4253 | os.close(w) |
| 4254 | os.close(r) |
| 4255 | # This is deliberate. If we didn't close the file descriptor |
| 4256 | # before closing wio, wio would try to flush its internal |
| 4257 | # buffer, and could block (in case of failure). |
| 4258 | try: |
| 4259 | wio.close() |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 4260 | except OSError as e: |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4261 | if e.errno != errno.EBADF: |
| 4262 | raise |
| 4263 | |
Antoine Pitrou | 20db511 | 2011-08-19 20:32:34 +0200 | [diff] [blame] | 4264 | def test_interrupted_write_retry_buffered(self): |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4265 | self.check_interrupted_write_retry(b"x", mode="wb") |
| 4266 | |
Antoine Pitrou | 20db511 | 2011-08-19 20:32:34 +0200 | [diff] [blame] | 4267 | def test_interrupted_write_retry_text(self): |
Antoine Pitrou | 707ce82 | 2011-02-25 21:24:11 +0000 | [diff] [blame] | 4268 | self.check_interrupted_write_retry("x", mode="w", encoding="latin1") |
| 4269 | |
Antoine Pitrou | f3b68b3 | 2010-12-03 18:41:39 +0000 | [diff] [blame] | 4270 | |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4271 | class CSignalsTest(SignalsTest): |
| 4272 | io = io |
| 4273 | |
| 4274 | class PySignalsTest(SignalsTest): |
| 4275 | io = pyio |
| 4276 | |
Antoine Pitrou | f3b68b3 | 2010-12-03 18:41:39 +0000 | [diff] [blame] | 4277 | # Handling reentrancy issues would slow down _pyio even more, so the |
| 4278 | # tests are disabled. |
| 4279 | test_reentrant_write_buffered = None |
| 4280 | test_reentrant_write_text = None |
| 4281 | |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4282 | |
Ezio Melotti | daa42c7 | 2013-03-23 16:30:16 +0200 | [diff] [blame] | 4283 | def load_tests(*args): |
Gregory P. Smith | 1bef907 | 2015-04-14 13:24:34 -0700 | [diff] [blame] | 4284 | tests = (CIOTest, PyIOTest, APIMismatchTest, |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 4285 | CBufferedReaderTest, PyBufferedReaderTest, |
| 4286 | CBufferedWriterTest, PyBufferedWriterTest, |
| 4287 | CBufferedRWPairTest, PyBufferedRWPairTest, |
| 4288 | CBufferedRandomTest, PyBufferedRandomTest, |
| 4289 | StatefulIncrementalDecoderTest, |
| 4290 | CIncrementalNewlineDecoderTest, PyIncrementalNewlineDecoderTest, |
| 4291 | CTextIOWrapperTest, PyTextIOWrapperTest, |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 4292 | CMiscIOTest, PyMiscIOTest, |
| 4293 | CSignalsTest, PySignalsTest, |
| 4294 | ) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 4295 | |
| 4296 | # Put the namespaces of the IO module we are testing and some useful mock |
| 4297 | # classes in the __dict__ of each test. |
| 4298 | mocks = (MockRawIO, MisbehavedRawIO, MockFileIO, CloseFailureIO, |
benfogle | 9703f09 | 2017-11-10 16:03:40 -0500 | [diff] [blame] | 4299 | MockNonBlockWriterIO, MockUnseekableIO, MockRawIOWithoutRead, |
| 4300 | SlowFlushRawIO) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 4301 | all_members = io.__all__ + ["IncrementalNewlineDecoder"] |
| 4302 | c_io_ns = {name : getattr(io, name) for name in all_members} |
| 4303 | py_io_ns = {name : getattr(pyio, name) for name in all_members} |
| 4304 | globs = globals() |
| 4305 | c_io_ns.update((x.__name__, globs["C" + x.__name__]) for x in mocks) |
| 4306 | py_io_ns.update((x.__name__, globs["Py" + x.__name__]) for x in mocks) |
| 4307 | # Avoid turning open into a bound method. |
| 4308 | py_io_ns["open"] = pyio.OpenWrapper |
| 4309 | for test in tests: |
| 4310 | if test.__name__.startswith("C"): |
| 4311 | for name, obj in c_io_ns.items(): |
| 4312 | setattr(test, name, obj) |
| 4313 | elif test.__name__.startswith("Py"): |
| 4314 | for name, obj in py_io_ns.items(): |
| 4315 | setattr(test, name, obj) |
| 4316 | |
Ezio Melotti | daa42c7 | 2013-03-23 16:30:16 +0200 | [diff] [blame] | 4317 | suite = unittest.TestSuite([unittest.makeSuite(test) for test in tests]) |
| 4318 | return suite |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 4319 | |
| 4320 | if __name__ == "__main__": |
Ezio Melotti | daa42c7 | 2013-03-23 16:30:16 +0200 | [diff] [blame] | 4321 | unittest.main() |