Debian Codegraph @

tests/test_textruns.py

raw
1 # SPDX-FileCopyrightText: © 2023 Christian BUHTZ <[email protected]>
2 # SPDX-FileCopyrightText: © 2025 Michael Olie <[email protected]>
3 #
4 # SPDX-License-Identifier: GPL-3.0-only
5 #
6 # This file is part of the program "Hyperorg" which is released under
7 # GNU General Public License v3 (GPLv3). See LICENSES directory
8 # or go to <https://spdx.org/licenses/GPL-3.0-only.html>.
9 """Tests about runs"""
10 import unittest
11 import logging
12 from hyperorg import textruns
13
14
15 class TestRun(unittest.TestCase):
16 """Runs"""
17
18 # pylint: disable=missing-function-docstring
19
20 class ConcreteRun(textruns.Run):
21 """A concrete but simple run just for testing"""
22 # pylint: disable=too-few-public-methods
23
24 def __init__(self, count):
25 runs = [f'run {i}' for i in range(count)]
26 super().__init__(runs=runs)
27
28 def test_abstract(self):
29 with self.assertRaises(TypeError):
30 textruns.Run()
31
32 def test_len(self):
33 sut = __class__.ConcreteRun(7)
34
35 self.assertEqual(len(sut), 7)
36
37 def test_get_item(self):
38 sut = __class__.ConcreteRun(7)
39
40 self.assertEqual(sut[0], 'run 0')
41 self.assertEqual(sut[5], 'run 5')
42
43 def test_get_item_out_of_index(self):
44 sut = __class__.ConcreteRun(7)
45
46 with self.assertRaises(IndexError):
47 _ = sut[7]
48
49 def test_equal(self):
50 runa = __class__.ConcreteRun(2)
51 runb = __class__.ConcreteRun(2)
52 self.assertTrue(runa == runb)
53
54
55 class TestMarkup(unittest.TestCase):
56 """Markup"""
57
58 # pylint: disable=missing-function-docstring
59
60 def test_init(self):
61 sut = textruns.Markup(
62 'marked',
63 textruns.Markup.Type.IMPORTANT
64 )
65
66 self.assertEqual(len(sut), 1)
67 self.assertEqual(sut[0], 'marked')
68 self.assertEqual(sut.markup_type, textruns.Markup.Type.IMPORTANT)
69
70 def test_nested_markup(self):
71 """Markup with markup in it."""
72
73 # This is an italic (emphasized) markup with one bold (important) word
74 # in it.
75 sut = textruns.Markup(
76 'foo *important* bar',
77 textruns.Token.EMPHASIZED
78 )
79
80 self.assertEqual(len(sut), 3)
81
82 self.assertEqual(sut[0], 'foo ')
83 self.assertEqual(sut[1][0], 'important')
84 self.assertEqual(sut[1].markup_type, textruns.Markup.Type.IMPORTANT)
85 self.assertEqual(sut[2], ' bar')
86
87 def test_link_inside(self):
88 """Link inside the markup"""
89 sut = textruns.Markup(
90 'foo [[id:123][geordie]] bar',
91 textruns.Token.UNDERLINED
92 )
93 self.assertEqual(len(sut), 3)
94
95 self.assertEqual(sut[0], 'foo ')
96 self.assertEqual(sut[1][0], 'geordie')
97 self.assertEqual(sut[1].link_type, textruns.Link.Type.ORGID)
98 self.assertEqual(sut[1].target, '123')
99 self.assertEqual(sut[2], ' bar')
100
101 def test_equal(self):
102 sut_a = textruns.Markup('foobar', textruns.Markup.Type.IMPORTANT)
103 sut_b = textruns.Markup('foobar', textruns.Markup.Type.IMPORTANT)
104 sut_c = textruns.Markup('foobar', textruns.Markup.Type.UNDERLINED)
105
106 self.assertTrue(sut_a == sut_b)
107 self.assertFalse(sut_a == sut_c)
108
109
110 class TestLink(unittest.TestCase):
111 """Test Link class."""
112
113 def test_from_label(self):
114 """Construct from label.
115
116 Be aware that the opening ``[[`` and closing ``]]`` are removed before
117 the Link run is initialized. That re-movement happens on the layer of
118 the `element` module.
119 """
120 link = textruns.Link.from_org_string('id:target][label')
121
122 self.assertEqual(link[0], 'label')
123 self.assertEqual(link.target, 'target')
124 self.assertEqual(link.link_type, textruns.Link.Type.ORGID)
125
126 def test_init_target_only(self):
127 """No label"""
128 link = textruns.Link.from_org_string('id:target')
129
130 self.assertEqual(len(link), 0)
131 self.assertEqual(link.target, 'target')
132 self.assertEqual(link.link_type, textruns.Link.Type.ORGID)
133
134 def test_init_all_types(self):
135 """Sub testing all available link types"""
136 test_data = {
137 link_type: f'{link_type.value}:foo'
138 for link_type in textruns.Link.Type
139 }
140
141 test_data[textruns.Link.Type.NONE] \
142 = test_data[textruns.Link.Type.NONE].replace(':', '')
143 test_data[textruns.Link.Type.HTTPS] \
144 = test_data[textruns.Link.Type.HTTPS].replace(':', '://')
145
146 for link_type, link in test_data.items():
147 sut = textruns.Link.from_org_string(link)
148 self.assertEqual(sut.link_type, link_type)
149
150 def test_case_insensitive_types(self):
151 """Upper or lower case doesn't matter when recognizing link type"""
152 test_data = {
153 textruns.Link.Type.ORGID: (
154 'ID:', 'id:', 'Id:', 'iD:'),
155 textruns.Link.Type.HTTPS: (
156 'https://', 'HTTPS://', 'Https://', 'HTtPs://', 'httPs://'),
157 textruns.Link.Type.FILE: (
158 'fIle:', 'fiLE:', 'FILE:', 'file:')
159 }
160
161 # pylint: disable-next=consider-using-dict-items
162 test_data = [(k, v) for k in test_data for v in test_data[k]]
163
164 for link_type, link_prefix in test_data:
165 with self.subTest((link_type, link_prefix)):
166
167 sut = textruns.Link.from_org_string(f'{link_prefix}foobar')
168
169 self.assertEqual(sut.link_type, link_type)
170
171 def test_no_type_links(self):
172 """Links without types are OK. """
173 link = textruns.Link.from_org_string('foo')
174
175 self.assertEqual(link.link_type, textruns.Link.Type.NONE)
176
177 def test_equal(self):
178 """Equal operator"""
179 sut_a = textruns.Link.from_org_string('foo][bar')
180 sut_b = textruns.Link.from_org_string('foo][bar')
181 sut_c = textruns.Link.from_org_string('id:foo][bar')
182 sut_d = textruns.Link.from_org_string('fxx][bar')
183
184 self.assertTrue(sut_a == sut_b)
185 self.assertFalse(sut_a == sut_c)
186 self.assertFalse(sut_a == sut_d)
187
188 def test_type_target_labels(self):
189 """Recognition of type, targets and labels at once"""
190 test_data = (
191 ('id:foo][bar', ('id', 'foo', 'bar')),
192 ('https:foo][bar', ('https', 'foo', 'bar')),
193 ('foo][bar', (None, 'foo', 'bar')),
194 ('id:foo', ('id', 'foo', None)),
195 ('id:foo][bar:extra', ('id', 'foo', 'bar:extra')),
196 ('foo][bar:extra', (None, 'foo', 'bar:extra')),
197 )
198
199 for sut, expect in test_data:
200 with self.subTest(sut):
201 # pylint: disable=protected-access
202 self.assertEqual(
203 textruns.Link._REX_TYPE_TARGET_LABEL.match(sut).groups(),
204 expect
205 )
206
207 def test_unknown_type_with_label(self):
208 """Link with in an unknown type (protocol) and a label."""
209 with self.assertLogs(level=logging.WARNING) as cm_log:
210 sut = textruns.Link.from_org_string(
211 'unknowntype:rainbowtarget][colorfullabel'
212 )
213
214 self.assertEqual(1, len(cm_log.output))
215 self.assertRegex(
216 cm_log.output[0],
217 r'.*Link type.*not supported.*'
218 )
219
220 self.assertEqual(sut.link_type, textruns.Link.Type.UNKNOWN)
221 # First run is the original type
222 self.assertEqual(sut[0], 'unknowntype')
223 self.assertEqual(sut[1], 'colorfullabel')
224 self.assertEqual(len(sut), 2)
225 self.assertEqual(sut.target, 'rainbowtarget')
226
227 def test_unknown_type_without_label(self):
228 """Link with in an unknown type (protocol)."""
229 with self.assertLogs(level=logging.WARNING) as cm_log:
230 sut = textruns.Link.from_org_string('unknowntype:rainbowtarget')
231
232 self.assertEqual(1, len(cm_log.output))
233 self.assertRegex(
234 cm_log.output[0],
235 r'.*Link type.*not supported.*'
236 )
237
238 self.assertEqual(sut.link_type, textruns.Link.Type.UNKNOWN)
239 # First run is the original type
240 self.assertEqual(sut[0], 'unknowntype')
241 self.assertEqual(len(sut), 1)
242 self.assertEqual(sut.target, 'rainbowtarget')
243
244
245 class TestImage(unittest.TestCase):
246 """Image"""
247
248 # pylint: disable=missing-function-docstring
249
250 def test_target(self):
251 sut = textruns.Image('img.png')
252 self.assertEqual(sut.target, 'img.png')
253
254 def test_alternative(self):
255 sut = textruns.Image('img.png')
256 self.assertEqual(sut.alternative, 'img.png')
257
258 def test_alternative_https(self):
259 sut = textruns.Image('https://foo.bar/img.png')
260 self.assertEqual(sut.alternative, 'img.png')
261
262 def test_leading_folder_seperator(self):
263 sut = textruns.Image('/img.png')
264
265 self.assertEqual(sut.target, '/img.png')
266
267
268 class TestInlineMath(unittest.TestCase):
269 """Test Math class."""
270
271 def test_init_defaults(self):
272 """Default init call."""
273 sut = textruns.InlineMath('e = mc^{2}')
274
275 self.assertEqual(len(sut), 1)
276 self.assertEqual(sut[0], 'e = mc^{2}')
277
278
279 class DontTouchVerbatimOrCode(unittest.TestCase):
280 """Test special rule that content enclosed by verbatim or code markups
281 (``=`` and ``~``) should not be parsed or cut.
282 """
283
284 # pylint: disable=missing-function-docstring
285
286 def test_markup_class(self):
287 """Class `textruns.Markup` shouldn't parse verbatim/code."""
288
289 for text in ['[[id:123][geordie]]',
290 '*don\'t parse it*']:
291
292 for markup_type in [textruns.Markup.Type.CODE,
293 textruns.Markup.Type.VERBATIM]:
294
295 markup = textruns.Markup(text, markup_type)
296
297 self.assertEqual(len(markup.runs), 1)
298 self.assertEqual(str(markup.runs[0]), text)
299
300 def test_ignore_links(self):
301 """Don't treat links when enclosded by verbatim or code markup."""
302 for markup_type in [textruns.Markup.Type.CODE,
303 textruns.Markup.Type.VERBATIM]:
304 text = 'Foo {m}very [[id:1234][important]] link{m} bar' \
305 .format(m=markup_type.value)
306
307 result = textruns.cut_into_runs(text)
308
309 self.assertEqual(len(result), 3)
310 self.assertIsInstance(result[1], textruns.Markup)
311
312 self.assertEqual(len(result[1].runs), 1)
313 self.assertEqual(str(result[1].runs[0]),
314 'very [[id:1234][important]] link')
315
316 self.assertEqual(result[1].markup_type, markup_type)
317
318 def test_ignore_markup(self):
319 for outer_type in [textruns.Markup.Type.CODE,
320 textruns.Markup.Type.VERBATIM]:
321 for markup_type in textruns.Markup.Type:
322
323 if markup_type == outer_type:
324 continue
325
326 text = 'Foo {vc}with {m}in-markup{m} bar{vc} fin.'.format(
327 vc=outer_type.value, m=markup_type.value)
328
329 result = textruns.cut_into_runs(text)
330
331 self.assertEqual(len(result), 3)
332 self.assertIsInstance(result[1], textruns.Markup)
333
334 self.assertEqual(len(result[1].runs), 1)
335 self.assertEqual(
336 str(result[1].runs[0]),
337 (f'with {markup_type.value}in-markup'
338 f'{markup_type.value} bar'))
339
340
341 class NestedLinkAndMarkup(unittest.TestCase):
342 """Test special situation with nested markup/links."""
343
344 # pylint: disable=missing-function-docstring
345
346 def test_markup_in_link(self):
347 text = 'Foo [[id:1234][This is *important*]] bar'
348 result = textruns.cut_into_runs(text)
349
350 self.assertEqual(len(result), 3)
351 self.assertEqual(result[0], 'Foo ')
352 self.assertEqual(len(result[1]), 2)
353 self.assertEqual(result[1][0], 'This is ')
354 self.assertEqual(result[1].link_type, textruns.Link.Type.ORGID)
355 self.assertEqual(result[1][1][0], 'important')
356 self.assertEqual(result[1][1].markup_type,
357 textruns.Markup.Type.IMPORTANT)
358 self.assertEqual(result[2], ' bar')
359
360 def test_link_in_markup(self):
361 text = 'Foo *very [[id:1234][important]] link* bar'
362 result = textruns.cut_into_runs(text)
363
364 self.assertEqual(len(result), 3)
365
366 self.assertEqual(result[0], 'Foo ')
367 self.assertEqual(len(result[1]), 3)
368 self.assertEqual(result[1][0], 'very ')
369 self.assertEqual(result[1][1][0], 'important')
370 self.assertEqual(result[1][1].target, '1234')
371 self.assertEqual(result[1][1].link_type, textruns.Link.Type.ORGID)
372 self.assertEqual(result[1][2], ' link')
373 self.assertEqual(result[1].markup_type, textruns.Markup.Type.IMPORTANT)
374 self.assertEqual(result[2], ' bar')
375
376
377 class ImagesAndLinks(unittest.TestCase):
378 """Images and Links"""
379 def test_inline_image(self):
380 """Simple inline image."""
381 sut = 'Foo [[img.png]] bar'
382
383 result = textruns.cut_into_runs(sut)
384
385 self.assertEqual(len(result), 3)
386 self.assertIsInstance(result[1], textruns.Image)
387 image = result[1]
388 self.assertEqual(image.target, 'img.png')
389
390 def test_inline_image_file_type(self):
391 """Inline image with "file:" prefix"""
392 sut = 'Foo [[file:img.png]] bar'
393
394 result = textruns.cut_into_runs(sut)
395
396 self.assertEqual(len(result), 3)
397 self.assertEqual(result[1].target, 'img.png')
398
399 def test_inline_linked_image_locale_file(self):
400 """Linked inline image with "file:" prefix"""
401 sut = 'Foo [[linktarget.png][file:labelimage.png]] bar'
402
403 result = textruns.cut_into_runs(sut)
404 self.assertEqual(len(result), 3)
405
406 link = result[1]
407 self.assertIsInstance(link, textruns.Link)
408
409 self.assertEqual(link.link_type, textruns.Link.Type.NONE)
410 self.assertEqual(link.target, 'linktarget.png')
411
412 # The "label" of the link is an image
413 image = link[0]
414 self.assertIsInstance(image, textruns.Image)
415 self.assertEqual(image.target, 'labelimage.png')
416
417 def test_inline_linked_image_https(self):
418 """Linked inline image with "https:" prefix"""
419 sut = 'Foo [[linktarget.png][https://labelimage.png]] bar'
420
421 result = textruns.cut_into_runs(sut)
422 self.assertEqual(len(result), 3)
423
424 link = result[1]
425 self.assertIsInstance(link, textruns.Link)
426
427 self.assertEqual(link.link_type, textruns.Link.Type.NONE)
428 self.assertEqual(link.target, 'linktarget.png')
429
430 # The "label" of the link is an image
431 image = link[0]
432 self.assertIsInstance(image, textruns.Image)
433 self.assertEqual(image.target, 'https://labelimage.png')
434
435 def test_not_a_linked_image(self):
436 """Just a linked text."""
437
438 # Images as labels are only recoginied with file: or https:// prefix.
439 # Otherwise it is just a string.
440 sut = 'Foo [[linktarget.png][labelimage.png]] bar'
441
442 result = textruns.cut_into_runs(sut)
443
444 link = result[1]
445
446 label = link[0]
447 self.assertEqual(label, 'labelimage.png')