Debian Codegraph @

test/test_io.py

raw symbols SCIP
1 #! /usr/bin/env python3
2
3 # $Id: test_io.py 9994 2024-12-04 13:32:39Z milde $
4 # Author: Lea Wiemann <[email protected]>
5 # Copyright: This module has been placed in the public domain.
6
7 """
8 Test module for `docutils.io`.
9 """
10
11 import codecs
12 import locale
13 import sys
14 import unittest
15 import warnings
16 from io import StringIO, BytesIO
17 from pathlib import Path
18
19 if __name__ == '__main__':
20 # prepend the "docutils root" to the Python library path
21 # so we import the local `docutils` package.
22 sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
23
24 from docutils import io as du_io
25
26 # For when we intentionally do things that trigger EncodingWarning
27 # (When using ``-X warn_default_encoding`` or PYTHONWARNDEFAULTENCODING=1)
28 # See: https://docs.python.org/3/library/io.html#io-encoding-warning
29 if sys.version_info[:2] > (3, 9):
30 SUPPRESS_ENCODING_WARNING = sys.flags.warn_default_encoding
31 else:
32 SUPPRESS_ENCODING_WARNING = False
33 EncodingWarning = UnicodeWarning # NoQA: A001 (builtin in Py > 0.9)
34
35 # DATA_ROOT is ./test/data/ from the docutils root
36 DATA_ROOT = Path(__file__).parent / 'data'
37
38 # normalize the preferred encoding's name:
39 with warnings.catch_warnings():
40 if SUPPRESS_ENCODING_WARNING:
41 warnings.filterwarnings('ignore', category=EncodingWarning)
42 preferredencoding = codecs.lookup(
43 locale.getpreferredencoding(do_setlocale=False)).name
44
45
46 # Stub: Buffer with 'strict' auto-conversion of input to byte string:
47 class BBuf(BytesIO):
48 def write(self, data):
49 if isinstance(data, str):
50 data.encode('ascii', 'strict')
51 super().write(data)
52
53
54 # Stub: Buffer expecting unicode string:
55 class UBuf(StringIO):
56 def write(self, data):
57 # emulate Python 3 handling of stdout, stderr
58 if isinstance(data, bytes):
59 raise TypeError('must be unicode, not bytes')
60 super().write(data)
61
62
63 class mock_stdout(UBuf):
64 encoding = 'utf-8'
65
66 def __init__(self):
67 self.buffer = BBuf()
68 super().__init__()
69
70
71 class HelperTests(unittest.TestCase):
72
73 def test_check_encoding_true(self):
74 """Return `True` if lookup returns the same codec"""
75 self.assertEqual(True, du_io.check_encoding(mock_stdout, 'utf-8'))
76 self.assertEqual(True, du_io.check_encoding(mock_stdout, 'utf_8'))
77 self.assertEqual(True, du_io.check_encoding(mock_stdout, 'utf8'))
78 self.assertEqual(True, du_io.check_encoding(mock_stdout, 'UTF-8'))
79
80 def test_check_encoding_false(self):
81 """Return `False` if lookup returns different codecs"""
82 self.assertEqual(False, du_io.check_encoding(mock_stdout, 'ascii'))
83 self.assertEqual(False, du_io.check_encoding(mock_stdout, 'latin-1'))
84
85 def test_check_encoding_none(self):
86 """Cases where the comparison fails."""
87 # stream.encoding is None:
88 self.assertEqual(None,
89 du_io.check_encoding(du_io.FileInput(encoding=None),
90 'ascii'))
91 # stream.encoding does not exist:
92 self.assertEqual(None, du_io.check_encoding(BBuf, 'ascii'))
93 # encoding is None or empty string:
94 self.assertEqual(None, du_io.check_encoding(mock_stdout, None))
95 self.assertEqual(None, du_io.check_encoding(mock_stdout, ''))
96 # encoding is invalid
97 self.assertEqual(None, du_io.check_encoding(mock_stdout, 'UTF-9'))
98
99 def test_error_string(self):
100 us = '\xfc' # bytes(us) fails
101 bs = b'\xc3\xbc' # str(bs) returns repr(bs)
102
103 self.assertEqual('Exception: spam',
104 du_io.error_string(Exception('spam')))
105 self.assertEqual('IndexError: ' + str(bs),
106 du_io.error_string(IndexError(bs)))
107 self.assertEqual('ImportError: %s' % us,
108 du_io.error_string(ImportError(us)))
109
110
111 class InputTests(unittest.TestCase):
112
113 def test_bom_handling(self):
114 # Provisional:
115 # default input encoding will change to UTF-8 in Docutils 0.22
116 source = '\ufeffdata\n\ufeff blah\n'
117 expected = 'data\n\ufeff blah\n' # only leading ZWNBSP removed
118 input_ = du_io.StringInput(source=source.encode('utf-16-be'),
119 encoding=None)
120 with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
121 self.assertEqual(expected, input_.read())
122 input_ = du_io.StringInput(source=source.encode('utf-16-le'),
123 encoding=None)
124 with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
125 self.assertEqual(expected, input_.read())
126 input_ = du_io.StringInput(source=source.encode('utf-8'),
127 encoding=None)
128 with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
129 self.assertEqual(expected, input_.read())
130 # With `str` input all ZWNBSPs are still there.
131 input_ = du_io.StringInput(source=source)
132 self.assertEqual(source, input_.read())
133
134 def test_encoding_declaration(self):
135 input_ = du_io.StringInput(source=b"""\
136 .. -*- coding: ascii -*-
137 data
138 blah
139 """, encoding=None)
140 with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
141 data = input_.read() # noqa: F841
142 self.assertEqual('ascii', input_.successful_encoding)
143 input_ = du_io.StringInput(source=b"""\
144 #! python
145 # -*- coding: ascii -*-
146 print("hello world")
147 """, encoding=None)
148 with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
149 data = input_.read() # noqa: F841
150 self.assertEqual('ascii', input_.successful_encoding)
151 input_ = du_io.StringInput(source=b"""\
152 #! python
153 # extraneous comment; prevents coding slug from being read
154 # -*- coding: ascii -*-
155 print("hello world")
156 """)
157 self.assertNotEqual(input_.successful_encoding, 'ascii')
158
159 def test_decode_unicode(self):
160 # With the special value "unicode" or "Unicode":
161 uniinput = du_io.Input(encoding='unicode')
162 # keep unicode instances as-is
163 self.assertEqual('ja', uniinput.decode('ja'))
164 # raise AssertionError if data is not a `str` instance
165 with self.assertRaises(AssertionError):
166 uniinput.decode(b'ja')
167
168
169 class OutputTests(unittest.TestCase):
170
171 bdata = b'\xfc'
172 udata = '\xfc'
173
174 def setUp(self):
175 self.bdrain = BBuf()
176 """Buffer accepting binary strings (bytes)"""
177 self.udrain = UBuf()
178 """Buffer accepting unicode strings"""
179 self.mock_stdout = mock_stdout()
180 """Stub of sys.stdout under Python 3"""
181
182 def test_write_unicode(self):
183 fo = du_io.FileOutput(destination=self.udrain, encoding='unicode',
184 autoclose=False)
185 fo.write(self.udata)
186 self.assertEqual(self.udata, self.udrain.getvalue())
187
188 def test_write_utf8(self):
189 fo = du_io.FileOutput(destination=self.udrain, encoding='utf-8',
190 autoclose=False)
191 fo.write(self.udata)
192 self.assertEqual(self.udata, self.udrain.getvalue())
193
194 def test_FileOutput_hande_io_errors_deprection_warning(self):
195 with self.assertWarnsRegex(DeprecationWarning,
196 '"handle_io_errors" is ignored'):
197 du_io.FileOutput(handle_io_errors=True)
198
199 # With destination in binary mode, data must be binary string
200 # and is written as-is:
201 def test_write_bytes(self):
202 fo = du_io.FileOutput(destination=self.bdrain, encoding='utf-8',
203 mode='wb', autoclose=False)
204 fo.write(self.bdata)
205 self.assertEqual(self.bdata, self.bdrain.getvalue())
206
207 def test_write_bytes_to_stdout(self):
208 # try writing data to `destination.buffer`, if data is
209 # instance of `bytes` and writing to `destination` fails:
210 fo = du_io.FileOutput(destination=self.mock_stdout)
211 fo.write(self.bdata)
212 self.assertEqual(self.bdata,
213 self.mock_stdout.buffer.getvalue())
214
215 def test_encoding_clash_resolved(self):
216 fo = du_io.FileOutput(destination=self.mock_stdout,
217 encoding='latin1', autoclose=False)
218 fo.write(self.udata)
219 self.assertEqual(self.udata.encode('latin1'),
220 self.mock_stdout.buffer.getvalue())
221
222 def test_encoding_clash_nonresolvable(self):
223 del self.mock_stdout.buffer
224 fo = du_io.FileOutput(destination=self.mock_stdout,
225 encoding='latin1', autoclose=False)
226 self.assertRaises(ValueError, fo.write, self.udata)
227
228
229 class ErrorOutputTests(unittest.TestCase):
230 def test_defaults(self):
231 e = du_io.ErrorOutput()
232 self.assertEqual(sys.stderr, e.destination)
233
234 def test_bbuf(self):
235 buf = BBuf() # buffer storing byte string
236 e = du_io.ErrorOutput(buf, encoding='ascii')
237 # write byte-string as-is
238 e.write(b'b\xfc')
239 self.assertEqual(b'b\xfc', buf.getvalue())
240 # encode unicode data with backslashescape fallback replacement:
241 e.write(' u\xfc')
242 self.assertEqual(b'b\xfc u\\xfc', buf.getvalue())
243 # handle Exceptions with Unicode string args
244 # unicode(Exception('e\xfc')) # fails in Python < 2.6
245 e.write(AttributeError(' e\xfc'))
246 self.assertEqual(b'b\xfc u\\xfc e\\xfc', buf.getvalue())
247 # encode with `encoding` attribute
248 e.encoding = 'utf-8'
249 e.write(' u\xfc')
250 self.assertEqual(b'b\xfc u\\xfc e\\xfc u\xc3\xbc', buf.getvalue())
251
252 def test_ubuf(self):
253 buf = UBuf() # buffer only accepting unicode string
254 # decode of binary strings
255 e = du_io.ErrorOutput(buf, encoding='ascii')
256 e.write(b'b\xfc')
257 # use REPLACEMENT CHARACTER
258 self.assertEqual(buf.getvalue(), 'b\ufffd')
259 # write Unicode string and Exceptions with Unicode args
260 e.write(' u\xfc')
261 self.assertEqual(buf.getvalue(), 'b\ufffd u\xfc')
262 e.write(AttributeError(' e\xfc'))
263 self.assertEqual(buf.getvalue(), 'b\ufffd u\xfc e\xfc')
264 # decode with `encoding` attribute
265 e.encoding = 'latin1'
266 e.write(b' b\xfc')
267 self.assertEqual(buf.getvalue(), 'b\ufffd u\xfc e\xfc b\xfc')
268
269
270 class FileInputTests(unittest.TestCase):
271
272 # test input encoding auto-detection:
273 #
274 # Up to Docutils 0.18, auto-detection was not used under Python 3
275 # unless reading a file with Python's default encoding failed
276
277 def test_bom_utf_8(self):
278 """Drop optional BOM from utf-8 encoded files.
279 """
280 with warnings.catch_warnings():
281 if SUPPRESS_ENCODING_WARNING:
282 warnings.filterwarnings('ignore', category=EncodingWarning)
283 source = du_io.FileInput(source_path=DATA_ROOT/'utf-8-sig.rst',
284 encoding=None)
285 with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
286 self.assertTrue(source.read().startswith('Grüße'))
287
288 def test_bom_utf_16(self):
289 """Drop BOM from utf-16 encoded files, use correct encoding.
290 """
291 # Assert correct decoding, BOM is gone.
292 with warnings.catch_warnings():
293 if SUPPRESS_ENCODING_WARNING:
294 warnings.filterwarnings('ignore', category=EncodingWarning)
295 source = du_io.FileInput(source_path=DATA_ROOT/'utf-16-le-sig.rst',
296 encoding=None)
297 with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
298 self.assertTrue(source.read().startswith('Grüße'))
299
300 def test_coding_slug(self):
301 """Use self-declared encoding.
302 """
303 with warnings.catch_warnings():
304 if SUPPRESS_ENCODING_WARNING:
305 warnings.filterwarnings('ignore', category=EncodingWarning)
306 source = du_io.FileInput(source_path=DATA_ROOT/'latin2.rst',
307 encoding=None)
308 with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
309 self.assertTrue(source.read().endswith('škoda\n'))
310
311 def test_fallback_utf8(self):
312 """Try 'utf-8', if encoding is not specified in the source."""
313 with warnings.catch_warnings():
314 if SUPPRESS_ENCODING_WARNING:
315 warnings.filterwarnings('ignore', category=EncodingWarning)
316 source = du_io.FileInput(source_path=DATA_ROOT/'utf8.rst',
317 encoding=None)
318 self.assertEqual('Grüße\n', source.read())
319
320 def test_readlines(self):
321 source = du_io.FileInput(source_path=DATA_ROOT/'include.rst')
322 data = source.readlines()
323 self.assertEqual(['Some include text.\n'], data)
324
325
326 if __name__ == '__main__':
327 unittest.main()