Debian Codegraph @

tests/test_reader.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
10 """Tests about reader.py. The Reader class using orgparser package to
11 read multiple org files."""
12 # pylint: disable=too-many-lines
13 import pathlib
14 import inspect
15 import logging
16 from collections import defaultdict
17 import unittest
18 from unittest import mock
19 from pyfakefs import fake_filesystem_unittest as pyfakefs_ut
20 from hyperorg.reader import Reader
21 from hyperorg.content import Node
22 from hyperorg import elements
23 from hyperorg import textruns
24
25
26 def _reset_node_class():
27 Node.nodes = {}
28 Node.heading_ids = {}
29 Node.index_data = {
30 'all': defaultdict(list),
31 'filetag': defaultdict(lambda: defaultdict(list))
32 }
33
34
35 org_raw_content = [
36 # node linking to another node
37 ''':PROPERTIES:
38 :ID: d197c651-f6c1-4e00-8d8e-ef13adac16e2
39 :END:
40 #+title: hyperorg_unittest_1
41 #+date: [2022-04-21 Do 16:55]
42 Test file for unittest
43
44 [[id:b0fc62f1-2926-4eec-a654-eab8fcea46d9][hyperorg_unittest_2]]''',
45
46 # the linked node
47 ''':PROPERTIES:
48 :ID: b0fc62f1-2926-4eec-a654-eab8fcea46d9
49 :END:
50 #+title: hyperorg_unittest_2
51 #+date: [2022-04-21 Do 16:55]
52 Second hyperorg test file''',
53
54 # node with child node (heading with own Org-ID)
55 ''':PROPERTIES:
56 :ID: 4a2f8510-f57e-468e-9832-8ddecd3335ac
57 :END:
58 #+title: killme
59 #+date: [2022-04-03 So 22:55]
60 Governments of the Industrial World,
61 * Heading
62 you weary giants of flesh and steel,
63 * Child
64 :PROPERTIES:
65 :ID: 95c99140-f044-450d-b631-6a5ff7608b2b
66 :END:
67 I come from Cyberspace, the new home of Mind,
68 * One more
69 On behalf of the future, I ask you of
70 the past to leave us alone.''',
71
72 # node with alias titles incl. subheadings
73 ''':PROPERTIES:
74 :ID: 5a2f8510-f57e-468e-9832-8ddecd3335ac
75 :ROAM_ALIASES: aliasnode "node with alias"
76 :END:
77 #+title: killme
78 #+date: [2022-04-03 So 22:55]
79 * Foo
80 bar
81 * Bar
82 :PROPERTIES:
83 :ID: da6759cb-ba23-4042-9486-abc0c76895ad
84 :ROAM_ALIASES: again "ein bar alias"
85 :END:
86 foo'''
87 ]
88
89 backlinks_raw_content = [
90
91 # node that is linked to
92 ''':PROPERTIES:
93 :ID: node-A
94 :END:
95 #+title: Node-A
96 Governments of the Industrial World,
97 * Heading Sub-A
98 :PROPERTIES:
99 :ID: sub-A
100 :END:
101 you weary giants of flesh and steel,
102 I come from Cyberspace, the new home of Mind,''',
103
104 # B
105 ''':PROPERTIES:
106 :ID: node-B
107 :END:
108 #+title: Node-B
109 * Foo
110 [[id:node-A][NodeA]]''',
111
112 # C
113 ''':PROPERTIES:
114 :ID: node-C
115 :END:
116 #+title: Node-C
117 * Heading Sub-C
118 :PROPERTIES:
119 :ID: sub-C
120 :END:
121 [[id:node-A][A]]''',
122
123 # D
124 ''':PROPERTIES:
125 :ID: node-D
126 :END:
127 #+title: Node-D
128 [[id:node-A][A]]
129 * Heading Sub-D
130 :PROPERTIES:
131 :ID: sub-D
132 :END:
133 [[id:node-A][a]]''',
134
135 # E
136 ''':PROPERTIES:
137 :ID: node-E
138 :END:
139 #+title: Node-E
140 [[id:node-A][a]]
141
142 [[id:node-A][a]]
143
144 [[id:node-A][a]]''',
145
146 # F
147 ''':PROPERTIES:
148 :ID: node-F
149 :END:
150 #+title: Node-F
151 [[id:sub-A][sA]]''',
152
153 # G
154 ''':PROPERTIES:
155 :ID: node-G
156 :END:
157 #+title: Node-G
158 * Heading Sub-Ga
159 :PROPERTIES:
160 :ID: sub-Ga
161 :END:
162 [[id:node-A][a]]
163 * Heading Sub-Gb
164 :PROPERTIES:
165 :ID: sub-Gb
166 :END:
167 [[id:node-A][a]]''',
168 ]
169
170
171 index_data_raw_content = [
172 # title and subheading title
173 ''':PROPERTIES:
174 :ID: node-A
175 :END:
176 #+title: Node-A
177 Governments of the Industrial World,
178 * Heading Sub-A
179 :PROPERTIES:
180 :ID: sub-A
181 :END:
182 you weary giants of flesh and steel,
183 I come from Cyberspace, the new home of Mind,''',
184
185 # title and alias
186 ''':PROPERTIES:
187 :ID: node-B
188 :ROAM_ALIASES: Frühstücksflocken
189 :END:
190 #+title: Cerial
191 Foo''',
192
193 # subheading alias
194 ''':PROPERTIES:
195 :ID: node-C
196 :END:
197 #+title: Node-C
198 * Heading Sub-C
199 :PROPERTIES:
200 :ID: sub-C
201 :ROAM_ALIASES: "Dr. Doom"
202 :END:
203 Jimmy''',
204
205 # Two Filetag
206 ''':PROPERTIES:
207 :ID: node-D
208 :END:
209 #+title: Node-D
210 #+filetags: Wiki Person
211 Foo''',
212
213 # wiki
214 ''':PROPERTIES:
215 :ID: node-E
216 :END:
217 #+title: Node-E
218 #+filetags: Wiki
219 foobar''',
220
221 # person
222 ''':PROPERTIES:
223 :ID: node-F
224 :END:
225 #+title: Node-F
226 #+filetags: Person
227 Ricky''',
228 ]
229
230
231 class General(unittest.TestCase):
232 """General tests about the Reader"""
233
234 def setUp(self):
235 _reset_node_class()
236
237 def test_input_dir_exists(self):
238 """Input dir exists."""
239 with mock.patch('pathlib.Path') as mocked_path:
240 mocked_path.exists.return_value = True
241 with self.assertLogs() as cm_log:
242 Reader(mocked_path)
243 # one log message only
244 self.assertEqual(len(cm_log.output), 1)
245 # content of log message
246 self.assertRegex(
247 cm_log.output[0],
248 r'^INFO.*reader:Input from.*'
249 )
250 # exists called one only
251 mocked_path.exists.assert_called_once()
252
253 def test_input_dir_not_exists(self):
254 """Input dir not exists."""
255 with mock.patch('pathlib.Path') as mocked_path:
256 mocked_path.exists.return_value = False
257 with self.assertLogs() as cm_log:
258 # exit()
259 with self.assertRaises(SystemExit):
260 Reader(mocked_path)
261 # exists() called
262 mocked_path.exists.assert_called_once()
263
264 # one log message only
265 self.assertEqual(len(cm_log.output), 2)
266 # content of log message
267 self.assertRegex(
268 cm_log.output[1],
269 r'^ERROR.*reader:Input directory.*does not exists.$'
270 )
271
272 def test_input_dir_store(self):
273 """Storing input dir parameter."""
274 with mock.patch('pathlib.Path.exists', return_value=True):
275 with mock.patch('pathlib.Path.is_dir', return_value=True):
276 fn = 'foobar'
277 Reader(pathlib.Path(fn))
278 self.assertEqual(str(Node.input_dir), fn)
279
280 def test_title_index_letter(self):
281 """Extract index letter from titles."""
282 # pylint: disable=protected-access
283 test_data = [
284 ('foo', 'F'),
285 ('Bar', 'B'),
286 ('Ähm', 'A'),
287 ('äm', 'A'),
288 ('öhm', 'O'),
289 ('Öhm', 'O'),
290 ('ühm', 'U'),
291 ('Ühm', 'U'),
292 ('=jup', '='),
293 ('ßjup', 'S'),
294 ('foo =bar=', 'F'),
295 # This is not implemented yet.
296 # ('=foo= bar', 'F'),
297 ]
298
299 for title, letter in test_data:
300 self.assertEqual(
301 Reader._title_to_index_letter(title),
302 letter,
303 (title, letter))
304
305 def test_add_to_index_data(self):
306 """Correct index data based on a new node"""
307
308 # pylint: disable=protected-access
309 self.maxDiff = None
310
311 # empty index data
312 self.assertEqual(
313 list(Node.index_data.keys()),
314 ['all', 'filetag']
315 )
316
317 self.assertEqual(Node.index_data['all'], {})
318 self.assertEqual(Node.index_data['filetag'], {})
319
320 # create content
321 node = Node(
322 body_lines=[
323 '#+title: Titel',
324 '#+filetags: My Tag',
325 'lore ipsum'],
326 filename='',
327 title_aliases=['Peter', 'Lustig']
328 )
329
330 # add it to index data
331 Reader._add_to_index_data(node, '1234')
332
333 expect = {
334 'all': {
335 'L': [(['Lustig'], '1234', True)],
336 'P': [(['Peter'], '1234', True)],
337 'T': [(['Titel'], '1234', False)]
338 },
339 'filetag': {
340 'My': {
341 'L': [(['Lustig'], '1234', True)],
342 'P': [(['Peter'], '1234', True)],
343 'T': [(['Titel'], '1234', False)]
344 },
345 'Tag': {
346 'L': [(['Lustig'], '1234', True)],
347 'P': [(['Peter'], '1234', True)],
348 'T': [(['Titel'], '1234', False)]
349 }
350 }
351 }
352
353 self.assertEqual(Node.index_data, expect)
354
355
356 class RealFiles(pyfakefs_ut.TestCase):
357 """Test with real files on a fake filesystem"""
358
359 # pylint: disable=protected-access
360
361 def setUp(self):
362 """Create a folder with three org files."""
363
364 Node.nodes = {}
365 Node.heading_ids = {}
366 Node.backlinks = {}
367
368 self.setUpPyfakefs(allow_root_user=False)
369 self.input_dir = pathlib.Path('/test_reader_RealFiles-input_dir')
370 self.input_dir.mkdir()
371
372 def _create_files(self, fn_idx=None):
373 """
374 """
375
376 if not fn_idx:
377 self._create_files([
378 ('test1.org', 0),
379 ('test2.org', 1),
380 ('killme.org', 2),
381 ('alias.org', 3)])
382 else:
383 for fn, idx in fn_idx:
384 with (self.input_dir / fn).open('w', 'utf-8') as handle:
385 handle.write(inspect.cleandoc(org_raw_content[idx]))
386
387 # create additional file that should be ignored
388 with (self.input_dir / 'ignore.me').open('wb') as handle:
389 handle.write(b'foobar')
390
391 def test_dotfiles(self):
392 """Ignore dotfiles.
393
394 Such files can appear as hidden files from text editors.
395 """
396
397 self._create_files()
398
399 # make on into a hidden dotfile
400 path = self.input_dir / 'test1.org'
401 path.rename(path.parent / f'.{path.name}')
402
403 file_count = len(list(self.input_dir.glob('*.org')))
404
405 # Five files do exist. One is the dotfile.
406 self.assertEqual(file_count, 4)
407
408 reader = Reader(self.input_dir)
409 reader.read_org_files()
410
411 # But only four should have been read.
412 self.assertEqual(len(Node.nodes), 3)
413
414 def test_alias_titles(self):
415 """Alias titles for node and subheadings.
416 """
417
418 self._create_files([('alias.org', 3)])
419
420 # read the files
421 reader = Reader(self.input_dir)
422 reader.read_org_files()
423
424 nodeid = '5a2f8510-f57e-468e-9832-8ddecd3335ac'
425 # subid = 'da6759cb-ba23-4042-9486-abc0c76895ad'
426 node = Node.nodes[nodeid]
427
428 self.assertEqual(
429 node._meta['aliases_org'],
430 ['aliasnode', 'node with alias']
431 )
432 self.assertEqual(
433 node._elements[2]._meta['aliases_org'],
434 ['again', 'ein bar alias']
435 )
436
437 def test_read_org(self):
438 """Read org-files via orgparse."""
439
440 # Prepare the filesystem (only two files)
441 self._create_files([('test1.org', 0), ('test2.org', 1)])
442
443 self.assertEqual(
444 [p.name for p in self.input_dir.glob('*')],
445 ['test1.org', 'test2.org', 'ignore.me']
446 )
447
448 # read the files
449 reader = Reader(self.input_dir)
450
451 reader.read_org_files()
452
453 # two nodes
454 self.assertEqual(len(Node.nodes), 2)
455
456 # check first node's content
457 key = 'd197c651-f6c1-4e00-8d8e-ef13adac16e2'
458 self.assertEqual(len(Node.nodes[key]._elements), 2)
459 self.assertEqual(list(Node.nodes[key]._meta.keys()), ['date'])
460 self.assertEqual(Node.nodes[key].title_org, 'hyperorg_unittest_1')
461 self.assertEqual(Node.nodes[key][0][0], 'Test file for unittest')
462
463 link_run = Node.nodes[key][1][0]
464 self.assertEqual(
465 link_run.target, 'b0fc62f1-2926-4eec-a654-eab8fcea46d9')
466 self.assertEqual(link_run[0], 'hyperorg_unittest_2')
467
468 # check second node's content
469 key = 'b0fc62f1-2926-4eec-a654-eab8fcea46d9'
470 node = Node.nodes[key]
471 self.assertEqual(len(node), 2) # incl. backlinks
472 self.assertEqual(list(node._meta.keys()), ['date'])
473 self.assertEqual(node.title_org, 'hyperorg_unittest_2')
474 self.assertEqual(node[0][0], 'Second hyperorg test file')
475
476 # 2nd nodes backlink
477 self.assertIsInstance(node._elements[1], elements.Backlinks)
478 link_run = node[1][0][0]
479 self.assertEqual(
480 link_run.target, 'd197c651-f6c1-4e00-8d8e-ef13adac16e2')
481 self.assertEqual(link_run[0], 'hyperorg_unittest_1')
482
483 @mock.patch('uuid.uuid4')
484 def test_read_org_with_child_node(self, mock_uid):
485 """Org-file with own ID for a heading/subtree."""
486
487 mock_uid.return_value = '987654'
488
489 self._create_files([('killme.org', 2)])
490 self.assertEqual(
491 [p.name for p in self.input_dir.glob('*.org')],
492 ['killme.org']
493 )
494
495 # read the files
496 reader = Reader(self.input_dir)
497 reader.read_org_files()
498
499 node_ids = [
500 # OrgID of the node
501 '4a2f8510-f57e-468e-9832-8ddecd3335ac',
502 # OrgID of the subheading
503 '95c99140-f044-450d-b631-6a5ff7608b2b']
504
505 # The headings with their own OrgId (also known as subtree)
506 # are created as an element of type hyperorg.Content.
507 # That instances are not listed in Content.nodes but in
508 # Content.heading_ids
509
510 # only one subheading orgid
511 self.assertEqual(len(Node.heading_ids), 1)
512 self.assertEqual(list(Node.heading_ids)[0], node_ids[1])
513 # its value is a tuple of the parents OrgId and its own element
514 # index in that parents element list
515 self.assertEqual(Node.heading_ids[node_ids[1]], (node_ids[0], 3))
516 # the parent node
517 self.assertEqual(len(Node.nodes), 1)
518 self.assertEqual(list(Node.nodes)[0], node_ids[0])
519 self.assertIsInstance(Node.nodes[node_ids[0]], Node)
520
521 # one content/node
522 self.assertEqual(len(Node.nodes), 1)
523 # ...and its OrgID
524 node = Node.nodes[node_ids[0]]
525
526 # one heading/subtree with OrgID
527 self.assertEqual(len(Node.heading_ids), 1)
528 # ...and its OrgID
529 heading_orgid, heading_idx = Node.heading_ids[node_ids[1]]
530
531 # heading points to the real node
532 self.assertEqual(heading_orgid, node_ids[0])
533
534 # ...and to the corresponding content element
535 self.assertEqual(heading_idx, 3) # 4nd element
536 self.assertIsInstance(node[heading_idx], Node)
537
538 # check each element
539 self.assertEqual(len(node), 6)
540 self.assertIsInstance(node[0], elements.Paragraph)
541 self.assertIsInstance(node[1], elements.Heading)
542 self.assertIsInstance(node[2], elements.Paragraph)
543 self.assertIsInstance(node[3], Node)
544 self.assertIsInstance(node[4], elements.Heading)
545 self.assertIsInstance(node[5], elements.Paragraph)
546
547 # check the sub-Content element
548 subtree = node[heading_idx]
549 self.assertEqual(len(subtree), 2)
550 self.assertIsInstance(subtree[0], elements.Heading)
551 self.assertIsInstance(subtree[1], elements.Paragraph)
552
553 # anchor for first heading generated?
554 self.assertEqual(subtree[0][0], 'Child')
555 self.assertEqual(subtree[0].anchor, '987654')
556
557 def test_read_org_sub_heading(self):
558 """Org-file with own ID for a heading/subtree."""
559
560 self._create_files([('killme.org', 2)])
561 self.assertEqual(
562 [p.name for p in self.input_dir.glob('*.org')],
563 ['killme.org']
564 )
565
566 # read the files
567 reader = Reader(self.input_dir)
568 reader.read_org_files()
569
570 self.assertEqual(len(Node.nodes), 1)
571 self.assertEqual(len(Node.heading_ids), 1)
572
573 node = list(Node.nodes.values())[0]
574 self.assertEqual(node.title_org, 'killme')
575
576 self.assertEqual(node[3].title_org, 'Child')
577
578 def test_node_with_subheading(self):
579 """Node with a subheading (result in a child node)"""
580
581 # create file
582 fn = 'foo.org'
583 with (self.input_dir / fn).open('w', 'utf-8') as handle:
584 body_lines = [
585 ':PROPERTIES:',
586 ':ID: f7c0d0d1-3d4c-4bcc-96c0-6fa19036f21e',
587 ':END:',
588 '#+title: Issue93sub',
589 '* Heading',
590 'Foobar',
591 '* Next Heading',
592 ':PROPERTIES:',
593 ':ID: c07df761-b328-4cde-8433-9343cee055c6',
594 ':END:',
595 '- Barfoo'
596 ]
597 handle.write('\n'.join(body_lines))
598
599 # read the files
600 reader = Reader(self.input_dir)
601 reader.read_org_files()
602
603 self.assertEqual(len(Node.nodes), 1)
604
605 self.assertEqual(len(Node.heading_ids), 1)
606
607 node = list(Node.nodes.values())[0]
608 self.assertEqual(node.title_org, 'Issue93sub')
609 self.assertEqual(node[2].title_org, 'Next Heading')
610
611 def test_invalid_unicode_char(self):
612 """Handle orgparse exception about invalid unicode characters"""
613 # create file
614 fn = 'invalid_char.org'
615 with (self.input_dir / fn).open('wb') as handle:
616 handle.write(b':PROPERTIES:\n')
617 handle.write(b':ID: f7c0d0d1\n')
618 handle.write(b':END:\n')
619 handle.write(b'nicht-UTF-8-kodierten Zeichen: \xfc')
620 handle.write(b' ende')
621
622 # read the files
623 with self.assertLogs(level=logging.ERROR) as cm_log:
624 reader = Reader(self.input_dir)
625 reader.read_org_files()
626
627 # one error
628 self.assertEqual(len(cm_log.output), 1)
629
630 self.assertRegex(
631 cm_log.output[0],
632 r'.*invalid start byte.*UnicodeDecodeError.*$'
633 )
634
635
636 class Globbing(pyfakefs_ut.TestCase):
637 """Test globbing of files"""
638
639 @classmethod
640 def setUpClass(cls):
641 cls.setUpClassPyfakefs() # pylint: disable=no-member
642
643 cls.input_dir = pathlib.Path('/') / 'alpha' / 'quadrant'
644
645 folders = [
646 'bajor',
647 '.gamma'
648 ]
649
650 files = [
651 'picard.org',
652 '.quark.org',
653 'grund.img',
654 'bajor/kira.oRg',
655 'bajor/.opaka.ORG',
656 'bajor/kaivin.png',
657 '.gamma/wayon.orG',
658 '.gamma/far.org'
659 ]
660
661 # create folders
662 for fn in folders:
663 fp = cls.input_dir / fn
664 fp.mkdir(parents=True)
665
666 # create files
667 for fn in files:
668 fp = cls.input_dir / fn
669 fp.touch()
670
671 def test_globbing(self):
672 """Test finding files"""
673 # pylint: disable=protected-access
674 reader = Reader(self.input_dir)
675
676 expected = [
677 self.input_dir / 'picard.org',
678 self.input_dir / 'bajor' / 'kira.oRg'
679 ]
680
681 result = reader._glob_from_input_dir()
682
683 self.assertEqual(sorted(expected), sorted(result))
684
685
686 class Backlinks(pyfakefs_ut.TestCase):
687 """Test handling of backlinks"""
688
689 def setUp(self):
690 """Create a folder with three org files."""
691
692 # reset Content
693 Node.nodes = {}
694 Node.heading_ids = {}
695
696 # fake filesystem
697 self.setUpPyfakefs(allow_root_user=False)
698 self.input_dir = pathlib.Path('/test_reader_Backlinks-input_dir')
699 self.input_dir.mkdir()
700
701 # create org files
702 for idx, base in enumerate('ABCDEFG'):
703 fp = self.input_dir / f'node_{base}.org'
704 with fp.open('w', 'utf-8') as handle:
705 handle.write(inspect.cleandoc(backlinks_raw_content[idx]))
706
707 def _delete_nodes(self, node_orgids):
708 """
709 """
710 for orgid in node_orgids:
711 fp = self.input_dir / f'node_{orgid}.org'
712 fp.unlink()
713
714 def test_simple(self):
715 """Simple node link from A to B."""
716
717 # pylint: disable=protected-access
718 # keep A and B
719 self._delete_nodes(list('CDEFG'))
720
721 # A and B are read now.
722 reader = Reader(self.input_dir)
723 reader.read_org_files()
724
725 self.assertEqual(Node.nodes['node-A']._orgids_linking, [])
726 self.assertEqual(Node.nodes['node-B']._orgids_linking, ['node-A'])
727
728 # B does link to A.
729 # Because of that A need to have a backlink to B.
730 backlink_element = Node.nodes['node-A'][2]
731
732 self.assertIsInstance(backlink_element, elements.Backlinks)
733
734 link_run = backlink_element[0][0]
735 self.assertEqual(link_run.target, 'node-B')
736 self.assertEqual(link_run[0], 'Node-B')
737 self.assertEqual(link_run.link_type, textruns.Link.Type.ORGID)
738
739 def test_link_from_subheading(self):
740 """Sub-heading links to a node.
741
742 The subheading "sub-C" does link to "A" which is just one link but
743 results in two backlinks including the parent of the subheading:
744 - Node-C
745 - Headinb Sub-C
746 """
747
748 # keep A and C
749 self._delete_nodes(list('BDEFG'))
750
751 reader = Reader(self.input_dir)
752 reader.read_org_files()
753
754 ble = Node.nodes['node-A'][2]
755
756 # the parent link
757 self.assertEqual(ble[0][0].target, 'node-C')
758
759 # the subheading link in a sub-list
760 self.assertEqual(ble[1][0][0].target, 'sub-C')
761
762 def test_link_from_node_and_subheading(self):
763 """Node and its Sub-heading linking a node."""
764
765 # keep A and D
766 self._delete_nodes(list('BCEFG'))
767
768 reader = Reader(self.input_dir)
769 reader.read_org_files()
770
771 # Backlinks of Node-A
772 ble = Node.nodes['node-A'][-1]
773
774 # Count of 1st level entries: parent + subheading
775 self.assertEqual(len(ble), 2)
776 # Count of 2nd level entries: the subheading only
777 self.assertEqual(len(ble[1]), 1)
778
779 self.assertEqual(ble[0][0].target, 'node-D')
780 self.assertEqual(ble[1][0][0].target, 'sub-D')
781
782 def test_three_duplicated_links(self):
783 """Three links from one node."""
784
785 # keep A and E
786 self._delete_nodes(list('BCDFG'))
787
788 reader = Reader(self.input_dir)
789 reader.read_org_files()
790
791 ble = Node.nodes['node-A'][2]
792
793 # "node-E" liks three times to "A", but duplicates not allowed
794 self.assertEqual(len(ble), 1)
795 self.assertEqual(ble[0][0].target, 'node-E')
796
797 def test_two_backlinks(self):
798 """Node A with two backlinks.
799
800 ListElement(
801 ordered=False,
802 _indention=0,
803 runs=[
804 [
805 Link(runs=['Enno Swart'],
806 kind=<Kind.ORGID: 'id'>,
807 target='8988edc3-725c-4037-91d6-0b693a94c374')
808 ],
809 [
810 Link(runs=['Zettelkasten'],
811 kind=<Kind.ORGID: 'id'>,
812 target='c107fe6b-cd42-4b52-b764-5dec62809cc8')
813 ]
814 ]
815 )
816
817 """
818 # keep A, B, C
819 self._delete_nodes(list('DEFG'))
820
821 reader = Reader(self.input_dir)
822 reader.read_org_files()
823
824 self.assertEqual(len(Node.nodes), 3)
825
826 node = Node.nodes['node-A']
827 back = node[2]
828
829 self.assertIsInstance(back, elements.Backlinks)
830 self.assertIsInstance(back[0][0], textruns.Link)
831 self.assertIsInstance(back[1][0], textruns.Link)
832 self.assertIsInstance(back[2], elements.ListElement)
833 self.assertIsInstance(back[2][0][0], textruns.Link)
834
835 # 1st link
836 self.assertEqual(back[0][0].target, 'node-B')
837 self.assertEqual(back[0][0].runs, ['Node-B'])
838
839 # 2nd link
840 self.assertEqual(back[1][0].target, 'node-C')
841 self.assertEqual(back[1][0].runs, ['Node-C'])
842
843 # 3rd link (to a subheading of node-c)
844 self.assertEqual(back[2][0][0].target, 'sub-C')
845 self.assertEqual(back[2][0][0].runs, ['Heading Sub-C'])
846
847 def test_link_to_subheading(self):
848 """Node links to a subheading."""
849
850 # keep A and F
851 self._delete_nodes(list('BCDEG'))
852
853 reader = Reader(self.input_dir)
854 reader.read_org_files()
855
856 ble = Node.nodes['node-A'][2]
857
858 # "node-F" links to A's subheading "sub-A"
859 self.assertEqual(ble[0][0].target, 'node-F')
860
861 def test_link_from_two_subheadings(self):
862 """Node links from two subheadings."""
863
864 # keep A and G
865 self._delete_nodes(list('BCDEF'))
866
867 reader = Reader(self.input_dir)
868 reader.read_org_files()
869
870 ble = Node.nodes['node-A'][2]
871
872 # "sub-Ga" and "sub-Gb" linking to "node-A"
873 self.assertEqual(ble[0][0].target, 'node-G')
874 self.assertEqual(ble[1][0][0].target, 'sub-Ga')
875 self.assertEqual(ble[1][1][0].target, 'sub-Gb')
876
877 def test_dead_link(self):
878 """Link to unexisting node.
879
880 When a node links to a node that doesn't exists a backlink can not be
881 created at the backlinked node because it doesn't exist.
882 E.g. A links to X but X was deleted before.
883 """
884
885
886 class IndexData(pyfakefs_ut.TestCase):
887 """Extracting index data from the nodes.
888
889 Titles, alias titles, filetags, index letters, etc
890
891 TODO
892 - test_add_to_index_data() (also for sub-heaings!)
893 """
894
895 def setUp(self):
896 """Create a folder with three org files."""
897
898 # reset Content
899 Node.nodes = {}
900 Node.heading_ids = {}
901 Node.index_data = {
902 Node.IDX_ALL: defaultdict(list),
903 Node.IDX_FILETAG: defaultdict(lambda: defaultdict(list))
904 }
905
906 # fake filesystem
907 self.setUpPyfakefs(allow_root_user=False)
908 self.input_dir = pathlib.Path('/test_reader_IndexData-input_dir')
909 self.input_dir.mkdir()
910
911 # create org files
912 for idx, base in enumerate('ABCDEF'):
913 fp = self.input_dir / f'node_{base}.org'
914 with fp.open('w', 'utf-8') as handle:
915 handle.write(inspect.cleandoc(index_data_raw_content[idx]))
916
917 def _delete_nodes(self, node_orgids):
918 """
919 """
920 for orgid in node_orgids:
921 fp = self.input_dir / f'node_{orgid}.org'
922 fp.unlink()
923
924 def test_simple(self):
925 """One node with sub-heading"""
926 self.maxDiff = None
927
928 # keep A
929 self._delete_nodes(list('BCDEF'))
930
931 reader = Reader(self.input_dir)
932 reader.read_org_files()
933
934 expected = {
935 Node.IDX_ALL: {
936 'H': [
937 (['Heading Sub-A'], 'sub-A', False)
938 ],
939 'N': [
940 (['Node-A'], 'node-A', False)
941 ]
942 },
943 Node.IDX_FILETAG: {
944 Node.IDX_NO_TAG: {
945 'H': [
946 (['Heading Sub-A'], 'sub-A', False)
947 ],
948 'N': [
949 (['Node-A'], 'node-A', False)
950 ]
951 }
952 }
953 }
954
955 result = Node.index_data
956 self.assertDictEqual(result, expected)
957
958 def test_aliases(self):
959 """One node with alias title"""
960 self.maxDiff = None
961 # keep A
962 self._delete_nodes(list('ACDEF'))
963
964 reader = Reader(self.input_dir)
965 reader.read_org_files()
966
967 expected = {
968 Node.IDX_ALL: {
969 'C': [
970 (['Cerial'], 'node-B', False)
971 ],
972 'F': [
973 (['Frühstücksflocken'], 'node-B', True)
974 ]
975 },
976 Node.IDX_FILETAG: {
977 Node.IDX_NO_TAG: {
978 'C': [
979 (['Cerial'], 'node-B', False)
980 ],
981 'F': [
982 (['Frühstücksflocken'], 'node-B', True)
983 ]
984 }
985 }
986 }
987
988 result = Node.index_data
989
990 self.assertEqual(result, expected)
991
992 def test_complex(self):
993 """Multiple nodes"""
994
995 self.maxDiff = None
996
997 reader = Reader(self.input_dir)
998 reader.read_org_files()
999
1000 expected = {
1001 Node.IDX_ALL: {
1002 'C': [
1003 (['Cerial'], 'node-B', False)
1004 ],
1005 'D': [
1006 (['Dr. Doom'], 'sub-C', True)
1007 ],
1008 'F': [
1009 (['Frühstücksflocken'], 'node-B', True)
1010 ],
1011 'H': [
1012 (['Heading Sub-A'], 'sub-A', False),
1013 (['Heading Sub-C'], 'sub-C', False),
1014 ],
1015 'N': [
1016 (['Node-A'], 'node-A', False),
1017 (['Node-C'], 'node-C', False),
1018 (['Node-D'], 'node-D', False),
1019 (['Node-E'], 'node-E', False),
1020 (['Node-F'], 'node-F', False),
1021 ]
1022 },
1023 Node.IDX_FILETAG: {
1024 Node.IDX_NO_TAG: {
1025 'C': [
1026 (['Cerial'], 'node-B', False)
1027 ],
1028 'D': [
1029 (['Dr. Doom'], 'sub-C', True)
1030 ],
1031 'F': [
1032 (['Frühstücksflocken'], 'node-B', True)
1033 ],
1034 'H': [
1035 (['Heading Sub-A'], 'sub-A', False),
1036 (['Heading Sub-C'], 'sub-C', False),
1037 ],
1038 'N': [
1039 (['Node-A'], 'node-A', False),
1040 (['Node-C'], 'node-C', False),
1041 ]
1042 },
1043 'Wiki': {
1044 'N': [
1045 (['Node-D'], 'node-D', False),
1046 (['Node-E'], 'node-E', False),
1047 ]
1048 },
1049 'Person': {
1050 'N': [
1051 (['Node-D'], 'node-D', False),
1052 (['Node-F'], 'node-F', False),
1053 ]
1054 },
1055 }
1056 }
1057
1058 result = Node.index_data
1059
1060 self.assertEqual(result, expected)