Debian Codegraph @

test/test_utils/test__init__.py

raw symbols SCIP
1 #! /usr/bin/env python3
2
3 # $Id: test__init__.py 10039 2025-03-08 18:53:20Z aa-turner $
4 # Author: David Goodger <[email protected]>
5 # Copyright: This module has been placed in the public domain.
6
7 """
8 Test module for utils/__init__.py.
9 """
10
11 from io import StringIO
12 import os
13 from pathlib import Path
14 import sys
15 import unittest
16
17 if __name__ == '__main__':
18 # prepend the "docutils root" to the Python library path
19 # so we import the local `docutils` package.
20 sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
21
22 from docutils import nodes, utils
23
24 TEST_ROOT = Path(__file__).parents[1] # ./test/ from the docutils root
25
26
27 class ReporterTests(unittest.TestCase):
28
29 stream = StringIO()
30 reporter = utils.Reporter('test data', 2, 4, stream, 1)
31
32 def setUp(self):
33 self.stream.seek(0)
34 self.stream.truncate()
35
36 def test_level0(self):
37 sw = self.reporter.system_message(0, 'debug output')
38 self.assertEqual(sw.pformat(), """\
39 <system_message level="0" source="test data" type="DEBUG">
40 <paragraph>
41 debug output
42 """)
43 self.assertEqual(self.stream.getvalue(),
44 'test data:: (DEBUG/0) debug output\n')
45
46 def test_level1(self):
47 sw = self.reporter.system_message(1, 'a little reminder')
48 self.assertEqual(sw.pformat(), """\
49 <system_message level="1" source="test data" type="INFO">
50 <paragraph>
51 a little reminder
52 """)
53 self.assertEqual(self.stream.getvalue(), '')
54
55 def test_level2(self):
56 sw = self.reporter.system_message(2, 'a warning')
57 self.assertEqual(sw.pformat(), """\
58 <system_message level="2" source="test data" type="WARNING">
59 <paragraph>
60 a warning
61 """)
62 self.assertEqual(self.stream.getvalue(),
63 'test data:: (WARNING/2) a warning\n')
64
65 def test_level3(self):
66 sw = self.reporter.system_message(3, 'an error')
67 self.assertEqual(sw.pformat(), """\
68 <system_message level="3" source="test data" type="ERROR">
69 <paragraph>
70 an error
71 """)
72 self.assertEqual(self.stream.getvalue(),
73 'test data:: (ERROR/3) an error\n')
74
75 def test_level4(self):
76 with self.assertRaises(utils.SystemMessage):
77 self.reporter.system_message(
78 4, 'a severe error, raises an exception')
79 self.assertEqual(self.stream.getvalue(), 'test data:: (SEVERE/4) '
80 'a severe error, raises an exception\n')
81
82 def test_unicode_message(self):
83 sw = self.reporter.system_message(0, 'mesidʒ')
84 self.assertEqual(sw.pformat(), """\
85 <system_message level="0" source="test data" type="DEBUG">
86 <paragraph>
87 mesidʒ
88 """)
89
90 def test_unicode_message_from_exception(self):
91 """Workaround for Python < 2.6 bug:
92 unicode(<exception instance>) uses __str__
93 and hence fails with unicode message"""
94 try:
95 raise Exception('mesidʒ')
96 except Exception as err:
97 sw = self.reporter.system_message(0, err)
98 self.assertEqual(sw.pformat(), """\
99 <system_message level="0" source="test data" type="DEBUG">
100 <paragraph>
101 mesidʒ
102 """)
103
104
105 class QuietReporterTests(unittest.TestCase):
106
107 stream = StringIO()
108 reporter = utils.Reporter('test data', 5, 5, stream, 0)
109
110 def setUp(self):
111 self.stream.seek(0)
112 self.stream.truncate()
113
114 def test_debug(self):
115 sw = self.reporter.debug('a debug message')
116 # None because debug is disabled.
117 self.assertEqual(sw, None)
118 self.assertEqual(self.stream.getvalue(), '')
119
120 def test_info(self):
121 sw = self.reporter.info('an informational message')
122 self.assertEqual(sw.pformat(), """\
123 <system_message level="1" source="test data" type="INFO">
124 <paragraph>
125 an informational message
126 """)
127 self.assertEqual(self.stream.getvalue(), '')
128
129 def test_warning(self):
130 sw = self.reporter.warning('a warning')
131 self.assertEqual(sw.pformat(), """\
132 <system_message level="2" source="test data" type="WARNING">
133 <paragraph>
134 a warning
135 """)
136 self.assertEqual(self.stream.getvalue(), '')
137
138 def test_error(self):
139 sw = self.reporter.error('an error')
140 self.assertEqual(sw.pformat(), """\
141 <system_message level="3" source="test data" type="ERROR">
142 <paragraph>
143 an error
144 """)
145 self.assertEqual(self.stream.getvalue(), '')
146
147 def test_severe(self):
148 sw = self.reporter.severe('a severe error')
149 self.assertEqual(sw.pformat(), """\
150 <system_message level="4" source="test data" type="SEVERE">
151 <paragraph>
152 a severe error
153 """)
154 self.assertEqual(self.stream.getvalue(), '')
155
156
157 class NameValueTests(unittest.TestCase):
158
159 def test_extract_name_value(self):
160 with self.assertRaises(utils.NameValueError):
161 utils.extract_name_value('hello')
162 with self.assertRaises(utils.NameValueError):
163 utils.extract_name_value('=hello')
164 with self.assertRaises(utils.NameValueError):
165 utils.extract_name_value('hello=')
166 with self.assertRaises(utils.NameValueError):
167 utils.extract_name_value('hello="')
168 with self.assertRaises(utils.NameValueError):
169 utils.extract_name_value('hello="something')
170 with self.assertRaises(utils.NameValueError):
171 utils.extract_name_value('hello="something"else')
172 output = utils.extract_name_value(
173 """att1=val1 att2=val2 att3="value number '3'" att4=val4""")
174 self.assertEqual(output, [('att1', 'val1'), ('att2', 'val2'),
175 ('att3', "value number '3'"),
176 ('att4', 'val4')])
177
178
179 class ExtensionOptionTests(unittest.TestCase):
180
181 optionspec = {'a': int, 'bbb': float, 'cdef': (lambda x: x),
182 'empty': (lambda x: x)}
183
184 def test_assemble_option_dict(self):
185 input_ = utils.extract_name_value('a=1 bbb=2.0 cdef=hol%s' % chr(224))
186 self.assertEqual(
187 utils.assemble_option_dict(input_, self.optionspec),
188 {'a': 1, 'bbb': 2.0, 'cdef': ('hol%s' % chr(224))})
189 input_ = utils.extract_name_value('a=1 b=2.0 c=hol%s' % chr(224))
190 with self.assertRaises(KeyError):
191 utils.assemble_option_dict(input_, self.optionspec)
192 input_ = utils.extract_name_value('a=1 bbb=two cdef=hol%s' % chr(224))
193 with self.assertRaises(ValueError):
194 utils.assemble_option_dict(input_, self.optionspec)
195
196 def test_extract_extension_options(self):
197 field_list = nodes.field_list()
198 field_list += nodes.field(
199 '', nodes.field_name('', 'a'),
200 nodes.field_body('', nodes.paragraph('', '1')))
201 field_list += nodes.field(
202 '', nodes.field_name('', 'bbb'),
203 nodes.field_body('', nodes.paragraph('', '2.0')))
204 field_list += nodes.field(
205 '', nodes.field_name('', 'cdef'),
206 nodes.field_body('', nodes.paragraph('', 'hol\u00e0')))
207 field_list += nodes.field(
208 '', nodes.field_name('', 'empty'), nodes.field_body())
209 self.assertEqual(
210 utils.extract_extension_options(field_list, self.optionspec),
211 {'a': 1, 'bbb': 2.0,
212 'cdef': 'hol\u00e0',
213 'empty': None})
214 with self.assertRaises(KeyError):
215 utils.extract_extension_options(field_list, {})
216 field_list += nodes.field(
217 '', nodes.field_name('', 'cdef'),
218 nodes.field_body('', nodes.paragraph('', 'one'),
219 nodes.paragraph('', 'two')))
220 with self.assertRaises(utils.BadOptionDataError):
221 utils.extract_extension_options(field_list, self.optionspec)
222 field_list[-1] = nodes.field(
223 '', nodes.field_name('', 'cdef bad'),
224 nodes.field_body('', nodes.paragraph('', 'no arguments')))
225 with self.assertRaises(utils.BadOptionError):
226 utils.extract_extension_options(field_list, self.optionspec)
227 field_list[-1] = nodes.field(
228 '', nodes.field_name('', 'cdef'),
229 nodes.field_body('', nodes.paragraph('', 'duplicate')))
230 with self.assertRaises(utils.DuplicateOptionError):
231 utils.extract_extension_options(field_list, self.optionspec)
232 field_list[-2] = nodes.field(
233 '', nodes.field_name('', 'unkown'),
234 nodes.field_body('', nodes.paragraph('', 'unknown')))
235 with self.assertRaises(KeyError):
236 utils.extract_extension_options(field_list, self.optionspec)
237
238
239 class HelperFunctionTests(unittest.TestCase):
240 def test_normalize_language_tag(self):
241 self.assertEqual(utils.normalize_language_tag('de'), ['de'])
242 self.assertEqual(utils.normalize_language_tag('de-AT'),
243 ['de-at', 'de'])
244 self.assertEqual(utils.normalize_language_tag('de-AT-1901'),
245 ['de-at-1901', 'de-at', 'de-1901', 'de'])
246 self.assertEqual(utils.normalize_language_tag('de-AT-1901-Latf'),
247 ['de-at-1901-latf', 'de-at-1901', 'de-at-latf',
248 'de-1901-latf', 'de-at', 'de-1901', 'de-latf', 'de'])
249 self.assertEqual(utils.normalize_language_tag('grc-ibycus-x-altquot'),
250 ['grc-ibycus-x-altquot', 'grc-ibycus',
251 'grc-x-altquot', 'grc'])
252
253 def test_xml_declaration(self):
254 # default is no encoding declaration
255 self.assertEqual(utils.xml_declaration(), '<?xml version="1.0"?>\n')
256 # if an encoding is passed, declare it
257 self.assertEqual(utils.xml_declaration('ISO-8859-2'),
258 '<?xml version="1.0" encoding="ISO-8859-2"?>\n')
259 # ignore pseudo encoding name "unicode" introduced by
260 # `docutils.io.Output.encode()`
261 self.assertEqual(utils.xml_declaration('Unicode'),
262 '<?xml version="1.0"?>\n')
263 # ... non-regarding case
264 self.assertEqual(utils.xml_declaration('UNICODE'),
265 '<?xml version="1.0"?>\n')
266 # allow %s for later interpolation
267 # (used for part 'html_prolog', cf. docs/api/publisher.html)
268 self.assertEqual(utils.xml_declaration('%s'),
269 '<?xml version="1.0" encoding="%s"?>\n')
270
271 def test_column_width(self):
272 self.assertEqual(utils.column_width('de'), 2)
273 self.assertEqual(utils.column_width('dâ'), 2) # pre-composed
274 self.assertEqual(utils.column_width('dâ'), 2) # combining
275
276 def test_decode_path(self):
277 try:
278 bytes_filename = 'späm'.encode(sys.getfilesystemencoding())
279 except UnicodeEncodeError:
280 bytes_filename = b'spam'
281 bytespath = utils.decode_path(bytes_filename)
282 unipath = utils.decode_path('späm')
283 defaultpath = utils.decode_path(None)
284 if bytes_filename != b'spam': # skip if ä cannot be encoded
285 self.assertEqual(bytespath, 'späm')
286 self.assertEqual(unipath, 'späm')
287 self.assertEqual(defaultpath, '')
288 self.assertTrue(isinstance(bytespath, str))
289 self.assertTrue(isinstance(unipath, str))
290 self.assertTrue(isinstance(defaultpath, str))
291 self.assertRaises(ValueError, utils.decode_path, 13)
292
293 def test_relative_path(self):
294 # Build and return a path to `target`, relative to `source`:
295 # Use '/' as path sep in result.
296 self.assertEqual(utils.relative_path('spam', 'spam'), '')
297 source = os.path.join('häm', 'spam', 'fileA')
298 target = os.path.join('häm', 'spam', 'fileB')
299 self.assertEqual(utils.relative_path(source, target), 'fileB')
300 source = os.path.join('häm', 'spam', 'fileA')
301 target = os.path.join('häm', 'fileB')
302 self.assertEqual(utils.relative_path(source, target), '../fileB')
303 source = os.path.join('häm', 'fileA')
304 target = os.path.join('..', 'spam', 'fileB')
305 self.assertEqual(utils.relative_path(source, target),
306 '../../spam/fileB')
307 # if source is None, default to the cwd:
308 target = os.path.join('eggs', 'fileB')
309 self.assertEqual(utils.relative_path(None, target), 'eggs/fileB')
310 # If there is no common prefix, return the absolute path to `target`:
311 if os.sep == '/':
312 source = '/foo/bar/fileA'
313 else:
314 source = r'C:\foo\bar\fileA'
315 target = os.path.join('eggs', 'fileB')
316 self.assertEqual(utils.relative_path(source, target),
317 os.path.abspath('eggs/fileB').replace('\\', '/'))
318 # Correctly process characters outside the ASCII range:
319 self.assertEqual(utils.relative_path('spam', 'spam'), '')
320 source = os.path.join('häm', 'spam', 'fileA')
321 target = os.path.join('häm', 'spam', 'fileB')
322 self.assertEqual(utils.relative_path(source, target), 'fileB')
323 source = os.path.join('häm', 'spam', 'fileA')
324 target = os.path.join('häm', 'fileB')
325 self.assertEqual(utils.relative_path(source, target), '../fileB')
326 # if source is None, default to the cwd:
327 target = os.path.join('eggs', 'fileB')
328 self.assertEqual(utils.relative_path(None, target), 'eggs/fileB')
329
330 def test_find_file_in_dirs(self):
331 # Search for file `path` in the sequence of directories `dirs`.
332 # Return the first expansion that matches an existing file.
333 dirs = (os.path.join(TEST_ROOT, 'nonex'),
334 TEST_ROOT,
335 os.path.join(TEST_ROOT, '..'))
336 result = utils.find_file_in_dirs('alltests.py', dirs)
337 expected = os.path.join(TEST_ROOT, 'alltests.py').replace('\\', '/')
338 self.assertEqual(expected, result)
339 result = utils.find_file_in_dirs('HISTORY.rst', dirs)
340 expected = (TEST_ROOT / '..' / 'HISTORY.rst').as_posix()
341 self.assertEqual(expected, result)
342 # normalize for second check
343 self.assertTrue(os.path.relpath(result, TEST_ROOT).startswith('..'),
344 'HISTORY.rst not found in "..".')
345 # Return `path` if the file exists in the cwd or if there is no match
346 self.assertEqual(utils.find_file_in_dirs('gibts/nicht.rst', dirs),
347 'gibts/nicht.rst')
348
349 # samples for the (un)escaping tests:
350 escaped = r'escapes: \*one, \\*two, \\\*three in\side no\ space' + '\\'
351 nulled = ('escapes: \x00*one, \x00\\*two, \x00\\\x00*three'
352 ' in\x00side no\x00 space\x00')
353 unescaped = r'escapes: *one, \*two, \*three inside nospace'
354
355 def test_escape2null(self):
356 nulled = utils.escape2null(self.escaped)
357 self.assertEqual(nulled, self.nulled)
358
359 def test_unescape(self):
360 unescaped = utils.unescape(self.nulled)
361 self.assertEqual(unescaped, self.unescaped)
362 restored = utils.unescape(self.nulled, restore_backslashes=True)
363 self.assertEqual(restored, self.escaped)
364
365
366 class StylesheetFunctionTests(unittest.TestCase):
367
368 stylesheet_dirs = [TEST_ROOT, os.path.join(TEST_ROOT, 'data')]
369
370 def test_get_stylesheet_list_stylesheet_path(self):
371 # look for stylesheets in stylesheet_dirs
372 self.stylesheet = None
373 self.stylesheet_path = 'ham.css, missing.css'
374
375 ham_css = os.path.join(TEST_ROOT, 'data', 'ham.css').replace('\\', '/')
376 self.assertEqual(utils.get_stylesheet_list(self),
377 [ham_css, 'missing.css'])
378
379 def test_get_stylesheet_list_stylesheet(self):
380 # use stylesheet paths verbatim
381 self.stylesheet = 'ham.css, missing.css'
382 self.stylesheet_path = None
383
384 self.assertEqual(utils.get_stylesheet_list(self),
385 ['ham.css', 'missing.css'])
386
387 def test_get_stylesheet_list_conflict(self):
388 # settings "stylesheet_path" and "stylesheet"
389 # must not be used together
390 self.stylesheet = 'ham.css, missing.css'
391 self.stylesheet_path = 'man.css, miss2.css'
392 with self.assertRaises(AssertionError):
393 utils.get_stylesheet_list(self)
394
395
396 if __name__ == '__main__':
397 unittest.main()