Debian Codegraph @

tests/test_exporter.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 exporting complete nodes as HTML
10
11 Dev note (2025-12, buhtz): Very mixed and unsharp. Should be reorganized and
12 split.
13 """
14 # pylint: disable=too-many-lines
15 import unittest
16 from unittest import mock
17 import pathlib
18 import inspect
19 from collections import defaultdict
20 import locale
21 import datetime
22 import pyfakefs.fake_filesystem_unittest as pyfakefs_ut
23 from tests.helper import unify_html
24 from tests.helper import extract_html_hyperorg_content
25 from hyperorg.exporter import Exporter
26 from hyperorg.content import Node
27 from hyperorg.reader import Reader
28 from hyperorg import textruns
29 from hyperorg import elements
30 from hyperorg import exporter
31
32
33 org_raw_content = [
34 # A-d197: node linking to another node
35 '''# inline comment
36 :PROPERTIES:
37 :ID: d197c651-f6c1-4e00-8d8e-ef13adac16e2
38 :END:
39 #+title: hyperorg_unittest_1
40 #+date: [2022-04-21 Do 16:55]
41 #+filetags: MyTag Zwei "Drei 3"
42 Test file for unittest
43
44 [[id:b0fc62f1-2926-4eec-a654-eab8fcea46d9][hyperorg_unittest_2]]''',
45
46 # B-b0fc: the linked node
47 '''#+begin_comment
48 block
49 comment
50 #+end_comment
51 :PROPERTIES:
52 :ID: b0fc62f1-2926-4eec-a654-eab8fcea46d9
53 :END:
54 #+title: hyperorg_unittest_2
55 #+date: [2022-04-21 Do 16:55]
56 Second hyperorg test file''',
57
58 # C-4a2f: node with child node (heading with own Org-ID)
59 ''':PROPERTIES:
60 :ID: 4a2f8510-f57e-468e-9832-8ddecd3335ac
61 :END:
62 #+title: killme
63 #+date: [2022-04-03 So 22:55]
64 #+filetags: Zwei
65 Governments of the Industrial World,
66 * Heading
67 you weary giants of flesh and steel,
68 * Child
69 :PROPERTIES:
70 :ID: 95c99140-f044-450d-b631-6a5ff7608b2b
71 :END:
72 I come from Cyberspace, the new home of Mind,
73 * One more
74 On behalf of the future, I ask you of
75 the past to leave us alone.''',
76
77 # node with alias titles incl. subheadings
78 ''':PROPERTIES:
79 :ID: 7a2f8517-f57e-868e-9832-8ddecd3335ac
80 :ROAM_ALIASES: aliasnode "node with alias"
81 :END:
82 #+title: Aliases node
83 #+date: [2022-04-03 So 22:55]
84 #+filetags: "Drei 3"
85 * Foo
86 bar
87 * Bar
88 :PROPERTIES:
89 :ID: da6759cb-ba23-4042-9486-abc0c76895ad
90 :ROAM_ALIASES: "ein bar alias" again
91 :END:
92 foo''',
93
94 # node with alias titles incl. subheadings
95 ''':PROPERTIES:
96 :ID: 1a2f3456-f57e-868e-9832-8ddecd3335xy
97 :END:
98 #+title: Email
99 #+filetags: MyTag
100 Angle brackets: Entry <[email protected]>
101
102 * &<>"'
103
104 - &<>"'
105
106 &<>"'
107
108 [[id:7a2f8517-f57e-868e-9832-8ddecd3335ac][&<>"']]
109
110 [[id:7a2f8517-f57e-868e-9832-8ddecd3335ac][TITLE]]
111
112 Bold *&<>"'*
113
114 Italic /&<>"'/
115
116 Underline _&<>"'_
117
118 Verbatim =&<>"'=
119
120 Code ~&<>"'~
121 ''',
122 # 5: a math file with inline math
123 ''':PROPERTIES:
124 :ID: 1a2f3456-f57e-868e-9832-8mathinline
125 :END:
126 #+title: Inline math
127
128 one paragraph $e = mc^2$ with formula.
129
130 second paragraph \\(e = mc^2\\) with formula.
131
132 $e = mc^2$
133
134 \\(e = mc^2\\)
135
136 ''',
137 # 6: math file with display math
138 ''':PROPERTIES:
139 :ID: 1a2f3456-f57e-868e-9832-8mathdisplay
140 :END:
141 #+title: Display math
142
143 first paragraph $$e = mc^2$$ second one
144
145 first paragraph \\[e = mc^2\\] second one
146
147 $$e = mc^2$$
148
149 \\[e = mc^2\\]
150 ''',
151 # 7: file with mixed math
152 ''':PROPERTIES:
153 :ID: 1a2f3456-f57e-868e-9832-8mathmixed
154 :END:
155 #+title: Mixed math
156
157 one paragraph $e = mc^2$ with formula.
158
159 second paragraph \\(e = mc^2\\) with formula.
160
161 $e = mc^2$
162
163 \\(e = mc^2\\)
164
165 first paragraph $$e = mc^2$$ second one
166
167 first paragraph \\[e = mc^2\\] second one
168
169 $$e = mc^2$$
170
171 \\[e = mc^2\\]
172 ''',
173 ]
174
175
176 class General(unittest.TestCase):
177 """Basic tests for Exporter class."""
178
179 # pylint: disable=protected-access
180
181 def setUp(self):
182 Node.nodes = {}
183 Node.heading_ids = {}
184 Node.index_data = {
185 Node.IDX_ALL: defaultdict(list),
186 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
187 }
188
189 def test_init(self):
190 """ctor"""
191 with mock.patch('pathlib.Path.mkdir') as mock_mkdir:
192 Exporter(pathlib.Path('foobar'))
193
194 # mkdir() called
195 mock_mkdir.assert_called_once_with(parents=True, exist_ok=True)
196
197 # output_dir set?
198 self.assertEqual(Exporter.output_dir, pathlib.Path('foobar'))
199
200 def test_as_html_filename(self):
201 """Convert a org filename to its html version."""
202 self.assertEqual(
203 Exporter._as_html_filename('foobar.org'),
204 pathlib.Path('foobar.html')
205 )
206
207 # does not return a string
208 self.assertNotEqual(
209 Exporter._as_html_filename('foobar.org'),
210 'foobar.html'
211 )
212
213 # include sub-folders
214 self.assertEqual(
215 Exporter._as_html_filename('subfolder/foobar.org'),
216 pathlib.Path('subfolder/foobar.html')
217 )
218
219 def test_as_index_filename(self):
220 """Index HTML filenames."""
221 self.assertEqual(
222 Exporter._as_index_filename('foobar', 'filetag'),
223 pathlib.Path('index__filetag_foobar.html')
224 )
225
226 self.assertEqual(
227 Exporter._as_index_filename('rofl', 'moon'),
228 pathlib.Path('index__moon_rofl.html')
229 )
230
231 @mock.patch('pathlib.Path.mkdir')
232 def test_footer(self, _):
233 """Footer."""
234 exp = Exporter(pathlib.Path())
235
236 expected_start = 'Generated with ' \
237 '<a href="https://codeberg.org/buhtz/hyperorg">hyperorg'
238 expected_end = ' on Fri Aug 6 18:23:45 1982'
239
240 mock_dt = mock.Mock(wraps=datetime.datetime)
241 mock_dt.now.return_value = datetime.datetime(1982, 8, 6, 18, 23, 45)
242 with mock.patch('datetime.datetime', new=mock_dt):
243 the_footer = exp._get_footer()
244
245 self.assertTrue(the_footer.startswith(expected_start))
246 self.assertTrue(the_footer.endswith(expected_end))
247
248 # footer string reused instead of re-generated
249 self.assertEqual(id(the_footer), id(exp._get_footer()))
250
251 @mock.patch('hyperorg.meta', {'Project-URL': {'homepage': 'https://w.x'}})
252 @mock.patch('hyperorg.__name__', 'FOOBAR')
253 @mock.patch('hyperorg.__version__', '123456')
254 def test_meta_generator(self):
255 """Generator items in HTML output"""
256 result = Exporter._get_html_meta_info_generator(0)
257
258 expect = '\n'.join([
259 '<meta name="generator" content="FOOBAR" />',
260 '<meta name="generator_version" content="123456" />',
261 '<meta name="generator_website" content="https://w.x" />'
262 ])
263
264 self.assertEqual(result, expect)
265
266 @mock.patch('hyperorg.exporter.Exporter._get_html_template_node')
267 @mock.patch('hyperorg.exporter.Exporter._get_mathjax_code')
268 @mock.patch('hyperorg.exporter.Exporter._elements_as_html')
269 @mock.patch('hyperorg.exporter.Exporter._get_footer')
270 def test_as_html(self,
271 mock_footer,
272 mock_elements,
273 mock_mathjax,
274 mock_template_node):
275 """Not sure what the intention is here.
276 I assume it is about the three placeholders"""
277
278 self.maxDiff = None
279 mock_template_node.return_value = inspect.cleandoc('''
280 {{ mathjax }}{{ title }}
281 {{ body }}
282 {{ footer }}
283 ''')
284
285 mock_elements.return_value = 'The Elements'
286 mock_footer.return_value = 'A Footer'
287 mock_mathjax.return_value = ''
288
289 expected = inspect.cleandoc('''
290 Test Title
291 The Elements
292 A Footer
293 ''')
294
295 with mock.patch('pathlib.Path.mkdir'):
296 exp = Exporter(pathlib.Path('out'))
297
298 node = Node(['#+title: Test Title'], 'file.org')
299
300 self.assertEqual(expected, exp._as_html(node, []))
301
302 @mock.patch('hyperorg.exporter.Exporter._backlinks_to_html')
303 @mock.patch('hyperorg.exporter.Exporter._paragraph_to_html')
304 @mock.patch('hyperorg.exporter.Exporter._heading_to_html')
305 @mock.patch('hyperorg.exporter.Exporter._list_to_html')
306 @mock.patch('hyperorg.exporter.Exporter._subtree_to_html')
307 # pylint: disable-next=too-many-arguments,too-many-positional-arguments
308 def test_elements_as_html(self, # noqa: PLR0913
309 mock_subtree,
310 mock_list,
311 mock_heading,
312 mock_paragraph,
313 mock_backlinks):
314 """Calling order.
315
316 Credits: https://stackoverflow.com/a/22677452/4865723
317 """
318 mock_subtree.return_value = ''
319 mock_list.return_value = ''
320 mock_heading.return_value = ''
321 mock_paragraph.return_value = ''
322 mock_backlinks.return_value = ''
323
324 manager = mock.Mock()
325 manager.attach_mock(mock_subtree, 'subtree')
326 manager.attach_mock(mock_list, 'alist')
327 manager.attach_mock(mock_heading, 'heading')
328 manager.attach_mock(mock_paragraph, 'paragraph')
329 manager.attach_mock(mock_backlinks, 'backlinks')
330
331 node = Node([], '')
332 node._elements.append(elements.ListElement('- fake', False))
333 node._elements.append(elements.Paragraph(''))
334 node._elements.append(Node([], ''))
335 node._elements.append(elements.Heading('* Fake'))
336 node._elements.append(elements.Backlinks())
337 node._elements[-1].runs = ['- fake']
338
339 expected_calls = [
340 mock.call.alist(node._elements[0]),
341 mock.call.paragraph(node._elements[1]),
342 mock.call.subtree(node._elements[2]),
343 mock.call.heading(node._elements[3]),
344 mock.call.backlinks(node._elements[4])
345 ]
346
347 Exporter._elements_as_html(node)
348
349 self.assertEqual(manager.mock_calls, expected_calls)
350
351 def test_compute_indexes(self):
352 """Items for navigation bar."""
353
354 Node.index_data = {
355 Node.IDX_ALL: {
356 'B': [('Title', 0, True) for _ in range(7)],
357 'R': [('Title', 0, True) for _ in range(19)],
358 'T': [('Title', 0, True) for _ in range(4)],
359 'W': [('Title', 0, True) for _ in range(2)],
360 'G': [('Title', 0, True) for _ in range(10)],
361 'A': [('Title', 0, True) for _ in range(5)],
362 },
363 Node.IDX_FILETAG: {
364 Node.IDX_NO_TAG: {
365 'B': [('Title', 0, True) for _ in range(7)],
366 'W': [('Title', 0, True) for _ in range(2)],
367 'T': [('Title', 0, True) for _ in range(4)],
368 },
369 'Tag': {
370 'G': [('Title', 0, True) for _ in range(10)],
371 'A': [('Title', 0, True) for _ in range(5)],
372 },
373 'Foo and Bar': {
374 'A': [('Title', 0, True) for _ in range(5)],
375 'R': [('Title', 0, True) for _ in range(19)],
376 'G': [('Title', 0, True) for _ in range(10)],
377 },
378 'Alice': {
379 'A': [('Title', 0, True) for _ in range(5)],
380 },
381
382 }
383 }
384
385 # "Index" as first entry.
386 # The rest sorted by title(entry) count
387 expect = [
388 ('Index', 'index', 47),
389 ('Foo and Bar', 'Foo_and_Bar', 34),
390 ('Tag', 'Tag', 15),
391 ('(no tags)', '_no_tags_', 13),
392 ('Alice', 'Alice', 5)
393 ]
394 result = Exporter._compute_indexes()
395
396 self.assertEqual(result, expect)
397
398 def test_compute_indexes_duplicate_filename(self):
399 """Duplicates in index filenames."""
400
401 Node.index_data = {
402 Node.IDX_ALL: {
403 'B': [('Title', 0, True) for _ in range(7)],
404 'G': [('Title', 0, True) for _ in range(10)],
405 'A': [('Title', 0, True) for _ in range(5)],
406 },
407 Node.IDX_FILETAG: {
408 Node.IDX_NO_TAG: {
409 'B': [('Title', 0, True) for _ in range(7)],
410 },
411 'Tag<': {
412 'G': [('Title', 0, True) for _ in range(10)],
413 },
414 'Tag:': {
415 'A': [('Title', 0, True) for _ in range(5)],
416 },
417
418 }
419 }
420
421 # "Index" as first entry.
422 # The rest sorted by title(entry) count
423 expect = [
424 ('Index', 'index', 22),
425 ('Tag<', 'Tag_1', 10),
426 ('(no tags)', '_no_tags_', 7),
427 ('Tag:', 'Tag_2', 5),
428 ]
429 result = Exporter._compute_indexes()
430
431 self.assertEqual(result, expect)
432
433 def test_compute_indexes_order(self):
434 """Correct order of items for navigation bar."""
435
436 Node.index_data = {
437 Node.IDX_ALL: {
438 'B': [('Title', 0, True) for _ in range(24)],
439 'A': [('Title', 0, True) for _ in range(5)],
440 },
441 Node.IDX_FILETAG: {
442 Node.IDX_NO_TAG: {
443 'B': [('Title', 0, True) for _ in range(24)],
444 },
445 'Tag': {
446 'A': [('Title', 0, True) for _ in range(5)],
447 },
448 'Alice': {
449 'A': [('Title', 0, True) for _ in range(5)],
450 },
451 'Xerxes': {
452 'A': [('Title', 0, True) for _ in range(5)],
453 },
454 }
455 }
456
457 # "Index" as first entry.
458 # The rest sorted by title(entry) count
459 expect = [
460 ('Index', 'index', 29),
461 ('(no tags)', '_no_tags_', 24),
462 ('Alice', 'Alice', 5),
463 ('Tag', 'Tag', 5),
464 ('Xerxes', 'Xerxes', 5),
465 ]
466 result = Exporter._compute_indexes()
467
468 self.assertEqual(result, expect)
469
470 def test_url_with_slash_at_end(self):
471 """If there is a slash at the end of an URL was interpreted as
472 emphasized inline markup. See #64.
473 """
474 node = Node(['[[https://my.world/]]'], '')
475
476 expected = '<p><a target="_blank" rel="noopener noreferrer" ' \
477 'href="https://my.world/">' \
478 'https://my.world/</a></p>'
479
480 result = Exporter._elements_as_html(node)
481
482 # We keep this test case and invert its result when #63 is closed.
483 self.assertEqual(result, expected)
484
485
486 class GenerateHRef(unittest.TestCase):
487 """Test function generate_href_value()"""
488
489 def setUp(self):
490 Node.nodes = {}
491 Node.heading_ids = {}
492 Node.index_data = {
493 Node.IDX_ALL: defaultdict(list),
494 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
495 }
496
497 def test_same_root(self):
498 """Target and start node in same root folder."""
499 Node.nodes = {
500 'root': Node([], 'root.org'),
501 'gin': Node([], 'gin.org'),
502 }
503
504 # gin links to root
505 sut = Exporter.generate_href_value('root', 'gin')
506 self.assertEqual(sut, 'root.html')
507
508 def test_sub_to_root(self):
509 """Target is root and start in subfolder"""
510 Node.nodes = {
511 'root': Node([], 'root.org'),
512 'gin': Node(
513 [], str(pathlib.Path('subfolder') / 'deep' / 'gin.org')),
514 }
515
516 # gin links to root
517 sut = Exporter.generate_href_value('root', 'gin')
518 self.assertEqual(sut, '../../root.html')
519
520 def test_root_to_sub(self):
521 """Target is in subfolder and root is start"""
522 Node.nodes = {
523 'root': Node([], 'root.org'),
524 'gin': Node(
525 [], str(pathlib.Path('subfolder') / 'deep' / 'gin.org')),
526 }
527
528 # root links to gin
529 sut = Exporter.generate_href_value('gin', 'root')
530 self.assertEqual(sut, 'subfolder/deep/gin.html')
531
532 def test_neighbors_in_subs_one_level(self):
533 """Target and start in different subfolders on same level"""
534 Node.nodes = {
535 'tonic': Node(
536 [], str(pathlib.Path('subFoo') / 'tonic.org')),
537 'gin': Node(
538 [], str(pathlib.Path('subBar') / 'gin.org')),
539 }
540
541 # tonic links to gin
542 sut = Exporter.generate_href_value('gin', 'tonic')
543 self.assertEqual(sut, '../subBar/gin.html')
544
545 def test_neighbors_in_subs_three_level(self):
546 """Target and start in different subfolders on same level"""
547 Node.nodes = {
548 'tonic': Node([], str(pathlib.Path('subFoo') /
549 'cocktail' / 'bar' / 'tonic.org')),
550 'gin': Node([], str(pathlib.Path('subBar') /
551 'snow' / 'white' / 'gin.org')),
552 }
553
554 # tonic links to gin
555 sut = Exporter.generate_href_value('gin', 'tonic')
556 self.assertEqual(sut, '../../../subBar/snow/white/gin.html')
557
558 def test_no_start(self):
559 """Target but no start node.
560
561 This is the case when using the function while generating index.html.
562 """
563 Node.nodes = {
564 'root': Node([], 'root.org'),
565 'gin': Node([], 'sub/folder/gin.org'),
566 }
567
568 sut = Exporter.generate_href_value('root', None)
569 self.assertEqual(sut, 'root.html')
570
571 sut = Exporter.generate_href_value('gin', None)
572 self.assertEqual(sut, 'sub/folder/gin.html')
573
574
575 class ParsedElements(pyfakefs_ut.TestCase):
576 """Test resulting elements list in Node instance.
577
578 Some related errors occurred in the past. The process is more complex then
579 it looks in the first place. A node with subheadings contain multiple
580 orgparse objects. Gluing them together to one list of elements brings
581 the complexity into the process that need to get tested.
582
583 Dev note (2025-12, buhtz): More related to Nodes class (content.py).
584 """
585
586 # pylint: disable=protected-access
587
588 def test_simple(self):
589 """Node with two paragraphs and one heading"""
590 self.maxDiff = None
591
592 sut = Node.nodes['1234']._elements # simple.org
593
594 self.assertEqual(sut[0], elements.Paragraph(['erster absatz']))
595 self.assertEqual(sut[1], elements.Heading('* Heading A'))
596 self.assertEqual(sut[2], elements.Paragraph(['zweiter absatz']))
597
598 def test_complex(self):
599 """Node with an IDed heading"""
600 self.maxDiff = None
601
602 sut = Node.nodes['9876']._elements # complex.org
603
604 self.assertEqual(sut[0], elements.Paragraph(['absatz eins']))
605 self.assertEqual(sut[1], elements.Heading('* A Heading'))
606 self.assertEqual(sut[2], elements.Paragraph(['absatz zwei']))
607
608 self.assertIsInstance(sut[3], Node)
609 self.assertEqual(sut[3][0].runs, ['Heading B mit ID'])
610 self.assertEqual(sut[3][0].level, 2)
611 self.assertIsNotNone(sut[3][0].anchor)
612 self.assertEqual(sut[3][1], elements.Paragraph(['absatz drei']))
613
614 self.assertEqual(sut[4], elements.Heading('* Heading C'))
615 self.assertEqual(sut[5], elements.Paragraph(['absatz vier']))
616
617 self.assertEqual(len(sut), 6)
618 self.assertEqual(len(sut[3]), 2)
619
620 @classmethod
621 def setUpClass(cls):
622 """Create a folder with three org files."""
623 Node.nodes = {}
624 Node.heading_ids = {}
625 Node.backlinks = {}
626 Node.index_data = {
627 Node.IDX_ALL: defaultdict(list),
628 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
629 }
630
631 # pylint: disable-next=no-member
632 cls.setUpClassPyfakefs(allow_root_user=False)
633 cls.input_dir = pathlib.Path('/org')
634 cls.input_dir.mkdir()
635 cls._create_files()
636 cls.reader = Reader(cls.input_dir)
637 cls.reader.read_org_files()
638
639 @classmethod
640 def _create_files(cls):
641 with (cls.input_dir / 'simple.org').open('w', 'utf-8') as handle:
642 content = [
643 ':PROPERTIES:',
644 ':ID: 1234',
645 ':END:',
646 '#+title: simple',
647 'erster absatz',
648 '* Heading A',
649 'zweiter absatz',
650 ]
651
652 handle.write('\n'.join(content))
653
654 with (cls.input_dir / 'complex.org').open('w', 'utf-8') as handle:
655 content = [
656 ':PROPERTIES:',
657 ':ID: 9876',
658 ':END:',
659 '#+title: complex',
660 '#+date: [2022-04-03 So 22:55]',
661 '#+filetags: Zwei',
662 'absatz eins',
663 '* A Heading',
664 'absatz zwei',
665 '* Heading B mit ID',
666 ':PROPERTIES:',
667 ':ID: 1357',
668 ':END:',
669 'absatz drei',
670 '* Heading C',
671 'absatz vier'
672 ]
673
674 handle.write('\n'.join(content))
675
676
677 class RealFiles(pyfakefs_ut.TestCase):
678 """Create real org files in a virtual file system."""
679
680 # pylint: disable=protected-access
681
682 def setUp(self):
683 """Create a folder with three org files."""
684 Node.nodes = {}
685 Node.heading_ids = {}
686 Node.backlinks = {}
687 Node.index_data = {
688 Node.IDX_ALL: defaultdict(list),
689 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
690 }
691
692 self.setUpPyfakefs(allow_root_user=False)
693 self.input_dir = pathlib.Path('/org')
694 self.input_dir.mkdir()
695
696 def _create_files(self, fn_idx=None):
697 """Create files in the (virtual) file system"""
698
699 if not fn_idx:
700 self._create_files([
701 ('test1.org', 0),
702 ('test2.org', 1),
703 ('killme.org', 2),
704 ('titles.org', 3),
705 ('email.org', 4)
706 ])
707
708 return
709
710 for fn, idx in fn_idx:
711 with (self.input_dir / fn).open('w', 'utf-8') as handle:
712 handle.write(inspect.cleandoc(org_raw_content[idx]))
713
714 def test_setup(self):
715 """Setup pyfakefs."""
716
717 self._create_files()
718 reader = Reader(self.input_dir)
719 reader.read_org_files()
720
721 # 3 nodes
722 expect = {
723 'd197c651-f6c1-4e00-8d8e-ef13adac16e2': 'test1.org',
724 'b0fc62f1-2926-4eec-a654-eab8fcea46d9': 'test2.org',
725 '4a2f8510-f57e-468e-9832-8ddecd3335ac': 'killme.org',
726 '7a2f8517-f57e-868e-9832-8ddecd3335ac': 'titles.org',
727 '1a2f3456-f57e-868e-9832-8ddecd3335xy': 'email.org'
728 }
729 self.assertEqual(len(Node.nodes), len(expect))
730
731 for orgid, expected_node in expect.items():
732 self.assertEqual(
733 Node.nodes[orgid].filename,
734 expected_node
735 )
736
737 @mock.patch('uuid.uuid4')
738 def test_no_mathjax(self, mock_uuid):
739 """No MathJax if no math class is in HTML"""
740 self._create_files([('titles.org', 3)])
741 mock_uuid.return_value = '091827465'
742
743 reader = Reader(self.input_dir)
744 reader.read_org_files()
745
746 exp = Exporter(pathlib.Path.cwd() / 'out')
747
748 html = exp._as_html(list(Node.nodes.values())[0], [])
749
750 self.assertFalse('MathJax' in html)
751
752 @mock.patch('uuid.uuid4')
753 def test_mathjax_inline(self, mock_uuid):
754 """MathJax because math class is in HTML"""
755 self._create_files([('inline.org', 5)])
756 mock_uuid.return_value = '091827465'
757
758 reader = Reader(self.input_dir)
759 reader.read_org_files()
760
761 exp = Exporter(pathlib.Path.cwd() / 'out')
762
763 html = exp._as_html(list(Node.nodes.values())[0], [])
764
765 self.assertTrue('MathJax' in html)
766
767 @mock.patch('uuid.uuid4')
768 def test_mathjax_display(self, mock_uuid):
769 """MathJax because math class is in HTML"""
770 self._create_files([('display.org', 6)])
771 mock_uuid.return_value = '091827465'
772
773 reader = Reader(self.input_dir)
774 reader.read_org_files()
775
776 exp = Exporter(pathlib.Path.cwd() / 'out')
777
778 html = exp._as_html(list(Node.nodes.values())[0], [])
779
780 self.assertTrue('MathJax' in html)
781
782 @mock.patch('uuid.uuid4')
783 def test_mathjax_mixed(self, mock_uuid):
784 """MathJax because math class is in HTML"""
785 self._create_files([('mixedmath.org', 7)])
786 mock_uuid.return_value = '091827465'
787
788 reader = Reader(self.input_dir)
789 reader.read_org_files()
790
791 exp = Exporter(pathlib.Path.cwd() / 'out')
792
793 html = exp._as_html(list(Node.nodes.values())[0], [])
794
795 self.assertTrue('MathJax' in html)
796
797 def test_inline_comment(self):
798 """Inline comment"""
799 self.maxDiff = None
800 self._create_files([('test1.org', 0)])
801
802 reader = Reader(self.input_dir)
803 reader.read_org_files()
804
805 self.assertEqual(len(Node.nodes), 1)
806 node = list(Node.nodes.values())[0]
807
808 self.assertEqual(node.title_org, 'hyperorg_unittest_1')
809 self.assertEqual(len(node), 2)
810
811 def test_block_comment(self):
812 """Block comment"""
813 # ('test2.org', 1),
814 self._create_files([('test2.org', 1)])
815 self.maxDiff = None
816 reader = Reader(self.input_dir)
817 reader.read_org_files()
818
819 self.assertEqual(len(Node.nodes), 1)
820 node = list(Node.nodes.values())[0]
821
822 self.assertEqual(node.title_org, 'hyperorg_unittest_2')
823 self.assertEqual(len(node), 1)
824
825 @mock.patch('uuid.uuid4')
826 def test_subtree_html_output(self, mock_uid):
827 """Node with a subtree in it.
828
829 Nodes with a subtree/heading having it's own OrgId resulting in
830 a Content instance having a Content instances as child element.
831 """
832 self._create_files([('killme.org', 2)])
833 self.maxDiff = None
834
835 mock_uid.return_value = 'x73902y'
836
837 reader = Reader(self.input_dir)
838 reader.read_org_files()
839
840 expected_html = '\n'.join([
841 '<header>',
842 '<div id="hyperorg-ctime">',
843 '<span class="label">date:</span>',
844 '&nbsp;<time>Sun Apr 3 22:55:00 2022</time>',
845 '</div>',
846 '<br />',
847 '<div><span class="label">filetags:</span>',
848 '&nbsp;Zwei</div>',
849 '</header>',
850 '<p>Governments of the Industrial World,</p>',
851 '<h2>Heading</h2>',
852 '<p>you weary giants of flesh and steel,</p>',
853 '<h2 id="x73902y">Child</h2>',
854 '<p>I come from Cyberspace, the new home of Mind,</p>',
855 '<h2>One more</h2>',
856 '<p>On behalf of the future, I ask you of '
857 'the past to leave us alone.</p>',
858 ])
859
860 node = Node.nodes['4a2f8510-f57e-468e-9832-8ddecd3335ac']
861 exp = Exporter(pathlib.Path('/out'))
862 html = exp._as_html(node, [])
863
864 self.assertEqual(
865 unify_html(extract_html_hyperorg_content(html)),
866 unify_html(expected_html)
867 )
868
869 def test_subtree_meta_fields_inherit(self):
870 """Parent nodes meta data inherits to child nodes.
871
872 The meta data in child nodes not used in the visual (HTML) output of
873 the node. But it is used to but this child node on the right index
874 (e.g. index.html).
875 """
876
877 self._create_files([('killme.org', 2)])
878 self.maxDiff = None
879
880 reader = Reader(self.input_dir)
881 reader.read_org_files()
882
883 self.assertEqual(len(Node.nodes), 1)
884 self.assertEqual(len(Node.heading_ids), 1)
885
886 # parent node
887 node = list(Node.nodes.values())[0]
888
889 # child node
890 child = list(Node.heading_ids.values())[0][1]
891 child = node[child]
892
893 self.assertEqual(node._meta, child._meta)
894
895 def test_href_value_node(self):
896 """a-tag href-attribute value for a simple node
897 """
898
899 self._create_files([('test1.org', 0), ('test2.org', 1)])
900 reader = Reader(self.input_dir)
901 reader.read_org_files()
902
903 orgid = 'b0fc62f1-2926-4eec-a654-eab8fcea46d9'
904
905 self.assertEqual(
906 Exporter.generate_href_value(
907 orgid, 'd197c651-f6c1-4e00-8d8e-ef13adac16e2'),
908 'test2.html')
909
910 @mock.patch('uuid.uuid4')
911 def test_href_value_subheading(self, mock_uuid):
912 """href-attribute value for a nodes subheading
913
914 See `Content` for more details. A heading with its own OrgId results
915 in a ``Content`` instance as a child element of a usual ``Content``.
916 """
917 self._create_files([('killme.org', 2)])
918 mock_uuid.return_value = '091827465'
919 reader = Reader(self.input_dir)
920 reader.read_org_files()
921
922 subheading_id = '95c99140-f044-450d-b631-6a5ff7608b2b'
923
924 # link to subheading
925 self.assertEqual(
926 Exporter.generate_href_value(subheading_id, None),
927 'killme.html#091827465')
928
929 @mock.patch('uuid.uuid4')
930 def test_alias_title_meta(self, mock_uuid):
931 """Alias titles as meta fields.
932 """
933 self.maxDiff = None
934 self._create_files([('titles.org', 3)])
935 mock_uuid.return_value = '091827465'
936
937 reader = Reader(self.input_dir)
938 reader.read_org_files()
939 exp = Exporter(pathlib.Path.cwd() / 'out')
940
941 orgid = '7a2f8517-f57e-868e-9832-8ddecd3335ac'
942
943 expected = '''
944 <h1>Aliases node</h1>
945 <section>
946 <header>
947 <div id="hyperorg-ctime">
948 <span class="label">date:</span>
949 &nbsp;<time>Sun Apr 3 22:55:00 2022</time>
950 </div>
951 <br />
952 <div>
953 <span class="label">Alias:</span>
954 &nbsp;aliasnode
955 </div>
956 <div>
957 <span class="label">Alias:</span>
958 &nbsp;node with alias
959 </div>
960 <div><span class="label">filetags:</span>
961 &nbsp;"Drei 3"</div>
962 </header>
963 <h2>Foo</h2>
964 <p>bar</p>
965 <h2 id="091827465">Bar</h2>
966 <header>
967 <div>
968 <span class="label">Alias:</span>
969 &nbsp;ein bar alias
970 </div>
971 <div>
972 <span class="label">Alias:</span>
973 &nbsp;again
974 </div>
975 </header>
976 <p>foo</p>
977 </section>
978 '''
979
980 html = exp._as_html(Node.nodes[orgid], [])
981 html = extract_html_hyperorg_content(html, 'main')
982
983 self.assertEqual(unify_html(html), unify_html(expected))
984
985 @mock.patch('uuid.uuid4')
986 @mock.patch('hyperorg.exporter.secrets.token_hex')
987 def test_index_all_title_types(self, mock_token, mock_uuid):
988 """Index with all types of titles.
989
990 Node titles, alias titles and the same for subheadings.
991 """
992
993 self.maxDiff = None
994 self._create_files()
995
996 mock_uuid.side_effect = ['uuid001', 'uuid002']
997 mock_token.side_effect = [
998 f'index{letter}' for letter in list('ABCEHKNXXXXXXXXXXXXX')
999 ] # "X" because of file-tag based indexes
1000
1001 reader = Reader(self.input_dir)
1002 reader.read_org_files()
1003
1004 exp = Exporter(pathlib.Path.cwd() / 'out')
1005 exp.export_to_html()
1006
1007 fp = pathlib.Path.cwd() / 'out' / 'index.html'
1008
1009 # index file created
1010 self.assertTrue(fp.exists())
1011
1012 # get file content
1013 with fp.open('r', encoding='utf-8') as handle:
1014 html = handle.read()
1015
1016 html = extract_html_hyperorg_content(
1017 html, ('main id="hyperorg-index"', 'main'))
1018
1019 expected = '''
1020 <h1>Node index</h1>
1021 <div class="hyperorg-index__letter-nav">
1022 <a href="#indexA">A</a>
1023 <a href="#indexB">B</a>
1024 <a href="#indexC">C</a>
1025 <a href="#indexE">E</a>
1026 <a href="#indexH">H</a>
1027 <a href="#indexK">K</a>
1028 <a href="#indexN">N</a>
1029 </div>
1030 <hr />
1031 <article class="hyperorg-index" id="indexA">
1032 <h2>A</h2>
1033 <div><a class="hyperorg-index__toplink" href="#top">Back
1034 to Top</a>
1035 <ul>
1036 <li><a href="titles.html">Aliases node</a></li>
1037 <li><a href="titles.html#uuid002"><em>again</em>
1038 </a></li>
1039 <li><a href="titles.html"><em>aliasnode</em></a></li>
1040 </ul>
1041 </div>
1042 </article>
1043 <hr />
1044 <article class="hyperorg-index" id="indexB">
1045 <h2>B</h2>
1046 <div><a class="hyperorg-index__toplink" href="#top">Back
1047 to Top</a>
1048 <ul>
1049 <li><a href="titles.html#uuid002">Bar</a></li>
1050 </ul>
1051 </div>
1052 </article>
1053 <hr />
1054 <article class="hyperorg-index" id="indexC">
1055 <h2>C</h2>
1056 <div><a class="hyperorg-index__toplink" href="#top">Back
1057 to Top</a>
1058 <ul>
1059 <li><a href="killme.html#uuid001">Child</a></li>
1060 </ul>
1061 </div>
1062 </article>
1063 <hr />
1064 <article class="hyperorg-index" id="indexE">
1065 <h2>E</h2>
1066 <div><a class="hyperorg-index__toplink" href="#top">Back
1067 to Top</a>
1068 <ul>
1069 <li><a href="email.html">Email</a></li>
1070 <li><a href="titles.html#uuid002"><em>ein bar
1071 alias</em></a></li>
1072 </ul>
1073 </div>
1074 </article>
1075 <hr />
1076 <article class="hyperorg-index" id="indexH">
1077 <h2>H</h2>
1078 <div><a class="hyperorg-index__toplink" href="#top">Back
1079 to Top</a>
1080 <ul>
1081 <li><a href="test1.html">hyperorg_unittest_1</a></li>
1082 <li><a href="test2.html">hyperorg_unittest_2</a></li>
1083 </ul>
1084 </div>
1085 </article>
1086 <hr />
1087 <article class="hyperorg-index" id="indexK">
1088 <h2>K</h2>
1089 <div><a class="hyperorg-index__toplink" href="#top">Back
1090 to Top</a>
1091 <ul>
1092 <li><a href="killme.html">killme</a></li>
1093 </ul>
1094 </div>
1095 </article>
1096 <hr />
1097 <article class="hyperorg-index" id="indexN">
1098 <h2>N</h2>
1099 <div><a class="hyperorg-index__toplink" href="#top">Back
1100 to Top</a>
1101 <ul>
1102 <li><a href="titles.html"><em>node with alias</em></a></li>
1103 </ul>
1104 </div>
1105 </article>
1106 '''
1107
1108 self.assertEqual(
1109 unify_html(html),
1110 unify_html(expected)
1111 )
1112
1113 @mock.patch('uuid.uuid4')
1114 def test_html_entities(self, mock_uuid):
1115 """Converting HTML entities (e.g. angle bracktes).
1116
1117 Characters like '<' need to converted into '&lt;' in HTML output.
1118 """
1119 self.maxDiff = None
1120 self._create_files([('titles.org', 3), ('email.org', 4)])
1121 mock_uuid.return_value = '091827465'
1122
1123 escaped_html = '&amp;&lt;&gt;&quot;&#x27;'
1124 expected = f'''
1125 <header><div>
1126 <span class="label">filetags:</span>&nbsp;MyTag</div>
1127 </header>
1128 <p>Angle brackets: Entry &lt;[email protected]&gt;</p>
1129 <h2>{escaped_html}</h2>
1130 <ul>
1131 <li>{escaped_html}</li>
1132 </ul>
1133 <p>{escaped_html}</p>
1134 <p><a href="titles.html">{escaped_html}</a></p>
1135 <p><a href="titles.html">TITLE</a></p>
1136 <p>Bold <strong>{escaped_html}</strong></p>
1137 <p>Italic <em>{escaped_html}</em></p>
1138 <p>Underline <u>{escaped_html}</u></p>
1139 <p>Verbatim <code class="verbatim">{escaped_html}</code></p>
1140 <p>Code <code>{escaped_html}</code></p>
1141 '''
1142
1143 reader = Reader(self.input_dir)
1144 reader.read_org_files()
1145
1146 exp = Exporter(pathlib.Path.cwd() / 'out')
1147
1148 html = exp._as_html(
1149 Node.nodes['1a2f3456-f57e-868e-9832-8ddecd3335xy'], [])
1150 html = extract_html_hyperorg_content(html, 'section')
1151
1152 self.assertEqual(unify_html(html), unify_html(expected))
1153
1154 def test_node_nav(self):
1155 """Navigation bar in nodes."""
1156 self.maxDiff = None
1157
1158 self._create_files([('killme.org', 0)])
1159
1160 expected = '''
1161 <ul>
1162 <li><a href="index.html">Index</a> (1)</li>
1163 <li><a href="index__filetag_Drei_3.html">Drei 3</a> (1)</li>
1164 <li><a href="index__filetag_MyTag.html">MyTag</a> (1)</li>
1165 <li><a href="index__filetag_Zwei.html">Zwei</a> (1)</li>
1166 </ul>'''
1167
1168 reader = Reader(self.input_dir)
1169 reader.read_org_files()
1170
1171 exp = Exporter(pathlib.Path.cwd() / 'out')
1172
1173 index_items = exp._compute_indexes()
1174
1175 html = exp._as_html(list(Node.nodes.values())[0], index_items)
1176 html = extract_html_hyperorg_content(html, 'nav')
1177
1178 self.assertEqual(unify_html(html), unify_html(expected))
1179
1180
1181 class Subfolders(pyfakefs_ut.TestCase):
1182 """Org files in sub foldres"""
1183 # pylint: disable=protected-access
1184
1185 def setUp(self):
1186 Node.nodes = {}
1187 Node.heading_ids = {}
1188 Node.backlinks = {}
1189 Node.index_data = {
1190 Node.IDX_ALL: defaultdict(list),
1191 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
1192 }
1193
1194 self.setUpPyfakefs(allow_root_user=False)
1195 self.input_dir = pathlib.Path('/org')
1196 self.input_dir.mkdir()
1197
1198 fp = self.input_dir / 'root.org'
1199 with fp.open('w', encoding='utf-8') as handle:
1200 handle.write(':PROPERTIES:\n')
1201 handle.write(':ID: 01root\n')
1202 handle.write(':END:\n')
1203 handle.write('#+title: root\n')
1204 handle.write('paragraph [[id:02apple][Apfel]]\n')
1205 handle.write('[[id:03banana][Ban]]\n')
1206 handle.write('[[id:04gin][gin]]\n')
1207
1208 fp = self.input_dir / 'subfolder' / 'apple.org'
1209 fp.parent.mkdir()
1210 with fp.open('w', encoding='utf-8') as handle:
1211 handle.write(':PROPERTIES:\n')
1212 handle.write(':ID: 02apple\n')
1213 handle.write(':END:\n')
1214 handle.write('#+title: apple\n')
1215 handle.write('paragraph')
1216
1217 fp = self.input_dir / 'subfolder' / 'banana.org'
1218 with fp.open('w', encoding='utf-8') as handle:
1219 handle.write(':PROPERTIES:\n')
1220 handle.write(':ID: 03banana\n')
1221 handle.write(':END:\n')
1222 handle.write('#+title: banana\n')
1223 handle.write('paragraph')
1224
1225 fp = self.input_dir / 'subfolder' / 'deep' / 'gin.org'
1226 fp.parent.mkdir()
1227 with fp.open('w', encoding='utf-8') as handle:
1228 handle.write(':PROPERTIES:\n')
1229 handle.write(':ID: 04gin\n')
1230 handle.write(':END:\n')
1231 handle.write('#+title: gin\n')
1232 handle.write('paragraph [[id:01root][root]]')
1233
1234 def test_file_folder_structure(self):
1235 """Created HTML in correct folder structure."""
1236 reader = Reader(self.input_dir)
1237 reader.read_org_files()
1238
1239 out_dir = self.input_dir.parent / 'out'
1240 exp = Exporter(out_dir)
1241 exp.export_to_html()
1242
1243 expect = [
1244 '/out/subfolder',
1245 '/out/subfolder/deep',
1246 '/out/root.html',
1247 '/out/subfolder/apple.html',
1248 '/out/subfolder/banana.html',
1249 '/out/subfolder/deep/gin.html',
1250 ]
1251
1252 sut = list(out_dir.glob('**/*'))
1253
1254 for path in expect:
1255 self.assertIn(pathlib.Path(path), sut)
1256
1257 def test_root(self):
1258 """Created HTML root node."""
1259 reader = Reader(self.input_dir)
1260 reader.read_org_files()
1261
1262 out_dir = self.input_dir.parent / 'out'
1263 exp = Exporter(out_dir)
1264 exp.export_to_html()
1265
1266 # Root node in root folder
1267 sut = (out_dir / 'root.html').read_text()
1268 sut = sut[:sut.index('<h2>Backlinks</h2>')]
1269
1270 expect = [
1271 'href="subfolder/apple.html"',
1272 'href="subfolder/banana.html"',
1273 'href="subfolder/deep/gin.html"',
1274 ]
1275
1276 for exp in expect:
1277 self.assertIn(exp, sut)
1278
1279
1280 class Index(unittest.TestCase):
1281 """Generation of index.html"""
1282
1283 # pylint: disable=protected-access
1284
1285 def setUp(self):
1286 Node.nodes = {}
1287 Node.heading_ids = {}
1288 Node.index_data = {
1289 Node.IDX_ALL: defaultdict(list),
1290 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
1291 }
1292
1293 try:
1294 # Patching meta data for <head> tag won't has an effect
1295 # because the template is generated only once (in the first test)
1296 # and then reused.
1297 # This force re-generating every time and prevent reusing.
1298 del Exporter._template_index
1299 except AttributeError:
1300 pass
1301
1302 @mock.patch('hyperorg.exporter.secrets.token_hex')
1303 def test_node_index_to_html_body(self, mock_token):
1304 """Node index dict as HTML. """
1305
1306 mock_token.side_effect = [
1307 f'index{letter}' for letter in list('BG')
1308 ]
1309
1310 self.maxDiff = None
1311 with mock.patch('pathlib.Path.mkdir'):
1312 exp = Exporter(pathlib.Path())
1313
1314 Node.nodes['a'] = Node(['#+title: Goofy'], '01goofy.org')
1315 Node.nodes['b'] = Node(['#+title: Gant'], '02gant.org', ['Gant'])
1316 Node.nodes['c'] = Node(['#+title: Bar'], '9bar.org')
1317
1318 nav, body = exp._node_index_to_html_body({
1319 'G': [
1320 ('Goofy', 'a', False),
1321 ('Gant', 'b', True)
1322 ],
1323 'B': [
1324 ('Bar', 'c', False)
1325 ]
1326 })
1327
1328 # navigation (sorted)
1329 self.assertEqual(
1330 unify_html(nav),
1331 '<a href="#indexB">B</a><a href="#indexG">G</a>')
1332
1333 # body (sorted titles)!
1334 expected_body = \
1335 '<hr /><article class="hyperorg-index" id="indexB">' \
1336 '<h2>B</h2>' \
1337 '<div>' \
1338 '<a class="hyperorg-index__toplink" href="#top">' \
1339 'Back to Top</a>' \
1340 '<ul><li><a href="9bar.html">Bar</a></li></ul>' \
1341 '</div></article><hr />' \
1342 '<article class="hyperorg-index" id="indexG">' \
1343 '<h2>G</h2>' \
1344 '<div>' \
1345 '<a class="hyperorg-index__toplink" href="#top">' \
1346 'Back to Top</a>' \
1347 '<ul>' \
1348 '<li><a href="02gant.html"><em>Gant</em></a></li>' \
1349 '<li><a href="01goofy.html">Goofy</a></li>' \
1350 '</ul>' \
1351 '</div>' \
1352 '</article>'
1353 self.assertEqual(unify_html(body), expected_body)
1354
1355 @mock.patch('hyperorg.meta', {'Project-URL': {'homepage': 'https://R.i'}})
1356 @mock.patch('hyperorg.__name__', 'BarFoo')
1357 @mock.patch('hyperorg.__version__', '1984')
1358 def test_html_template_index(self):
1359 """HTML template for index."""
1360 self.maxDiff = None
1361 expected = '''
1362 <!DOCTYPE html>
1363 <html lang="{{ language }}">
1364 <head>
1365 {{ meta_generator }}
1366 <meta charset="UTF-8" />
1367 <link rel="stylesheet" href="style.css" />
1368 <title>Node index</title>
1369 </head>
1370 <body id="top">
1371 <nav>{{ node nav }}</nav>
1372 <main id="hyperorg-index">
1373 <h1>Node index</h1>
1374 <div class="hyperorg-index__letter-nav">
1375 {{ index letter nav }}
1376 </div>
1377 {{ body }}
1378 </main>
1379 <footer>
1380 {{ footer }}
1381 </footer>
1382 </body>
1383 </html>
1384 '''
1385 expected = inspect.cleandoc(expected)
1386 expected = expected.replace(
1387 '{{ language }}',
1388 locale.getlocale()[0].split('_')[0]
1389 )
1390 expected = expected.replace(
1391 '{{ meta_generator }}',
1392 '<meta name="generator" content="BarFoo" />\n'
1393 ' <meta name="generator_version" content="1984" />\n'
1394 ' <meta name="generator_website" content="https://R.i" />'
1395 )
1396
1397 html = Exporter._get_html_template_index()
1398
1399 self.assertEqual(expected, html)
1400
1401 @mock.patch('hyperorg.exporter.secrets.token_hex')
1402 def test_index_html(self, mock_token): # noqa: PLR0915
1403 """Test index.html
1404
1405 Dev note: Separate it into multiple tests.
1406 """
1407
1408 # pylint: disable=too-many-statements
1409
1410 mock_token.side_effect = [
1411 f'index{letter}' for letter in list('BRTWAGAGRABT23456')
1412 ]
1413
1414 Node.index_data = {
1415 Node.IDX_ALL: {
1416 'B': [('Title', 0, True) for _ in range(4)],
1417 'R': [('Title', 0, True) for _ in range(3)],
1418 'T': [('Title', 0, True) for _ in range(1)],
1419 'W': [('Title', 0, True) for _ in range(2)],
1420 },
1421 Node.IDX_FILETAG: {
1422 Node.IDX_NO_TAG: {
1423 'B': [('Title', 0, True) for _ in range(2)],
1424 'T': [('Title', 0, True) for _ in range(4)],
1425 },
1426 'Tag': {
1427 'G': [('Title', 0, True) for _ in range(10)],
1428 'A': [('Title', 0, True) for _ in range(5)],
1429 },
1430 'Foo and Bar': {
1431 'A': [('Title', 0, True) for _ in range(5)],
1432 'R': [('Title', 0, True) for _ in range(3)],
1433 'G': [('Title', 0, True) for _ in range(1)],
1434 },
1435 'Alice': {
1436 'A': [('Title', 0, True) for _ in range(4)],
1437 },
1438
1439 }
1440 }
1441
1442 index_items = [
1443 ('Index', 'index', 8),
1444 ('Alice', 'Alice', 4),
1445 ('Tag', 'Tag', 2),
1446 ('(no tags)', '_no_tags_', 2),
1447 ('Foo and Bar', 'Foo_and_Bar', 1)
1448 ]
1449
1450 expected_nav = '''
1451 <ul>
1452 <li><a href="index.html">Index</a> (8)</li>
1453 <li><a href="index__filetag_Alice.html">Alice</a> (4)</li>
1454 <li><a href="index__filetag_Tag.html">Tag</a> (2)</li>
1455 <li><a href="index__filetag__no_tags_.html">(no tags)</a> (2)</li>
1456 <li><a href="index__filetag_Foo_and_Bar.html">Foo and Bar</a> (1)</li>
1457 </ul>'''
1458
1459 out_path = pathlib.Path('out')
1460
1461 with mock.patch('pathlib.Path.mkdir'):
1462 exp = Exporter(out_path)
1463
1464 # ------------------
1465 # --- index.html ---
1466 # ------------------
1467 html_code = exp._node_index_to_html(
1468 Node.index_data[Node.IDX_ALL],
1469 index_items)
1470
1471 main = unify_html(extract_html_hyperorg_content(html_code, 'main'))
1472
1473 # navigation bar
1474 self.assertEqual(
1475 unify_html(expected_nav),
1476 unify_html(extract_html_hyperorg_content(html_code, 'nav'))
1477 )
1478
1479 # letter navigation
1480 expect_letter_nav = [
1481 '<div class="hyperorg-index__letter-nav">',
1482 ' <a href="#indexB">B</a>',
1483 ' <a href="#indexR">R</a>',
1484 ' <a href="#indexT">T</a>', # codespell-ignore
1485 ' <a href="#indexW">W</a>',
1486 '</div>'
1487 ]
1488 expect_letter_nav = '\n'.join(expect_letter_nav)
1489
1490 # codespell-ignore
1491 self.assertIn(unify_html(expect_letter_nav), main)
1492
1493 # section B
1494 expect = '''
1495 <article class="hyperorg-index" id="indexB">
1496 <h2>B</h2>
1497 <div>
1498 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1499 <ul>
1500 <li><a href="None"><em>Title</em></a></li>
1501 <li><a href="None"><em>Title</em></a></li>
1502 <li><a href="None"><em>Title</em></a></li>
1503 <li><a href="None"><em>Title</em></a></li>
1504 </ul>
1505 </div>
1506 </article>
1507 '''
1508 self.assertIn(unify_html(expect), main)
1509
1510 # section R
1511 expect = '''
1512 <article class="hyperorg-index" id="indexR">
1513 <h2>R</h2>
1514 <div>
1515 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1516 <ul>
1517 <li><a href="None"><em>Title</em></a></li>
1518 <li><a href="None"><em>Title</em></a></li>
1519 <li><a href="None"><em>Title</em></a></li>
1520 </ul>
1521 </div>
1522 </article>
1523 '''
1524 self.assertIn(unify_html(expect), main)
1525
1526 # section T
1527 expect = [
1528 '<article class="hyperorg-index" id="indexT">', # codespell-ignore
1529 ' <h2>T</h2>',
1530 ' <div>',
1531 ' <a class="hyperorg-index__toplink" '
1532 'href="#top">Back to Top</a>',
1533 ' <ul>',
1534 ' <li><a href="None"><em>Title</em></a></li>',
1535 ' </ul>',
1536 ' </div>',
1537 '</article>'
1538 ]
1539 expect = '\n'.join(expect)
1540 self.assertIn(unify_html(expect), main)
1541
1542 # section W
1543 expect = '''
1544 <article class="hyperorg-index" id="indexW">
1545 <h2>W</h2>
1546 <div>
1547 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1548 <ul>
1549 <li><a href="None"><em>Title</em></a></li>
1550 <li><a href="None"><em>Title</em></a></li>
1551 </ul>
1552 </div>
1553 </article>
1554 '''
1555 self.assertIn(unify_html(expect), main)
1556
1557 # ------------------
1558 # --- Tag ---
1559 # ------------------
1560 html_code = exp._node_index_to_html(
1561 Node.index_data[Node.IDX_FILETAG]['Tag'],
1562 index_items)
1563
1564 main = unify_html(extract_html_hyperorg_content(html_code, 'main'))
1565
1566 # navigation bar
1567 self.assertEqual(
1568 unify_html(expected_nav),
1569 unify_html(extract_html_hyperorg_content(html_code, 'nav'))
1570 )
1571
1572 # letter navigation
1573 expect_letter_nav = '''
1574 <div class="hyperorg-index__letter-nav">
1575 <a href="#indexA">A</a>
1576 <a href="#indexG">G</a>
1577 </div>
1578 '''
1579
1580 self.assertIn(unify_html(expect_letter_nav), main)
1581
1582 # section A
1583 expect = '''
1584 <article class="hyperorg-index" id="indexA">
1585 <h2>A</h2>
1586 <div>
1587 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1588 <ul>
1589 <li><a href="None"><em>Title</em></a></li>
1590 <li><a href="None"><em>Title</em></a></li>
1591 <li><a href="None"><em>Title</em></a></li>
1592 <li><a href="None"><em>Title</em></a></li>
1593 <li><a href="None"><em>Title</em></a></li>
1594 </ul>
1595 </div>
1596 </article>
1597 '''
1598 self.assertIn(unify_html(expect), main)
1599
1600 # section G
1601 expect = '''
1602 <article class="hyperorg-index" id="indexG">
1603 <h2>G</h2>
1604 <div>
1605 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1606 <ul>
1607 <li><a href="None"><em>Title</em></a></li>
1608 <li><a href="None"><em>Title</em></a></li>
1609 <li><a href="None"><em>Title</em></a></li>
1610 <li><a href="None"><em>Title</em></a></li>
1611 <li><a href="None"><em>Title</em></a></li>
1612 <li><a href="None"><em>Title</em></a></li>
1613 <li><a href="None"><em>Title</em></a></li>
1614 <li><a href="None"><em>Title</em></a></li>
1615 <li><a href="None"><em>Title</em></a></li>
1616 <li><a href="None"><em>Title</em></a></li>
1617 </ul>
1618 </div>
1619 </article>
1620 '''
1621 self.assertIn(unify_html(expect), main)
1622
1623 # ------------------
1624 # --- Foo and Bar ---
1625 # ------------------
1626 html_code = exp._node_index_to_html(
1627 Node.index_data[Node.IDX_FILETAG]['Foo and Bar'],
1628 index_items)
1629
1630 main = unify_html(extract_html_hyperorg_content(html_code, 'main'))
1631
1632 # navigation bar
1633 self.assertEqual(
1634 unify_html(expected_nav),
1635 unify_html(extract_html_hyperorg_content(html_code, 'nav'))
1636 )
1637
1638 # letter navigation
1639 expect_letter_nav = '''
1640 <div class="hyperorg-index__letter-nav">
1641 <a href="#indexA">A</a>
1642 <a href="#indexG">G</a>
1643 <a href="#indexR">R</a>
1644 </div>
1645 '''
1646 self.assertIn(unify_html(expect_letter_nav), main)
1647
1648 # section A
1649 expect = '''
1650 <article class="hyperorg-index" id="indexA">
1651 <h2>A</h2>
1652 <div>
1653 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1654 <ul>
1655 <li><a href="None"><em>Title</em></a></li>
1656 <li><a href="None"><em>Title</em></a></li>
1657 <li><a href="None"><em>Title</em></a></li>
1658 <li><a href="None"><em>Title</em></a></li>
1659 <li><a href="None"><em>Title</em></a></li>
1660 </ul>
1661 </div>
1662 </article>
1663 '''
1664 self.assertIn(unify_html(expect), main)
1665
1666 # section G
1667 expect = '''
1668 <article class="hyperorg-index" id="indexG">
1669 <h2>G</h2>
1670 <div>
1671 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1672 <ul>
1673 <li><a href="None"><em>Title</em></a></li>
1674 </ul>
1675 </div>
1676 </article>
1677 '''
1678 self.assertIn(unify_html(expect), main)
1679
1680 # section R
1681 expect = '''
1682 <article class="hyperorg-index" id="indexR">
1683 <h2>R</h2>
1684 <div>
1685 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1686 <ul>
1687 <li><a href="None"><em>Title</em></a></li>
1688 <li><a href="None"><em>Title</em></a></li>
1689 <li><a href="None"><em>Title</em></a></li>
1690 </ul>
1691 </div>
1692 </article>
1693 '''
1694 self.assertIn(unify_html(expect), main)
1695
1696 # ------------------
1697 # --- Alice ---
1698 # ------------------
1699 html_code = exp._node_index_to_html(
1700 Node.index_data[Node.IDX_FILETAG]['Alice'],
1701 index_items)
1702
1703 main = unify_html(extract_html_hyperorg_content(html_code, 'main'))
1704
1705 # navigation bar
1706 self.assertEqual(
1707 unify_html(expected_nav),
1708 unify_html(extract_html_hyperorg_content(html_code, 'nav'))
1709 )
1710
1711 # letter navigation
1712 expect_letter_nav = '''
1713 <div class="hyperorg-index__letter-nav">
1714 <a href="#indexA">A</a>
1715 </div>
1716 '''
1717 self.assertIn(unify_html(expect_letter_nav), main)
1718
1719 # section A
1720 expect = '''
1721 <article class="hyperorg-index" id="indexA">
1722 <h2>A</h2>
1723 <div>
1724 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1725 <ul>
1726 <li><a href="None"><em>Title</em></a></li>
1727 <li><a href="None"><em>Title</em></a></li>
1728 <li><a href="None"><em>Title</em></a></li>
1729 <li><a href="None"><em>Title</em></a></li>
1730 </ul>
1731 </div>
1732 </article>
1733 '''
1734 self.assertIn(unify_html(expect), main)
1735
1736 # ------------------
1737 # --- no tags ---
1738 # ------------------
1739 html_code = exp._node_index_to_html(
1740 Node.index_data[Node.IDX_FILETAG][Node.IDX_NO_TAG],
1741 index_items)
1742
1743 main = unify_html(extract_html_hyperorg_content(html_code, 'main'))
1744
1745 # navigation bar
1746 self.assertEqual(
1747 unify_html(expected_nav),
1748 unify_html(extract_html_hyperorg_content(html_code, 'nav'))
1749 )
1750
1751 # letter navigation
1752 expect_letter_nav = [
1753 '<div class="hyperorg-index__letter-nav">',
1754 ' <a href="#indexB">B</a>',
1755 ' <a href="#indexT">T</a>', # codespell-ignore
1756 '</div>'
1757 ]
1758 expect_letter_nav = '\n'.join(expect_letter_nav)
1759
1760 self.assertIn(unify_html(expect_letter_nav), main)
1761
1762 # section B
1763 expect = '''
1764 <article class="hyperorg-index" id="indexB">
1765 <h2>B</h2>
1766 <div>
1767 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1768 <ul>
1769 <li><a href="None"><em>Title</em></a></li>
1770 <li><a href="None"><em>Title</em></a></li>
1771 </ul>
1772 </div>
1773 </article>
1774 '''
1775 self.assertIn(unify_html(expect), main)
1776
1777 # section T
1778 expect = [
1779 '<article class="hyperorg-index" id="indexT">', # codespell-ignore
1780 ' <h2>T</h2>',
1781 ' <div>',
1782 ' <a class="hyperorg-index__toplink" '
1783 'href="#top">Back to Top</a>',
1784 ' <ul>',
1785 ' <li><a href="None"><em>Title</em></a></li>',
1786 ' <li><a href="None"><em>Title</em></a></li>',
1787 ' <li><a href="None"><em>Title</em></a></li>',
1788 ' <li><a href="None"><em>Title</em></a></li>',
1789 ' </ul>',
1790 ' </div>',
1791 '</article>'
1792 ]
1793 expect = '\n'.join(expect)
1794
1795 self.assertIn(unify_html(expect), main)
1796
1797 @mock.patch('hyperorg.exporter.secrets.token_hex')
1798 def test_index_with_markup_entry(self, mock_token):
1799 """Index file where one of its entries has a title with markup in it.
1800 """
1801
1802 mock_token.side_effect = [
1803 f'index{letter}' for letter in list('F')
1804 ]
1805
1806 entry = (
1807 [
1808 'Foo ',
1809 textruns.Markup('bar', textruns.Markup.Type.VERBATIM),
1810 ],
1811 0,
1812 True
1813 )
1814 Node.index_data = {
1815 Node.IDX_ALL: {
1816 'F': [entry],
1817 },
1818 Node.IDX_FILETAG: {
1819 Node.IDX_NO_TAG: {
1820 'F': [entry],
1821 },
1822 }
1823 }
1824
1825 index_items = [
1826 ('Index', 'index', 1),
1827 ('(no tags)', '_no_tags_', 1),
1828 ]
1829
1830 out_path = pathlib.Path('out')
1831
1832 with mock.patch('pathlib.Path.mkdir'):
1833 exp = Exporter(out_path)
1834
1835 # ------------------
1836 # --- index.html ---
1837 # ------------------
1838 html_code = exp._node_index_to_html(
1839 Node.index_data[Node.IDX_ALL],
1840 index_items)
1841
1842 main = unify_html(extract_html_hyperorg_content(html_code, 'main'))
1843
1844 # section B
1845 expect = '''
1846 <article class="hyperorg-index" id="indexF">
1847 <h2>F</h2>
1848 <div>
1849 <a class="hyperorg-index__toplink" href="#top">Back to Top</a>
1850 <ul>
1851 <li><a href="None">
1852 <em>Foo <code class="verbatim">bar</code></em>
1853 </a></li>
1854 </ul>
1855 </div>
1856 </article>
1857 '''
1858 self.assertIn(unify_html(expect), main)
1859
1860
1861 class MetaFields(unittest.TestCase):
1862 """Test export of meta fields into HTML"""
1863
1864 # pylint: disable=protected-access
1865
1866 def test_empty(self):
1867 """No meta data."""
1868 node = Node(['#+title: One Two'], '')
1869 self.assertEqual(Exporter._meta_to_html(node), '')
1870
1871 def test_inline_comment_before(self):
1872 """Inline comment before properties"""
1873 self.maxDiff = None
1874
1875 node = Node([
1876 '# inline comment',
1877 '#+title: Titel',
1878 'body'], '')
1879
1880 self.assertEqual(len(node), 1)
1881 self.assertEqual(node.title_org, 'Titel')
1882 self.assertEqual(node[0][0], 'body')
1883
1884 def test_block_comment_before(self):
1885 """Block comment before properties"""
1886 self.maxDiff = None
1887
1888 node = Node([
1889 '#+begin_comment',
1890 'block comment',
1891 '#+end_comment',
1892 '#+title: Titel',
1893 'body'], '')
1894 self.assertEqual(len(node), 1)
1895 self.assertEqual(node.title_org, 'Titel')
1896 self.assertEqual(node[0][0], 'body')
1897
1898 def test_exclude_tags(self):
1899 """Exclude tags."""
1900 self.maxDiff = None
1901
1902 node = Node([
1903 '#+filetags: One "Two zwei" Three',
1904 '#+foo: Bar bar',
1905 '#+in: Blue',
1906 '#+out: Red'], '')
1907
1908 self.assertEqual(
1909 unify_html(Exporter._meta_to_html(node,
1910 exclude_fields=['out', 'foo'])),
1911 unify_html('''
1912 <div>
1913 <span class="label">filetags:</span>
1914 &nbsp;One "Two zwei" Three</div>
1915 <div>
1916 <span class="label">in:</span>
1917 &nbsp;Blue</div>'''))
1918
1919 def test_exclude_tags_not_present(self):
1920 """Exclude tag that is not present."""
1921 self.maxDiff = None
1922
1923 node = Node([
1924 '#+in: Blue',
1925 '#+out: Red'], '')
1926
1927 self.assertEqual(
1928 unify_html(Exporter._meta_to_html(node,
1929 exclude_fields=['out', 'foo'])),
1930 unify_html('''
1931 <div>
1932 <span class="label">in:</span>
1933 &nbsp;Blue</div>'''))
1934
1935 def test_filetags(self):
1936 """filetags and others"""
1937 self.maxDiff = None
1938 node = Node([
1939 '#+filetags: One "Two zwei" Three',
1940 '#+foo: Bar bar'], '')
1941 self.assertEqual(
1942 unify_html(Exporter._meta_to_html(node)),
1943 unify_html('''
1944 <div>
1945 <span class="label">filetags:</span>
1946 &nbsp;One "Two zwei" Three</div>
1947 <div>
1948 <span class="label">foo:</span>
1949 &nbsp;Bar bar</div>'''))
1950
1951 def test_locale_conform_datestring(self):
1952 """Datestring"""
1953
1954 # datetime object as value
1955 val_in = datetime.datetime(2021, 11, 28, 16, 20)
1956 val_out = Exporter._as_locale_conform_date_string(val_in)
1957 self.assertEqual(val_out, 'Sun Nov 28 16:20:00 2021')
1958
1959 # This timestamp as a string exists because it wasn't
1960 # parseable by `dateutils.parser.parse()`.
1961 val_in = '2021-11-28 So 16:20'
1962 val_out = Exporter._as_locale_conform_date_string(val_in)
1963 self.assertEqual(val_out, val_out)
1964
1965 # Now with brackets like %U generates them
1966 val_in = '[2021-11-28 So 16:20]'
1967 val_out = Exporter._as_locale_conform_date_string(val_in)
1968 self.assertEqual(val_out, val_out)
1969
1970 def test_one_date_only(self):
1971 """Only on date in meta section.
1972
1973 This date is treated as creation date and placed their.
1974 """
1975 node = Node([], '')
1976 node._meta['Foobar'] = datetime.datetime(2021, 11, 28, 16, 20)
1977 html = unify_html(Exporter._meta_to_html(node))
1978
1979 self.assertEqual(
1980 html,
1981 unify_html('''
1982 <div id="hyperorg-ctime">
1983 <span class="label">Foobar:</span>&nbsp;
1984 <time>Sun Nov 28 16:20:00 2021</time>
1985 </div>
1986 <br />
1987 '''))
1988
1989 def test_m_and_c_date(self):
1990 """Creation and modification date in meta section."""
1991 self.maxDiff = None
1992 node = Node([], '')
1993 node._meta['mtime'] = datetime.datetime(2021, 11, 28, 16, 20)
1994 node._meta['ctime'] = datetime.datetime(2021, 11, 28, 16, 25)
1995
1996 self.assertEqual(
1997 unify_html(Exporter._meta_to_html(node)),
1998 unify_html('''
1999 <div id="hyperorg-mtime">
2000 <span class="label">Modified:</span>&nbsp;
2001 <time>Sun Nov 28 16:20:00 2021</time>
2002 </div>
2003 <div id="hyperorg-ctime">
2004 <span class="label">Created:</span>&nbsp;
2005 <time>Sun Nov 28 16:25:00 2021</time>
2006 </div>
2007 <br />
2008 '''))
2009
2010 def test_m_or_c_and_extra_date(self):
2011 """Unknown dates."""
2012
2013 self.maxDiff = None
2014
2015 # cdate, mdate and extra date
2016 node = Node([], '')
2017 node._meta['mtime'] = datetime.datetime(2021, 11, 28, 16, 20)
2018 node._meta['ctime'] = datetime.datetime(2021, 11, 28, 17, 20)
2019 node._meta['foo'] = datetime.datetime(2021, 11, 28, 18, 20)
2020
2021 self.assertEqual(
2022 unify_html(Exporter._meta_to_html(node)),
2023 unify_html('''
2024 <div id="hyperorg-mtime">
2025 <span class="label">Modified:</span>&nbsp;
2026 <time>Sun Nov 28 16:20:00 2021</time>
2027 </div>
2028 <div id="hyperorg-ctime">
2029 <span class="label">Created:</span>&nbsp;
2030 <time>Sun Nov 28 17:20:00 2021</time>
2031 </div>
2032 <br />
2033 <div>
2034 <span class="label">foo:</span>&nbsp;
2035 <time>Sun Nov 28 18:20:00 2021</time>
2036 </div>
2037 '''))
2038
2039 # cdate and extra date
2040 node = Node([], '')
2041 node._meta['ctime'] = datetime.datetime(2021, 11, 28, 17, 20)
2042 node._meta['foo'] = datetime.datetime(2021, 11, 28, 18, 20)
2043
2044 self.assertEqual(
2045 unify_html(Exporter._meta_to_html(node)),
2046 unify_html('''
2047 <div id="hyperorg-ctime">
2048 <span class="label">Created:</span>&nbsp;
2049 <time>Sun Nov 28 17:20:00 2021</time>
2050 </div>
2051 <br />
2052 <div>
2053 <span class="label">foo:</span>&nbsp;
2054 <time>Sun Nov 28 18:20:00 2021</time>
2055 </div>
2056 '''))
2057
2058 # mdate and extra date
2059 node = Node([], '')
2060 node._meta['mtime'] = datetime.datetime(2021, 11, 28, 16, 20)
2061 node._meta['foo'] = datetime.datetime(2021, 11, 28, 18, 20)
2062
2063 self.assertEqual(
2064 unify_html(Exporter._meta_to_html(node)),
2065 unify_html('''
2066 <div id="hyperorg-mtime">
2067 <span class="label">Modified:</span>&nbsp;
2068 <time>Sun Nov 28 16:20:00 2021</time>
2069 </div>
2070 <br />
2071 <div>
2072 <span class="label">foo:</span>&nbsp;
2073 <time>Sun Nov 28 18:20:00 2021</time>
2074 </div>
2075 '''))
2076
2077 def test_aliases(self):
2078 """Alias titles."""
2079
2080 node = Node([], '', ['Title one', 'A second title'])
2081
2082 self.assertEqual(
2083 unify_html(Exporter._meta_to_html(node)),
2084 unify_html('''
2085 <div>
2086 <span class="label">Alias:</span>&nbsp;Title one
2087 </div>
2088 <div>
2089 <span class="label">Alias:</span>&nbsp;A second title
2090 </div>
2091 ''')
2092 )
2093
2094
2095 class FileOperations(pyfakefs_ut.TestCase):
2096 """Test file operations related to exporting into HTML"""
2097
2098 # pylint: disable=protected-access
2099
2100 def setUp(self):
2101 self.setUpPyfakefs(allow_root_user=False)
2102 Node.nodes = {}
2103 Node.heading_ids = {}
2104 Node.index_data = {
2105 Node.IDX_ALL: defaultdict(list),
2106 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
2107 }
2108
2109 def test_create_output_dir(self):
2110 """Create output folder on demand."""
2111 out_dir = pathlib.Path('output')
2112
2113 # folder doesn't exists
2114 self.assertFalse(out_dir.exists())
2115
2116 exp = Exporter(pathlib.Path('output'))
2117 exp.export_to_html() # creates the folder
2118
2119 # folder exists now
2120 self.assertTrue(out_dir.exists())
2121
2122 def test_create_html_node_files(self):
2123 """Spielwiese."""
2124 Node.nodes = {
2125 '1': Node(['eins'], 'eins.org'),
2126 '2': Node(['zwei'], 'zwei.org'),
2127 }
2128
2129 out_dir = pathlib.Path('output')
2130 exp = Exporter(out_dir)
2131 exp.export_to_html()
2132
2133 for fn in ['eins.html', 'zwei.html']:
2134 self.assertTrue((out_dir / fn).exists())
2135
2136 def test_create_html_index_files(self):
2137 """Spielwiese."""
2138 Node.nodes = {
2139 '1': Node(['eins'], 'eins.org'),
2140 '2': Node(['#+filetags: zwei', 'zwei'], 'zwei.org'),
2141 '3': Node(['#+filetags: zwei', 'drei'], 'drei.org'),
2142 '4': Node(['#+filetags: blau', 'vier'], 'vier.org'),
2143 }
2144
2145 for orgid, node in Node.nodes.items():
2146 Reader._add_to_index_data(node, orgid)
2147
2148 out_dir = pathlib.Path('output')
2149 exp = Exporter(out_dir)
2150 exp.export_to_html()
2151
2152 for fn in ['index.html',
2153 'index__filetag__no_tags_.html',
2154 'index__filetag_zwei.html',
2155 'index__filetag_blau.html']:
2156 self.assertTrue((out_dir / fn).exists(), fn)
2157
2158 def test_delete_old_files(self):
2159 """Delete out-folder before creation."""
2160 out_dir = pathlib.Path('output')
2161
2162 # create "old" files
2163 out_dir.mkdir()
2164 (out_dir / 'foo.bar').touch()
2165 (out_dir / 'ada.html').touch()
2166 att_dir = out_dir / 'attachments'
2167 att_dir.mkdir()
2168 (att_dir / 'foo.png').touch()
2169 (att_dir / 'bar.pdf').touch()
2170
2171 Node.nodes = {
2172 '1': Node(['eins'], 'eins.org'),
2173 '2': Node(['zwei'], 'zwei.org'),
2174 }
2175
2176 exp = Exporter(out_dir)
2177 exp.export_to_html()
2178
2179 fs_elements = [str(i) for i in out_dir.rglob('**/*')]
2180 fs_elements.append(str(out_dir))
2181
2182 self.assertCountEqual(
2183 fs_elements,
2184 [
2185 'output',
2186 'output/pygments.css',
2187 'output/style.css',
2188 'output/eins.html',
2189 'output/zwei.html',
2190 'output/index.html',
2191 # '/output/index__no_tags_.html'
2192 ]
2193 )
2194
2195 def test_dont_delete_org_files(self):
2196 """Don't delete org files."""
2197 out_dir = pathlib.Path('output')
2198
2199 # create files in output dir
2200 out_dir.mkdir()
2201 (out_dir / 'foo.bar').touch()
2202 (out_dir / 'bar.org').touch() # shouldn't be there nor deleted!
2203 (out_dir / 'ada.html').touch()
2204
2205 with self.assertRaises(FileExistsError):
2206 exp = Exporter(out_dir)
2207 exp.export_to_html()
2208
2209 def test_dont_delete_Org_files(self): # pylint: disable=invalid-name
2210 """Don't delete Org files."""
2211 out_dir = pathlib.Path('output')
2212
2213 # create files in output dir
2214 out_dir.mkdir()
2215 (out_dir / 'bar.Org').touch() # shouldn't be there nor deleted!
2216
2217 with self.assertRaises(FileExistsError):
2218 exp = Exporter(out_dir)
2219 exp.export_to_html()
2220
2221 def test_dont_delete_oRg_files(self): # pylint: disable=invalid-name
2222 """Don't delete oRg files."""
2223 out_dir = pathlib.Path('output')
2224
2225 # create files in output dir
2226 out_dir.mkdir()
2227 (out_dir / 'bar.oRg').touch() # shouldn't be there nor deleted!
2228
2229 with self.assertRaises(FileExistsError):
2230 exp = Exporter(out_dir)
2231 exp.export_to_html()
2232
2233 def test_dont_delete_orG_files(self): # pylint: disable=invalid-name
2234 """Don't delete orG files."""
2235 out_dir = pathlib.Path('output')
2236
2237 # create files in output dir
2238 out_dir.mkdir()
2239 (out_dir / 'bar.orG').touch() # shouldn't be there nor deleted!
2240
2241 with self.assertRaises(FileExistsError):
2242 exp = Exporter(out_dir)
2243 exp.export_to_html()
2244
2245 def test_dont_delete_ORG_files(self): # pylint: disable=invalid-name
2246 """Don't delete ORG files."""
2247 out_dir = pathlib.Path('output')
2248
2249 # create files in output dir
2250 out_dir.mkdir()
2251 (out_dir / 'bar.ORG').touch() # shouldn't be there nor deleted!
2252
2253 with self.assertRaises(FileExistsError):
2254 exp = Exporter(out_dir)
2255 exp.export_to_html()
2256
2257
2258 class Attachments(pyfakefs_ut.TestCase):
2259 """Test handling of attachments"""
2260
2261 # pylint: disable=protected-access,missing-function-docstring
2262
2263 def setUp(self):
2264 self.setUpPyfakefs(allow_root_user=False)
2265 Node.nodes = {}
2266 Node.heading_ids = {}
2267 Node.index_data = {
2268 Node.IDX_ALL: defaultdict(list),
2269 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
2270 }
2271
2272 def test_symlink_in_subfolder(self):
2273 indir = pathlib.Path.home() / 'org'
2274 outdir = pathlib.Path.home() / 'html'
2275 target = pathlib.Path('attachments/images/fancy.png')
2276 target_file = indir / target
2277
2278 indir.mkdir(parents=True)
2279 outdir.mkdir(parents=True)
2280 target_file.parent.mkdir(parents=True)
2281 target_file.touch()
2282
2283 self.assertTrue(indir.exists())
2284 self.assertTrue(outdir.exists())
2285 self.assertTrue(target_file.exists())
2286
2287 exporter._establish_file_link(
2288 target=target,
2289 target_is_in=indir,
2290 link_is_in=outdir,
2291 use_hardlinks=False
2292 )
2293
2294 link_file = outdir / target
2295
2296 self.assertTrue(link_file.exists())
2297 self.assertTrue(link_file.is_symlink())
2298
2299 def test_symlink_in_root_folder(self):
2300 indir = pathlib.Path.home() / 'org'
2301 outdir = pathlib.Path.home() / 'html'
2302 target = pathlib.Path('logo.png')
2303 target_file = indir / target
2304
2305 indir.mkdir(parents=True)
2306 outdir.mkdir(parents=True)
2307 target_file.parent.mkdir(parents=True, exist_ok=True)
2308 target_file.touch()
2309
2310 self.assertTrue(indir.exists())
2311 self.assertTrue(outdir.exists())
2312 self.assertTrue(target_file.exists())
2313
2314 exporter._establish_file_link(
2315 target=target,
2316 target_is_in=indir,
2317 link_is_in=outdir,
2318 use_hardlinks=False
2319 )
2320
2321 link_file = outdir / target
2322
2323 self.assertTrue(link_file.is_symlink())
2324
2325 def test_paragraph_with_image_and_link(self):
2326 indir = pathlib.Path.home() / 'org'
2327 outdir = pathlib.Path.home() / 'html'
2328 pic = pathlib.Path('attachments/images/pic.png')
2329 pdf = pathlib.Path('attachments/documents/bug.pdf')
2330 target_pic = indir / pic
2331 target_pdf = indir / pdf
2332
2333 indir.mkdir(parents=True)
2334 outdir.mkdir(parents=True)
2335 target_pic.parent.mkdir(parents=True)
2336 target_pic.touch()
2337 target_pdf.parent.mkdir(parents=True)
2338 target_pdf.touch()
2339
2340 Node.input_dir = indir
2341 Exporter.output_dir = outdir
2342 Exporter.use_hardlinks = False
2343
2344 sut = elements.Paragraph([
2345 'lore ipsum [[attachments/images/pic.png]] and',
2346 ' [[attachments/documents/bug.pdf]] link'
2347 ])
2348
2349 # pre-test
2350 self.assertFalse((outdir / pic).exists())
2351 self.assertFalse((outdir / pdf).exists())
2352
2353 Exporter._paragraph_to_html(sut)
2354
2355 self.assertTrue((outdir / pic).exists())
2356 self.assertTrue((outdir / pdf).exists())
2357
2358 def test_ignore_absolute_pathes(self):
2359 """Files existing outside from the input directory are ignored."""
2360 indir = pathlib.Path.home() / 'org'
2361 outdir = pathlib.Path.home() / 'html'
2362 target_file_a = pathlib.Path.home() / 'extern' / 'A_donot.touch'
2363
2364 # This can't be tested yet because pyfakefs doesn't resolve '~'
2365 # target_file_B = pathlib.Path('~') / 'extern' / 'B_donot.touch'
2366
2367 indir.mkdir(parents=True)
2368 outdir.mkdir(parents=True)
2369 target_file_a.parent.mkdir(parents=True, exist_ok=True)
2370 target_file_a.touch()
2371 # target_file_B.resolve().touch()
2372
2373 self.assertTrue(indir.exists())
2374 self.assertTrue(outdir.exists())
2375 self.assertTrue(target_file_a.exists())
2376
2377 self.assertEqual(len(list(outdir.iterdir())), 0)
2378
2379 for fp in (target_file_a, ):
2380 exporter._establish_file_link(
2381 target=fp,
2382 target_is_in=indir,
2383 link_is_in=outdir,
2384 use_hardlinks=False
2385 )
2386
2387 self.assertEqual(len(list(outdir.iterdir())), 0)
2388
2389 def test_remove_parent_folder_if_target_not_exists(self):
2390 indir = pathlib.Path.home() / 'org'
2391 outdir = pathlib.Path.home() / 'html'
2392 target_file = pathlib.Path('attachment') / 'image' / 'not.exist'
2393
2394 indir.mkdir(parents=True)
2395 outdir.mkdir(parents=True)
2396 target_file.parent.mkdir(parents=True, exist_ok=True)
2397
2398 self.assertTrue(indir.exists())
2399 self.assertTrue(outdir.exists())
2400
2401 self.assertFalse(target_file.exists())
2402
2403 exporter._establish_file_link(
2404 target=target_file,
2405 target_is_in=indir,
2406 link_is_in=outdir,
2407 use_hardlinks=True
2408 )
2409
2410 self.assertFalse((outdir / target_file.parent).exists())
2411 self.assertFalse((outdir / target_file.parent.parent).exists())
2412
2413
2414 class FigureImages(unittest.TestCase):
2415 """Test exporting Images and Figures into HTML"""
2416
2417 # pylint: disable=protected-access,missing-function-docstring
2418 @classmethod
2419 def setUpClass(cls):
2420 def _mock_me(*args, **kwargs): # pylint: disable=unused-argument
2421 pass
2422 cls._establish_file_link = exporter._establish_file_link
2423 exporter._establish_file_link = _mock_me
2424
2425 @classmethod
2426 def tearDownClass(cls):
2427 exporter._establish_file_link = cls._establish_file_link
2428
2429 def setUp(self):
2430 Node.nodes = {}
2431 Node.input_dir = '/'
2432
2433 def test_link_to_image_file_not_figure(self):
2434 """The image file's filename is used as a link label not the image
2435 itself, because "file:" isn't used as a prefix.
2436 """
2437
2438 with mock.patch('pathlib.Path.mkdir'):
2439 exp = Exporter(pathlib.Path())
2440
2441 sut = Node(['[[link.png][label.jpeg]]'], '')
2442
2443 expect = ('<p><a target="_blank" rel="noopener noreferrer" '
2444 'href="link.png">label.jpeg</a></p>')
2445
2446 result = exp._as_html(sut, [])
2447 result = extract_html_hyperorg_content(result)
2448
2449 self.assertEqual(unify_html(result), unify_html(expect))
2450
2451 def test_linked(self):
2452
2453 with mock.patch('pathlib.Path.mkdir'):
2454 exp = Exporter(pathlib.Path())
2455
2456 sut = Node(['[[link.png][file:label.jpeg]]'], '')
2457
2458 expect = '\n'.join([
2459 '<figure>',
2460 ' <a target="_blank" rel="noopener noreferrer" '
2461 'href="link.png">',
2462 ' <img src="label.jpeg" alt="label.jpeg" />',
2463 ' </a>',
2464 '</figure>'
2465 ])
2466
2467 result = exp._as_html(sut, [])
2468 result = extract_html_hyperorg_content(result)
2469
2470 self.assertEqual(unify_html(result), unify_html(expect))
2471
2472 def test_without_caption(self):
2473
2474 with mock.patch('pathlib.Path.mkdir'):
2475 exp = Exporter(pathlib.Path())
2476
2477 sut = Node(['[[image.png]]'], '')
2478
2479 expect = '\n'.join([
2480 '<figure>',
2481 ' <img src="image.png" alt="image.png" />',
2482 '</figure>'
2483 ])
2484
2485 result = exp._as_html(sut, [])
2486 result = extract_html_hyperorg_content(result)
2487
2488 self.assertEqual(unify_html(result), unify_html(expect))
2489
2490 def test_with_caption(self):
2491
2492 with mock.patch('pathlib.Path.mkdir'):
2493 exp = Exporter(pathlib.Path())
2494
2495 sut = Node([
2496 'foobar',
2497 '#+CAPTION: foobar',
2498 '[[image.png]]'
2499 ], '')
2500
2501 expect = '\n'.join([
2502 '<p>foobar</p>',
2503 '<figure>',
2504 ' <img src="image.png" alt="image.png" />',
2505 ' <figcaption>foobar</figcaption>',
2506 '</figure>'
2507 ])
2508
2509 result = exp._as_html(sut, [])
2510 result = extract_html_hyperorg_content(result)
2511
2512 self.assertEqual(unify_html(result), unify_html(expect))
2513
2514 def test_with_attributes(self):
2515
2516 with mock.patch('pathlib.Path.mkdir'):
2517 exp = Exporter(pathlib.Path())
2518
2519 sut = Node([
2520 'foobar',
2521 '#+ATTR_HTML: :width 300 :bar foo',
2522 '[[image.png]]'
2523 ], '')
2524
2525 expect = '\n'.join([
2526 '<p>foobar</p>',
2527 '<figure title="{\'bar\': \'foo\'}">',
2528 ' <img src="image.png" '
2529 'alt="image.png" width="300" />',
2530 '</figure>'
2531 ])
2532
2533 result = exp._as_html(sut, [])
2534 result = extract_html_hyperorg_content(result)
2535
2536 self.assertEqual(unify_html(result), unify_html(expect))
2537
2538 def test_linked_image_with_attributes_and_downloaded(self):
2539 """Figure with linked image.
2540
2541 The attributes are lost when it is a linked image inside the figure.
2542 """
2543
2544 with mock.patch('pathlib.Path.mkdir'):
2545 exp = Exporter(pathlib.Path())
2546
2547 sut = Node([
2548 'foobar',
2549 '#+ATTR_HTML: :width 300 :bar foo',
2550 '#+DOWNLOADED: https://foo.bar',
2551 '[[file:link.png][file:image.png]]'
2552 ], '')
2553
2554 expect = '\n'.join([
2555 '<p>foobar</p>',
2556 '<figure title="#+DOWNLOADED: '
2557 'https://foo.bar {\'bar\': \'foo\'}">',
2558 ' <a target="_blank" rel="noopener noreferrer" '
2559 'href="link.png"><img src="image.png" '
2560 'alt="image.png" width="300" /></a>',
2561 '</figure>'
2562 ])
2563
2564 result = exp._as_html(sut, [])
2565 result = extract_html_hyperorg_content(result)
2566
2567 self.assertEqual(unify_html(result), unify_html(expect))
2568
2569 def test_with_caption_and_multiple_attributes(self):
2570
2571 with mock.patch('pathlib.Path.mkdir'):
2572 exp = Exporter(pathlib.Path())
2573
2574 sut = Node([
2575 'foobar',
2576 '#+ATTR_HTML: :width 123',
2577 '#+caption: FooBar',
2578 '#+ATTR_HTML: :style border:4px solid pink',
2579 '#+ATTR_HTML: :alt another alt',
2580 '[[image.png]]'
2581 ], '')
2582
2583 expect = '\n'.join([
2584 '<p>foobar</p>',
2585 '<figure>',
2586 ' <img src="image.png" alt="another alt" width="123" '
2587 'style="border:4px solid pink" />',
2588 ' <figcaption>FooBar</figcaption>',
2589 '</figure>'
2590 ])
2591
2592 result = exp._as_html(sut, [])
2593 result = extract_html_hyperorg_content(result)
2594
2595 self.assertEqual(unify_html(result), unify_html(expect))
2596
2597 def test_unknown_attributes_to_tooltip(self):
2598
2599 with mock.patch('pathlib.Path.mkdir'):
2600 exp = Exporter(pathlib.Path())
2601
2602 sut = Node([
2603 'foobar',
2604 '#+UnkNown: pink',
2605 '#+fooBAR: elephant',
2606 '[[image.png]]'
2607 ], '')
2608
2609 expect = '\n'.join([
2610 '<p>foobar</p>',
2611 '<figure title="#+UNKNOWN: pink\n#+FOOBAR: elephant">',
2612 ' <img src="image.png" alt="image.png" />',
2613 '</figure>'
2614 ])
2615
2616 result = exp._as_html(sut, [])
2617 result = extract_html_hyperorg_content(result)
2618
2619 self.assertEqual(unify_html(result), unify_html(expect))
2620
2621 def test_with_title_attribute(self):
2622
2623 with mock.patch('pathlib.Path.mkdir'):
2624 exp = Exporter(pathlib.Path())
2625
2626 sut = Node([
2627 'foobar',
2628 ('#+ATTR_HTML: :title NASA/Apollo 17 crew; '
2629 'taken by either Harrison Schmitt or Ron Evans'),
2630 '[[image.png]]'
2631 ], '')
2632
2633 expect = '\n'.join([
2634 '<p>foobar</p>',
2635 '<figure>',
2636 ' <img src="image.png" alt="image.png" ',
2637 'title="NASA/Apollo 17 crew; taken by '
2638 'either Harrison Schmitt or Ron Evans" />',
2639 '</figure>'
2640 ])
2641
2642 result = exp._as_html(sut, [])
2643 result = extract_html_hyperorg_content(result)
2644
2645 self.assertEqual(unify_html(result), unify_html(expect))
2646
2647
2648 class Headings(unittest.TestCase):
2649 """Test exporting Heading elements into HTML"""
2650
2651 # pylint: disable=protected-access
2652
2653 def setUp(self):
2654 Node.nodes = {}
2655 Node.heading_ids = {}
2656
2657 @mock.patch('uuid.uuid4')
2658 def test_with_anchor(self, mock_uuid):
2659 """Heading with anchor."""
2660 mock_uuid.return_value = '123456'
2661
2662 node = Node(['* eins', '* zwei'], '')
2663 node[1].generate_anchor()
2664
2665 with mock.patch('pathlib.Path.mkdir'):
2666 exp = Exporter(pathlib.Path())
2667
2668 generated_html = exp._as_html(node, [])
2669 generated_html = extract_html_hyperorg_content(generated_html)
2670 generated_html = generated_html.strip()
2671
2672 self.assertEqual(
2673 generated_html,
2674 '<h2>eins</h2>\n<h2 id="123456">zwei</h2>'
2675 )
2676
2677 def test_two_headings(self):
2678 """Two headings."""
2679 test_data = [
2680 (['* eins', '* zwei'],
2681 '<h2>eins</h2>\n<h2>zwei</h2>'),
2682 ]
2683
2684 with mock.patch('pathlib.Path.mkdir'):
2685 exp = Exporter(pathlib.Path())
2686
2687 for content, target_html in test_data:
2688 node = Node(content, '')
2689 html = exp._as_html(node, [])
2690 html = extract_html_hyperorg_content(html)
2691 html = html.strip()
2692
2693 self.assertEqual(html, target_html)
2694
2695 def test_title_for_page_and_h1(self):
2696 """Title as h1-tag and page title."""
2697
2698 with mock.patch('pathlib.Path.mkdir'):
2699 exp = Exporter(pathlib.Path())
2700
2701 # first (one and only) node
2702 node = Node(['Lorem ipsum'], 'filename')
2703
2704 with mock.patch('hyperorg.exporter.Exporter._get_footer') as m_footer:
2705 m_footer.return_value = ''
2706 self.maxDiff = None
2707 html = unify_html(exp._as_html(node, []))
2708
2709 self.assertTrue('<title>[no title]</title>' in html)
2710 self.assertTrue('<h1>[no title]</h1>' in html)
2711
2712
2713 class NodeWithMathToHtml(unittest.TestCase):
2714 """A node with several display and inline math
2715 converted to HTML.
2716
2717 Dev note (buhtz, 2025-12): In this test suite the goal is not to parse org
2718 content. The Node is constructed and than converted into HTML.
2719 """
2720 # pylint: disable=protected-access
2721
2722 def test_display_simple(self):
2723 """One display math"""
2724 sut = Node([], '')
2725 sut._elements.append(elements.DisplayMath('a=b'))
2726
2727 self.assertEqual(
2728 Exporter._body_and_meta(sut),
2729 r'<div class="math">\[a=b\]</div>'
2730 )
2731
2732 def test_display_multiple(self):
2733 """Multiple display math"""
2734 sut = Node([], '')
2735 sut._elements.append(elements.DisplayMath('a=b'))
2736 sut._elements.append(elements.DisplayMath('c=d'))
2737 sut._elements.append(elements.DisplayMath('e=f'))
2738
2739 self.assertEqual(
2740 Exporter._body_and_meta(sut),
2741 '<div class="math">\\[a=b\\]</div>\n'
2742 '<div class="math">\\[c=d\\]</div>\n'
2743 '<div class="math">\\[e=f\\]</div>'
2744 )
2745
2746 def test_inline_simple(self):
2747 """Single inline math"""
2748 sut = Node([], '')
2749
2750 formula = textruns.InlineMath('a=b')
2751 par = elements.Paragraph()
2752 par.runs.append(formula)
2753 sut._elements.append(par)
2754
2755 self.assertEqual(
2756 Exporter._body_and_meta(sut),
2757 r'<p><span class="math">\(a=b\)</span></p>'
2758 )
2759
2760 def test_inline_multi(self):
2761 """Multiple inline math in one paragraph"""
2762 sut = Node([], '')
2763
2764 formula_one = textruns.InlineMath('a=b')
2765 formula_two = textruns.InlineMath('c=d')
2766 formula_three = textruns.InlineMath('e=f')
2767 par = elements.Paragraph()
2768 par.runs.append(formula_one)
2769 par.runs.append(formula_two)
2770 par.runs.append(formula_three)
2771
2772 sut._elements.append(par)
2773
2774 self.assertEqual(
2775 Exporter._body_and_meta(sut),
2776 '<p>'
2777 '<span class="math">\\(a=b\\)</span>'
2778 '<span class="math">\\(c=d\\)</span>'
2779 '<span class="math">\\(e=f\\)</span>'
2780 '</p>'
2781 )
2782
2783 def test_inline_multi_with_text(self):
2784 """Combined with text"""
2785 sut = Node([], '')
2786
2787 formula_one = textruns.InlineMath('a=b')
2788 formula_two = textruns.InlineMath('c=d')
2789 formula_three = textruns.InlineMath('e=f')
2790 par = elements.Paragraph()
2791 par.runs.append('foo')
2792 par.runs.append(formula_one)
2793 par.runs.append('bar')
2794 par.runs.append(formula_two)
2795 par.runs.append('one more')
2796 par.runs.append(formula_three)
2797 par.runs.append('end')
2798
2799 sut._elements.append(par)
2800
2801 self.assertEqual(
2802 Exporter._body_and_meta(sut),
2803 '<p>'
2804 'foo'
2805 '<span class="math">\\(a=b\\)</span>'
2806 'bar'
2807 '<span class="math">\\(c=d\\)</span>'
2808 'one more'
2809 '<span class="math">\\(e=f\\)</span>'
2810 'end'
2811 '</p>'
2812 )