Debian Codegraph @

test/test_transforms/test_smartquotes.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # $Id: test_smartquotes.py 10287 2026-01-07 13:40:59Z milde $
3 # :Copyright: © 2011 Günter Milde.
4 # :Maintainer: [email protected]
5 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
6 #
7 # Copying and distribution of this file, with or without modification,
8 # are permitted in any medium without royalty provided the copyright
9 # notice and this notice are preserved.
10 # This file is offered as-is, without any warranty.
11 #
12 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
13
14 """
15 Test module for universal.SmartQuotes transform.
16 """
17
18 from pathlib import Path
19 import sys
20 import unittest
21
22 if __name__ == '__main__':
23 # prepend the "docutils root" to the Python library path
24 # so we import the local `docutils` package.
25 sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
26
27 from docutils.frontend import get_default_settings
28 from docutils.parsers.rst import Parser
29 from docutils.transforms.universal import (SmartQuotes, FilterMessages,
30 TestMessages)
31 from docutils.utils import new_document
32
33
34 class TransformTestCase(unittest.TestCase):
35 maxDiff = None
36
37 def test_transforms(self):
38 parser = Parser()
39 settings = get_default_settings(Parser)
40 settings.warning_stream = ''
41 settings.smart_quotes = True
42 settings.syntax_highlight = 'none'
43 settings.trim_footnote_ref_space = True
44 for name, (transforms, cases) in totest.items():
45 for casenum, (case_input, case_expected) in enumerate(cases):
46 with self.subTest(id=f'totest[{name!r}][{casenum}]'):
47 document = new_document('test data', settings.copy())
48 parser.parse(case_input, document)
49 # Don't do a ``populate_from_components()`` because that
50 # would enable the Transformer's default transforms.
51 document.transformer.add_transforms(transforms)
52 document.transformer.add_transform(TestMessages)
53 document.transformer.apply_transforms()
54 output = document.pformat()
55 self.assertEqual(case_expected, output)
56
57 settings.language_code = 'de'
58 for name, (transforms, cases) in totest_de.items():
59 for casenum, (case_input, case_expected) in enumerate(cases):
60 with self.subTest(id=f'totest_de[{name!r}][{casenum}]'):
61 document = new_document('test data', settings.copy())
62 parser.parse(case_input, document)
63 # Don't do a ``populate_from_components()`` because that
64 # would enable the Transformer's default transforms.
65 document.transformer.add_transforms(transforms)
66 document.transformer.add_transform(TestMessages)
67 # Filter with increased priority: call later, so that
68 # messages added by `TestMessages` are filtered, too.
69 document.transformer.add_transform(FilterMessages, 890)
70 document.transformer.apply_transforms()
71 output = document.pformat()
72 self.assertEqual(case_expected, output)
73
74 settings.smart_quotes = 'alternative'
75 for name, (transforms, cases) in totest_de_alt.items():
76 for casenum, (case_input, case_expected) in enumerate(cases):
77 with self.subTest(id=f'totest_de_alt[{name!r}][{casenum}]'):
78 document = new_document('test data', settings.copy())
79 parser.parse(case_input, document)
80 # Don't do a ``populate_from_components()`` because that
81 # would enable the Transformer's default transforms.
82 document.transformer.add_transforms(transforms)
83 document.transformer.add_transform(TestMessages)
84 document.transformer.apply_transforms()
85 output = document.pformat()
86 self.assertEqual(case_expected, output)
87
88 settings.smart_quotes = True
89 settings.smartquotes_locales = [('de', '«»()'), ('nl', '„”’’')]
90 for name, (transforms, cases) in totest_locales.items():
91 for casenum, (case_input, case_expected) in enumerate(cases):
92 with self.subTest(id=f'totest_locales[{name!r}][{casenum}]'):
93 document = new_document('test data', settings.copy())
94 parser.parse(case_input, document)
95 # Don't do a ``populate_from_components()`` because that
96 # would enable the Transformer's default transforms.
97 document.transformer.add_transforms(transforms)
98 document.transformer.add_transform(TestMessages)
99 document.transformer.apply_transforms()
100 output = document.pformat()
101 self.assertEqual(case_expected, output)
102
103
104 totest = {}
105 totest_de = {}
106 totest_de_alt = {}
107 totest_locales = {}
108
109 totest['smartquotes'] = ((SmartQuotes,), [
110 ["""\
111 Test "smart quotes", 'secondary smart quotes',
112 "'nested' smart" quotes
113 -- and ---also long--- dashes.
114 """,
115 """\
116 <document source="test data">
117 <paragraph>
118 Test “smart quotes”, ‘secondary smart quotes’,
119 “‘nested’ smart” quotes
120 – and —also long— dashes.
121 """],
122 [r"""Escaped \"ASCII quotes\" and \'secondary ASCII quotes\'.
123 """,
124 """\
125 <document source="test data">
126 <paragraph>
127 Escaped "ASCII quotes" and 'secondary ASCII quotes'.
128 """],
129 ["""\
130 Do not "educate" quotes ``inside "literal" text`` and ::
131
132 "literal" blocks.
133
134 .. role:: python(code)
135
136 Keep quotes straight in code and math:
137 :code:`print "hello"` :python:`print("hello")` :math:`1' 12"`.
138
139 .. code::
140
141 print("hello")
142
143 .. math::
144
145 f'(x) = df(x)/dx
146
147 """,
148 """\
149 <document source="test data">
150 <paragraph>
151 Do not “educate” quotes \n\
152 <literal>
153 inside "literal" text
154 and
155 <literal_block xml:space="preserve">
156 "literal" blocks.
157 <paragraph>
158 Keep quotes straight in code and math:
159 <literal classes="code">
160 print "hello"
161 \n\
162 <literal classes="code python">
163 print("hello")
164 \n\
165 <math>
166 1' 12"
167 .
168 <literal_block classes="code" xml:space="preserve">
169 print("hello")
170 <math_block xml:space="preserve">
171 f'(x) = df(x)/dx
172 """],
173 ["""\
174 Closing quotes, if preceded by
175 wor"d char's
176 or punctuation:"a",'a';'a' (TODO: opening quotes if followed by word-char?).
177
178 Opening quotes after
179 normal space "a" 'a',
180 thin space "a" 'a',
181 em space "a" 'a',
182 NBSP "a" 'a',
183 ZWSP\u200B"a" and\u200B'a',
184 ZWNJ\u200C"a" and\u200C'a',
185 escaped space\\ "a" and\\ 'a',
186
187 hyphen -"a", -'a'
188 en dash –"a"–'a',
189 em dash —"a"—'a'.
190
191 opening brackets ("a") ('a') ["a"] ['a'] {"a"} {'a'}
192
193 But not if followed by (optional punctuation and) whitespace:
194 "-", "–", "—", "(", "a[", "{"
195 '-', '–', '—', '((', '[', '{'
196 """,
197 """\
198 <document source="test data">
199 <paragraph>
200 Closing quotes, if preceded by
201 wor”d char’s
202 or punctuation:”a”,’a’;’a’ (TODO: opening quotes if followed by word-char?).
203 <paragraph>
204 Opening quotes after
205 normal space “a” ‘a’,
206 thin space “a” ‘a’,
207 em space “a” ‘a’,
208 NBSP “a” ‘a’,
209 ZWSP\u200B“a” and\u200B‘a’,
210 ZWNJ\u200C“a” and\u200C‘a’,
211 escaped space“a” and‘a’,
212 <paragraph>
213 hyphen -“a”, -‘a’
214 en dash –“a”–‘a’,
215 em dash —“a”—‘a’.
216 <paragraph>
217 opening brackets (“a”) (‘a’) [“a”] [‘a’] {“a”} {‘a’}
218 <paragraph>
219 But not if followed by (optional punctuation and) whitespace:
220 “-”, “–”, “—”, “(”, “a[”, “{”
221 ‘-’, ‘–’, ‘—’, ‘((’, ‘[’, ‘{’
222 """],
223 ["""\
224 Quotes and inline-elements:
225
226 * Around "_`targets`", "*emphasized*" or "``literal``" text
227 and links to "targets_".
228
229 * Inside *"emphasized"* or other `inline "roles"`
230
231 Do not drop characters from intra-word inline markup like
232 *re*\\ ``Structured``\\ *Text*.
233 """,
234 """\
235 <document source="test data">
236 <paragraph>
237 Quotes and inline-elements:
238 <bullet_list bullet="*">
239 <list_item>
240 <paragraph>
241 Around “
242 <target ids="targets" names="targets">
243 targets
244 ”, “
245 <emphasis>
246 emphasized
247 ” or “
248 <literal>
249 literal
250 ” text
251 and links to “
252 <reference name="targets" refname="targets">
253 targets
254 ”.
255 <list_item>
256 <paragraph>
257 Inside \n\
258 <emphasis>
259 “emphasized”
260 or other \n\
261 <title_reference>
262 inline “roles”
263 <paragraph>
264 Do not drop characters from intra-word inline markup like
265 <emphasis>
266 re
267 <literal>
268 Structured
269 <emphasis>
270 Text
271 .
272 """],
273 ["""\
274 Do not convert context-character at inline-tag boundaries
275 (in French, smart quotes expand to two characters).
276
277 .. class:: language-fr-ch-x-altquot
278
279 Around "_`targets`", "*emphasized*" or "``literal``" text
280 and links to "targets_".
281
282 Inside *"emphasized"* or other `inline "roles"`:
283 (``"string"``), (``'string'``), *\"betont\"*, \"*betont*".
284
285 Do not drop characters from intra-word inline markup like
286 *re*\\ ``Structured``\\ *Text*.
287 """,
288 """\
289 <document source="test data">
290 <paragraph>
291 Do not convert context-character at inline-tag boundaries
292 (in French, smart quotes expand to two characters).
293 <paragraph classes="language-fr-ch-x-altquot">
294 Around «\u202f
295 <target ids="targets" names="targets">
296 targets
297 \u202f», «\u202f
298 <emphasis>
299 emphasized
300 \u202f» or «\u202f
301 <literal>
302 literal
303 \u202f» text
304 and links to «\u202f
305 <reference name="targets" refname="targets">
306 targets
307 \u202f».
308 <paragraph classes="language-fr-ch-x-altquot">
309 Inside \n\
310 <emphasis>
311 «\u202femphasized\u202f»
312 or other \n\
313 <title_reference>
314 inline «\u202froles\u202f»
315 :
316 (
317 <literal>
318 "string"
319 ), (
320 <literal>
321 'string'
322 ), \n\
323 <emphasis>
324 «\u202fbetont\u202f»
325 , «\u202f
326 <emphasis>
327 betont
328 \u202f».
329 <paragraph classes="language-fr-ch-x-altquot">
330 Do not drop characters from intra-word inline markup like
331 <emphasis>
332 re
333 <literal>
334 Structured
335 <emphasis>
336 Text
337 .
338 """],
339 [r"""
340 Docutils escape mechanism uses the backslash:
341
342 \Remove \non-escaped \backslashes\:
343 \item \newline \tab \" \' \*.
344
345 \ Remove-\ escaped-\ white\ space-\
346 including-\ newlines.
347
348 \\Keep\\escaped\\backslashes\\
349 (but\\only\\one).
350
351 \\ Keep \\ space\\ around \\ backslashes.
352
353 Keep backslashes ``\in\ literal``, :math:`in \mathrm{math}`,
354 and :code:`in\ code`.
355
356 Test around inline elements:\ [*]_
357
358 *emphasized*, H\ :sub:`2`\ O and :math:`x^2`
359
360 *emphasized*, H\ :sub:`2`\ O and :math:`x^2`
361 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
362
363 .. [*] and footnotes
364 """,
365 """\
366 <document source="test data">
367 <paragraph>
368 Docutils escape mechanism uses the backslash:
369 <paragraph>
370 Remove non-escaped backslashes:
371 item newline tab " \' *.
372 <paragraph>
373 Remove-escaped-whitespace-including-newlines.
374 <paragraph>
375 \\Keep\\escaped\\backslashes\\
376 (but\\only\\one).
377 <paragraph>
378 \\ Keep \\ space\\ around \\ backslashes.
379 <paragraph>
380 Keep backslashes \n\
381 <literal>
382 \\in\\ literal
383 , \n\
384 <math>
385 in \\mathrm{math}
386 ,
387 and \n\
388 <literal classes="code">
389 in\\ code
390 .
391 <paragraph>
392 Test around inline elements:
393 <footnote_reference auto="*" ids="footnote-reference-1">
394 <paragraph>
395 <emphasis>
396 emphasized
397 , H
398 <subscript>
399 2
400 O and \n\
401 <math>
402 x^2
403 <section ids="emphasized-h2o-and-x-2" names="emphasized,\\ h2o\\ and\\ x^2">
404 <title>
405 <emphasis>
406 emphasized
407 , H
408 <subscript>
409 2
410 O and \n\
411 <math>
412 x^2
413 <footnote auto="*" ids="footnote-1">
414 <paragraph>
415 and footnotes
416 """],
417 [r"""
418 Character-level m\ *a*\ **r**\ ``k``\ `u`:title:\p
419 with backslash-escaped whitespace, including new\
420 lines.
421 """,
422 """\
423 <document source="test data">
424 <paragraph>
425 Character-level m
426 <emphasis>
427 a
428 <strong>
429 r
430 <literal>
431 k
432 <title_reference>
433 u
434 p
435 with backslash-escaped whitespace, including newlines.
436 """],
437 ["""\
438 .. class:: language-de
439
440 German "smart quotes" and 'secondary smart quotes'.
441
442 .. class:: language-en-UK-x-altquot
443
444 British "primary quotes" use single and
445 'secondary quotes' double quote signs.
446
447 .. class:: language-foo
448
449 "Quoting style" for unknown languages is 'ASCII'.
450
451 .. class:: language-de-x-altquot
452
453 Alternative German "smart quotes" and 'secondary smart quotes'.
454 """,
455 """\
456 <document source="test data">
457 <paragraph classes="language-de">
458 German „smart quotes“ and ‚secondary smart quotes‘.
459 <paragraph classes="language-en-uk-x-altquot">
460 British ‘primary quotes’ use single and
461 “secondary quotes” double quote signs.
462 <paragraph classes="language-foo">
463 "Quoting style" for unknown languages is 'ASCII'.
464 <paragraph classes="language-de-x-altquot">
465 Alternative German »smart quotes« and ›secondary smart quotes‹.
466 <system_message level="2" line="12" source="test data" type="WARNING">
467 <paragraph>
468 No smart quotes defined for language "foo".
469 """],
470 ])
471
472 totest_de['smartquotes'] = ((SmartQuotes,), [
473 ["""\
474 German "smart quotes" and 'secondary smart quotes'.
475
476 .. class:: language-en
477
478 English "smart quotes" and 'secondary smart quotes'.
479 """,
480 """\
481 <document source="test data">
482 <paragraph>
483 German „smart quotes“ and ‚secondary smart quotes‘.
484 <paragraph classes="language-en">
485 English “smart quotes” and ‘secondary smart quotes’.
486 """],
487 ])
488
489 totest_de_alt['smartquotes'] = ((SmartQuotes,), [
490 ["""\
491 Alternative German "smart quotes" and 'secondary smart quotes'.
492
493 In this case, the apostrophe isn't a closing secondary quote!
494
495 .. class:: language-en-UK
496
497 British "quotes" use single and 'secondary quotes' double quote signs
498 (there are no alternative quotes defined).
499
500 .. class:: language-ro
501
502 Romanian "smart quotes" and 'secondary' smart quotes.
503 """,
504 """\
505 <document source="test data">
506 <paragraph>
507 Alternative German »smart quotes« and ›secondary smart quotes‹.
508 <paragraph>
509 In this case, the apostrophe isn’t a closing secondary quote!
510 <paragraph classes="language-en-uk">
511 British ‘quotes’ use single and “secondary quotes” double quote signs
512 (there are no alternative quotes defined).
513 <paragraph classes="language-ro">
514 Romanian „smart quotes” and «secondary» smart quotes.
515 """],
516 ])
517
518 totest_locales['smartquotes'] = ((SmartQuotes,), [
519 ["""\
520 German "smart quotes" and 'secondary smart quotes'.
521
522 .. class:: language-nl
523
524 Dutch "smart quotes" and 's Gravenhage (leading apostrophe).
525 """,
526 """\
527 <document source="test data">
528 <paragraph>
529 German «smart quotes» and (secondary smart quotes).
530 <paragraph classes="language-nl">
531 Dutch „smart quotes” and ’s Gravenhage (leading apostrophe).
532 """],
533 ])
534
535
536 if __name__ == '__main__':
537 unittest.main()