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 |
| 18 | # the type it is testing as a attribute. Then it provides custom subclasses to |
| 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 | |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 22 | import os |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 23 | import sys |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 24 | import time |
Guido van Rossum | d410395 | 2007-04-12 05:44:49 +0000 | [diff] [blame] | 25 | import array |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 26 | import random |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 27 | import unittest |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 28 | import weakref |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 29 | import abc |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 30 | import signal |
| 31 | import errno |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 32 | import warnings |
Georg Brandl | 1b37e87 | 2010-03-14 10:45:50 +0000 | [diff] [blame] | 33 | from itertools import cycle, count |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 34 | from collections import deque |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 35 | from test import support |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 36 | |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 37 | import codecs |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 38 | import io # C implementation of io |
| 39 | import _pyio as pyio # Python implementation of io |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 40 | try: |
| 41 | import threading |
| 42 | except ImportError: |
| 43 | threading = None |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 44 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 45 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 46 | def _default_chunk_size(): |
| 47 | """Get the default TextIOWrapper chunk size""" |
| 48 | with open(__file__, "r", encoding="latin1") as f: |
| 49 | return f._CHUNK_SIZE |
| 50 | |
| 51 | |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 52 | class MockRawIOWithoutRead: |
| 53 | """A RawIO implementation without read(), so as to exercise the default |
| 54 | RawIO.read() which calls readinto().""" |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 55 | |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 56 | def __init__(self, read_stack=()): |
| 57 | self._read_stack = list(read_stack) |
| 58 | self._write_stack = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 59 | self._reads = 0 |
Antoine Pitrou | 32cfede | 2010-08-11 13:31:33 +0000 | [diff] [blame] | 60 | self._extraneous_reads = 0 |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 61 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 62 | def write(self, b): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 63 | self._write_stack.append(bytes(b)) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 64 | return len(b) |
| 65 | |
| 66 | def writable(self): |
| 67 | return True |
| 68 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 69 | def fileno(self): |
| 70 | return 42 |
| 71 | |
| 72 | def readable(self): |
| 73 | return True |
| 74 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 75 | def seekable(self): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 76 | return True |
| 77 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 78 | def seek(self, pos, whence): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 79 | return 0 # wrong but we gotta return something |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 80 | |
| 81 | def tell(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 82 | return 0 # same comment as above |
| 83 | |
| 84 | def readinto(self, buf): |
| 85 | self._reads += 1 |
| 86 | max_len = len(buf) |
| 87 | try: |
| 88 | data = self._read_stack[0] |
| 89 | except IndexError: |
Antoine Pitrou | 32cfede | 2010-08-11 13:31:33 +0000 | [diff] [blame] | 90 | self._extraneous_reads += 1 |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 91 | return 0 |
| 92 | if data is None: |
| 93 | del self._read_stack[0] |
| 94 | return None |
| 95 | n = len(data) |
| 96 | if len(data) <= max_len: |
| 97 | del self._read_stack[0] |
| 98 | buf[:n] = data |
| 99 | return n |
| 100 | else: |
| 101 | buf[:] = data[:max_len] |
| 102 | self._read_stack[0] = data[max_len:] |
| 103 | return max_len |
| 104 | |
| 105 | def truncate(self, pos=None): |
| 106 | return pos |
| 107 | |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 108 | class CMockRawIOWithoutRead(MockRawIOWithoutRead, io.RawIOBase): |
| 109 | pass |
| 110 | |
| 111 | class PyMockRawIOWithoutRead(MockRawIOWithoutRead, pyio.RawIOBase): |
| 112 | pass |
| 113 | |
| 114 | |
| 115 | class MockRawIO(MockRawIOWithoutRead): |
| 116 | |
| 117 | def read(self, n=None): |
| 118 | self._reads += 1 |
| 119 | try: |
| 120 | return self._read_stack.pop(0) |
| 121 | except: |
| 122 | self._extraneous_reads += 1 |
| 123 | return b"" |
| 124 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 125 | class CMockRawIO(MockRawIO, io.RawIOBase): |
| 126 | pass |
| 127 | |
| 128 | class PyMockRawIO(MockRawIO, pyio.RawIOBase): |
| 129 | pass |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 130 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 131 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 132 | class MisbehavedRawIO(MockRawIO): |
| 133 | def write(self, b): |
| 134 | return super().write(b) * 2 |
| 135 | |
| 136 | def read(self, n=None): |
| 137 | return super().read(n) * 2 |
| 138 | |
| 139 | def seek(self, pos, whence): |
| 140 | return -123 |
| 141 | |
| 142 | def tell(self): |
| 143 | return -456 |
| 144 | |
| 145 | def readinto(self, buf): |
| 146 | super().readinto(buf) |
| 147 | return len(buf) * 5 |
| 148 | |
| 149 | class CMisbehavedRawIO(MisbehavedRawIO, io.RawIOBase): |
| 150 | pass |
| 151 | |
| 152 | class PyMisbehavedRawIO(MisbehavedRawIO, pyio.RawIOBase): |
| 153 | pass |
| 154 | |
| 155 | |
| 156 | class CloseFailureIO(MockRawIO): |
| 157 | closed = 0 |
| 158 | |
| 159 | def close(self): |
| 160 | if not self.closed: |
| 161 | self.closed = 1 |
| 162 | raise IOError |
| 163 | |
| 164 | class CCloseFailureIO(CloseFailureIO, io.RawIOBase): |
| 165 | pass |
| 166 | |
| 167 | class PyCloseFailureIO(CloseFailureIO, pyio.RawIOBase): |
| 168 | pass |
| 169 | |
| 170 | |
| 171 | class MockFileIO: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 172 | |
| 173 | def __init__(self, data): |
| 174 | self.read_history = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 175 | super().__init__(data) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 176 | |
| 177 | def read(self, n=None): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 178 | res = super().read(n) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 179 | self.read_history.append(None if res is None else len(res)) |
| 180 | return res |
| 181 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 182 | def readinto(self, b): |
| 183 | res = super().readinto(b) |
| 184 | self.read_history.append(res) |
| 185 | return res |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 186 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 187 | class CMockFileIO(MockFileIO, io.BytesIO): |
| 188 | pass |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 189 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 190 | class PyMockFileIO(MockFileIO, pyio.BytesIO): |
| 191 | pass |
| 192 | |
| 193 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 194 | class MockUnseekableIO: |
| 195 | def seekable(self): |
| 196 | return False |
| 197 | |
| 198 | def seek(self, *args): |
| 199 | raise self.UnsupportedOperation("not seekable") |
| 200 | |
| 201 | def tell(self, *args): |
| 202 | raise self.UnsupportedOperation("not seekable") |
| 203 | |
| 204 | class CMockUnseekableIO(MockUnseekableIO, io.BytesIO): |
| 205 | UnsupportedOperation = io.UnsupportedOperation |
| 206 | |
| 207 | class PyMockUnseekableIO(MockUnseekableIO, pyio.BytesIO): |
| 208 | UnsupportedOperation = pyio.UnsupportedOperation |
| 209 | |
| 210 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 211 | class MockNonBlockWriterIO: |
| 212 | |
| 213 | def __init__(self): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 214 | self._write_stack = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 215 | self._blocker_char = None |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 216 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 217 | def pop_written(self): |
| 218 | s = b"".join(self._write_stack) |
| 219 | self._write_stack[:] = [] |
| 220 | return s |
| 221 | |
| 222 | def block_on(self, char): |
| 223 | """Block when a given char is encountered.""" |
| 224 | self._blocker_char = char |
| 225 | |
| 226 | def readable(self): |
| 227 | return True |
| 228 | |
| 229 | def seekable(self): |
| 230 | return True |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 231 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 232 | def writable(self): |
| 233 | return True |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 234 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 235 | def write(self, b): |
| 236 | b = bytes(b) |
| 237 | n = -1 |
| 238 | if self._blocker_char: |
| 239 | try: |
| 240 | n = b.index(self._blocker_char) |
| 241 | except ValueError: |
| 242 | pass |
| 243 | else: |
| 244 | self._blocker_char = None |
| 245 | self._write_stack.append(b[:n]) |
| 246 | raise self.BlockingIOError(0, "test blocking", n) |
| 247 | self._write_stack.append(b) |
| 248 | return len(b) |
| 249 | |
| 250 | class CMockNonBlockWriterIO(MockNonBlockWriterIO, io.RawIOBase): |
| 251 | BlockingIOError = io.BlockingIOError |
| 252 | |
| 253 | class PyMockNonBlockWriterIO(MockNonBlockWriterIO, pyio.RawIOBase): |
| 254 | BlockingIOError = pyio.BlockingIOError |
| 255 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 256 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 257 | class IOTest(unittest.TestCase): |
| 258 | |
Neal Norwitz | e7789b1 | 2008-03-24 06:18:09 +0000 | [diff] [blame] | 259 | def setUp(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 260 | support.unlink(support.TESTFN) |
Neal Norwitz | e7789b1 | 2008-03-24 06:18:09 +0000 | [diff] [blame] | 261 | |
Guido van Rossum | 4d0f5a4 | 2007-03-07 22:59:39 +0000 | [diff] [blame] | 262 | def tearDown(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 263 | support.unlink(support.TESTFN) |
Guido van Rossum | 4d0f5a4 | 2007-03-07 22:59:39 +0000 | [diff] [blame] | 264 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 265 | def write_ops(self, f): |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 266 | self.assertEqual(f.write(b"blah."), 5) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 267 | f.truncate(0) |
| 268 | self.assertEqual(f.tell(), 5) |
| 269 | f.seek(0) |
| 270 | |
| 271 | self.assertEqual(f.write(b"blah."), 5) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 272 | self.assertEqual(f.seek(0), 0) |
| 273 | self.assertEqual(f.write(b"Hello."), 6) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 274 | self.assertEqual(f.tell(), 6) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 275 | self.assertEqual(f.seek(-1, 1), 5) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 276 | self.assertEqual(f.tell(), 5) |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 277 | self.assertEqual(f.write(bytearray(b" world\n\n\n")), 9) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 278 | self.assertEqual(f.seek(0), 0) |
Guido van Rossum | 2b08b38 | 2007-05-08 20:18:39 +0000 | [diff] [blame] | 279 | self.assertEqual(f.write(b"h"), 1) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 280 | self.assertEqual(f.seek(-1, 2), 13) |
| 281 | self.assertEqual(f.tell(), 13) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 282 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 283 | self.assertEqual(f.truncate(12), 12) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 284 | self.assertEqual(f.tell(), 13) |
Christian Heimes | 8e42a0a | 2007-11-08 18:04:45 +0000 | [diff] [blame] | 285 | self.assertRaises(TypeError, f.seek, 0.0) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 286 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 287 | def read_ops(self, f, buffered=False): |
| 288 | data = f.read(5) |
| 289 | self.assertEqual(data, b"hello") |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 290 | data = bytearray(data) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 291 | self.assertEqual(f.readinto(data), 5) |
| 292 | self.assertEqual(data, b" worl") |
| 293 | self.assertEqual(f.readinto(data), 2) |
| 294 | self.assertEqual(len(data), 5) |
| 295 | self.assertEqual(data[:2], b"d\n") |
| 296 | self.assertEqual(f.seek(0), 0) |
| 297 | self.assertEqual(f.read(20), b"hello world\n") |
| 298 | self.assertEqual(f.read(1), b"") |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 299 | self.assertEqual(f.readinto(bytearray(b"x")), 0) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 300 | self.assertEqual(f.seek(-6, 2), 6) |
| 301 | self.assertEqual(f.read(5), b"world") |
| 302 | self.assertEqual(f.read(0), b"") |
Guido van Rossum | 254348e | 2007-11-21 19:29:53 +0000 | [diff] [blame] | 303 | self.assertEqual(f.readinto(bytearray()), 0) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 304 | self.assertEqual(f.seek(-6, 1), 5) |
| 305 | self.assertEqual(f.read(5), b" worl") |
| 306 | self.assertEqual(f.tell(), 10) |
Christian Heimes | 8e42a0a | 2007-11-08 18:04:45 +0000 | [diff] [blame] | 307 | self.assertRaises(TypeError, f.seek, 0.0) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 308 | if buffered: |
| 309 | f.seek(0) |
| 310 | self.assertEqual(f.read(), b"hello world\n") |
| 311 | f.seek(6) |
| 312 | self.assertEqual(f.read(), b"world\n") |
| 313 | self.assertEqual(f.read(), b"") |
| 314 | |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 315 | LARGE = 2**31 |
| 316 | |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 317 | def large_file_ops(self, f): |
| 318 | assert f.readable() |
| 319 | assert f.writable() |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 320 | self.assertEqual(f.seek(self.LARGE), self.LARGE) |
| 321 | self.assertEqual(f.tell(), self.LARGE) |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 322 | self.assertEqual(f.write(b"xxx"), 3) |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 323 | self.assertEqual(f.tell(), self.LARGE + 3) |
| 324 | self.assertEqual(f.seek(-1, 1), self.LARGE + 2) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 325 | self.assertEqual(f.truncate(), self.LARGE + 2) |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 326 | self.assertEqual(f.tell(), self.LARGE + 2) |
| 327 | self.assertEqual(f.seek(0, 2), self.LARGE + 2) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 328 | self.assertEqual(f.truncate(self.LARGE + 1), self.LARGE + 1) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 329 | self.assertEqual(f.tell(), self.LARGE + 2) |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 330 | self.assertEqual(f.seek(0, 2), self.LARGE + 1) |
| 331 | self.assertEqual(f.seek(-1, 2), self.LARGE) |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 332 | self.assertEqual(f.read(2), b"x") |
| 333 | |
Benjamin Peterson | 81971ea | 2009-05-14 22:01:31 +0000 | [diff] [blame] | 334 | def test_invalid_operations(self): |
| 335 | # Try writing on a file opened in read mode and vice-versa. |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 336 | exc = self.UnsupportedOperation |
Benjamin Peterson | 81971ea | 2009-05-14 22:01:31 +0000 | [diff] [blame] | 337 | for mode in ("w", "wb"): |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 338 | with self.open(support.TESTFN, mode) as fp: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 339 | self.assertRaises(exc, fp.read) |
| 340 | self.assertRaises(exc, fp.readline) |
| 341 | with self.open(support.TESTFN, "wb", buffering=0) as fp: |
| 342 | self.assertRaises(exc, fp.read) |
| 343 | self.assertRaises(exc, fp.readline) |
| 344 | with self.open(support.TESTFN, "rb", buffering=0) as fp: |
| 345 | self.assertRaises(exc, fp.write, b"blah") |
| 346 | self.assertRaises(exc, fp.writelines, [b"blah\n"]) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 347 | with self.open(support.TESTFN, "rb") as fp: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 348 | self.assertRaises(exc, fp.write, b"blah") |
| 349 | self.assertRaises(exc, fp.writelines, [b"blah\n"]) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 350 | with self.open(support.TESTFN, "r") as fp: |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 351 | self.assertRaises(exc, fp.write, "blah") |
| 352 | self.assertRaises(exc, fp.writelines, ["blah\n"]) |
| 353 | # Non-zero seeking from current or end pos |
| 354 | self.assertRaises(exc, fp.seek, 1, self.SEEK_CUR) |
| 355 | self.assertRaises(exc, fp.seek, -1, self.SEEK_END) |
Benjamin Peterson | 81971ea | 2009-05-14 22:01:31 +0000 | [diff] [blame] | 356 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 357 | def test_raw_file_io(self): |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 358 | with self.open(support.TESTFN, "wb", buffering=0) as f: |
| 359 | self.assertEqual(f.readable(), False) |
| 360 | self.assertEqual(f.writable(), True) |
| 361 | self.assertEqual(f.seekable(), True) |
| 362 | self.write_ops(f) |
| 363 | with self.open(support.TESTFN, "rb", buffering=0) as f: |
| 364 | self.assertEqual(f.readable(), True) |
| 365 | self.assertEqual(f.writable(), False) |
| 366 | self.assertEqual(f.seekable(), True) |
| 367 | self.read_ops(f) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 368 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 369 | def test_buffered_file_io(self): |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 370 | with self.open(support.TESTFN, "wb") as f: |
| 371 | self.assertEqual(f.readable(), False) |
| 372 | self.assertEqual(f.writable(), True) |
| 373 | self.assertEqual(f.seekable(), True) |
| 374 | self.write_ops(f) |
| 375 | with self.open(support.TESTFN, "rb") as f: |
| 376 | self.assertEqual(f.readable(), True) |
| 377 | self.assertEqual(f.writable(), False) |
| 378 | self.assertEqual(f.seekable(), True) |
| 379 | self.read_ops(f, True) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 380 | |
Guido van Rossum | 48fc58a | 2007-06-07 23:45:37 +0000 | [diff] [blame] | 381 | def test_readline(self): |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 382 | with self.open(support.TESTFN, "wb") as f: |
| 383 | f.write(b"abc\ndef\nxyzzy\nfoo\x00bar\nanother line") |
| 384 | with self.open(support.TESTFN, "rb") as f: |
| 385 | self.assertEqual(f.readline(), b"abc\n") |
| 386 | self.assertEqual(f.readline(10), b"def\n") |
| 387 | self.assertEqual(f.readline(2), b"xy") |
| 388 | self.assertEqual(f.readline(4), b"zzy\n") |
| 389 | self.assertEqual(f.readline(), b"foo\x00bar\n") |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 390 | self.assertEqual(f.readline(None), b"another line") |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 391 | self.assertRaises(TypeError, f.readline, 5.3) |
| 392 | with self.open(support.TESTFN, "r") as f: |
| 393 | self.assertRaises(TypeError, f.readline, 5.3) |
Guido van Rossum | 48fc58a | 2007-06-07 23:45:37 +0000 | [diff] [blame] | 394 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 395 | def test_raw_bytes_io(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 396 | f = self.BytesIO() |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 397 | self.write_ops(f) |
| 398 | data = f.getvalue() |
| 399 | self.assertEqual(data, b"hello world\n") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 400 | f = self.BytesIO(data) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 401 | self.read_ops(f, True) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 402 | |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 403 | def test_large_file_ops(self): |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 404 | # On Windows and Mac OSX this test comsumes large resources; It takes |
| 405 | # a long time to build the >2GB file and takes >2GB of disk space |
| 406 | # therefore the resource must be enabled to run this test. |
| 407 | if sys.platform[:3] == 'win' or sys.platform == 'darwin': |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 408 | if not support.is_resource_enabled("largefile"): |
Guido van Rossum | 34d69e5 | 2007-04-10 20:08:41 +0000 | [diff] [blame] | 409 | print("\nTesting large file ops skipped on %s." % sys.platform, |
| 410 | file=sys.stderr) |
| 411 | print("It requires %d bytes and a long time." % self.LARGE, |
| 412 | file=sys.stderr) |
| 413 | print("Use 'regrtest.py -u largefile test_io' to run it.", |
| 414 | file=sys.stderr) |
| 415 | return |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 416 | with self.open(support.TESTFN, "w+b", 0) as f: |
| 417 | self.large_file_ops(f) |
| 418 | with self.open(support.TESTFN, "w+b") as f: |
| 419 | self.large_file_ops(f) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 420 | |
| 421 | def test_with_open(self): |
| 422 | for bufsize in (0, 1, 100): |
| 423 | f = None |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 424 | with self.open(support.TESTFN, "wb", bufsize) as f: |
Guido van Rossum | 1f2ca56 | 2007-08-27 20:44:15 +0000 | [diff] [blame] | 425 | f.write(b"xxx") |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 426 | self.assertEqual(f.closed, True) |
| 427 | f = None |
| 428 | try: |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 429 | with self.open(support.TESTFN, "wb", bufsize) as f: |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 430 | 1/0 |
| 431 | except ZeroDivisionError: |
| 432 | self.assertEqual(f.closed, True) |
| 433 | else: |
| 434 | self.fail("1/0 didn't raise an exception") |
| 435 | |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 436 | # issue 5008 |
| 437 | def test_append_mode_tell(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 438 | with self.open(support.TESTFN, "wb") as f: |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 439 | f.write(b"xxx") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 440 | with self.open(support.TESTFN, "ab", buffering=0) as f: |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 441 | self.assertEqual(f.tell(), 3) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 442 | with self.open(support.TESTFN, "ab") as f: |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 443 | self.assertEqual(f.tell(), 3) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 444 | with self.open(support.TESTFN, "a") as f: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 445 | self.assertTrue(f.tell() > 0) |
Antoine Pitrou | 08838b6 | 2009-01-21 00:55:13 +0000 | [diff] [blame] | 446 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 447 | def test_destructor(self): |
| 448 | record = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 449 | class MyFileIO(self.FileIO): |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 450 | def __del__(self): |
| 451 | record.append(1) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 452 | try: |
| 453 | f = super().__del__ |
| 454 | except AttributeError: |
| 455 | pass |
| 456 | else: |
| 457 | f() |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 458 | def close(self): |
| 459 | record.append(2) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 460 | super().close() |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 461 | def flush(self): |
| 462 | record.append(3) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 463 | super().flush() |
Brett Cannon | 5a9e91b | 2010-10-29 23:53:03 +0000 | [diff] [blame] | 464 | with support.check_warnings(('', ResourceWarning)): |
| 465 | f = MyFileIO(support.TESTFN, "wb") |
| 466 | f.write(b"xxx") |
| 467 | del f |
| 468 | support.gc_collect() |
| 469 | self.assertEqual(record, [1, 2, 3]) |
| 470 | with self.open(support.TESTFN, "rb") as f: |
| 471 | self.assertEqual(f.read(), b"xxx") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 472 | |
| 473 | def _check_base_destructor(self, base): |
| 474 | record = [] |
| 475 | class MyIO(base): |
| 476 | def __init__(self): |
| 477 | # This exercises the availability of attributes on object |
| 478 | # destruction. |
| 479 | # (in the C version, close() is called by the tp_dealloc |
| 480 | # function, not by __del__) |
| 481 | self.on_del = 1 |
| 482 | self.on_close = 2 |
| 483 | self.on_flush = 3 |
| 484 | def __del__(self): |
| 485 | record.append(self.on_del) |
| 486 | try: |
| 487 | f = super().__del__ |
| 488 | except AttributeError: |
| 489 | pass |
| 490 | else: |
| 491 | f() |
| 492 | def close(self): |
| 493 | record.append(self.on_close) |
| 494 | super().close() |
| 495 | def flush(self): |
| 496 | record.append(self.on_flush) |
| 497 | super().flush() |
| 498 | f = MyIO() |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 499 | del f |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 500 | support.gc_collect() |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 501 | self.assertEqual(record, [1, 2, 3]) |
| 502 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 503 | def test_IOBase_destructor(self): |
| 504 | self._check_base_destructor(self.IOBase) |
| 505 | |
| 506 | def test_RawIOBase_destructor(self): |
| 507 | self._check_base_destructor(self.RawIOBase) |
| 508 | |
| 509 | def test_BufferedIOBase_destructor(self): |
| 510 | self._check_base_destructor(self.BufferedIOBase) |
| 511 | |
| 512 | def test_TextIOBase_destructor(self): |
| 513 | self._check_base_destructor(self.TextIOBase) |
| 514 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 515 | def test_close_flushes(self): |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 516 | with self.open(support.TESTFN, "wb") as f: |
| 517 | f.write(b"xxx") |
| 518 | with self.open(support.TESTFN, "rb") as f: |
| 519 | self.assertEqual(f.read(), b"xxx") |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 520 | |
Guido van Rossum | d410395 | 2007-04-12 05:44:49 +0000 | [diff] [blame] | 521 | def test_array_writes(self): |
| 522 | a = array.array('i', range(10)) |
Antoine Pitrou | 1ce3eb5 | 2010-09-01 20:29:34 +0000 | [diff] [blame] | 523 | n = len(a.tobytes()) |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 524 | with self.open(support.TESTFN, "wb", 0) as f: |
| 525 | self.assertEqual(f.write(a), n) |
| 526 | with self.open(support.TESTFN, "wb") as f: |
| 527 | self.assertEqual(f.write(a), n) |
Guido van Rossum | d410395 | 2007-04-12 05:44:49 +0000 | [diff] [blame] | 528 | |
Guido van Rossum | 2dced8b | 2007-10-30 17:27:30 +0000 | [diff] [blame] | 529 | def test_closefd(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 530 | self.assertRaises(ValueError, self.open, support.TESTFN, 'w', |
Guido van Rossum | 2dced8b | 2007-10-30 17:27:30 +0000 | [diff] [blame] | 531 | closefd=False) |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 532 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 533 | def test_read_closed(self): |
| 534 | with self.open(support.TESTFN, "w") as f: |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 535 | f.write("egg\n") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 536 | with self.open(support.TESTFN, "r") as f: |
| 537 | file = self.open(f.fileno(), "r", closefd=False) |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 538 | self.assertEqual(file.read(), "egg\n") |
| 539 | file.seek(0) |
| 540 | file.close() |
| 541 | self.assertRaises(ValueError, file.read) |
| 542 | |
| 543 | def test_no_closefd_with_filename(self): |
| 544 | # can't use closefd in combination with a file name |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 545 | self.assertRaises(ValueError, self.open, support.TESTFN, "r", closefd=False) |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 546 | |
| 547 | def test_closefd_attr(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 548 | with self.open(support.TESTFN, "wb") as f: |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 549 | f.write(b"egg\n") |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 550 | with self.open(support.TESTFN, "r") as f: |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 551 | self.assertEqual(f.buffer.raw.closefd, True) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 552 | file = self.open(f.fileno(), "r", closefd=False) |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 553 | self.assertEqual(file.buffer.raw.closefd, False) |
| 554 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 555 | def test_garbage_collection(self): |
| 556 | # FileIO objects are collected, and collecting them flushes |
| 557 | # all data to disk. |
Benjamin Peterson | ebe5d8a | 2010-10-31 01:30:11 +0000 | [diff] [blame] | 558 | with support.check_warnings(('', ResourceWarning)): |
| 559 | f = self.FileIO(support.TESTFN, "wb") |
| 560 | f.write(b"abcxxx") |
| 561 | f.f = f |
| 562 | wr = weakref.ref(f) |
| 563 | del f |
| 564 | support.gc_collect() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 565 | self.assertTrue(wr() is None, wr) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 566 | with self.open(support.TESTFN, "rb") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 567 | self.assertEqual(f.read(), b"abcxxx") |
Christian Heimes | ecc42a2 | 2008-11-05 19:30:32 +0000 | [diff] [blame] | 568 | |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 569 | def test_unbounded_file(self): |
| 570 | # Issue #1174606: reading from an unbounded stream such as /dev/zero. |
| 571 | zero = "/dev/zero" |
| 572 | if not os.path.exists(zero): |
Antoine Pitrou | c50cb8e | 2009-04-19 00:10:36 +0000 | [diff] [blame] | 573 | self.skipTest("{0} does not exist".format(zero)) |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 574 | if sys.maxsize > 0x7FFFFFFF: |
Antoine Pitrou | c50cb8e | 2009-04-19 00:10:36 +0000 | [diff] [blame] | 575 | self.skipTest("test can only run in a 32-bit address space") |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 576 | if support.real_max_memuse < support._2G: |
Antoine Pitrou | c50cb8e | 2009-04-19 00:10:36 +0000 | [diff] [blame] | 577 | self.skipTest("test requires at least 2GB of memory") |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 578 | with self.open(zero, "rb", buffering=0) as f: |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 579 | self.assertRaises(OverflowError, f.read) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 580 | with self.open(zero, "rb") as f: |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 581 | self.assertRaises(OverflowError, f.read) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 582 | with self.open(zero, "r") as f: |
Antoine Pitrou | 7d037a7 | 2009-03-29 18:55:12 +0000 | [diff] [blame] | 583 | self.assertRaises(OverflowError, f.read) |
| 584 | |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 585 | def test_flush_error_on_close(self): |
| 586 | f = self.open(support.TESTFN, "wb", buffering=0) |
| 587 | def bad_flush(): |
| 588 | raise IOError() |
| 589 | f.flush = bad_flush |
| 590 | self.assertRaises(IOError, f.close) # exception not swallowed |
| 591 | |
| 592 | def test_multi_close(self): |
| 593 | f = self.open(support.TESTFN, "wb", buffering=0) |
| 594 | f.close() |
| 595 | f.close() |
| 596 | f.close() |
| 597 | self.assertRaises(ValueError, f.flush) |
| 598 | |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 599 | def test_RawIOBase_read(self): |
| 600 | # Exercise the default RawIOBase.read() implementation (which calls |
| 601 | # readinto() internally). |
| 602 | rawio = self.MockRawIOWithoutRead((b"abc", b"d", None, b"efg", None)) |
| 603 | self.assertEqual(rawio.read(2), b"ab") |
| 604 | self.assertEqual(rawio.read(2), b"c") |
| 605 | self.assertEqual(rawio.read(2), b"d") |
| 606 | self.assertEqual(rawio.read(2), None) |
| 607 | self.assertEqual(rawio.read(2), b"ef") |
| 608 | self.assertEqual(rawio.read(2), b"g") |
| 609 | self.assertEqual(rawio.read(2), None) |
| 610 | self.assertEqual(rawio.read(2), b"") |
| 611 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 612 | class CIOTest(IOTest): |
| 613 | pass |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 614 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 615 | class PyIOTest(IOTest): |
| 616 | pass |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 617 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 618 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 619 | class CommonBufferedTests: |
| 620 | # Tests common to BufferedReader, BufferedWriter and BufferedRandom |
| 621 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 622 | def test_detach(self): |
| 623 | raw = self.MockRawIO() |
| 624 | buf = self.tp(raw) |
| 625 | self.assertIs(buf.detach(), raw) |
| 626 | self.assertRaises(ValueError, buf.detach) |
| 627 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 628 | def test_fileno(self): |
| 629 | rawio = self.MockRawIO() |
| 630 | bufio = self.tp(rawio) |
| 631 | |
| 632 | self.assertEquals(42, bufio.fileno()) |
| 633 | |
| 634 | def test_no_fileno(self): |
| 635 | # XXX will we always have fileno() function? If so, kill |
| 636 | # this test. Else, write it. |
| 637 | pass |
| 638 | |
| 639 | def test_invalid_args(self): |
| 640 | rawio = self.MockRawIO() |
| 641 | bufio = self.tp(rawio) |
| 642 | # Invalid whence |
| 643 | self.assertRaises(ValueError, bufio.seek, 0, -1) |
| 644 | self.assertRaises(ValueError, bufio.seek, 0, 3) |
| 645 | |
| 646 | def test_override_destructor(self): |
| 647 | tp = self.tp |
| 648 | record = [] |
| 649 | class MyBufferedIO(tp): |
| 650 | def __del__(self): |
| 651 | record.append(1) |
| 652 | try: |
| 653 | f = super().__del__ |
| 654 | except AttributeError: |
| 655 | pass |
| 656 | else: |
| 657 | f() |
| 658 | def close(self): |
| 659 | record.append(2) |
| 660 | super().close() |
| 661 | def flush(self): |
| 662 | record.append(3) |
| 663 | super().flush() |
| 664 | rawio = self.MockRawIO() |
| 665 | bufio = MyBufferedIO(rawio) |
| 666 | writable = bufio.writable() |
| 667 | del bufio |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 668 | support.gc_collect() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 669 | if writable: |
| 670 | self.assertEqual(record, [1, 2, 3]) |
| 671 | else: |
| 672 | self.assertEqual(record, [1, 2]) |
| 673 | |
| 674 | def test_context_manager(self): |
| 675 | # Test usability as a context manager |
| 676 | rawio = self.MockRawIO() |
| 677 | bufio = self.tp(rawio) |
| 678 | def _with(): |
| 679 | with bufio: |
| 680 | pass |
| 681 | _with() |
| 682 | # bufio should now be closed, and using it a second time should raise |
| 683 | # a ValueError. |
| 684 | self.assertRaises(ValueError, _with) |
| 685 | |
| 686 | def test_error_through_destructor(self): |
| 687 | # Test that the exception state is not modified by a destructor, |
| 688 | # even if close() fails. |
| 689 | rawio = self.CloseFailureIO() |
| 690 | def f(): |
| 691 | self.tp(rawio).xyzzy |
| 692 | with support.captured_output("stderr") as s: |
| 693 | self.assertRaises(AttributeError, f) |
| 694 | s = s.getvalue().strip() |
| 695 | if s: |
| 696 | # The destructor *may* have printed an unraisable error, check it |
| 697 | self.assertEqual(len(s.splitlines()), 1) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 698 | self.assertTrue(s.startswith("Exception IOError: "), s) |
| 699 | self.assertTrue(s.endswith(" ignored"), s) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 700 | |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 701 | def test_repr(self): |
| 702 | raw = self.MockRawIO() |
| 703 | b = self.tp(raw) |
| 704 | clsname = "%s.%s" % (self.tp.__module__, self.tp.__name__) |
| 705 | self.assertEqual(repr(b), "<%s>" % clsname) |
| 706 | raw.name = "dummy" |
| 707 | self.assertEqual(repr(b), "<%s name='dummy'>" % clsname) |
| 708 | raw.name = b"dummy" |
| 709 | self.assertEqual(repr(b), "<%s name=b'dummy'>" % clsname) |
| 710 | |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 711 | def test_flush_error_on_close(self): |
| 712 | raw = self.MockRawIO() |
| 713 | def bad_flush(): |
| 714 | raise IOError() |
| 715 | raw.flush = bad_flush |
| 716 | b = self.tp(raw) |
| 717 | self.assertRaises(IOError, b.close) # exception not swallowed |
| 718 | |
| 719 | def test_multi_close(self): |
| 720 | raw = self.MockRawIO() |
| 721 | b = self.tp(raw) |
| 722 | b.close() |
| 723 | b.close() |
| 724 | b.close() |
| 725 | self.assertRaises(ValueError, b.flush) |
| 726 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 727 | def test_unseekable(self): |
| 728 | bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) |
| 729 | self.assertRaises(self.UnsupportedOperation, bufio.tell) |
| 730 | self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) |
| 731 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 732 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 733 | class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): |
| 734 | read_mode = "rb" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 735 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 736 | def test_constructor(self): |
| 737 | rawio = self.MockRawIO([b"abc"]) |
| 738 | bufio = self.tp(rawio) |
| 739 | bufio.__init__(rawio) |
| 740 | bufio.__init__(rawio, buffer_size=1024) |
| 741 | bufio.__init__(rawio, buffer_size=16) |
| 742 | self.assertEquals(b"abc", bufio.read()) |
| 743 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) |
| 744 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) |
| 745 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) |
| 746 | rawio = self.MockRawIO([b"abc"]) |
| 747 | bufio.__init__(rawio) |
| 748 | self.assertEquals(b"abc", bufio.read()) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 749 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 750 | def test_read(self): |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 751 | for arg in (None, 7): |
| 752 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 753 | bufio = self.tp(rawio) |
| 754 | self.assertEquals(b"abcdefg", bufio.read(arg)) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 755 | # Invalid args |
| 756 | self.assertRaises(ValueError, bufio.read, -2) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 757 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 758 | def test_read1(self): |
| 759 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 760 | bufio = self.tp(rawio) |
| 761 | self.assertEquals(b"a", bufio.read(1)) |
| 762 | self.assertEquals(b"b", bufio.read1(1)) |
| 763 | self.assertEquals(rawio._reads, 1) |
| 764 | self.assertEquals(b"c", bufio.read1(100)) |
| 765 | self.assertEquals(rawio._reads, 1) |
| 766 | self.assertEquals(b"d", bufio.read1(100)) |
| 767 | self.assertEquals(rawio._reads, 2) |
| 768 | self.assertEquals(b"efg", bufio.read1(100)) |
| 769 | self.assertEquals(rawio._reads, 3) |
| 770 | self.assertEquals(b"", bufio.read1(100)) |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 771 | self.assertEquals(rawio._reads, 4) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 772 | # Invalid args |
| 773 | self.assertRaises(ValueError, bufio.read1, -1) |
| 774 | |
| 775 | def test_readinto(self): |
| 776 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 777 | bufio = self.tp(rawio) |
| 778 | b = bytearray(2) |
| 779 | self.assertEquals(bufio.readinto(b), 2) |
| 780 | self.assertEquals(b, b"ab") |
| 781 | self.assertEquals(bufio.readinto(b), 2) |
| 782 | self.assertEquals(b, b"cd") |
| 783 | self.assertEquals(bufio.readinto(b), 2) |
| 784 | self.assertEquals(b, b"ef") |
| 785 | self.assertEquals(bufio.readinto(b), 1) |
| 786 | self.assertEquals(b, b"gf") |
| 787 | self.assertEquals(bufio.readinto(b), 0) |
| 788 | self.assertEquals(b, b"gf") |
| 789 | |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 790 | def test_readlines(self): |
| 791 | def bufio(): |
| 792 | rawio = self.MockRawIO((b"abc\n", b"d\n", b"ef")) |
| 793 | return self.tp(rawio) |
| 794 | self.assertEquals(bufio().readlines(), [b"abc\n", b"d\n", b"ef"]) |
| 795 | self.assertEquals(bufio().readlines(5), [b"abc\n", b"d\n"]) |
| 796 | self.assertEquals(bufio().readlines(None), [b"abc\n", b"d\n", b"ef"]) |
| 797 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 798 | def test_buffering(self): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 799 | data = b"abcdefghi" |
| 800 | dlen = len(data) |
| 801 | |
| 802 | tests = [ |
| 803 | [ 100, [ 3, 1, 4, 8 ], [ dlen, 0 ] ], |
| 804 | [ 100, [ 3, 3, 3], [ dlen ] ], |
| 805 | [ 4, [ 1, 2, 4, 2 ], [ 4, 4, 1 ] ], |
| 806 | ] |
| 807 | |
| 808 | for bufsize, buf_read_sizes, raw_read_sizes in tests: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 809 | rawio = self.MockFileIO(data) |
| 810 | bufio = self.tp(rawio, buffer_size=bufsize) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 811 | pos = 0 |
| 812 | for nbytes in buf_read_sizes: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 813 | self.assertEquals(bufio.read(nbytes), data[pos:pos+nbytes]) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 814 | pos += nbytes |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 815 | # this is mildly implementation-dependent |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 816 | self.assertEquals(rawio.read_history, raw_read_sizes) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 817 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 818 | def test_read_non_blocking(self): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 819 | # Inject some None's in there to simulate EWOULDBLOCK |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 820 | rawio = self.MockRawIO((b"abc", b"d", None, b"efg", None, None, None)) |
| 821 | bufio = self.tp(rawio) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 822 | |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 823 | self.assertEquals(b"abcd", bufio.read(6)) |
| 824 | self.assertEquals(b"e", bufio.read(1)) |
| 825 | self.assertEquals(b"fg", bufio.read()) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 826 | self.assertEquals(b"", bufio.peek(1)) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 827 | self.assertTrue(None is bufio.read()) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 828 | self.assertEquals(b"", bufio.read()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 829 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 830 | def test_read_past_eof(self): |
| 831 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 832 | bufio = self.tp(rawio) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 833 | |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 834 | self.assertEquals(b"abcdefg", bufio.read(9000)) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 835 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 836 | def test_read_all(self): |
| 837 | rawio = self.MockRawIO((b"abc", b"d", b"efg")) |
| 838 | bufio = self.tp(rawio) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 839 | |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 840 | self.assertEquals(b"abcdefg", bufio.read()) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 841 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 842 | @unittest.skipUnless(threading, 'Threading required for this test.') |
Antoine Pitrou | 5bc4fa7 | 2010-10-14 15:34:31 +0000 | [diff] [blame] | 843 | @support.requires_resource('cpu') |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 844 | def test_threads(self): |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 845 | try: |
| 846 | # Write out many bytes with exactly the same number of 0's, |
| 847 | # 1's... 255's. This will help us check that concurrent reading |
| 848 | # doesn't duplicate or forget contents. |
| 849 | N = 1000 |
| 850 | l = list(range(256)) * N |
| 851 | random.shuffle(l) |
| 852 | s = bytes(bytearray(l)) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 853 | with self.open(support.TESTFN, "wb") as f: |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 854 | f.write(s) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 855 | with self.open(support.TESTFN, self.read_mode, buffering=0) as raw: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 856 | bufio = self.tp(raw, 8) |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 857 | errors = [] |
| 858 | results = [] |
| 859 | def f(): |
| 860 | try: |
| 861 | # Intra-buffer read then buffer-flushing read |
| 862 | for n in cycle([1, 19]): |
| 863 | s = bufio.read(n) |
| 864 | if not s: |
| 865 | break |
| 866 | # list.append() is atomic |
| 867 | results.append(s) |
| 868 | except Exception as e: |
| 869 | errors.append(e) |
| 870 | raise |
| 871 | threads = [threading.Thread(target=f) for x in range(20)] |
| 872 | for t in threads: |
| 873 | t.start() |
| 874 | time.sleep(0.02) # yield |
| 875 | for t in threads: |
| 876 | t.join() |
| 877 | self.assertFalse(errors, |
| 878 | "the following exceptions were caught: %r" % errors) |
| 879 | s = b''.join(results) |
| 880 | for i in range(256): |
| 881 | c = bytes(bytearray([i])) |
| 882 | self.assertEqual(s.count(c), N) |
| 883 | finally: |
| 884 | support.unlink(support.TESTFN) |
| 885 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 886 | def test_misbehaved_io(self): |
| 887 | rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) |
| 888 | bufio = self.tp(rawio) |
| 889 | self.assertRaises(IOError, bufio.seek, 0) |
| 890 | self.assertRaises(IOError, bufio.tell) |
| 891 | |
Antoine Pitrou | 32cfede | 2010-08-11 13:31:33 +0000 | [diff] [blame] | 892 | def test_no_extraneous_read(self): |
| 893 | # Issue #9550; when the raw IO object has satisfied the read request, |
| 894 | # we should not issue any additional reads, otherwise it may block |
| 895 | # (e.g. socket). |
| 896 | bufsize = 16 |
| 897 | for n in (2, bufsize - 1, bufsize, bufsize + 1, bufsize * 2): |
| 898 | rawio = self.MockRawIO([b"x" * n]) |
| 899 | bufio = self.tp(rawio, bufsize) |
| 900 | self.assertEqual(bufio.read(n), b"x" * n) |
| 901 | # Simple case: one raw read is enough to satisfy the request. |
| 902 | self.assertEqual(rawio._extraneous_reads, 0, |
| 903 | "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) |
| 904 | # A more complex case where two raw reads are needed to satisfy |
| 905 | # the request. |
| 906 | rawio = self.MockRawIO([b"x" * (n - 1), b"x"]) |
| 907 | bufio = self.tp(rawio, bufsize) |
| 908 | self.assertEqual(bufio.read(n), b"x" * n) |
| 909 | self.assertEqual(rawio._extraneous_reads, 0, |
| 910 | "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) |
| 911 | |
| 912 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 913 | class CBufferedReaderTest(BufferedReaderTest): |
| 914 | tp = io.BufferedReader |
| 915 | |
| 916 | def test_constructor(self): |
| 917 | BufferedReaderTest.test_constructor(self) |
| 918 | # The allocation can succeed on 32-bit builds, e.g. with more |
| 919 | # than 2GB RAM and a 64-bit kernel. |
| 920 | if sys.maxsize > 0x7FFFFFFF: |
| 921 | rawio = self.MockRawIO() |
| 922 | bufio = self.tp(rawio) |
| 923 | self.assertRaises((OverflowError, MemoryError, ValueError), |
| 924 | bufio.__init__, rawio, sys.maxsize) |
| 925 | |
| 926 | def test_initialization(self): |
| 927 | rawio = self.MockRawIO([b"abc"]) |
| 928 | bufio = self.tp(rawio) |
| 929 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) |
| 930 | self.assertRaises(ValueError, bufio.read) |
| 931 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) |
| 932 | self.assertRaises(ValueError, bufio.read) |
| 933 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) |
| 934 | self.assertRaises(ValueError, bufio.read) |
| 935 | |
| 936 | def test_misbehaved_io_read(self): |
| 937 | rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) |
| 938 | bufio = self.tp(rawio) |
| 939 | # _pyio.BufferedReader seems to implement reading different, so that |
| 940 | # checking this is not so easy. |
| 941 | self.assertRaises(IOError, bufio.read, 10) |
| 942 | |
| 943 | def test_garbage_collection(self): |
| 944 | # C BufferedReader objects are collected. |
| 945 | # The Python version has __del__, so it ends into gc.garbage instead |
| 946 | rawio = self.FileIO(support.TESTFN, "w+b") |
| 947 | f = self.tp(rawio) |
| 948 | f.f = f |
| 949 | wr = weakref.ref(f) |
| 950 | del f |
Benjamin Peterson | 45cec32 | 2009-04-24 23:14:50 +0000 | [diff] [blame] | 951 | support.gc_collect() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 952 | self.assertTrue(wr() is None, wr) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 953 | |
| 954 | class PyBufferedReaderTest(BufferedReaderTest): |
| 955 | tp = pyio.BufferedReader |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 956 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 957 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 958 | class BufferedWriterTest(unittest.TestCase, CommonBufferedTests): |
| 959 | write_mode = "wb" |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 960 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 961 | def test_constructor(self): |
| 962 | rawio = self.MockRawIO() |
| 963 | bufio = self.tp(rawio) |
| 964 | bufio.__init__(rawio) |
| 965 | bufio.__init__(rawio, buffer_size=1024) |
| 966 | bufio.__init__(rawio, buffer_size=16) |
| 967 | self.assertEquals(3, bufio.write(b"abc")) |
| 968 | bufio.flush() |
| 969 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) |
| 970 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) |
| 971 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) |
| 972 | bufio.__init__(rawio) |
| 973 | self.assertEquals(3, bufio.write(b"ghi")) |
| 974 | bufio.flush() |
| 975 | self.assertEquals(b"".join(rawio._write_stack), b"abcghi") |
| 976 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 977 | def test_detach_flush(self): |
| 978 | raw = self.MockRawIO() |
| 979 | buf = self.tp(raw) |
| 980 | buf.write(b"howdy!") |
| 981 | self.assertFalse(raw._write_stack) |
| 982 | buf.detach() |
| 983 | self.assertEqual(raw._write_stack, [b"howdy!"]) |
| 984 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 985 | def test_write(self): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 986 | # Write to the buffered IO but don't overflow the buffer. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 987 | writer = self.MockRawIO() |
| 988 | bufio = self.tp(writer, 8) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 989 | bufio.write(b"abc") |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 990 | self.assertFalse(writer._write_stack) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 991 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 992 | def test_write_overflow(self): |
| 993 | writer = self.MockRawIO() |
| 994 | bufio = self.tp(writer, 8) |
| 995 | contents = b"abcdefghijklmnop" |
| 996 | for n in range(0, len(contents), 3): |
| 997 | bufio.write(contents[n:n+3]) |
| 998 | flushed = b"".join(writer._write_stack) |
| 999 | # At least (total - 8) bytes were implicitly flushed, perhaps more |
| 1000 | # depending on the implementation. |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1001 | self.assertTrue(flushed.startswith(contents[:-8]), flushed) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1002 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1003 | def check_writes(self, intermediate_func): |
| 1004 | # Lots of writes, test the flushed output is as expected. |
| 1005 | contents = bytes(range(256)) * 1000 |
| 1006 | n = 0 |
| 1007 | writer = self.MockRawIO() |
| 1008 | bufio = self.tp(writer, 13) |
| 1009 | # Generator of write sizes: repeat each N 15 times then proceed to N+1 |
| 1010 | def gen_sizes(): |
| 1011 | for size in count(1): |
| 1012 | for i in range(15): |
| 1013 | yield size |
| 1014 | sizes = gen_sizes() |
| 1015 | while n < len(contents): |
| 1016 | size = min(next(sizes), len(contents) - n) |
| 1017 | self.assertEquals(bufio.write(contents[n:n+size]), size) |
| 1018 | intermediate_func(bufio) |
| 1019 | n += size |
| 1020 | bufio.flush() |
| 1021 | self.assertEquals(contents, b"".join(writer._write_stack)) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1022 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1023 | def test_writes(self): |
| 1024 | self.check_writes(lambda bufio: None) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1025 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1026 | def test_writes_and_flushes(self): |
| 1027 | self.check_writes(lambda bufio: bufio.flush()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1028 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1029 | def test_writes_and_seeks(self): |
| 1030 | def _seekabs(bufio): |
| 1031 | pos = bufio.tell() |
| 1032 | bufio.seek(pos + 1, 0) |
| 1033 | bufio.seek(pos - 1, 0) |
| 1034 | bufio.seek(pos, 0) |
| 1035 | self.check_writes(_seekabs) |
| 1036 | def _seekrel(bufio): |
| 1037 | pos = bufio.seek(0, 1) |
| 1038 | bufio.seek(+1, 1) |
| 1039 | bufio.seek(-1, 1) |
| 1040 | bufio.seek(pos, 0) |
| 1041 | self.check_writes(_seekrel) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1042 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1043 | def test_writes_and_truncates(self): |
| 1044 | self.check_writes(lambda bufio: bufio.truncate(bufio.tell())) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1045 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1046 | def test_write_non_blocking(self): |
| 1047 | raw = self.MockNonBlockWriterIO() |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1048 | bufio = self.tp(raw, 8) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1049 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1050 | self.assertEquals(bufio.write(b"abcd"), 4) |
| 1051 | self.assertEquals(bufio.write(b"efghi"), 5) |
| 1052 | # 1 byte will be written, the rest will be buffered |
| 1053 | raw.block_on(b"k") |
| 1054 | self.assertEquals(bufio.write(b"jklmn"), 5) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1055 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1056 | # 8 bytes will be written, 8 will be buffered and the rest will be lost |
| 1057 | raw.block_on(b"0") |
| 1058 | try: |
| 1059 | bufio.write(b"opqrwxyz0123456789") |
| 1060 | except self.BlockingIOError as e: |
| 1061 | written = e.characters_written |
| 1062 | else: |
| 1063 | self.fail("BlockingIOError should have been raised") |
| 1064 | self.assertEquals(written, 16) |
| 1065 | self.assertEquals(raw.pop_written(), |
| 1066 | b"abcdefghijklmnopqrwxyz") |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1067 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1068 | self.assertEquals(bufio.write(b"ABCDEFGHI"), 9) |
| 1069 | s = raw.pop_written() |
| 1070 | # Previously buffered bytes were flushed |
| 1071 | self.assertTrue(s.startswith(b"01234567A"), s) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1072 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1073 | def test_write_and_rewind(self): |
| 1074 | raw = io.BytesIO() |
| 1075 | bufio = self.tp(raw, 4) |
| 1076 | self.assertEqual(bufio.write(b"abcdef"), 6) |
| 1077 | self.assertEqual(bufio.tell(), 6) |
| 1078 | bufio.seek(0, 0) |
| 1079 | self.assertEqual(bufio.write(b"XY"), 2) |
| 1080 | bufio.seek(6, 0) |
| 1081 | self.assertEqual(raw.getvalue(), b"XYcdef") |
| 1082 | self.assertEqual(bufio.write(b"123456"), 6) |
| 1083 | bufio.flush() |
| 1084 | self.assertEqual(raw.getvalue(), b"XYcdef123456") |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1085 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1086 | def test_flush(self): |
| 1087 | writer = self.MockRawIO() |
| 1088 | bufio = self.tp(writer, 8) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1089 | bufio.write(b"abc") |
| 1090 | bufio.flush() |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1091 | self.assertEquals(b"abc", writer._write_stack[0]) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 1092 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1093 | def test_destructor(self): |
| 1094 | writer = self.MockRawIO() |
| 1095 | bufio = self.tp(writer, 8) |
| 1096 | bufio.write(b"abc") |
| 1097 | del bufio |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 1098 | support.gc_collect() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1099 | self.assertEquals(b"abc", writer._write_stack[0]) |
| 1100 | |
| 1101 | def test_truncate(self): |
| 1102 | # Truncate implicitly flushes the buffer. |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1103 | with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1104 | bufio = self.tp(raw, 8) |
| 1105 | bufio.write(b"abcdef") |
| 1106 | self.assertEqual(bufio.truncate(3), 3) |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 1107 | self.assertEqual(bufio.tell(), 6) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1108 | with self.open(support.TESTFN, "rb", buffering=0) as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1109 | self.assertEqual(f.read(), b"abc") |
| 1110 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 1111 | @unittest.skipUnless(threading, 'Threading required for this test.') |
Antoine Pitrou | 5bc4fa7 | 2010-10-14 15:34:31 +0000 | [diff] [blame] | 1112 | @support.requires_resource('cpu') |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1113 | def test_threads(self): |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1114 | try: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1115 | # Write out many bytes from many threads and test they were |
| 1116 | # all flushed. |
| 1117 | N = 1000 |
| 1118 | contents = bytes(range(256)) * N |
| 1119 | sizes = cycle([1, 19]) |
| 1120 | n = 0 |
| 1121 | queue = deque() |
| 1122 | while n < len(contents): |
| 1123 | size = next(sizes) |
| 1124 | queue.append(contents[n:n+size]) |
| 1125 | n += size |
| 1126 | del contents |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1127 | # We use a real file object because it allows us to |
| 1128 | # exercise situations where the GIL is released before |
| 1129 | # writing the buffer to the raw streams. This is in addition |
| 1130 | # to concurrency issues due to switching threads in the middle |
| 1131 | # of Python code. |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1132 | with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1133 | bufio = self.tp(raw, 8) |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1134 | errors = [] |
| 1135 | def f(): |
| 1136 | try: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1137 | while True: |
| 1138 | try: |
| 1139 | s = queue.popleft() |
| 1140 | except IndexError: |
| 1141 | return |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1142 | bufio.write(s) |
| 1143 | except Exception as e: |
| 1144 | errors.append(e) |
| 1145 | raise |
| 1146 | threads = [threading.Thread(target=f) for x in range(20)] |
| 1147 | for t in threads: |
| 1148 | t.start() |
| 1149 | time.sleep(0.02) # yield |
| 1150 | for t in threads: |
| 1151 | t.join() |
| 1152 | self.assertFalse(errors, |
| 1153 | "the following exceptions were caught: %r" % errors) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1154 | bufio.close() |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1155 | with self.open(support.TESTFN, "rb") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1156 | s = f.read() |
| 1157 | for i in range(256): |
| 1158 | self.assertEquals(s.count(bytes([i])), N) |
Antoine Pitrou | 8769576 | 2008-08-14 22:44:29 +0000 | [diff] [blame] | 1159 | finally: |
| 1160 | support.unlink(support.TESTFN) |
| 1161 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1162 | def test_misbehaved_io(self): |
| 1163 | rawio = self.MisbehavedRawIO() |
| 1164 | bufio = self.tp(rawio, 5) |
| 1165 | self.assertRaises(IOError, bufio.seek, 0) |
| 1166 | self.assertRaises(IOError, bufio.tell) |
| 1167 | self.assertRaises(IOError, bufio.write, b"abcdef") |
| 1168 | |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1169 | def test_max_buffer_size_deprecation(self): |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 1170 | with support.check_warnings(("max_buffer_size is deprecated", |
| 1171 | DeprecationWarning)): |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1172 | self.tp(self.MockRawIO(), 8, 12) |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1173 | |
| 1174 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1175 | class CBufferedWriterTest(BufferedWriterTest): |
| 1176 | tp = io.BufferedWriter |
| 1177 | |
| 1178 | def test_constructor(self): |
| 1179 | BufferedWriterTest.test_constructor(self) |
| 1180 | # The allocation can succeed on 32-bit builds, e.g. with more |
| 1181 | # than 2GB RAM and a 64-bit kernel. |
| 1182 | if sys.maxsize > 0x7FFFFFFF: |
| 1183 | rawio = self.MockRawIO() |
| 1184 | bufio = self.tp(rawio) |
| 1185 | self.assertRaises((OverflowError, MemoryError, ValueError), |
| 1186 | bufio.__init__, rawio, sys.maxsize) |
| 1187 | |
| 1188 | def test_initialization(self): |
| 1189 | rawio = self.MockRawIO() |
| 1190 | bufio = self.tp(rawio) |
| 1191 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) |
| 1192 | self.assertRaises(ValueError, bufio.write, b"def") |
| 1193 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) |
| 1194 | self.assertRaises(ValueError, bufio.write, b"def") |
| 1195 | self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) |
| 1196 | self.assertRaises(ValueError, bufio.write, b"def") |
| 1197 | |
| 1198 | def test_garbage_collection(self): |
| 1199 | # C BufferedWriter objects are collected, and collecting them flushes |
| 1200 | # all data to disk. |
| 1201 | # The Python version has __del__, so it ends into gc.garbage instead |
| 1202 | rawio = self.FileIO(support.TESTFN, "w+b") |
| 1203 | f = self.tp(rawio) |
| 1204 | f.write(b"123xxx") |
| 1205 | f.x = f |
| 1206 | wr = weakref.ref(f) |
| 1207 | del f |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 1208 | support.gc_collect() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1209 | self.assertTrue(wr() is None, wr) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 1210 | with self.open(support.TESTFN, "rb") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1211 | self.assertEqual(f.read(), b"123xxx") |
| 1212 | |
| 1213 | |
| 1214 | class PyBufferedWriterTest(BufferedWriterTest): |
| 1215 | tp = pyio.BufferedWriter |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 1216 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1217 | class BufferedRWPairTest(unittest.TestCase): |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 1218 | |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1219 | def test_constructor(self): |
| 1220 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 1221 | self.assertFalse(pair.closed) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1222 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 1223 | def test_detach(self): |
| 1224 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1225 | self.assertRaises(self.UnsupportedOperation, pair.detach) |
| 1226 | |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1227 | def test_constructor_max_buffer_size_deprecation(self): |
Florent Xicluna | 8fbddf1 | 2010-03-17 20:29:51 +0000 | [diff] [blame] | 1228 | with support.check_warnings(("max_buffer_size is deprecated", |
| 1229 | DeprecationWarning)): |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1230 | self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12) |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1231 | |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1232 | def test_constructor_with_not_readable(self): |
| 1233 | class NotReadable(MockRawIO): |
| 1234 | def readable(self): |
| 1235 | return False |
| 1236 | |
| 1237 | self.assertRaises(IOError, self.tp, NotReadable(), self.MockRawIO()) |
| 1238 | |
| 1239 | def test_constructor_with_not_writeable(self): |
| 1240 | class NotWriteable(MockRawIO): |
| 1241 | def writable(self): |
| 1242 | return False |
| 1243 | |
| 1244 | self.assertRaises(IOError, self.tp, self.MockRawIO(), NotWriteable()) |
| 1245 | |
| 1246 | def test_read(self): |
| 1247 | pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) |
| 1248 | |
| 1249 | self.assertEqual(pair.read(3), b"abc") |
| 1250 | self.assertEqual(pair.read(1), b"d") |
| 1251 | self.assertEqual(pair.read(), b"ef") |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 1252 | pair = self.tp(self.BytesIO(b"abc"), self.MockRawIO()) |
| 1253 | self.assertEqual(pair.read(None), b"abc") |
| 1254 | |
| 1255 | def test_readlines(self): |
| 1256 | pair = lambda: self.tp(self.BytesIO(b"abc\ndef\nh"), self.MockRawIO()) |
| 1257 | self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) |
| 1258 | self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) |
| 1259 | self.assertEqual(pair().readlines(5), [b"abc\n", b"def\n"]) |
Antoine Pitrou | cf4c749 | 2009-04-19 00:09:36 +0000 | [diff] [blame] | 1260 | |
| 1261 | def test_read1(self): |
| 1262 | # .read1() is delegated to the underlying reader object, so this test |
| 1263 | # can be shallow. |
| 1264 | pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) |
| 1265 | |
| 1266 | self.assertEqual(pair.read1(3), b"abc") |
| 1267 | |
| 1268 | def test_readinto(self): |
| 1269 | pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) |
| 1270 | |
| 1271 | data = bytearray(5) |
| 1272 | self.assertEqual(pair.readinto(data), 5) |
| 1273 | self.assertEqual(data, b"abcde") |
| 1274 | |
| 1275 | def test_write(self): |
| 1276 | w = self.MockRawIO() |
| 1277 | pair = self.tp(self.MockRawIO(), w) |
| 1278 | |
| 1279 | pair.write(b"abc") |
| 1280 | pair.flush() |
| 1281 | pair.write(b"def") |
| 1282 | pair.flush() |
| 1283 | self.assertEqual(w._write_stack, [b"abc", b"def"]) |
| 1284 | |
| 1285 | def test_peek(self): |
| 1286 | pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) |
| 1287 | |
| 1288 | self.assertTrue(pair.peek(3).startswith(b"abc")) |
| 1289 | self.assertEqual(pair.read(3), b"abc") |
| 1290 | |
| 1291 | def test_readable(self): |
| 1292 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1293 | self.assertTrue(pair.readable()) |
| 1294 | |
| 1295 | def test_writeable(self): |
| 1296 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1297 | self.assertTrue(pair.writable()) |
| 1298 | |
| 1299 | def test_seekable(self): |
| 1300 | # BufferedRWPairs are never seekable, even if their readers and writers |
| 1301 | # are. |
| 1302 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1303 | self.assertFalse(pair.seekable()) |
| 1304 | |
| 1305 | # .flush() is delegated to the underlying writer object and has been |
| 1306 | # tested in the test_write method. |
| 1307 | |
| 1308 | def test_close_and_closed(self): |
| 1309 | pair = self.tp(self.MockRawIO(), self.MockRawIO()) |
| 1310 | self.assertFalse(pair.closed) |
| 1311 | pair.close() |
| 1312 | self.assertTrue(pair.closed) |
| 1313 | |
| 1314 | def test_isatty(self): |
| 1315 | class SelectableIsAtty(MockRawIO): |
| 1316 | def __init__(self, isatty): |
| 1317 | MockRawIO.__init__(self) |
| 1318 | self._isatty = isatty |
| 1319 | |
| 1320 | def isatty(self): |
| 1321 | return self._isatty |
| 1322 | |
| 1323 | pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(False)) |
| 1324 | self.assertFalse(pair.isatty()) |
| 1325 | |
| 1326 | pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(False)) |
| 1327 | self.assertTrue(pair.isatty()) |
| 1328 | |
| 1329 | pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(True)) |
| 1330 | self.assertTrue(pair.isatty()) |
| 1331 | |
| 1332 | pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(True)) |
| 1333 | self.assertTrue(pair.isatty()) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1334 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1335 | class CBufferedRWPairTest(BufferedRWPairTest): |
| 1336 | tp = io.BufferedRWPair |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 1337 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1338 | class PyBufferedRWPairTest(BufferedRWPairTest): |
| 1339 | tp = pyio.BufferedRWPair |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 1340 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1341 | |
| 1342 | class BufferedRandomTest(BufferedReaderTest, BufferedWriterTest): |
| 1343 | read_mode = "rb+" |
| 1344 | write_mode = "wb+" |
| 1345 | |
| 1346 | def test_constructor(self): |
| 1347 | BufferedReaderTest.test_constructor(self) |
| 1348 | BufferedWriterTest.test_constructor(self) |
| 1349 | |
| 1350 | def test_read_and_write(self): |
| 1351 | raw = self.MockRawIO((b"asdf", b"ghjk")) |
Benjamin Peterson | 59406a9 | 2009-03-26 17:10:29 +0000 | [diff] [blame] | 1352 | rw = self.tp(raw, 8) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1353 | |
| 1354 | self.assertEqual(b"as", rw.read(2)) |
| 1355 | rw.write(b"ddd") |
| 1356 | rw.write(b"eee") |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1357 | self.assertFalse(raw._write_stack) # Buffer writes |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1358 | self.assertEqual(b"ghjk", rw.read()) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1359 | self.assertEquals(b"dddeee", raw._write_stack[0]) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1360 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1361 | def test_seek_and_tell(self): |
| 1362 | raw = self.BytesIO(b"asdfghjkl") |
| 1363 | rw = self.tp(raw) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1364 | |
| 1365 | self.assertEquals(b"as", rw.read(2)) |
| 1366 | self.assertEquals(2, rw.tell()) |
| 1367 | rw.seek(0, 0) |
| 1368 | self.assertEquals(b"asdf", rw.read(4)) |
| 1369 | |
| 1370 | rw.write(b"asdf") |
| 1371 | rw.seek(0, 0) |
| 1372 | self.assertEquals(b"asdfasdfl", rw.read()) |
| 1373 | self.assertEquals(9, rw.tell()) |
| 1374 | rw.seek(-4, 2) |
| 1375 | self.assertEquals(5, rw.tell()) |
| 1376 | rw.seek(2, 1) |
| 1377 | self.assertEquals(7, rw.tell()) |
| 1378 | self.assertEquals(b"fl", rw.read(11)) |
Christian Heimes | 8e42a0a | 2007-11-08 18:04:45 +0000 | [diff] [blame] | 1379 | self.assertRaises(TypeError, rw.seek, 0.0) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 1380 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1381 | def check_flush_and_read(self, read_func): |
| 1382 | raw = self.BytesIO(b"abcdefghi") |
| 1383 | bufio = self.tp(raw) |
| 1384 | |
| 1385 | self.assertEquals(b"ab", read_func(bufio, 2)) |
| 1386 | bufio.write(b"12") |
| 1387 | self.assertEquals(b"ef", read_func(bufio, 2)) |
| 1388 | self.assertEquals(6, bufio.tell()) |
| 1389 | bufio.flush() |
| 1390 | self.assertEquals(6, bufio.tell()) |
| 1391 | self.assertEquals(b"ghi", read_func(bufio)) |
| 1392 | raw.seek(0, 0) |
| 1393 | raw.write(b"XYZ") |
| 1394 | # flush() resets the read buffer |
| 1395 | bufio.flush() |
| 1396 | bufio.seek(0, 0) |
| 1397 | self.assertEquals(b"XYZ", read_func(bufio, 3)) |
| 1398 | |
| 1399 | def test_flush_and_read(self): |
| 1400 | self.check_flush_and_read(lambda bufio, *args: bufio.read(*args)) |
| 1401 | |
| 1402 | def test_flush_and_readinto(self): |
| 1403 | def _readinto(bufio, n=-1): |
| 1404 | b = bytearray(n if n >= 0 else 9999) |
| 1405 | n = bufio.readinto(b) |
| 1406 | return bytes(b[:n]) |
| 1407 | self.check_flush_and_read(_readinto) |
| 1408 | |
| 1409 | def test_flush_and_peek(self): |
| 1410 | def _peek(bufio, n=-1): |
| 1411 | # This relies on the fact that the buffer can contain the whole |
| 1412 | # raw stream, otherwise peek() can return less. |
| 1413 | b = bufio.peek(n) |
| 1414 | if n != -1: |
| 1415 | b = b[:n] |
| 1416 | bufio.seek(len(b), 1) |
| 1417 | return b |
| 1418 | self.check_flush_and_read(_peek) |
| 1419 | |
| 1420 | def test_flush_and_write(self): |
| 1421 | raw = self.BytesIO(b"abcdefghi") |
| 1422 | bufio = self.tp(raw) |
| 1423 | |
| 1424 | bufio.write(b"123") |
| 1425 | bufio.flush() |
| 1426 | bufio.write(b"45") |
| 1427 | bufio.flush() |
| 1428 | bufio.seek(0, 0) |
| 1429 | self.assertEquals(b"12345fghi", raw.getvalue()) |
| 1430 | self.assertEquals(b"12345fghi", bufio.read()) |
| 1431 | |
| 1432 | def test_threads(self): |
| 1433 | BufferedReaderTest.test_threads(self) |
| 1434 | BufferedWriterTest.test_threads(self) |
| 1435 | |
| 1436 | def test_writes_and_peek(self): |
| 1437 | def _peek(bufio): |
| 1438 | bufio.peek(1) |
| 1439 | self.check_writes(_peek) |
| 1440 | def _peek(bufio): |
| 1441 | pos = bufio.tell() |
| 1442 | bufio.seek(-1, 1) |
| 1443 | bufio.peek(1) |
| 1444 | bufio.seek(pos, 0) |
| 1445 | self.check_writes(_peek) |
| 1446 | |
| 1447 | def test_writes_and_reads(self): |
| 1448 | def _read(bufio): |
| 1449 | bufio.seek(-1, 1) |
| 1450 | bufio.read(1) |
| 1451 | self.check_writes(_read) |
| 1452 | |
| 1453 | def test_writes_and_read1s(self): |
| 1454 | def _read1(bufio): |
| 1455 | bufio.seek(-1, 1) |
| 1456 | bufio.read1(1) |
| 1457 | self.check_writes(_read1) |
| 1458 | |
| 1459 | def test_writes_and_readintos(self): |
| 1460 | def _read(bufio): |
| 1461 | bufio.seek(-1, 1) |
| 1462 | bufio.readinto(bytearray(1)) |
| 1463 | self.check_writes(_read) |
| 1464 | |
Antoine Pitrou | a0ceb73 | 2009-08-06 20:29:56 +0000 | [diff] [blame] | 1465 | def test_write_after_readahead(self): |
| 1466 | # Issue #6629: writing after the buffer was filled by readahead should |
| 1467 | # first rewind the raw stream. |
| 1468 | for overwrite_size in [1, 5]: |
| 1469 | raw = self.BytesIO(b"A" * 10) |
| 1470 | bufio = self.tp(raw, 4) |
| 1471 | # Trigger readahead |
| 1472 | self.assertEqual(bufio.read(1), b"A") |
| 1473 | self.assertEqual(bufio.tell(), 1) |
| 1474 | # Overwriting should rewind the raw stream if it needs so |
| 1475 | bufio.write(b"B" * overwrite_size) |
| 1476 | self.assertEqual(bufio.tell(), overwrite_size + 1) |
| 1477 | # If the write size was smaller than the buffer size, flush() and |
| 1478 | # check that rewind happens. |
| 1479 | bufio.flush() |
| 1480 | self.assertEqual(bufio.tell(), overwrite_size + 1) |
| 1481 | s = raw.getvalue() |
| 1482 | self.assertEqual(s, |
| 1483 | b"A" + b"B" * overwrite_size + b"A" * (9 - overwrite_size)) |
| 1484 | |
Antoine Pitrou | 905a2ff | 2010-01-31 22:47:27 +0000 | [diff] [blame] | 1485 | def test_truncate_after_read_or_write(self): |
| 1486 | raw = self.BytesIO(b"A" * 10) |
| 1487 | bufio = self.tp(raw, 100) |
| 1488 | self.assertEqual(bufio.read(2), b"AA") # the read buffer gets filled |
| 1489 | self.assertEqual(bufio.truncate(), 2) |
| 1490 | self.assertEqual(bufio.write(b"BB"), 2) # the write buffer increases |
| 1491 | self.assertEqual(bufio.truncate(), 4) |
| 1492 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1493 | def test_misbehaved_io(self): |
| 1494 | BufferedReaderTest.test_misbehaved_io(self) |
| 1495 | BufferedWriterTest.test_misbehaved_io(self) |
| 1496 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 1497 | # You can't construct a BufferedRandom over a non-seekable stream. |
| 1498 | test_unseekable = None |
| 1499 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1500 | class CBufferedRandomTest(BufferedRandomTest): |
| 1501 | tp = io.BufferedRandom |
| 1502 | |
| 1503 | def test_constructor(self): |
| 1504 | BufferedRandomTest.test_constructor(self) |
| 1505 | # The allocation can succeed on 32-bit builds, e.g. with more |
| 1506 | # than 2GB RAM and a 64-bit kernel. |
| 1507 | if sys.maxsize > 0x7FFFFFFF: |
| 1508 | rawio = self.MockRawIO() |
| 1509 | bufio = self.tp(rawio) |
| 1510 | self.assertRaises((OverflowError, MemoryError, ValueError), |
| 1511 | bufio.__init__, rawio, sys.maxsize) |
| 1512 | |
| 1513 | def test_garbage_collection(self): |
| 1514 | CBufferedReaderTest.test_garbage_collection(self) |
| 1515 | CBufferedWriterTest.test_garbage_collection(self) |
| 1516 | |
| 1517 | class PyBufferedRandomTest(BufferedRandomTest): |
| 1518 | tp = pyio.BufferedRandom |
| 1519 | |
| 1520 | |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1521 | # To fully exercise seek/tell, the StatefulIncrementalDecoder has these |
| 1522 | # properties: |
| 1523 | # - A single output character can correspond to many bytes of input. |
| 1524 | # - The number of input bytes to complete the character can be |
| 1525 | # undetermined until the last input byte is received. |
| 1526 | # - The number of input bytes can vary depending on previous input. |
| 1527 | # - A single input byte can correspond to many characters of output. |
| 1528 | # - The number of output characters can be undetermined until the |
| 1529 | # last input byte is received. |
| 1530 | # - The number of output characters can vary depending on previous input. |
| 1531 | |
| 1532 | class StatefulIncrementalDecoder(codecs.IncrementalDecoder): |
| 1533 | """ |
| 1534 | For testing seek/tell behavior with a stateful, buffering decoder. |
| 1535 | |
| 1536 | Input is a sequence of words. Words may be fixed-length (length set |
| 1537 | by input) or variable-length (period-terminated). In variable-length |
| 1538 | mode, extra periods are ignored. Possible words are: |
| 1539 | - 'i' followed by a number sets the input length, I (maximum 99). |
| 1540 | When I is set to 0, words are space-terminated. |
| 1541 | - 'o' followed by a number sets the output length, O (maximum 99). |
| 1542 | - Any other word is converted into a word followed by a period on |
| 1543 | the output. The output word consists of the input word truncated |
| 1544 | or padded out with hyphens to make its length equal to O. If O |
| 1545 | is 0, the word is output verbatim without truncating or padding. |
| 1546 | I and O are initially set to 1. When I changes, any buffered input is |
| 1547 | re-scanned according to the new I. EOF also terminates the last word. |
| 1548 | """ |
| 1549 | |
| 1550 | def __init__(self, errors='strict'): |
Christian Heimes | ab56887 | 2008-03-23 02:11:13 +0000 | [diff] [blame] | 1551 | codecs.IncrementalDecoder.__init__(self, errors) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1552 | self.reset() |
| 1553 | |
| 1554 | def __repr__(self): |
| 1555 | return '<SID %x>' % id(self) |
| 1556 | |
| 1557 | def reset(self): |
| 1558 | self.i = 1 |
| 1559 | self.o = 1 |
| 1560 | self.buffer = bytearray() |
| 1561 | |
| 1562 | def getstate(self): |
| 1563 | i, o = self.i ^ 1, self.o ^ 1 # so that flags = 0 after reset() |
| 1564 | return bytes(self.buffer), i*100 + o |
| 1565 | |
| 1566 | def setstate(self, state): |
| 1567 | buffer, io = state |
| 1568 | self.buffer = bytearray(buffer) |
| 1569 | i, o = divmod(io, 100) |
| 1570 | self.i, self.o = i ^ 1, o ^ 1 |
| 1571 | |
| 1572 | def decode(self, input, final=False): |
| 1573 | output = '' |
| 1574 | for b in input: |
| 1575 | if self.i == 0: # variable-length, terminated with period |
| 1576 | if b == ord('.'): |
| 1577 | if self.buffer: |
| 1578 | output += self.process_word() |
| 1579 | else: |
| 1580 | self.buffer.append(b) |
| 1581 | else: # fixed-length, terminate after self.i bytes |
| 1582 | self.buffer.append(b) |
| 1583 | if len(self.buffer) == self.i: |
| 1584 | output += self.process_word() |
| 1585 | if final and self.buffer: # EOF terminates the last word |
| 1586 | output += self.process_word() |
| 1587 | return output |
| 1588 | |
| 1589 | def process_word(self): |
| 1590 | output = '' |
| 1591 | if self.buffer[0] == ord('i'): |
| 1592 | self.i = min(99, int(self.buffer[1:] or 0)) # set input length |
| 1593 | elif self.buffer[0] == ord('o'): |
| 1594 | self.o = min(99, int(self.buffer[1:] or 0)) # set output length |
| 1595 | else: |
| 1596 | output = self.buffer.decode('ascii') |
| 1597 | if len(output) < self.o: |
| 1598 | output += '-'*self.o # pad out with hyphens |
| 1599 | if self.o: |
| 1600 | output = output[:self.o] # truncate to output length |
| 1601 | output += '.' |
| 1602 | self.buffer = bytearray() |
| 1603 | return output |
| 1604 | |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 1605 | codecEnabled = False |
| 1606 | |
| 1607 | @classmethod |
| 1608 | def lookupTestDecoder(cls, name): |
| 1609 | if cls.codecEnabled and name == 'test_decoder': |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 1610 | latin1 = codecs.lookup('latin-1') |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 1611 | return codecs.CodecInfo( |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 1612 | name='test_decoder', encode=latin1.encode, decode=None, |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 1613 | incrementalencoder=None, |
| 1614 | streamreader=None, streamwriter=None, |
| 1615 | incrementaldecoder=cls) |
| 1616 | |
| 1617 | # Register the previous decoder for testing. |
| 1618 | # Disabled by default, tests will enable it. |
| 1619 | codecs.register(StatefulIncrementalDecoder.lookupTestDecoder) |
| 1620 | |
| 1621 | |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1622 | class StatefulIncrementalDecoderTest(unittest.TestCase): |
| 1623 | """ |
| 1624 | Make sure the StatefulIncrementalDecoder actually works. |
| 1625 | """ |
| 1626 | |
| 1627 | test_cases = [ |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 1628 | # I=1, O=1 (fixed-length input == fixed-length output) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1629 | (b'abcd', False, 'a.b.c.d.'), |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 1630 | # I=0, O=0 (variable-length input, variable-length output) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1631 | (b'oiabcd', True, 'abcd.'), |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 1632 | # I=0, O=0 (should ignore extra periods) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1633 | (b'oi...abcd...', True, 'abcd.'), |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 1634 | # I=0, O=6 (variable-length input, fixed-length output) |
| 1635 | (b'i.o6.x.xyz.toolongtofit.', False, 'x-----.xyz---.toolon.'), |
| 1636 | # I=2, O=6 (fixed-length input < fixed-length output) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1637 | (b'i.i2.o6xyz', True, 'xy----.z-----.'), |
Ka-Ping Yee | d24a5b6 | 2008-03-20 10:51:27 +0000 | [diff] [blame] | 1638 | # I=6, O=3 (fixed-length input > fixed-length output) |
| 1639 | (b'i.o3.i6.abcdefghijklmnop', True, 'abc.ghi.mno.'), |
| 1640 | # I=0, then 3; O=29, then 15 (with longer output) |
| 1641 | (b'i.o29.a.b.cde.o15.abcdefghijabcdefghij.i3.a.b.c.d.ei00k.l.m', True, |
| 1642 | 'a----------------------------.' + |
| 1643 | 'b----------------------------.' + |
| 1644 | 'cde--------------------------.' + |
| 1645 | 'abcdefghijabcde.' + |
| 1646 | 'a.b------------.' + |
| 1647 | '.c.------------.' + |
| 1648 | 'd.e------------.' + |
| 1649 | 'k--------------.' + |
| 1650 | 'l--------------.' + |
| 1651 | 'm--------------.') |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1652 | ] |
| 1653 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1654 | def test_decoder(self): |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 1655 | # Try a few one-shot test cases. |
| 1656 | for input, eof, output in self.test_cases: |
| 1657 | d = StatefulIncrementalDecoder() |
| 1658 | self.assertEquals(d.decode(input, eof), output) |
| 1659 | |
| 1660 | # Also test an unfinished decode, followed by forcing EOF. |
| 1661 | d = StatefulIncrementalDecoder() |
| 1662 | self.assertEquals(d.decode(b'oiabcd'), '') |
| 1663 | self.assertEquals(d.decode(b'', 1), 'abcd.') |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1664 | |
| 1665 | class TextIOWrapperTest(unittest.TestCase): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1666 | |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 1667 | def setUp(self): |
| 1668 | self.testdata = b"AAA\r\nBBB\rCCC\r\nDDD\nEEE\r\n" |
| 1669 | self.normalized = b"AAA\nBBB\nCCC\nDDD\nEEE\n".decode("ascii") |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1670 | support.unlink(support.TESTFN) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 1671 | |
Guido van Rossum | d071281 | 2007-04-11 16:32:43 +0000 | [diff] [blame] | 1672 | def tearDown(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1673 | support.unlink(support.TESTFN) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1674 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1675 | def test_constructor(self): |
| 1676 | r = self.BytesIO(b"\xc3\xa9\n\n") |
| 1677 | b = self.BufferedReader(r, 1000) |
| 1678 | t = self.TextIOWrapper(b) |
| 1679 | t.__init__(b, encoding="latin1", newline="\r\n") |
| 1680 | self.assertEquals(t.encoding, "latin1") |
| 1681 | self.assertEquals(t.line_buffering, False) |
| 1682 | t.__init__(b, encoding="utf8", line_buffering=True) |
| 1683 | self.assertEquals(t.encoding, "utf8") |
| 1684 | self.assertEquals(t.line_buffering, True) |
| 1685 | self.assertEquals("\xe9\n", t.readline()) |
| 1686 | self.assertRaises(TypeError, t.__init__, b, newline=42) |
| 1687 | self.assertRaises(ValueError, t.__init__, b, newline='xyzzy') |
| 1688 | |
Benjamin Peterson | d2e0c79 | 2009-05-01 20:40:59 +0000 | [diff] [blame] | 1689 | def test_detach(self): |
| 1690 | r = self.BytesIO() |
| 1691 | b = self.BufferedWriter(r) |
| 1692 | t = self.TextIOWrapper(b) |
| 1693 | self.assertIs(t.detach(), b) |
| 1694 | |
| 1695 | t = self.TextIOWrapper(b, encoding="ascii") |
| 1696 | t.write("howdy") |
| 1697 | self.assertFalse(r.getvalue()) |
| 1698 | t.detach() |
| 1699 | self.assertEqual(r.getvalue(), b"howdy") |
| 1700 | self.assertRaises(ValueError, t.detach) |
| 1701 | |
Benjamin Peterson | c4c0eae | 2009-03-09 00:07:03 +0000 | [diff] [blame] | 1702 | def test_repr(self): |
| 1703 | raw = self.BytesIO("hello".encode("utf-8")) |
| 1704 | b = self.BufferedReader(raw) |
| 1705 | t = self.TextIOWrapper(b, encoding="utf-8") |
Antoine Pitrou | 716c444 | 2009-05-23 19:04:03 +0000 | [diff] [blame] | 1706 | modname = self.TextIOWrapper.__module__ |
| 1707 | self.assertEqual(repr(t), |
| 1708 | "<%s.TextIOWrapper encoding='utf-8'>" % modname) |
| 1709 | raw.name = "dummy" |
| 1710 | self.assertEqual(repr(t), |
| 1711 | "<%s.TextIOWrapper name='dummy' encoding='utf-8'>" % modname) |
| 1712 | raw.name = b"dummy" |
| 1713 | self.assertEqual(repr(t), |
| 1714 | "<%s.TextIOWrapper name=b'dummy' encoding='utf-8'>" % modname) |
Benjamin Peterson | c4c0eae | 2009-03-09 00:07:03 +0000 | [diff] [blame] | 1715 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1716 | def test_line_buffering(self): |
| 1717 | r = self.BytesIO() |
| 1718 | b = self.BufferedWriter(r, 1000) |
| 1719 | t = self.TextIOWrapper(b, newline="\n", line_buffering=True) |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 1720 | t.write("X") |
| 1721 | self.assertEquals(r.getvalue(), b"") # No flush happened |
| 1722 | t.write("Y\nZ") |
| 1723 | self.assertEquals(r.getvalue(), b"XY\nZ") # All got flushed |
| 1724 | t.write("A\rB") |
| 1725 | self.assertEquals(r.getvalue(), b"XY\nZA\rB") |
| 1726 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1727 | def test_encoding(self): |
| 1728 | # Check the encoding attribute is always set, and valid |
| 1729 | b = self.BytesIO() |
| 1730 | t = self.TextIOWrapper(b, encoding="utf8") |
| 1731 | self.assertEqual(t.encoding, "utf8") |
| 1732 | t = self.TextIOWrapper(b) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1733 | self.assertTrue(t.encoding is not None) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1734 | codecs.lookup(t.encoding) |
| 1735 | |
| 1736 | def test_encoding_errors_reading(self): |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1737 | # (1) default |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1738 | b = self.BytesIO(b"abc\n\xff\n") |
| 1739 | t = self.TextIOWrapper(b, encoding="ascii") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1740 | self.assertRaises(UnicodeError, t.read) |
| 1741 | # (2) explicit strict |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1742 | b = self.BytesIO(b"abc\n\xff\n") |
| 1743 | t = self.TextIOWrapper(b, encoding="ascii", errors="strict") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1744 | self.assertRaises(UnicodeError, t.read) |
| 1745 | # (3) ignore |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1746 | b = self.BytesIO(b"abc\n\xff\n") |
| 1747 | t = self.TextIOWrapper(b, encoding="ascii", errors="ignore") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1748 | self.assertEquals(t.read(), "abc\n\n") |
| 1749 | # (4) replace |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1750 | b = self.BytesIO(b"abc\n\xff\n") |
| 1751 | t = self.TextIOWrapper(b, encoding="ascii", errors="replace") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1752 | self.assertEquals(t.read(), "abc\n\ufffd\n") |
| 1753 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1754 | def test_encoding_errors_writing(self): |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1755 | # (1) default |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1756 | b = self.BytesIO() |
| 1757 | t = self.TextIOWrapper(b, encoding="ascii") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1758 | self.assertRaises(UnicodeError, t.write, "\xff") |
| 1759 | # (2) explicit strict |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1760 | b = self.BytesIO() |
| 1761 | t = self.TextIOWrapper(b, encoding="ascii", errors="strict") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1762 | self.assertRaises(UnicodeError, t.write, "\xff") |
| 1763 | # (3) ignore |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1764 | b = self.BytesIO() |
| 1765 | t = self.TextIOWrapper(b, encoding="ascii", errors="ignore", |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 1766 | newline="\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1767 | t.write("abc\xffdef\n") |
| 1768 | t.flush() |
Christian Heimes | ecda261 | 2007-12-05 17:59:44 +0000 | [diff] [blame] | 1769 | self.assertEquals(b.getvalue(), b"abcdef\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1770 | # (4) replace |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1771 | b = self.BytesIO() |
| 1772 | t = self.TextIOWrapper(b, encoding="ascii", errors="replace", |
Guido van Rossum | f64db9f | 2007-12-06 01:04:26 +0000 | [diff] [blame] | 1773 | newline="\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1774 | t.write("abc\xffdef\n") |
| 1775 | t.flush() |
Christian Heimes | ecda261 | 2007-12-05 17:59:44 +0000 | [diff] [blame] | 1776 | self.assertEquals(b.getvalue(), b"abc?def\n") |
Guido van Rossum | e7fc50f | 2007-12-03 22:54:21 +0000 | [diff] [blame] | 1777 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1778 | def test_newlines(self): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1779 | input_lines = [ "unix\n", "windows\r\n", "os9\r", "last\n", "nonl" ] |
| 1780 | |
| 1781 | tests = [ |
| 1782 | [ None, [ 'unix\n', 'windows\n', 'os9\n', 'last\n', 'nonl' ] ], |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 1783 | [ '', input_lines ], |
| 1784 | [ '\n', [ "unix\n", "windows\r\n", "os9\rlast\n", "nonl" ] ], |
| 1785 | [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ], |
| 1786 | [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ], |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1787 | ] |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 1788 | encodings = ( |
| 1789 | 'utf-8', 'latin-1', |
| 1790 | 'utf-16', 'utf-16-le', 'utf-16-be', |
| 1791 | 'utf-32', 'utf-32-le', 'utf-32-be', |
| 1792 | ) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1793 | |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 1794 | # 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] | 1795 | # character in TextIOWrapper._pending_line. |
| 1796 | for encoding in encodings: |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 1797 | # XXX: str.encode() should return bytes |
| 1798 | data = bytes(''.join(input_lines).encode(encoding)) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1799 | for do_reads in (False, True): |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 1800 | for bufsize in range(1, 10): |
| 1801 | for newline, exp_lines in tests: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1802 | bufio = self.BufferedReader(self.BytesIO(data), bufsize) |
| 1803 | textio = self.TextIOWrapper(bufio, newline=newline, |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1804 | encoding=encoding) |
| 1805 | if do_reads: |
| 1806 | got_lines = [] |
| 1807 | while True: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1808 | c2 = textio.read(2) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1809 | if c2 == '': |
| 1810 | break |
| 1811 | self.assertEquals(len(c2), 2) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1812 | got_lines.append(c2 + textio.readline()) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1813 | else: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 1814 | got_lines = list(textio) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1815 | |
| 1816 | for got_line, exp_line in zip(got_lines, exp_lines): |
| 1817 | self.assertEquals(got_line, exp_line) |
| 1818 | self.assertEquals(len(got_lines), len(exp_lines)) |
| 1819 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1820 | def test_newlines_input(self): |
| 1821 | 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] | 1822 | normalized = testdata.replace(b"\r\n", b"\n").replace(b"\r", b"\n") |
| 1823 | for newline, expected in [ |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 1824 | (None, normalized.decode("ascii").splitlines(True)), |
| 1825 | ("", testdata.decode("ascii").splitlines(True)), |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1826 | ("\n", ["AAA\n", "BB\x00B\n", "CCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), |
| 1827 | ("\r\n", ["AAA\nBB\x00B\nCCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), |
| 1828 | ("\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] | 1829 | ]: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1830 | buf = self.BytesIO(testdata) |
| 1831 | txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 1832 | self.assertEquals(txt.readlines(), expected) |
| 1833 | txt.seek(0) |
| 1834 | self.assertEquals(txt.read(), "".join(expected)) |
| 1835 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1836 | def test_newlines_output(self): |
| 1837 | testdict = { |
| 1838 | "": b"AAA\nBBB\nCCC\nX\rY\r\nZ", |
| 1839 | "\n": b"AAA\nBBB\nCCC\nX\rY\r\nZ", |
| 1840 | "\r": b"AAA\rBBB\rCCC\rX\rY\r\rZ", |
| 1841 | "\r\n": b"AAA\r\nBBB\r\nCCC\r\nX\rY\r\r\nZ", |
| 1842 | } |
| 1843 | tests = [(None, testdict[os.linesep])] + sorted(testdict.items()) |
| 1844 | for newline, expected in tests: |
| 1845 | buf = self.BytesIO() |
| 1846 | txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) |
| 1847 | txt.write("AAA\nB") |
| 1848 | txt.write("BB\nCCC\n") |
| 1849 | txt.write("X\rY\r\nZ") |
| 1850 | txt.flush() |
| 1851 | self.assertEquals(buf.closed, False) |
| 1852 | self.assertEquals(buf.getvalue(), expected) |
| 1853 | |
| 1854 | def test_destructor(self): |
| 1855 | l = [] |
| 1856 | base = self.BytesIO |
| 1857 | class MyBytesIO(base): |
| 1858 | def close(self): |
| 1859 | l.append(self.getvalue()) |
| 1860 | base.close(self) |
| 1861 | b = MyBytesIO() |
| 1862 | t = self.TextIOWrapper(b, encoding="ascii") |
| 1863 | t.write("abc") |
| 1864 | del t |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 1865 | support.gc_collect() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1866 | self.assertEquals([b"abc"], l) |
| 1867 | |
| 1868 | def test_override_destructor(self): |
| 1869 | record = [] |
| 1870 | class MyTextIO(self.TextIOWrapper): |
| 1871 | def __del__(self): |
| 1872 | record.append(1) |
| 1873 | try: |
| 1874 | f = super().__del__ |
| 1875 | except AttributeError: |
| 1876 | pass |
| 1877 | else: |
| 1878 | f() |
| 1879 | def close(self): |
| 1880 | record.append(2) |
| 1881 | super().close() |
| 1882 | def flush(self): |
| 1883 | record.append(3) |
| 1884 | super().flush() |
| 1885 | b = self.BytesIO() |
| 1886 | t = MyTextIO(b, encoding="ascii") |
| 1887 | del t |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 1888 | support.gc_collect() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1889 | self.assertEqual(record, [1, 2, 3]) |
| 1890 | |
| 1891 | def test_error_through_destructor(self): |
| 1892 | # Test that the exception state is not modified by a destructor, |
| 1893 | # even if close() fails. |
| 1894 | rawio = self.CloseFailureIO() |
| 1895 | def f(): |
| 1896 | self.TextIOWrapper(rawio).xyzzy |
| 1897 | with support.captured_output("stderr") as s: |
| 1898 | self.assertRaises(AttributeError, f) |
| 1899 | s = s.getvalue().strip() |
| 1900 | if s: |
| 1901 | # The destructor *may* have printed an unraisable error, check it |
| 1902 | self.assertEqual(len(s.splitlines()), 1) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1903 | self.assertTrue(s.startswith("Exception IOError: "), s) |
| 1904 | self.assertTrue(s.endswith(" ignored"), s) |
Guido van Rossum | 8358db2 | 2007-08-18 21:39:55 +0000 | [diff] [blame] | 1905 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1906 | # Systematic tests of the text I/O API |
| 1907 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1908 | def test_basic_io(self): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1909 | for chunksize in (1, 2, 3, 4, 5, 15, 16, 17, 31, 32, 33, 63, 64, 65): |
| 1910 | for enc in "ascii", "latin1", "utf8" :# , "utf-16-be", "utf-16-le": |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1911 | f = self.open(support.TESTFN, "w+", encoding=enc) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1912 | f._CHUNK_SIZE = chunksize |
| 1913 | self.assertEquals(f.write("abc"), 3) |
| 1914 | f.close() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1915 | f = self.open(support.TESTFN, "r+", encoding=enc) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1916 | f._CHUNK_SIZE = chunksize |
| 1917 | self.assertEquals(f.tell(), 0) |
| 1918 | self.assertEquals(f.read(), "abc") |
| 1919 | cookie = f.tell() |
| 1920 | self.assertEquals(f.seek(0), 0) |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 1921 | self.assertEquals(f.read(None), "abc") |
| 1922 | f.seek(0) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1923 | self.assertEquals(f.read(2), "ab") |
| 1924 | self.assertEquals(f.read(1), "c") |
| 1925 | self.assertEquals(f.read(1), "") |
| 1926 | self.assertEquals(f.read(), "") |
| 1927 | self.assertEquals(f.tell(), cookie) |
| 1928 | self.assertEquals(f.seek(0), 0) |
| 1929 | self.assertEquals(f.seek(0, 2), cookie) |
| 1930 | self.assertEquals(f.write("def"), 3) |
| 1931 | self.assertEquals(f.seek(cookie), cookie) |
| 1932 | self.assertEquals(f.read(), "def") |
| 1933 | if enc.startswith("utf"): |
| 1934 | self.multi_line_test(f, enc) |
| 1935 | f.close() |
| 1936 | |
| 1937 | def multi_line_test(self, f, enc): |
| 1938 | f.seek(0) |
| 1939 | f.truncate() |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1940 | sample = "s\xff\u0fff\uffff" |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1941 | wlines = [] |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 1942 | 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] | 1943 | chars = [] |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 1944 | for i in range(size): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1945 | chars.append(sample[i % len(sample)]) |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1946 | line = "".join(chars) + "\n" |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1947 | wlines.append((f.tell(), line)) |
| 1948 | f.write(line) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1949 | f.seek(0) |
| 1950 | rlines = [] |
| 1951 | while True: |
| 1952 | pos = f.tell() |
| 1953 | line = f.readline() |
| 1954 | if not line: |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1955 | break |
| 1956 | rlines.append((pos, line)) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1957 | self.assertEquals(rlines, wlines) |
| 1958 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1959 | def test_telling(self): |
| 1960 | f = self.open(support.TESTFN, "w+", encoding="utf8") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 1961 | p0 = f.tell() |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1962 | f.write("\xff\n") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 1963 | p1 = f.tell() |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1964 | f.write("\xff\n") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 1965 | p2 = f.tell() |
| 1966 | f.seek(0) |
| 1967 | self.assertEquals(f.tell(), p0) |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1968 | self.assertEquals(f.readline(), "\xff\n") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 1969 | self.assertEquals(f.tell(), p1) |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1970 | self.assertEquals(f.readline(), "\xff\n") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 1971 | self.assertEquals(f.tell(), p2) |
| 1972 | f.seek(0) |
| 1973 | for line in f: |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1974 | self.assertEquals(line, "\xff\n") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame] | 1975 | self.assertRaises(IOError, f.tell) |
| 1976 | self.assertEquals(f.tell(), p2) |
| 1977 | f.close() |
| 1978 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1979 | def test_seeking(self): |
| 1980 | chunk_size = _default_chunk_size() |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 1981 | prefix_size = chunk_size - 2 |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1982 | u_prefix = "a" * prefix_size |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 1983 | prefix = bytes(u_prefix.encode("utf-8")) |
| 1984 | self.assertEquals(len(u_prefix), len(prefix)) |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1985 | u_suffix = "\u8888\n" |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 1986 | suffix = bytes(u_suffix.encode("utf-8")) |
| 1987 | line = prefix + suffix |
Benjamin Peterson | ebe5d8a | 2010-10-31 01:30:11 +0000 | [diff] [blame] | 1988 | with self.open(support.TESTFN, "wb") as f: |
| 1989 | f.write(line*2) |
| 1990 | with self.open(support.TESTFN, "r", encoding="utf-8") as f: |
| 1991 | s = f.read(prefix_size) |
| 1992 | self.assertEquals(s, str(prefix, "ascii")) |
| 1993 | self.assertEquals(f.tell(), prefix_size) |
| 1994 | self.assertEquals(f.readline(), u_suffix) |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 1995 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1996 | def test_seeking_too(self): |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 1997 | # Regression test for a specific bug |
| 1998 | data = b'\xe0\xbf\xbf\n' |
Benjamin Peterson | ebe5d8a | 2010-10-31 01:30:11 +0000 | [diff] [blame] | 1999 | with self.open(support.TESTFN, "wb") as f: |
| 2000 | f.write(data) |
| 2001 | with self.open(support.TESTFN, "r", encoding="utf-8") as f: |
| 2002 | f._CHUNK_SIZE # Just test that it exists |
| 2003 | f._CHUNK_SIZE = 2 |
| 2004 | f.readline() |
| 2005 | f.tell() |
Guido van Rossum | d76e779 | 2007-04-17 02:38:04 +0000 | [diff] [blame] | 2006 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2007 | def test_seek_and_tell(self): |
| 2008 | #Test seek/tell using the StatefulIncrementalDecoder. |
| 2009 | # Make test faster by doing smaller seeks |
| 2010 | CHUNK_SIZE = 128 |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2011 | |
Benjamin Peterson | 5fd871d | 2009-03-05 00:49:53 +0000 | [diff] [blame] | 2012 | def test_seek_and_tell_with_data(data, min_pos=0): |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2013 | """Tell/seek to various points within a data stream and ensure |
| 2014 | that the decoded data returned by read() is consistent.""" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2015 | f = self.open(support.TESTFN, 'wb') |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2016 | f.write(data) |
| 2017 | f.close() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2018 | f = self.open(support.TESTFN, encoding='test_decoder') |
| 2019 | f._CHUNK_SIZE = CHUNK_SIZE |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2020 | decoded = f.read() |
| 2021 | f.close() |
| 2022 | |
Neal Norwitz | e2b0705 | 2008-03-18 19:52:05 +0000 | [diff] [blame] | 2023 | for i in range(min_pos, len(decoded) + 1): # seek positions |
| 2024 | for j in [1, 5, len(decoded) - i]: # read lengths |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2025 | f = self.open(support.TESTFN, encoding='test_decoder') |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2026 | self.assertEquals(f.read(i), decoded[:i]) |
| 2027 | cookie = f.tell() |
| 2028 | self.assertEquals(f.read(j), decoded[i:i + j]) |
| 2029 | f.seek(cookie) |
| 2030 | self.assertEquals(f.read(), decoded[i:]) |
| 2031 | f.close() |
| 2032 | |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 2033 | # Enable the test decoder. |
| 2034 | StatefulIncrementalDecoder.codecEnabled = 1 |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2035 | |
| 2036 | # Run the tests. |
| 2037 | try: |
| 2038 | # Try each test case. |
| 2039 | for input, _, _ in StatefulIncrementalDecoderTest.test_cases: |
Benjamin Peterson | 5fd871d | 2009-03-05 00:49:53 +0000 | [diff] [blame] | 2040 | test_seek_and_tell_with_data(input) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2041 | |
| 2042 | # Position each test case so that it crosses a chunk boundary. |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2043 | for input, _, _ in StatefulIncrementalDecoderTest.test_cases: |
| 2044 | offset = CHUNK_SIZE - len(input)//2 |
| 2045 | prefix = b'.'*offset |
| 2046 | # Don't bother seeking into the prefix (takes too long). |
| 2047 | min_pos = offset*2 |
Benjamin Peterson | 5fd871d | 2009-03-05 00:49:53 +0000 | [diff] [blame] | 2048 | test_seek_and_tell_with_data(prefix + input, min_pos) |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2049 | |
| 2050 | # Ensure our test decoder won't interfere with subsequent tests. |
| 2051 | finally: |
Benjamin Peterson | ad9d48d | 2008-04-02 21:49:44 +0000 | [diff] [blame] | 2052 | StatefulIncrementalDecoder.codecEnabled = 0 |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 2053 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2054 | def test_encoded_writes(self): |
Alexandre Vassalotti | a38f73b | 2008-01-07 18:30:48 +0000 | [diff] [blame] | 2055 | data = "1234567890" |
| 2056 | tests = ("utf-16", |
| 2057 | "utf-16-le", |
| 2058 | "utf-16-be", |
| 2059 | "utf-32", |
| 2060 | "utf-32-le", |
| 2061 | "utf-32-be") |
| 2062 | for encoding in tests: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2063 | buf = self.BytesIO() |
| 2064 | f = self.TextIOWrapper(buf, encoding=encoding) |
Alexandre Vassalotti | a38f73b | 2008-01-07 18:30:48 +0000 | [diff] [blame] | 2065 | # Check if the BOM is written only once (see issue1753). |
| 2066 | f.write(data) |
| 2067 | f.write(data) |
| 2068 | f.seek(0) |
| 2069 | self.assertEquals(f.read(), data * 2) |
Benjamin Peterson | 9363a65 | 2009-03-05 00:42:09 +0000 | [diff] [blame] | 2070 | f.seek(0) |
| 2071 | self.assertEquals(f.read(), data * 2) |
Alexandre Vassalotti | a38f73b | 2008-01-07 18:30:48 +0000 | [diff] [blame] | 2072 | self.assertEquals(buf.getvalue(), (data * 2).encode(encoding)) |
| 2073 | |
Benjamin Peterson | a1b4901 | 2009-03-31 23:11:32 +0000 | [diff] [blame] | 2074 | def test_unreadable(self): |
| 2075 | class UnReadable(self.BytesIO): |
| 2076 | def readable(self): |
| 2077 | return False |
| 2078 | txt = self.TextIOWrapper(UnReadable()) |
| 2079 | self.assertRaises(IOError, txt.read) |
| 2080 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2081 | def test_read_one_by_one(self): |
| 2082 | txt = self.TextIOWrapper(self.BytesIO(b"AA\r\nBB")) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2083 | reads = "" |
| 2084 | while True: |
| 2085 | c = txt.read(1) |
| 2086 | if not c: |
| 2087 | break |
| 2088 | reads += c |
| 2089 | self.assertEquals(reads, "AA\nBB") |
| 2090 | |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 2091 | def test_readlines(self): |
| 2092 | txt = self.TextIOWrapper(self.BytesIO(b"AA\nBB\nCC")) |
| 2093 | self.assertEqual(txt.readlines(), ["AA\n", "BB\n", "CC"]) |
| 2094 | txt.seek(0) |
| 2095 | self.assertEqual(txt.readlines(None), ["AA\n", "BB\n", "CC"]) |
| 2096 | txt.seek(0) |
| 2097 | self.assertEqual(txt.readlines(5), ["AA\n", "BB\n"]) |
| 2098 | |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2099 | # read in amounts equal to TextIOWrapper._CHUNK_SIZE which is 128. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2100 | def test_read_by_chunk(self): |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2101 | # make sure "\r\n" straddles 128 char boundary. |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2102 | 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] | 2103 | reads = "" |
| 2104 | while True: |
| 2105 | c = txt.read(128) |
| 2106 | if not c: |
| 2107 | break |
| 2108 | reads += c |
| 2109 | self.assertEquals(reads, "A"*127+"\nB") |
| 2110 | |
| 2111 | def test_issue1395_1(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2112 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2113 | |
| 2114 | # read one char at a time |
| 2115 | reads = "" |
| 2116 | while True: |
| 2117 | c = txt.read(1) |
| 2118 | if not c: |
| 2119 | break |
| 2120 | reads += c |
| 2121 | self.assertEquals(reads, self.normalized) |
| 2122 | |
| 2123 | def test_issue1395_2(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2124 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2125 | txt._CHUNK_SIZE = 4 |
| 2126 | |
| 2127 | reads = "" |
| 2128 | while True: |
| 2129 | c = txt.read(4) |
| 2130 | if not c: |
| 2131 | break |
| 2132 | reads += c |
| 2133 | self.assertEquals(reads, self.normalized) |
| 2134 | |
| 2135 | def test_issue1395_3(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2136 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2137 | txt._CHUNK_SIZE = 4 |
| 2138 | |
| 2139 | reads = txt.read(4) |
| 2140 | reads += txt.read(4) |
| 2141 | reads += txt.readline() |
| 2142 | reads += txt.readline() |
| 2143 | reads += txt.readline() |
| 2144 | self.assertEquals(reads, self.normalized) |
| 2145 | |
| 2146 | def test_issue1395_4(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2147 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2148 | txt._CHUNK_SIZE = 4 |
| 2149 | |
| 2150 | reads = txt.read(4) |
| 2151 | reads += txt.read() |
| 2152 | self.assertEquals(reads, self.normalized) |
| 2153 | |
| 2154 | def test_issue1395_5(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2155 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2156 | txt._CHUNK_SIZE = 4 |
| 2157 | |
| 2158 | reads = txt.read(4) |
| 2159 | pos = txt.tell() |
| 2160 | txt.seek(0) |
| 2161 | txt.seek(pos) |
| 2162 | self.assertEquals(txt.read(4), "BBB\n") |
| 2163 | |
Ka-Ping Yee | ddaa706 | 2008-03-17 20:35:15 +0000 | [diff] [blame] | 2164 | def test_issue2282(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2165 | buffer = self.BytesIO(self.testdata) |
| 2166 | txt = self.TextIOWrapper(buffer, encoding="ascii") |
Ka-Ping Yee | ddaa706 | 2008-03-17 20:35:15 +0000 | [diff] [blame] | 2167 | |
| 2168 | self.assertEqual(buffer.seekable(), txt.seekable()) |
| 2169 | |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 2170 | def test_append_bom(self): |
| 2171 | # The BOM is not written again when appending to a non-empty file |
| 2172 | filename = support.TESTFN |
| 2173 | for charset in ('utf-8-sig', 'utf-16', 'utf-32'): |
| 2174 | with self.open(filename, 'w', encoding=charset) as f: |
| 2175 | f.write('aaa') |
| 2176 | pos = f.tell() |
| 2177 | with self.open(filename, 'rb') as f: |
| 2178 | self.assertEquals(f.read(), 'aaa'.encode(charset)) |
| 2179 | |
| 2180 | with self.open(filename, 'a', encoding=charset) as f: |
| 2181 | f.write('xxx') |
| 2182 | with self.open(filename, 'rb') as f: |
| 2183 | self.assertEquals(f.read(), 'aaaxxx'.encode(charset)) |
| 2184 | |
| 2185 | def test_seek_bom(self): |
| 2186 | # Same test, but when seeking manually |
| 2187 | filename = support.TESTFN |
| 2188 | for charset in ('utf-8-sig', 'utf-16', 'utf-32'): |
| 2189 | with self.open(filename, 'w', encoding=charset) as f: |
| 2190 | f.write('aaa') |
| 2191 | pos = f.tell() |
| 2192 | with self.open(filename, 'r+', encoding=charset) as f: |
| 2193 | f.seek(pos) |
| 2194 | f.write('zzz') |
| 2195 | f.seek(0) |
| 2196 | f.write('bbb') |
| 2197 | with self.open(filename, 'rb') as f: |
| 2198 | self.assertEquals(f.read(), 'bbbzzz'.encode(charset)) |
| 2199 | |
Benjamin Peterson | 0926ad1 | 2009-06-06 18:02:12 +0000 | [diff] [blame] | 2200 | def test_errors_property(self): |
| 2201 | with self.open(support.TESTFN, "w") as f: |
| 2202 | self.assertEqual(f.errors, "strict") |
| 2203 | with self.open(support.TESTFN, "w", errors="replace") as f: |
| 2204 | self.assertEqual(f.errors, "replace") |
| 2205 | |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 2206 | @unittest.skipUnless(threading, 'Threading required for this test.') |
Amaury Forgeot d'Arc | ccd686a | 2009-08-29 23:00:38 +0000 | [diff] [blame] | 2207 | def test_threads_write(self): |
| 2208 | # Issue6750: concurrent writes could duplicate data |
| 2209 | event = threading.Event() |
| 2210 | with self.open(support.TESTFN, "w", buffering=1) as f: |
| 2211 | def run(n): |
| 2212 | text = "Thread%03d\n" % n |
| 2213 | event.wait() |
| 2214 | f.write(text) |
| 2215 | threads = [threading.Thread(target=lambda n=x: run(n)) |
| 2216 | for x in range(20)] |
| 2217 | for t in threads: |
| 2218 | t.start() |
| 2219 | time.sleep(0.02) |
| 2220 | event.set() |
| 2221 | for t in threads: |
| 2222 | t.join() |
| 2223 | with self.open(support.TESTFN) as f: |
| 2224 | content = f.read() |
| 2225 | for n in range(20): |
| 2226 | self.assertEquals(content.count("Thread%03d\n" % n), 1) |
| 2227 | |
Antoine Pitrou | 6be8876 | 2010-05-03 16:48:20 +0000 | [diff] [blame] | 2228 | def test_flush_error_on_close(self): |
| 2229 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
| 2230 | def bad_flush(): |
| 2231 | raise IOError() |
| 2232 | txt.flush = bad_flush |
| 2233 | self.assertRaises(IOError, txt.close) # exception not swallowed |
| 2234 | |
| 2235 | def test_multi_close(self): |
| 2236 | txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") |
| 2237 | txt.close() |
| 2238 | txt.close() |
| 2239 | txt.close() |
| 2240 | self.assertRaises(ValueError, txt.flush) |
| 2241 | |
Antoine Pitrou | 0d739d7 | 2010-09-05 23:01:12 +0000 | [diff] [blame] | 2242 | def test_unseekable(self): |
| 2243 | txt = self.TextIOWrapper(self.MockUnseekableIO(self.testdata)) |
| 2244 | self.assertRaises(self.UnsupportedOperation, txt.tell) |
| 2245 | self.assertRaises(self.UnsupportedOperation, txt.seek, 0) |
| 2246 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2247 | class CTextIOWrapperTest(TextIOWrapperTest): |
| 2248 | |
| 2249 | def test_initialization(self): |
| 2250 | r = self.BytesIO(b"\xc3\xa9\n\n") |
| 2251 | b = self.BufferedReader(r, 1000) |
| 2252 | t = self.TextIOWrapper(b) |
| 2253 | self.assertRaises(TypeError, t.__init__, b, newline=42) |
| 2254 | self.assertRaises(ValueError, t.read) |
| 2255 | self.assertRaises(ValueError, t.__init__, b, newline='xyzzy') |
| 2256 | self.assertRaises(ValueError, t.read) |
| 2257 | |
| 2258 | def test_garbage_collection(self): |
| 2259 | # C TextIOWrapper objects are collected, and collecting them flushes |
| 2260 | # all data to disk. |
| 2261 | # The Python version has __del__, so it ends in gc.garbage instead. |
| 2262 | rawio = io.FileIO(support.TESTFN, "wb") |
| 2263 | b = self.BufferedWriter(rawio) |
| 2264 | t = self.TextIOWrapper(b, encoding="ascii") |
| 2265 | t.write("456def") |
| 2266 | t.x = t |
| 2267 | wr = weakref.ref(t) |
| 2268 | del t |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 2269 | support.gc_collect() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 2270 | self.assertTrue(wr() is None, wr) |
Hirokazu Yamamoto | c7d6aa4 | 2009-06-18 00:07:14 +0000 | [diff] [blame] | 2271 | with self.open(support.TESTFN, "rb") as f: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2272 | self.assertEqual(f.read(), b"456def") |
| 2273 | |
| 2274 | class PyTextIOWrapperTest(TextIOWrapperTest): |
| 2275 | pass |
| 2276 | |
| 2277 | |
| 2278 | class IncrementalNewlineDecoderTest(unittest.TestCase): |
| 2279 | |
| 2280 | def check_newline_decoding_utf8(self, decoder): |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2281 | # UTF-8 specific tests for a newline decoder |
| 2282 | def _check_decode(b, s, **kwargs): |
| 2283 | # We exercise getstate() / setstate() as well as decode() |
| 2284 | state = decoder.getstate() |
| 2285 | self.assertEquals(decoder.decode(b, **kwargs), s) |
| 2286 | decoder.setstate(state) |
| 2287 | self.assertEquals(decoder.decode(b, **kwargs), s) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2288 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2289 | _check_decode(b'\xe8\xa2\x88', "\u8888") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2290 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2291 | _check_decode(b'\xe8', "") |
| 2292 | _check_decode(b'\xa2', "") |
| 2293 | _check_decode(b'\x88', "\u8888") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2294 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2295 | _check_decode(b'\xe8', "") |
| 2296 | _check_decode(b'\xa2', "") |
| 2297 | _check_decode(b'\x88', "\u8888") |
| 2298 | |
| 2299 | _check_decode(b'\xe8', "") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2300 | self.assertRaises(UnicodeDecodeError, decoder.decode, b'', final=True) |
| 2301 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2302 | decoder.reset() |
| 2303 | _check_decode(b'\n', "\n") |
| 2304 | _check_decode(b'\r', "") |
| 2305 | _check_decode(b'', "\n", final=True) |
| 2306 | _check_decode(b'\r', "\n", final=True) |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2307 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2308 | _check_decode(b'\r', "") |
| 2309 | _check_decode(b'a', "\na") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2310 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2311 | _check_decode(b'\r\r\n', "\n\n") |
| 2312 | _check_decode(b'\r', "") |
| 2313 | _check_decode(b'\r', "\n") |
| 2314 | _check_decode(b'\na', "\na") |
Amaury Forgeot d'Arc | 1ff9910 | 2007-11-19 20:34:10 +0000 | [diff] [blame] | 2315 | |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2316 | _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n") |
| 2317 | _check_decode(b'\xe8\xa2\x88', "\u8888") |
| 2318 | _check_decode(b'\n', "\n") |
| 2319 | _check_decode(b'\xe8\xa2\x88\r', "\u8888") |
| 2320 | _check_decode(b'\n', "\n") |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 2321 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2322 | def check_newline_decoding(self, decoder, encoding): |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2323 | result = [] |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2324 | if encoding is not None: |
| 2325 | encoder = codecs.getincrementalencoder(encoding)() |
| 2326 | def _decode_bytewise(s): |
| 2327 | # Decode one byte at a time |
| 2328 | for b in encoder.encode(s): |
| 2329 | result.append(decoder.decode(bytes([b]))) |
| 2330 | else: |
| 2331 | encoder = None |
| 2332 | def _decode_bytewise(s): |
| 2333 | # Decode one char at a time |
| 2334 | for c in s: |
| 2335 | result.append(decoder.decode(c)) |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2336 | self.assertEquals(decoder.newlines, None) |
| 2337 | _decode_bytewise("abc\n\r") |
| 2338 | self.assertEquals(decoder.newlines, '\n') |
| 2339 | _decode_bytewise("\nabc") |
| 2340 | self.assertEquals(decoder.newlines, ('\n', '\r\n')) |
| 2341 | _decode_bytewise("abc\r") |
| 2342 | self.assertEquals(decoder.newlines, ('\n', '\r\n')) |
| 2343 | _decode_bytewise("abc") |
| 2344 | self.assertEquals(decoder.newlines, ('\r', '\n', '\r\n')) |
| 2345 | _decode_bytewise("abc\r") |
| 2346 | self.assertEquals("".join(result), "abc\n\nabcabc\nabcabc") |
| 2347 | decoder.reset() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2348 | input = "abc" |
| 2349 | if encoder is not None: |
| 2350 | encoder.reset() |
| 2351 | input = encoder.encode(input) |
| 2352 | self.assertEquals(decoder.decode(input), "abc") |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2353 | self.assertEquals(decoder.newlines, None) |
| 2354 | |
| 2355 | def test_newline_decoder(self): |
| 2356 | encodings = ( |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2357 | # None meaning the IncrementalNewlineDecoder takes unicode input |
| 2358 | # rather than bytes input |
| 2359 | None, 'utf-8', 'latin-1', |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2360 | 'utf-16', 'utf-16-le', 'utf-16-be', |
| 2361 | 'utf-32', 'utf-32-le', 'utf-32-be', |
| 2362 | ) |
| 2363 | for enc in encodings: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2364 | decoder = enc and codecs.getincrementaldecoder(enc)() |
| 2365 | decoder = self.IncrementalNewlineDecoder(decoder, translate=True) |
| 2366 | self.check_newline_decoding(decoder, enc) |
Alexandre Vassalotti | 472f07d | 2008-01-06 00:34:32 +0000 | [diff] [blame] | 2367 | decoder = codecs.getincrementaldecoder("utf-8")() |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2368 | decoder = self.IncrementalNewlineDecoder(decoder, translate=True) |
| 2369 | self.check_newline_decoding_utf8(decoder) |
| 2370 | |
Antoine Pitrou | 66913e2 | 2009-03-06 23:40:56 +0000 | [diff] [blame] | 2371 | def test_newline_bytes(self): |
| 2372 | # Issue 5433: Excessive optimization in IncrementalNewlineDecoder |
| 2373 | def _check(dec): |
| 2374 | self.assertEquals(dec.newlines, None) |
| 2375 | self.assertEquals(dec.decode("\u0D00"), "\u0D00") |
| 2376 | self.assertEquals(dec.newlines, None) |
| 2377 | self.assertEquals(dec.decode("\u0A00"), "\u0A00") |
| 2378 | self.assertEquals(dec.newlines, None) |
| 2379 | dec = self.IncrementalNewlineDecoder(None, translate=False) |
| 2380 | _check(dec) |
| 2381 | dec = self.IncrementalNewlineDecoder(None, translate=True) |
| 2382 | _check(dec) |
| 2383 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2384 | class CIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): |
| 2385 | pass |
| 2386 | |
| 2387 | class PyIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): |
| 2388 | pass |
Antoine Pitrou | 180a336 | 2008-12-14 16:36:46 +0000 | [diff] [blame] | 2389 | |
Alexandre Vassalotti | 472f07d | 2008-01-06 00:34:32 +0000 | [diff] [blame] | 2390 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 2391 | # XXX Tests for open() |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 2392 | |
Guido van Rossum | 5abbf75 | 2007-08-27 17:39:33 +0000 | [diff] [blame] | 2393 | class MiscIOTest(unittest.TestCase): |
| 2394 | |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2395 | def tearDown(self): |
| 2396 | support.unlink(support.TESTFN) |
| 2397 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2398 | def test___all__(self): |
| 2399 | for name in self.io.__all__: |
| 2400 | obj = getattr(self.io, name, None) |
Benjamin Peterson | bfb9594 | 2009-04-02 01:13:40 +0000 | [diff] [blame] | 2401 | self.assertTrue(obj is not None, name) |
Guido van Rossum | 5abbf75 | 2007-08-27 17:39:33 +0000 | [diff] [blame] | 2402 | if name == "open": |
| 2403 | continue |
Benjamin Peterson | 6a52a9c | 2009-04-29 22:00:44 +0000 | [diff] [blame] | 2404 | elif "error" in name.lower() or name == "UnsupportedOperation": |
Benjamin Peterson | bfb9594 | 2009-04-02 01:13:40 +0000 | [diff] [blame] | 2405 | self.assertTrue(issubclass(obj, Exception), name) |
| 2406 | elif not name.startswith("SEEK_"): |
| 2407 | self.assertTrue(issubclass(obj, self.IOBase)) |
Benjamin Peterson | 65676e4 | 2008-11-05 21:42:45 +0000 | [diff] [blame] | 2408 | |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2409 | def test_attributes(self): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2410 | f = self.open(support.TESTFN, "wb", buffering=0) |
Benjamin Peterson | 44309e6 | 2008-11-22 00:41:45 +0000 | [diff] [blame] | 2411 | self.assertEquals(f.mode, "wb") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2412 | f.close() |
| 2413 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2414 | f = self.open(support.TESTFN, "U") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2415 | self.assertEquals(f.name, support.TESTFN) |
| 2416 | self.assertEquals(f.buffer.name, support.TESTFN) |
| 2417 | self.assertEquals(f.buffer.raw.name, support.TESTFN) |
| 2418 | self.assertEquals(f.mode, "U") |
Benjamin Peterson | 44309e6 | 2008-11-22 00:41:45 +0000 | [diff] [blame] | 2419 | self.assertEquals(f.buffer.mode, "rb") |
| 2420 | self.assertEquals(f.buffer.raw.mode, "rb") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2421 | f.close() |
| 2422 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2423 | f = self.open(support.TESTFN, "w+") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2424 | self.assertEquals(f.mode, "w+") |
Benjamin Peterson | 44309e6 | 2008-11-22 00:41:45 +0000 | [diff] [blame] | 2425 | self.assertEquals(f.buffer.mode, "rb+") # Does it really matter? |
| 2426 | self.assertEquals(f.buffer.raw.mode, "rb+") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2427 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2428 | g = self.open(f.fileno(), "wb", closefd=False) |
Benjamin Peterson | 44309e6 | 2008-11-22 00:41:45 +0000 | [diff] [blame] | 2429 | self.assertEquals(g.mode, "wb") |
| 2430 | self.assertEquals(g.raw.mode, "wb") |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2431 | self.assertEquals(g.name, f.fileno()) |
| 2432 | self.assertEquals(g.raw.name, f.fileno()) |
| 2433 | f.close() |
| 2434 | g.close() |
| 2435 | |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 2436 | def test_io_after_close(self): |
| 2437 | for kwargs in [ |
| 2438 | {"mode": "w"}, |
| 2439 | {"mode": "wb"}, |
| 2440 | {"mode": "w", "buffering": 1}, |
| 2441 | {"mode": "w", "buffering": 2}, |
| 2442 | {"mode": "wb", "buffering": 0}, |
| 2443 | {"mode": "r"}, |
| 2444 | {"mode": "rb"}, |
| 2445 | {"mode": "r", "buffering": 1}, |
| 2446 | {"mode": "r", "buffering": 2}, |
| 2447 | {"mode": "rb", "buffering": 0}, |
| 2448 | {"mode": "w+"}, |
| 2449 | {"mode": "w+b"}, |
| 2450 | {"mode": "w+", "buffering": 1}, |
| 2451 | {"mode": "w+", "buffering": 2}, |
| 2452 | {"mode": "w+b", "buffering": 0}, |
| 2453 | ]: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2454 | f = self.open(support.TESTFN, **kwargs) |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 2455 | f.close() |
| 2456 | self.assertRaises(ValueError, f.flush) |
| 2457 | self.assertRaises(ValueError, f.fileno) |
| 2458 | self.assertRaises(ValueError, f.isatty) |
| 2459 | self.assertRaises(ValueError, f.__iter__) |
| 2460 | if hasattr(f, "peek"): |
| 2461 | self.assertRaises(ValueError, f.peek, 1) |
| 2462 | self.assertRaises(ValueError, f.read) |
| 2463 | if hasattr(f, "read1"): |
| 2464 | self.assertRaises(ValueError, f.read1, 1024) |
| 2465 | if hasattr(f, "readinto"): |
| 2466 | self.assertRaises(ValueError, f.readinto, bytearray(1024)) |
| 2467 | self.assertRaises(ValueError, f.readline) |
| 2468 | self.assertRaises(ValueError, f.readlines) |
| 2469 | self.assertRaises(ValueError, f.seek, 0) |
| 2470 | self.assertRaises(ValueError, f.tell) |
| 2471 | self.assertRaises(ValueError, f.truncate) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2472 | self.assertRaises(ValueError, f.write, |
| 2473 | b"" if "b" in kwargs['mode'] else "") |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 2474 | self.assertRaises(ValueError, f.writelines, []) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2475 | self.assertRaises(ValueError, next, f) |
Antoine Pitrou | 8043cf8 | 2009-01-09 19:54:29 +0000 | [diff] [blame] | 2476 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2477 | def test_blockingioerror(self): |
| 2478 | # Various BlockingIOError issues |
| 2479 | self.assertRaises(TypeError, self.BlockingIOError) |
| 2480 | self.assertRaises(TypeError, self.BlockingIOError, 1) |
| 2481 | self.assertRaises(TypeError, self.BlockingIOError, 1, 2, 3, 4) |
| 2482 | self.assertRaises(TypeError, self.BlockingIOError, 1, "", None) |
| 2483 | b = self.BlockingIOError(1, "") |
| 2484 | self.assertEqual(b.characters_written, 0) |
| 2485 | class C(str): |
| 2486 | pass |
| 2487 | c = C("") |
| 2488 | b = self.BlockingIOError(1, c) |
| 2489 | c.b = b |
| 2490 | b.c = c |
| 2491 | wr = weakref.ref(c) |
| 2492 | del c, b |
Benjamin Peterson | 24fb1d0 | 2009-04-24 23:26:21 +0000 | [diff] [blame] | 2493 | support.gc_collect() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 2494 | self.assertTrue(wr() is None, wr) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2495 | |
| 2496 | def test_abcs(self): |
| 2497 | # Test the visible base classes are ABCs. |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 2498 | self.assertIsInstance(self.IOBase, abc.ABCMeta) |
| 2499 | self.assertIsInstance(self.RawIOBase, abc.ABCMeta) |
| 2500 | self.assertIsInstance(self.BufferedIOBase, abc.ABCMeta) |
| 2501 | self.assertIsInstance(self.TextIOBase, abc.ABCMeta) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2502 | |
| 2503 | def _check_abc_inheritance(self, abcmodule): |
| 2504 | with self.open(support.TESTFN, "wb", buffering=0) as f: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 2505 | self.assertIsInstance(f, abcmodule.IOBase) |
| 2506 | self.assertIsInstance(f, abcmodule.RawIOBase) |
| 2507 | self.assertNotIsInstance(f, abcmodule.BufferedIOBase) |
| 2508 | self.assertNotIsInstance(f, abcmodule.TextIOBase) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2509 | with self.open(support.TESTFN, "wb") as f: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 2510 | self.assertIsInstance(f, abcmodule.IOBase) |
| 2511 | self.assertNotIsInstance(f, abcmodule.RawIOBase) |
| 2512 | self.assertIsInstance(f, abcmodule.BufferedIOBase) |
| 2513 | self.assertNotIsInstance(f, abcmodule.TextIOBase) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2514 | with self.open(support.TESTFN, "w") as f: |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 2515 | self.assertIsInstance(f, abcmodule.IOBase) |
| 2516 | self.assertNotIsInstance(f, abcmodule.RawIOBase) |
| 2517 | self.assertNotIsInstance(f, abcmodule.BufferedIOBase) |
| 2518 | self.assertIsInstance(f, abcmodule.TextIOBase) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2519 | |
| 2520 | def test_abc_inheritance(self): |
| 2521 | # Test implementations inherit from their respective ABCs |
| 2522 | self._check_abc_inheritance(self) |
| 2523 | |
| 2524 | def test_abc_inheritance_official(self): |
| 2525 | # Test implementations inherit from the official ABCs of the |
| 2526 | # baseline "io" module. |
| 2527 | self._check_abc_inheritance(io) |
| 2528 | |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 2529 | def _check_warn_on_dealloc(self, *args, **kwargs): |
| 2530 | f = open(*args, **kwargs) |
| 2531 | r = repr(f) |
| 2532 | with self.assertWarns(ResourceWarning) as cm: |
| 2533 | f = None |
| 2534 | support.gc_collect() |
| 2535 | self.assertIn(r, str(cm.warning.args[0])) |
| 2536 | |
| 2537 | def test_warn_on_dealloc(self): |
| 2538 | self._check_warn_on_dealloc(support.TESTFN, "wb", buffering=0) |
| 2539 | self._check_warn_on_dealloc(support.TESTFN, "wb") |
| 2540 | self._check_warn_on_dealloc(support.TESTFN, "w") |
| 2541 | |
| 2542 | def _check_warn_on_dealloc_fd(self, *args, **kwargs): |
| 2543 | fds = [] |
Benjamin Peterson | 556c735 | 2010-10-31 01:35:43 +0000 | [diff] [blame^] | 2544 | def cleanup_fds(): |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 2545 | for fd in fds: |
| 2546 | try: |
| 2547 | os.close(fd) |
| 2548 | except EnvironmentError as e: |
| 2549 | if e.errno != errno.EBADF: |
| 2550 | raise |
Benjamin Peterson | 556c735 | 2010-10-31 01:35:43 +0000 | [diff] [blame^] | 2551 | self.addCleanup(cleanup_fds) |
| 2552 | r, w = os.pipe() |
| 2553 | fds += r, w |
| 2554 | self._check_warn_on_dealloc(r, *args, **kwargs) |
| 2555 | # When using closefd=False, there's no warning |
| 2556 | r, w = os.pipe() |
| 2557 | fds += r, w |
| 2558 | with warnings.catch_warnings(record=True) as recorded: |
| 2559 | open(r, *args, closefd=False, **kwargs) |
| 2560 | support.gc_collect() |
| 2561 | self.assertEqual(recorded, []) |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 2562 | |
| 2563 | def test_warn_on_dealloc_fd(self): |
| 2564 | self._check_warn_on_dealloc_fd("rb", buffering=0) |
| 2565 | self._check_warn_on_dealloc_fd("rb") |
| 2566 | self._check_warn_on_dealloc_fd("r") |
| 2567 | |
| 2568 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2569 | class CMiscIOTest(MiscIOTest): |
| 2570 | io = io |
| 2571 | |
| 2572 | class PyMiscIOTest(MiscIOTest): |
| 2573 | io = pyio |
Barry Warsaw | 40e8246 | 2008-11-20 20:14:50 +0000 | [diff] [blame] | 2574 | |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 2575 | |
| 2576 | @unittest.skipIf(os.name == 'nt', 'POSIX signals required for this test.') |
| 2577 | class SignalsTest(unittest.TestCase): |
| 2578 | |
| 2579 | def setUp(self): |
| 2580 | self.oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt) |
| 2581 | |
| 2582 | def tearDown(self): |
| 2583 | signal.signal(signal.SIGALRM, self.oldalrm) |
| 2584 | |
| 2585 | def alarm_interrupt(self, sig, frame): |
| 2586 | 1/0 |
| 2587 | |
| 2588 | @unittest.skipUnless(threading, 'Threading required for this test.') |
| 2589 | def check_interrupted_write(self, item, bytes, **fdopen_kwargs): |
| 2590 | """Check that a partial write, when it gets interrupted, properly |
| 2591 | invokes the signal handler.""" |
| 2592 | read_results = [] |
| 2593 | def _read(): |
| 2594 | s = os.read(r, 1) |
| 2595 | read_results.append(s) |
| 2596 | t = threading.Thread(target=_read) |
| 2597 | t.daemon = True |
| 2598 | r, w = os.pipe() |
Benjamin Peterson | d8fc2e1 | 2010-10-31 01:19:53 +0000 | [diff] [blame] | 2599 | fdopen_kwargs["closefd"] = False |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 2600 | try: |
| 2601 | wio = self.io.open(w, **fdopen_kwargs) |
| 2602 | t.start() |
| 2603 | signal.alarm(1) |
| 2604 | # Fill the pipe enough that the write will be blocking. |
| 2605 | # It will be interrupted by the timer armed above. Since the |
| 2606 | # other thread has read one byte, the low-level write will |
| 2607 | # return with a successful (partial) result rather than an EINTR. |
| 2608 | # The buffered IO layer must check for pending signal |
| 2609 | # handlers, which in this case will invoke alarm_interrupt(). |
| 2610 | self.assertRaises(ZeroDivisionError, |
| 2611 | wio.write, item * (1024 * 1024)) |
| 2612 | t.join() |
| 2613 | # We got one byte, get another one and check that it isn't a |
| 2614 | # repeat of the first one. |
| 2615 | read_results.append(os.read(r, 1)) |
| 2616 | self.assertEqual(read_results, [bytes[0:1], bytes[1:2]]) |
| 2617 | finally: |
| 2618 | os.close(w) |
| 2619 | os.close(r) |
| 2620 | # This is deliberate. If we didn't close the file descriptor |
| 2621 | # before closing wio, wio would try to flush its internal |
| 2622 | # buffer, and block again. |
| 2623 | try: |
| 2624 | wio.close() |
| 2625 | except IOError as e: |
| 2626 | if e.errno != errno.EBADF: |
| 2627 | raise |
| 2628 | |
| 2629 | def test_interrupted_write_unbuffered(self): |
| 2630 | self.check_interrupted_write(b"xy", b"xy", mode="wb", buffering=0) |
| 2631 | |
| 2632 | def test_interrupted_write_buffered(self): |
| 2633 | self.check_interrupted_write(b"xy", b"xy", mode="wb") |
| 2634 | |
| 2635 | def test_interrupted_write_text(self): |
| 2636 | self.check_interrupted_write("xy", b"xy", mode="w", encoding="ascii") |
| 2637 | |
| 2638 | class CSignalsTest(SignalsTest): |
| 2639 | io = io |
| 2640 | |
| 2641 | class PySignalsTest(SignalsTest): |
| 2642 | io = pyio |
| 2643 | |
| 2644 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 2645 | def test_main(): |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2646 | tests = (CIOTest, PyIOTest, |
| 2647 | CBufferedReaderTest, PyBufferedReaderTest, |
| 2648 | CBufferedWriterTest, PyBufferedWriterTest, |
| 2649 | CBufferedRWPairTest, PyBufferedRWPairTest, |
| 2650 | CBufferedRandomTest, PyBufferedRandomTest, |
| 2651 | StatefulIncrementalDecoderTest, |
| 2652 | CIncrementalNewlineDecoderTest, PyIncrementalNewlineDecoderTest, |
| 2653 | CTextIOWrapperTest, PyTextIOWrapperTest, |
Antoine Pitrou | b46b9d5 | 2010-08-21 19:09:32 +0000 | [diff] [blame] | 2654 | CMiscIOTest, PyMiscIOTest, |
| 2655 | CSignalsTest, PySignalsTest, |
| 2656 | ) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2657 | |
| 2658 | # Put the namespaces of the IO module we are testing and some useful mock |
| 2659 | # classes in the __dict__ of each test. |
| 2660 | mocks = (MockRawIO, MisbehavedRawIO, MockFileIO, CloseFailureIO, |
Antoine Pitrou | 328ec74 | 2010-09-14 18:37:24 +0000 | [diff] [blame] | 2661 | MockNonBlockWriterIO, MockUnseekableIO, MockRawIOWithoutRead) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2662 | all_members = io.__all__ + ["IncrementalNewlineDecoder"] |
| 2663 | c_io_ns = {name : getattr(io, name) for name in all_members} |
| 2664 | py_io_ns = {name : getattr(pyio, name) for name in all_members} |
| 2665 | globs = globals() |
| 2666 | c_io_ns.update((x.__name__, globs["C" + x.__name__]) for x in mocks) |
| 2667 | py_io_ns.update((x.__name__, globs["Py" + x.__name__]) for x in mocks) |
| 2668 | # Avoid turning open into a bound method. |
| 2669 | py_io_ns["open"] = pyio.OpenWrapper |
| 2670 | for test in tests: |
| 2671 | if test.__name__.startswith("C"): |
| 2672 | for name, obj in c_io_ns.items(): |
| 2673 | setattr(test, name, obj) |
| 2674 | elif test.__name__.startswith("Py"): |
| 2675 | for name, obj in py_io_ns.items(): |
| 2676 | setattr(test, name, obj) |
| 2677 | |
| 2678 | support.run_unittest(*tests) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 2679 | |
| 2680 | if __name__ == "__main__": |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 2681 | test_main() |