Debian Codegraph @

pypy/module/_io/test/apptest_textio.py

raw symbols SCIP
1 #encoding: utf-8
2 # spaceconfig = {"usemodules" : ["_locale", "array"]}
3 from pytest import raises
4 import _io
5 import os
6 import sys
7 import array
8 import codecs
9
10 def test_constructor():
11
12 r = _io.BytesIO(b"\xc3\xa9\n\n")
13 b = _io.BufferedReader(r, 1000)
14 t = _io.TextIOWrapper(b)
15 t.__init__(b, encoding="latin1", newline="\r\n")
16 assert t.encoding == "latin1"
17 assert t.line_buffering == False
18 t.__init__(b, encoding="utf8", line_buffering=True)
19 assert t.encoding == "utf8"
20 assert t.line_buffering == True
21 assert t.readline() == "\xe9\n"
22 raises(TypeError, t.__init__, b, newline=42)
23 raises(ValueError, t.__init__, b, newline='xyzzy')
24 raises(UnicodeEncodeError, t.__init__, b, errors='\udcfe')
25 t = _io.TextIOWrapper(b)
26 assert t.encoding
27
28 def test_properties():
29
30 r = _io.BytesIO(b"\xc3\xa9\n\n")
31 b = _io.BufferedReader(r, 1000)
32 t = _io.TextIOWrapper(b)
33 assert t.readable()
34 assert t.seekable()
35 #
36 class CustomFile(object):
37 def isatty(self): return 'YES'
38 readable = writable = seekable = lambda self: False
39 t = _io.TextIOWrapper(CustomFile())
40 assert t.isatty() == 'YES'
41
42 def test_default_implementations():
43
44 file = _io._TextIOBase()
45 raises(_io.UnsupportedOperation, file.read)
46 raises(_io.UnsupportedOperation, file.seek, 0)
47 raises(_io.UnsupportedOperation, file.readline)
48 raises(_io.UnsupportedOperation, file.detach)
49
50 def test_isatty():
51
52 class Tty(_io.BytesIO):
53 def isatty(self):
54 return True
55 txt = _io.TextIOWrapper(Tty())
56 assert txt.isatty()
57
58 def test_unreadable():
59
60 class UnReadable(_io.BytesIO):
61 def readable(self):
62 return False
63 txt = _io.TextIOWrapper(UnReadable())
64 raises(IOError, txt.read)
65
66 def test_unwritable():
67
68 class UnWritable(_io.BytesIO):
69 def writable(self):
70 return False
71 txt = _io.TextIOWrapper(UnWritable())
72 raises(_io.UnsupportedOperation, txt.write, "blah")
73 raises(_io.UnsupportedOperation, txt.writelines, ["blah\n"])
74
75 def test_invalid_seek():
76
77 t = _io.TextIOWrapper(_io.BytesIO(b"\xc3\xa9\n\n"))
78 raises(_io.UnsupportedOperation, t.seek, 1, 1)
79 raises(_io.UnsupportedOperation, t.seek, 1, 2)
80
81 def test_unseekable():
82
83 class Unseekable(_io.BytesIO):
84 def seekable(self):
85 return False
86 txt = _io.TextIOWrapper(Unseekable())
87 raises(_io.UnsupportedOperation, txt.tell)
88 raises(_io.UnsupportedOperation, txt.seek, 0)
89
90 def test_detach():
91
92 b = _io.BytesIO()
93 f = _io.TextIOWrapper(b)
94 assert f.detach() is b
95 raises(ValueError, f.fileno)
96 raises(ValueError, f.close)
97 raises(ValueError, f.detach)
98 raises(ValueError, f.flush)
99
100 # Operations independent of the detached stream should still work
101 repr(f)
102 assert isinstance(f.encoding, str)
103 assert f.errors == "strict"
104 assert not f.line_buffering
105
106 assert not b.closed
107 b.close()
108
109 def test_newlinetranslate():
110
111 r = _io.BytesIO(b"abc\r\ndef\rg")
112 b = _io.BufferedReader(r, 1000)
113 t = _io.TextIOWrapper(b)
114 assert t.read() == "abc\ndef\ng"
115
116 def test_one_by_one():
117
118 r = _io.BytesIO(b"abc\r\ndef\rg")
119 t = _io.TextIOWrapper(r)
120 reads = []
121 while True:
122 c = t.read(1)
123 assert len(c) <= 1
124 if not c:
125 break
126 reads.append(c)
127 assert ''.join(reads) == "abc\ndef\ng"
128
129 def test_read_some_then_all():
130
131 r = _io.BytesIO(b"abc\ndef\n")
132 t = _io.TextIOWrapper(r)
133 reads = t.read(4)
134 reads += t.read()
135 assert reads == "abc\ndef\n"
136
137 def test_read_some_then_readline():
138
139 r = _io.BytesIO(b"abc\ndef\n")
140 t = _io.TextIOWrapper(r)
141 reads = t.read(4)
142 reads += t.readline()
143 assert reads == "abc\ndef\n"
144
145 def test_read_bug_unicode():
146
147 r = _io.BytesIO(b"\xc3\xa4bc\ndef\n")
148 t = _io.TextIOWrapper(r, encoding="utf-8")
149 reads = t.read(4)
150 assert reads == u"äbc\n"
151 reads += t.readline()
152 assert reads == u"äbc\ndef\n"
153
154 def test_encoded_writes():
155
156 data = "1234567890"
157 tests = ("utf-16",
158 "utf-16-le",
159 "utf-16-be",
160 "utf-32",
161 "utf-32-le",
162 "utf-32-be")
163 for encoding in tests:
164 buf = _io.BytesIO()
165 f = _io.TextIOWrapper(buf, encoding=encoding)
166 # Check if the BOM is written only once (see issue1753).
167 f.write(data)
168 f.write(data)
169 f.seek(0)
170 assert f.read() == data * 2
171 f.seek(0)
172 assert f.read() == data * 2
173 assert buf.getvalue() == (data * 2).encode(encoding)
174
175 def test_writelines_error():
176
177 txt = _io.TextIOWrapper(_io.BytesIO())
178 raises(TypeError, txt.writelines, [1, 2, 3])
179 raises(TypeError, txt.writelines, None)
180 raises(TypeError, txt.writelines, b'abc')
181
182 def test_tell():
183
184 r = _io.BytesIO(b"abc\ndef\n")
185 t = _io.TextIOWrapper(r)
186 assert t.tell() == 0
187 t.read(4)
188 assert t.tell() == 4
189
190 def test_destructor():
191
192 l = []
193 class MyBytesIO(_io.BytesIO):
194 def close(self):
195 l.append(self.getvalue())
196 _io.BytesIO.close(self)
197 b = MyBytesIO()
198 t = _io.TextIOWrapper(b, encoding="ascii")
199 t.write("abc")
200 del t
201 import gc; gc.collect()
202 assert l == [b"abc"]
203
204 def test_newlines():
205
206 input_lines = [ "unix\n", "windows\r\n", "os9\r", "last\n", "nonl" ]
207
208 tests = [
209 [ None, [ 'unix\n', 'windows\n', 'os9\n', 'last\n', 'nonl' ] ],
210 [ '', input_lines ],
211 [ '\n', [ "unix\n", "windows\r\n", "os9\rlast\n", "nonl" ] ],
212 [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ],
213 [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ],
214 ]
215
216 # Try a range of buffer sizes to test the case where \r is the last
217 # character in TextIOWrapper._pending_line.
218 encoding = "ascii"
219 # XXX: str.encode() should return bytes
220 data = bytes(''.join(input_lines).encode(encoding))
221 for do_reads in (False, True):
222 for bufsize in range(1, 10):
223 for newline, exp_lines in tests:
224 bufio = _io.BufferedReader(_io.BytesIO(data), bufsize)
225 textio = _io.TextIOWrapper(bufio, newline=newline,
226 encoding=encoding)
227 if do_reads:
228 got_lines = []
229 while True:
230 c2 = textio.read(2)
231 if c2 == '':
232 break
233 len(c2) == 2
234 got_lines.append(c2 + textio.readline())
235 else:
236 got_lines = list(textio)
237
238 for got_line, exp_line in zip(got_lines, exp_lines):
239 assert got_line == exp_line
240 assert len(got_lines) == len(exp_lines)
241
242 def test_readline_none():
243 import _io
244 t = _io.TextIOWrapper(_io.BytesIO(b"hello\nworld"))
245 raises(TypeError, t.readline, None)
246
247 def test_readline():
248
249
250 s = b"AAA\r\nBBB\rCCC\r\nDDD\nEEE\r\n"
251 r = "AAA\nBBB\nCCC\nDDD\nEEE\n"
252 txt = _io.TextIOWrapper(_io.BytesIO(s), encoding="ascii")
253 txt._CHUNK_SIZE = 4
254
255 reads = txt.read(4)
256 reads += txt.read(4)
257 reads += txt.readline()
258 reads += txt.readline()
259 reads += txt.readline()
260 assert reads == r
261
262 def test_name():
263
264
265 t = _io.TextIOWrapper(_io.BytesIO(b""))
266 # CPython raises an AttributeError, we raise a TypeError.
267 raises((AttributeError, TypeError), setattr, t, "name", "anything")
268
269 def test_repr():
270
271
272 t = _io.TextIOWrapper(_io.BytesIO(b""), encoding="utf-8")
273 assert repr(t) == "<_io.TextIOWrapper encoding='utf-8'>"
274 t = _io.TextIOWrapper(_io.BytesIO(b""), encoding="ascii")
275 assert repr(t) == "<_io.TextIOWrapper encoding='ascii'>"
276 t = _io.TextIOWrapper(_io.BytesIO(b""), encoding="utf-8")
277 assert repr(t) == "<_io.TextIOWrapper encoding='utf-8'>"
278 b = _io.BytesIO(b"")
279 t = _io.TextIOWrapper(b, encoding="utf-8")
280 b.name = "dummy"
281 assert repr(t) == "<_io.TextIOWrapper name='dummy' encoding='utf-8'>"
282 t.mode = "r"
283 assert repr(t) == "<_io.TextIOWrapper name='dummy' mode='r' encoding='utf-8'>"
284 b.name = b"dummy"
285 assert repr(t) == "<_io.TextIOWrapper name=b'dummy' mode='r' encoding='utf-8'>"
286
287 def test_rawio():
288 # Issue #12591: TextIOWrapper must work with raw I/O objects, so
289 # that subprocess.Popen() can have the required unbuffered
290 # semantics with universal_newlines=True.
291
292 raw = get_MockRawIO()([b'abc', b'def', b'ghi\njkl\nopq\n'])
293 txt = _io.TextIOWrapper(raw, encoding='ascii', newline='\n')
294 # Reads
295 assert txt.read(4) == 'abcd'
296 assert txt.readline() == 'efghi\n'
297 assert list(txt) == ['jkl\n', 'opq\n']
298
299 def test_rawio_write_through():
300 # Issue #12591: with write_through=True, writes don't need a flush
301
302 raw = get_MockRawIO()([b'abc', b'def', b'ghi\njkl\nopq\n'])
303 txt = _io.TextIOWrapper(raw, encoding='ascii', newline='\n',
304 write_through=True)
305 txt.write('1')
306 txt.write('23\n4')
307 txt.write('5')
308 assert b''.join(raw._write_stack) == b'123\n45'
309
310 def get_MockRawIO():
311
312 class MockRawIO(_io._RawIOBase):
313 def __init__(self, read_stack=()):
314 self._read_stack = list(read_stack)
315 self._write_stack = []
316 self._reads = 0
317 self._extraneous_reads = 0
318
319 def write(self, b):
320 self._write_stack.append(bytes(b))
321 return len(b)
322
323 def writable(self):
324 return True
325
326 def fileno(self):
327 return 42
328
329 def readable(self):
330 return True
331
332 def seekable(self):
333 return True
334
335 def seek(self, pos, whence):
336 return 0 # wrong but we gotta return something
337
338 def tell(self):
339 return 0 # same comment as above
340
341 def readinto(self, buf):
342 self._reads += 1
343 max_len = len(buf)
344 try:
345 data = self._read_stack[0]
346 except IndexError:
347 self._extraneous_reads += 1
348 return 0
349 if data is None:
350 del self._read_stack[0]
351 return None
352 n = len(data)
353 if len(data) <= max_len:
354 del self._read_stack[0]
355 buf[:n] = data
356 return n
357 else:
358 buf[:] = data[:max_len]
359 self._read_stack[0] = data[max_len:]
360 return max_len
361
362 def truncate(self, pos=None):
363 return pos
364
365 def read(self, n=None):
366 self._reads += 1
367 try:
368 return self._read_stack.pop(0)
369 except:
370 self._extraneous_reads += 1
371 return b""
372 return MockRawIO
373
374 def test_flush_error_on_close():
375
376 txt = _io.TextIOWrapper(_io.BytesIO(b""), encoding="ascii")
377 def bad_flush():
378 raise IOError()
379 txt.flush = bad_flush
380 raises(IOError, txt.close) # exception not swallowed
381 assert txt.closed
382
383 def test_close_error_on_close():
384 buffer = _io.BytesIO(b'testdata')
385 def bad_flush():
386 raise OSError('flush')
387 def bad_close():
388 raise OSError('close')
389 buffer.close = bad_close
390 txt = _io.TextIOWrapper(buffer, encoding="ascii")
391 txt.flush = bad_flush
392 err = raises(OSError, txt.close)
393 assert err.value.args == ('close',)
394 assert isinstance(err.value.__context__, OSError)
395 assert err.value.__context__.args == ('flush',)
396 assert not txt.closed
397
398 def test_illegal_decoder():
399
400 raises(LookupError, _io.TextIOWrapper, _io.BytesIO(),
401 encoding='quopri_codec')
402
403 def test_read_nonbytes():
404
405 class NonbytesStream(_io.StringIO):
406 read1 = _io.StringIO.read
407 t = _io.TextIOWrapper(NonbytesStream(u'a'))
408 raises(TypeError, t.read, 1)
409 t = _io.TextIOWrapper(NonbytesStream(u'a'))
410 raises(TypeError, t.readline)
411 t = _io.TextIOWrapper(NonbytesStream(u'a'))
412 raises(TypeError, t.read)
413
414 def test_read_byteslike():
415
416 class MemviewBytesIO(_io.BytesIO):
417 '''A BytesIO object whose read method returns memoryviews
418 rather than bytes'''
419
420 def read1(self, len_):
421 return _to_memoryview(super().read1(len_))
422
423 def read(self, len_):
424 return _to_memoryview(super().read(len_))
425
426 def _to_memoryview(buf):
427 '''Convert bytes-object *buf* to a non-trivial memoryview'''
428
429 arr = array.array('i')
430 idx = len(buf) - len(buf) % arr.itemsize
431 arr.frombytes(buf[:idx])
432 return memoryview(arr)
433
434 r = MemviewBytesIO(b'Just some random string\n')
435 t = _io.TextIOWrapper(r, 'utf-8')
436
437 # TextIOwrapper will not read the full string, because
438 # we truncate it to a multiple of the native int size
439 # so that we can construct a more complex memoryview.
440 bytes_val = _to_memoryview(r.getvalue()).tobytes()
441
442 assert t.read(200) == bytes_val.decode('utf-8')
443
444 def test_device_encoding():
445 encoding = os.device_encoding(sys.stderr.fileno())
446 if not encoding:
447 skip("Requires a result from "
448 "os.device_encoding(sys.stderr.fileno())")
449
450 f = _io.TextIOWrapper(sys.stderr.buffer)
451 assert f.encoding == encoding
452
453 def test_device_encoding_ovf():
454
455 b = _io.BytesIO()
456 b.fileno = lambda: sys.maxsize + 1
457 if sys.implementation.name == 'pypy':
458 raises(OverflowError, _io.TextIOWrapper, b)
459 else:
460 u = _io.TextIOWrapper(b)
461
462 def test_uninitialized():
463
464 t = _io.TextIOWrapper.__new__(_io.TextIOWrapper)
465 del t
466 t = _io.TextIOWrapper.__new__(_io.TextIOWrapper)
467 raises(Exception, repr, t)
468 raises(ValueError, t.read, 0)
469 t.__init__(_io.BytesIO())
470 assert t.read(0) == u''
471
472 def test_issue25862():
473 # CPython issue #25862
474 # Assertion failures occurred in tell() after read() and write().
475 from _io import TextIOWrapper, BytesIO
476 t = TextIOWrapper(BytesIO(b'test'), encoding='ascii')
477 t.read(1)
478 t.read()
479 t.tell()
480 t = TextIOWrapper(BytesIO(b'test'), encoding='ascii')
481 t.read(1)
482 t.write('x')
483 t.tell()
484
485 def test_newline_decoder():
486
487 def check_newline_decoding_utf8(decoder):
488 # UTF-8 specific tests for a newline decoder
489 def _check_decode(b, s, **kwargs):
490 # We exercise getstate() / setstate() as well as decode()
491 state = decoder.getstate()
492 assert decoder.decode(b, **kwargs) == s
493 decoder.setstate(state)
494 assert decoder.decode(b, **kwargs) == s
495
496 _check_decode(b'\xe8\xa2\x88', "\u8888")
497
498 _check_decode(b'\xe8', "")
499 _check_decode(b'\xa2', "")
500 _check_decode(b'\x88', "\u8888")
501
502 _check_decode(b'\xe8', "")
503 _check_decode(b'\xa2', "")
504 _check_decode(b'\x88', "\u8888")
505
506 _check_decode(b'\xe8', "")
507 raises(UnicodeDecodeError, decoder.decode, b'', final=True)
508
509 decoder.reset()
510 _check_decode(b'\n', "\n")
511 _check_decode(b'\r', "")
512 _check_decode(b'', "\n", final=True)
513 _check_decode(b'\r', "\n", final=True)
514
515 _check_decode(b'\r', "")
516 _check_decode(b'a', "\na")
517
518 _check_decode(b'\r\r\n', "\n\n")
519 _check_decode(b'\r', "")
520 _check_decode(b'\r', "\n")
521 _check_decode(b'\na', "\na")
522
523 _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n")
524 _check_decode(b'\xe8\xa2\x88', "\u8888")
525 _check_decode(b'\n', "\n")
526 _check_decode(b'\xe8\xa2\x88\r', "\u8888")
527 _check_decode(b'\n', "\n")
528
529 def check_newline_decoding(decoder, encoding):
530 result = []
531 if encoding is not None:
532 encoder = codecs.getincrementalencoder(encoding)()
533 def _decode_bytewise(s):
534 # Decode one byte at a time
535 for b in encoder.encode(s):
536 result.append(decoder.decode(bytes([b])))
537 else:
538 encoder = None
539 def _decode_bytewise(s):
540 # Decode one char at a time
541 for c in s:
542 result.append(decoder.decode(c))
543 assert decoder.newlines == None
544 _decode_bytewise("abc\n\r")
545 assert decoder.newlines == '\n'
546 _decode_bytewise("\nabc")
547 assert decoder.newlines == ('\n', '\r\n')
548 _decode_bytewise("abc\r")
549 assert decoder.newlines == ('\n', '\r\n')
550 _decode_bytewise("abc")
551 assert decoder.newlines == ('\r', '\n', '\r\n')
552 _decode_bytewise("abc\r")
553 assert "".join(result) == "abc\n\nabcabc\nabcabc"
554 decoder.reset()
555 input = "abc"
556 if encoder is not None:
557 encoder.reset()
558 input = encoder.encode(input)
559 assert decoder.decode(input) == "abc"
560 assert decoder.newlines is None
561
562 encodings = (
563 # None meaning the IncrementalNewlineDecoder takes unicode input
564 # rather than bytes input
565 None, 'utf-8', 'latin-1',
566 'utf-16', 'utf-16-le', 'utf-16-be',
567 'utf-32', 'utf-32-le', 'utf-32-be',
568 )
569 for enc in encodings:
570 decoder = enc and codecs.getincrementaldecoder(enc)()
571 decoder = _io.IncrementalNewlineDecoder(decoder, translate=True)
572 check_newline_decoding(decoder, enc)
573 decoder = codecs.getincrementaldecoder("utf-8")()
574 decoder = _io.IncrementalNewlineDecoder(decoder, translate=True)
575 check_newline_decoding_utf8(decoder)
576
577 def test_newline_bytes():
578
579 # Issue 5433: Excessive optimization in IncrementalNewlineDecoder
580 def _check(dec):
581 assert dec.newlines is None
582 assert dec.decode("\u0D00") == "\u0D00"
583 assert dec.newlines is None
584 assert dec.decode("\u0A00") == "\u0A00"
585 assert dec.newlines is None
586 dec = _io.IncrementalNewlineDecoder(None, translate=False)
587 _check(dec)
588 dec = _io.IncrementalNewlineDecoder(None, translate=True)
589 _check(dec)
590
591 def test_newlines2():
592 inner_decoder = codecs.getincrementaldecoder("utf-8")()
593 decoder = _io.IncrementalNewlineDecoder(inner_decoder, translate=True)
594 msg = b"abc\r\n\n\r\r\n\n"
595 decoded = ''
596 for ch in msg:
597 decoded += decoder.decode(bytes([ch]))
598 assert set(decoder.newlines) == {"\r", "\n", "\r\n"}
599
600 def test_reconfigure_line_buffering():
601 r = _io.BytesIO()
602 b = _io.BufferedWriter(r, 1000)
603 t = _io.TextIOWrapper(b, newline="\n", line_buffering=False)
604 t.write("AB\nC")
605 assert r.getvalue() == b""
606
607 t.reconfigure(line_buffering=True) # implicit flush
608 assert r.getvalue() == b"AB\nC"
609 t.write("DEF\nG")
610 assert r.getvalue() == b"AB\nCDEF\nG"
611 t.write("H")
612 assert r.getvalue() == b"AB\nCDEF\nG"
613 t.reconfigure(line_buffering=False) # implicit flush
614 assert r.getvalue() == b"AB\nCDEF\nGH"
615 t.write("IJ")
616 assert r.getvalue() == b"AB\nCDEF\nGH"
617
618 # Keeping default value
619 t.reconfigure()
620 t.reconfigure(line_buffering=None)
621 assert t.line_buffering == False
622 assert type(t.line_buffering) is bool
623 t.reconfigure(line_buffering=True)
624 t.reconfigure()
625 t.reconfigure(line_buffering=None)
626 assert t.line_buffering == True
627
628 def test_reconfigure_write_through():
629 raw = get_MockRawIO()([])
630 t = _io.TextIOWrapper(raw, encoding='ascii', newline='\n')
631 t.write('1')
632 t.reconfigure(write_through=True) # implied flush
633 assert t.write_through == True
634 assert b''.join(raw._write_stack) == b'1'
635 t.write('23')
636 assert b''.join(raw._write_stack) == b'123'
637 t.reconfigure(write_through=False)
638 assert t.write_through == False
639 t.write('45')
640 t.flush()
641 assert b''.join(raw._write_stack) == b'12345'
642 # Keeping default value
643 t.reconfigure()
644 t.reconfigure(write_through=None)
645 assert t.write_through == False
646 t.reconfigure(write_through=True)
647 t.reconfigure()
648 t.reconfigure(write_through=None)
649 assert t.write_through == True
650
651 def test_reconfigure_newline():
652 import os
653 raw = _io.BytesIO(b'CR\rEOF')
654 txt = _io.TextIOWrapper(raw, 'ascii', newline='\n')
655 txt.reconfigure(newline=None)
656 assert txt.readline() == 'CR\n'
657 raw = _io.BytesIO(b'CR\rEOF')
658 txt = _io.TextIOWrapper(raw, 'ascii', newline='\n')
659 txt.reconfigure(newline='')
660 assert txt.readline() == 'CR\r'
661 raw = _io.BytesIO(b'CR\rLF\nEOF')
662 txt = _io.TextIOWrapper(raw, 'ascii', newline='\r')
663 txt.reconfigure(newline='\n')
664 assert txt.readline() == 'CR\rLF\n'
665 raw = _io.BytesIO(b'LF\nCR\rEOF')
666 txt = _io.TextIOWrapper(raw, 'ascii', newline='\n')
667 txt.reconfigure(newline='\r')
668 assert txt.readline() == 'LF\nCR\r'
669 raw = _io.BytesIO(b'CR\rCRLF\r\nEOF')
670 txt = _io.TextIOWrapper(raw, 'ascii', newline='\r')
671 txt.reconfigure(newline='\r\n')
672 assert txt.readline() == 'CR\rCRLF\r\n'
673
674 txt = _io.TextIOWrapper(_io.BytesIO(), 'ascii', newline='\r')
675 txt.reconfigure(newline=None)
676 txt.write('linesep\n')
677 txt.reconfigure(newline='')
678 txt.write('LF\n')
679 txt.reconfigure(newline='\n')
680 txt.write('LF\n')
681 txt.reconfigure(newline='\r')
682 txt.write('CR\n')
683 txt.reconfigure(newline='\r\n')
684 txt.write('CRLF\n')
685 expected = 'linesep' + os.linesep + 'LF\nLF\nCR\rCRLF\r\n'
686 assert txt.detach().getvalue().decode('ascii') == expected
687
688 def test_reconfigure_encoding_read():
689 # latin1 -> utf8
690 # (latin1 can decode utf-8 encoded string)
691 data = 'abc\xe9\n'.encode('latin1') + 'd\xe9f\n'.encode('utf8')
692 raw = _io.BytesIO(data)
693 txt = _io.TextIOWrapper(raw, encoding='latin1', newline='\n')
694 assert txt.readline() == 'abc\xe9\n'
695 with raises(_io.UnsupportedOperation):
696 txt.reconfigure(encoding='utf-8')
697 with raises(_io.UnsupportedOperation):
698 txt.reconfigure(newline=None)
699
700 def test_reconfigure_write_fromascii():
701 # ascii has a specific encodefunc in the C implementation,
702 # but utf-8-sig has not. Make sure that we get rid of the
703 # cached encodefunc when we switch encoders.
704 raw = _io.BytesIO()
705 txt = _io.TextIOWrapper(raw, encoding='ascii', newline='\n')
706 txt.write('foo\n')
707 txt.reconfigure(encoding='utf-8-sig')
708 txt.write('\xe9\n')
709 txt.flush()
710 res = raw.getvalue()
711 assert raw.getvalue() == b'foo\n\xc3\xa9\n'
712
713 def test_reconfigure_write():
714 # latin -> utf8
715 raw = _io.BytesIO()
716 txt = _io.TextIOWrapper(raw, encoding='latin1', newline='\n')
717 txt.write('abc\xe9\n')
718 txt.reconfigure(encoding='utf-8')
719 assert raw.getvalue() == b'abc\xe9\n'
720 txt.write('d\xe9f\n')
721 txt.flush()
722 assert raw.getvalue() == b'abc\xe9\nd\xc3\xa9f\n'
723
724 # ascii -> utf-8-sig: ensure that no BOM is written in the middle of
725 # the file
726 raw = _io.BytesIO()
727 txt = _io.TextIOWrapper(raw, encoding='ascii', newline='\n')
728 txt.write('abc\n')
729 txt.reconfigure(encoding='utf-8-sig')
730 txt.write('d\xe9f\n')
731 txt.flush()
732 assert raw.getvalue() == b'abc\nd\xc3\xa9f\n'
733
734 def test_reconfigure_write_non_seekable():
735 raw = _io.BytesIO()
736 raw.seekable = lambda: False
737 raw.seek = None
738 txt = _io.TextIOWrapper(raw, encoding='ascii', newline='\n')
739 txt.write('abc\n')
740 txt.reconfigure(encoding='utf-8-sig')
741 txt.write('d\xe9f\n')
742 txt.flush()
743
744 # If the raw stream is not seekable, there'll be a BOM
745 assert raw.getvalue() == b'abc\n\xef\xbb\xbfd\xc3\xa9f\n'
746
747 def test_reconfigure_defaults():
748 txt = _io.TextIOWrapper(_io.BytesIO(), 'ascii', 'replace', '\n')
749 txt.reconfigure(encoding=None)
750 assert txt.encoding == 'ascii'
751 assert txt.errors == 'replace'
752 txt.write('LF\n')
753
754 txt.reconfigure(newline='\r\n')
755 assert txt.encoding == 'ascii'
756 assert txt.errors == 'replace'
757
758 txt.reconfigure(errors='ignore')
759 assert txt.encoding == 'ascii'
760 assert txt.errors == 'ignore'
761 txt.write('CRLF\n')
762
763 txt.reconfigure(encoding='utf-8', newline=None)
764 assert txt.errors == 'strict'
765 txt.seek(0)
766 assert txt.read() == 'LF\nCRLF\n'
767
768 assert txt.detach().getvalue() == b'LF\nCRLF\r\n'
769
770
771 def test_text_encoding():
772 assert _io.text_encoding("abc") == "abc"
773 if sys.flags.utf8_mode:
774 # default on PyPy, will be default on CPython 3.15+
775 assert _io.text_encoding(None) == "utf-8"
776 else:
777 assert _io.text_encoding(None) == "locale"
778
779 def test_pseudo_encoding_locale():
780 r = _io.BytesIO(b"\xc3\xa9\n\n")
781 t1 = _io.TextIOWrapper(r, encoding="locale")
782 t2 = _io.TextIOWrapper(r)
783 assert t1.encoding.lower() == t2.encoding.lower()
784
785 def test_bug_write_during_flush():
786 # from https://github.com/python/cpython/issues/119506
787 import _io
788
789 class MyIO(_io.BytesIO):
790 def __init__(self):
791 _io.BytesIO.__init__(self)
792 self.writes = []
793 self.done_extra_write = False
794
795 def write(self, b):
796 self.writes.append(b)
797 if not self.done_extra_write:
798 tw.write("c")
799 self.done_extra_write = True
800 return len(b)
801 CHUNK_SIZE = 8192
802
803 buf = MyIO()
804 tw = _io.TextIOWrapper(buf)
805 tw.write("a" * (CHUNK_SIZE - 1))
806 tw.write("b" * 2)
807 tw.flush()
808 assert b''.join(tw.buffer.writes) == b"a" * (CHUNK_SIZE - 1) + b"b" * 2 + b"c"
809
810 buf = MyIO()
811 tw = _io.TextIOWrapper(buf)
812 tw.write("abc")
813 tw.write("def")
814 tw.write("b" * CHUNK_SIZE)
815 tw.flush()
816 assert b''.join(tw.buffer.writes) == b"abcdefc" + b"b" * CHUNK_SIZE